Skip to main content

bynk_lsp/
extract.rs

1//! v0.213 (ADR 0239): `textDocument/codeAction` extract-variable —
2//! `CodeActionKind::REFACTOR_EXTRACT`. The smallest expression node whose
3//! span fully contains the requested selection is bound to a fresh `let`
4//! inserted immediately above its enclosing statement (or block tail), and
5//! the selection's span is replaced with the new name.
6//!
7//! `text` is whatever snapshot the caller passes in — for `code_action` that's
8//! the last **committed** analysis round's snapshot (ADR 0235's
9//! stale-while-revalidate posture), not necessarily the very latest keystroke.
10//! Like `crate::structure`, this reparses that snapshot fresh each call — no
11//! cached AST is retained in `Analysis`, and extraction is selection-driven
12//! the same way folding/selection ranges are.
13//!
14//! Track #800 settles as: [`plan_function`] reuses the exact same
15//! smallest-containing-expression selection algorithm, but lifts the
16//! expression into a new top-level `fn` (threading its free identifiers as
17//! parameters) rather than a local `let`. It is capability-free-only — `fn`
18//! has no `given` clause to propagate a capability-using body into, unlike
19//! `Handler`/`Provider` (that language-change question is deliberately not
20//! taken on here) — so it declines whenever the selection's site carries any
21//! recorded [`Requirement`], covered or not.
22//!
23//! #813 extends [`plan_function`] to a contiguous run of one or more full
24//! statements (optionally including the block's tail), not just one
25//! expression — offered when the selection's span aligns exactly with
26//! statement boundaries (whitespace-trimmed at either end, so a real
27//! "select these lines" gesture matches); a selection that doesn't align
28//! falls back to the single-expression algorithm above unchanged. A run that
29//! stops before the tail synthesises a `fn … -> ()` — or `-> Effect[()]`
30//! when the run itself performs an effect, so `do`/`<-` stay legal in
31//! the lifted body — with no explicit tail, the same implicit-unit-tail
32//! shape the parser already synthesises for any statements-only block
33//! (v0.146, ADR 0170); the call site becomes `let _ = …(…)` (or `do …(…)`
34//! in the effectful case) rather than a bare expression, since Bynk has no
35//! expression-statement form. It declines whenever a `:=` (`Cell` store
36//! write) statement falls inside the run — a lifted top-level `fn` has no
37//! store fields to write, so this always fails to typecheck, not merely a
38//! conservative guess — or whenever a binding the run introduces is still
39//! referenced later in the same block: lifting it away would strand that
40//! reference.
41
42use bynk_check::checker::{TyId, Types};
43use bynk_check::expr_types::type_at_span;
44use bynk_check::locals::{LocalBinding, locals_at};
45use bynk_check::requirements::Requirement;
46use bynk_syntax::ast::*;
47use bynk_syntax::lexer::tokenize;
48use bynk_syntax::parser::parse_unit_with_recovery;
49use bynk_syntax::span::Span;
50use std::collections::HashMap;
51use tower_lsp::lsp_types::*;
52
53/// Extract-variable actions for the requested range. Only offered for a
54/// genuine selection (`requested.start != requested.end`) — a bare cursor
55/// offers nothing, the refactor-vs-quickfix posture other editors take.
56pub fn extract_variable(
57    text: &str,
58    requested: Span,
59    uri: &Url,
60    version: Option<i32>,
61) -> Vec<CodeActionOrCommand> {
62    if requested.start == requested.end {
63        return Vec::new();
64    }
65    let Ok(tokens) = tokenize(text) else {
66        return Vec::new();
67    };
68    let (Some(unit), _errs) = parse_unit_with_recovery(&tokens, text) else {
69        return Vec::new();
70    };
71    let Some(site) = find_site(&unit, requested) else {
72        return Vec::new();
73    };
74    // #1819: the `let` goes above the enclosing statement, outside any arm
75    // pattern, lambda parameter or `is` binding the descent passed. A
76    // selection reading one of those would bind it out of scope, so offer
77    // nothing, as extract-function declines what it can't lift soundly. The
78    // match is by name, deliberately conservative: a selection that rebinds
79    // the name, or reads an outer binding sharing it, is declined too, never
80    // hoisted wrongly.
81    let mut read = Vec::new();
82    collect_idents(site.expr, &mut read);
83    if read.iter().any(|id| site.binders.binds(&id.name)) {
84        return Vec::new();
85    }
86
87    let selected = &text[site.expr_span.start..site.expr_span.end];
88    let name = fresh_name(text);
89    let indent = line_indent(text, site.insertion_offset);
90    let insert_pos = crate::position::offset_to_position(text, site.insertion_offset);
91
92    let edits = vec![
93        OneOf::Left(TextEdit {
94            range: Range::new(insert_pos, insert_pos),
95            new_text: format!("let {name} = {selected}\n{indent}"),
96        }),
97        OneOf::Left(TextEdit {
98            range: crate::position::span_to_range(text, site.expr_span),
99            new_text: name.clone(),
100        }),
101    ];
102    vec![CodeActionOrCommand::CodeAction(CodeAction {
103        title: format!("Extract variable `{name}`"),
104        kind: Some(CodeActionKind::REFACTOR_EXTRACT),
105        edit: Some(WorkspaceEdit {
106            changes: None,
107            document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
108                text_document: OptionalVersionedTextDocumentIdentifier {
109                    uri: uri.clone(),
110                    version,
111                },
112                edits,
113            }])),
114            change_annotations: None,
115        }),
116        ..Default::default()
117    })]
118}
119
120/// Extract-function actions for the requested range (track #800). Locates
121/// the same smallest-containing-expression the extract-variable selection
122/// algorithm would, but only within a `Commons`/`Context` file's top-level
123/// `fn`/`Provider`/`Service`/`Agent` items — a new top-level `fn` needs
124/// somewhere top-level to live, so an `Adapter` (no Bynk bodies) or a `Suite`
125/// test case (no enclosing top-level item to insert above) offers nothing.
126///
127/// Declines (offers nothing) rather than guessing whenever:
128/// - the selection's site carries any recorded capability [`Requirement`],
129///   covered or not — the settled capability-free-only surface (#2100: the
130///   user's decision); a plain `fn` has no `given` to cover it once lifted.
131///   The refusal carries a reason, shown as a disabled action.
132/// - the selection contains a `?` outside a lambda (#2100): lifted, it would
133///   return from the new `fn` instead.
134/// - the selection's expression type, or any free variable's type, isn't
135///   recorded in `expr_types`/the rendered `locals` types — no action rather
136///   than a guessed type. Since ADR 0094 a file with an unrelated error
137///   elsewhere still records both (best-effort partial types), so the action
138///   is offered there too.
139/// - two distinct outer-scope bindings share a free variable's name (a rare
140///   nested-shadow collision) — threading either one as the parameter would
141///   silently pick the wrong variable for the other occurrence.
142/// - any expression inside the selection failed to type (its recorded type
143///   is `Ty::Error`) — the selection's own type would render as
144///   `<type error>`, and a binding whose value failed to type is never
145///   recorded in `locals`, so a read of one would not be threaded as a
146///   parameter and the lifted `fn` would name an unbound variable.
147///
148/// Free variables are the selection's `Ident` references (walked via
149/// [`expr_children`], the same exhaustive child iterator `locate` uses) whose
150/// nearest enclosing binding — [`locals_at`] at the reference's own offset —
151/// sits outside the selection; an identifier with no local binding at all
152/// (a top-level `fn`, a capability, a type name) is left alone, already
153/// resolvable at the new `fn`'s own top-level scope.
154///
155/// #813: the selection may also resolve to a contiguous statement run (see
156/// [`FunctionSelection::Stmts`]) rather than one expression — free-variable
157/// synthesis is the same walk, just seeded from every selected statement's
158/// values (via [`statement_exprs`]) instead of a single expression.
159///
160/// #2100 slice 2: the rules above live in [`plan_function`], which also
161/// refuses a selection containing `?` (an early return). The server lists the
162/// action lazily through [`function_listed`] and computes the edit in
163/// `codeAction/resolve`. This eager form, the plan as one action with its
164/// edit, is what the unit tests below drive.
165#[cfg(test)]
166#[allow(clippy::too_many_arguments)]
167pub fn extract_function(
168    text: &str,
169    requested: Span,
170    uri: &Url,
171    version: Option<i32>,
172    requirements: &[Requirement],
173    locals: &[LocalBinding],
174    expr_types: &[(Span, TyId)],
175    tys: &Types,
176) -> Vec<CodeActionOrCommand> {
177    let Ok(plan) = plan_function(text, requested, requirements, locals, expr_types, tys) else {
178        return Vec::new();
179    };
180    let edits = plan
181        .edits
182        .iter()
183        .map(|(span, new_text)| {
184            OneOf::Left(TextEdit {
185                range: crate::position::span_to_range(text, *span),
186                new_text: new_text.clone(),
187            })
188        })
189        .collect();
190    vec![CodeActionOrCommand::CodeAction(CodeAction {
191        title: format!("Extract function `{}`", plan.name),
192        kind: Some(CodeActionKind::REFACTOR_EXTRACT),
193        edit: Some(WorkspaceEdit {
194            changes: None,
195            document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
196                text_document: OptionalVersionedTextDocumentIdentifier {
197                    uri: uri.clone(),
198                    version,
199                },
200                edits,
201            }])),
202            change_annotations: None,
203        }),
204        ..Default::default()
205    })]
206}
207
208/// #2100 slice 2: a planned extract-function — the new `fn`'s name and the
209/// two edits (insert the `fn`, replace the selection with its call).
210pub struct FunctionPlan {
211    pub name: String,
212    pub edits: Vec<(Span, String)>,
213}
214
215/// #2100 slice 2: why extract-function is not offered for a selection.
216/// `reason` is `Some` when the selection is a real candidate the user should
217/// be told about (a client that supports it shows a disabled action with the
218/// reason); `None` when there is simply nothing to extract there.
219#[derive(Debug)]
220pub struct FunctionRefusal {
221    pub reason: Option<String>,
222}
223
224impl FunctionRefusal {
225    fn silent() -> Self {
226        FunctionRefusal { reason: None }
227    }
228}
229
230/// #2100 slice 2: the extract-function plan for `requested`, or why there is
231/// none. Extracted functions stay capability-free (a `fn` has no `given`
232/// clause), and a selection containing `?` is refused: lifted into a new
233/// `fn`, the `?` would return from that `fn` instead of the one it was
234/// written in.
235pub fn plan_function(
236    text: &str,
237    requested: Span,
238    requirements: &[Requirement],
239    locals: &[LocalBinding],
240    expr_types: &[(Span, TyId)],
241    tys: &Types,
242) -> Result<FunctionPlan, FunctionRefusal> {
243    let silent = || FunctionRefusal::silent();
244    if requested.start == requested.end {
245        return Err(silent());
246    }
247    let tokens = tokenize(text).map_err(|_| silent())?;
248    let (Some(unit), _errs) = parse_unit_with_recovery(&tokens, text) else {
249        return Err(silent());
250    };
251    let site = find_function_site(&unit, requested, text).ok_or_else(silent)?;
252    let mut caps: Vec<&str> = requirements
253        .iter()
254        .filter(|r| contains(site.span, r.site))
255        .map(|r| r.capability.as_str())
256        .collect();
257    if !caps.is_empty() {
258        caps.sort_unstable();
259        caps.dedup();
260        let names = caps
261            .iter()
262            .map(|c| format!("`{c}`"))
263            .collect::<Vec<_>>()
264            .join(", ");
265        return Err(FunctionRefusal {
266            reason: Some(format!(
267                "the selection uses {names}; an extracted function stays capability-free, \
268                 since a `fn` has no `given` clause to carry {}",
269                if caps.len() == 1 { "it" } else { "them" }
270            )),
271        });
272    }
273    if expr_types
274        .iter()
275        .any(|(s, t)| contains(site.span, *s) && t.is_error(tys))
276    {
277        return Err(silent());
278    }
279
280    let mut exprs: Vec<&Expr> = Vec::new();
281    let (ret_ty_display, call_site_form): (String, CallSiteForm) = match &site.selection {
282        FunctionSelection::Expr(expr) => {
283            let Some(ret_ty) = type_at_span(expr_types, site.span) else {
284                return Err(silent());
285            };
286            exprs.push(expr);
287            (ret_ty.display(tys), CallSiteForm::Bare)
288        }
289        FunctionSelection::Stmts {
290            stmts,
291            tail,
292            remainder,
293        } => {
294            // A lifted top-level `fn` has no `store` fields — a `:=` inside
295            // the run (however deeply nested through `if`/`match`/block
296            // sub-expressions) would always fail to resolve its target.
297            if stmts_contain_assign_stmt(stmts) {
298                return Err(silent());
299            }
300            for s in *stmts {
301                statement_exprs(s, &mut exprs);
302            }
303            match tail {
304                Some(t) => {
305                    let Some(ret_ty) = type_at_span(expr_types, t.span) else {
306                        return Err(silent());
307                    };
308                    exprs.push(t);
309                    (ret_ty.display(tys), CallSiteForm::Bare)
310                }
311                None => {
312                    if leaks_a_binding(stmts, remainder, locals, site.span) {
313                        return Err(silent());
314                    }
315                    if stmts_contain_effect_stmt(stmts) {
316                        ("Effect[()]".to_string(), CallSiteForm::Do)
317                    } else {
318                        ("()".to_string(), CallSiteForm::Discard)
319                    }
320                }
321            }
322        }
323    };
324
325    // An early return can't be lifted: inside a new `fn`, `?` would return
326    // from that `fn` rather than the one the selection was written in.
327    if exprs.iter().any(|e| has_early_return(e)) {
328        return Err(FunctionRefusal {
329            reason: Some(
330                "the selection contains `?`, which would return from the extracted \
331                 function instead of the one it is written in"
332                    .to_string(),
333            ),
334        });
335    }
336
337    let mut idents = Vec::new();
338    for e in &exprs {
339        collect_idents(e, &mut idents);
340    }
341    let mut free: Vec<(&str, Span, &str)> = Vec::new();
342    for id in &idents {
343        let Some(binding) = locals_at(locals, id.span.start)
344            .into_iter()
345            .find(|b| b.name == id.name)
346        else {
347            continue;
348        };
349        if contains(site.span, binding.def_span) {
350            continue; // bound inside the selection itself, not free
351        }
352        free.push((id.name.as_str(), binding.def_span, binding.ty.as_str()));
353    }
354    let mut def_by_name: HashMap<&str, Span> = HashMap::new();
355    for (name, def_span, _) in &free {
356        match def_by_name.get(name) {
357            Some(prev) if *prev != *def_span => return Err(silent()),
358            _ => {
359                def_by_name.insert(name, *def_span);
360            }
361        }
362    }
363    let mut params: Vec<(&str, &str)> = Vec::new();
364    for (name, _, ty) in &free {
365        if !params.iter().any(|(n, _)| n == name) {
366            params.push((name, ty));
367        }
368    }
369
370    let fn_name = fresh_word(text, "extractedFn");
371    let param_list = params
372        .iter()
373        .map(|(n, t)| format!("{n}: {t}"))
374        .collect::<Vec<_>>()
375        .join(", ");
376    let arg_list = params
377        .iter()
378        .map(|(n, _)| n.to_string())
379        .collect::<Vec<_>>()
380        .join(", ");
381    let selected = &text[site.span.start..site.span.end];
382    let new_fn = format!("fn {fn_name}({param_list}) -> {ret_ty_display} {{\n  {selected}\n}}\n\n");
383
384    // Bynk has no expression-statement form, so a tail-excluded statement
385    // run's call can't stand alone as `fn_name(args)` — it needs `let _ =`
386    // (pure) or `do` (effectful) to be a legal statement. A bare expression
387    // (single-expression selection, or a run that includes the tail) needs
388    // neither: it replaces an expression position, not a statement.
389    let call_expr = format!("{fn_name}({arg_list})");
390    let call_site_text = match call_site_form {
391        CallSiteForm::Bare => call_expr,
392        CallSiteForm::Discard => format!("let _ = {call_expr}"),
393        CallSiteForm::Do => format!("do {call_expr}"),
394    };
395
396    Ok(FunctionPlan {
397        name: fn_name,
398        edits: vec![
399            (Span::new(site.item_start, site.item_start), new_fn),
400            (site.span, call_site_text),
401        ],
402    })
403}
404
405const FUNCTION_DATA_TAG: &str = "bynk.extractFunction";
406
407/// #2100 slice 2: the listed extract-function action for a selection — no
408/// edit yet (`codeAction/resolve` computes and re-checks it), or, when the
409/// selection is refused for a reason worth telling and the client supports
410/// it, a disabled action carrying that reason. `None` otherwise.
411pub fn function_listed(
412    planned: &Result<FunctionPlan, FunctionRefusal>,
413    requested: Span,
414    uri: &Url,
415    version: Option<i32>,
416    disabled_support: bool,
417) -> Option<CodeActionOrCommand> {
418    match planned {
419        Ok(plan) => Some(CodeActionOrCommand::CodeAction(CodeAction {
420            title: format!("Extract function `{}`", plan.name),
421            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
422            data: Some(serde_json::json!({
423                "kind": FUNCTION_DATA_TAG,
424                "uri": uri.as_str(),
425                "version": version,
426                "start": requested.start,
427                "end": requested.end,
428            })),
429            ..Default::default()
430        })),
431        Err(FunctionRefusal {
432            reason: Some(reason),
433        }) if disabled_support => Some(CodeActionOrCommand::CodeAction(CodeAction {
434            title: "Extract function".to_string(),
435            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
436            disabled: Some(CodeActionDisabled {
437                reason: reason.clone(),
438            }),
439            ..Default::default()
440        })),
441        Err(_) => None,
442    }
443}
444
445/// #2100 slice 2: what a listed extract-function action's `data` names.
446pub struct FunctionTarget {
447    pub uri: Url,
448    pub version: Option<i32>,
449    pub requested: Span,
450}
451
452impl FunctionTarget {
453    pub fn of(action: &CodeAction) -> Option<Self> {
454        let data = action.data.as_ref()?;
455        if data.get("kind")?.as_str()? != FUNCTION_DATA_TAG {
456            return None;
457        }
458        Some(FunctionTarget {
459            uri: Url::parse(data.get("uri")?.as_str()?).ok()?,
460            version: data
461                .get("version")
462                .and_then(serde_json::Value::as_i64)
463                .and_then(|v| i32::try_from(v).ok()),
464            requested: Span::new(
465                usize::try_from(data.get("start")?.as_u64()?).ok()?,
466                usize::try_from(data.get("end")?.as_u64()?).ok()?,
467            ),
468        })
469    }
470}
471
472/// #2100 slice 2: `e` contains a `?` that returns from the enclosing body —
473/// one inside a lambda returns from the lambda, so it moves with it.
474fn has_early_return(e: &Expr) -> bool {
475    match &e.kind {
476        ExprKind::Question(_) => true,
477        ExprKind::Lambda(_) => false,
478        _ => expr_children(e).into_iter().any(has_early_return),
479    }
480}
481
482/// The smallest expression node fully containing the selection, and the byte
483/// offset immediately before its enclosing statement (or block tail) — where
484/// the new `let` line is inserted. `expr` is retained (not just its span) so
485/// [`plan_function`] can walk it for free identifiers without a second
486/// descent through the tree.
487struct Site<'a> {
488    insertion_offset: usize,
489    expr_span: Span,
490    expr: &'a Expr,
491    /// #1819: the names bound between `insertion_offset` and the selection,
492    /// by an expression-bodied arm's pattern or a lambda's parameters: in
493    /// scope at the selection, not at the insertion point. A descent into a
494    /// block resets them along with the offset, since the `let` then goes
495    /// inside the scope that binds them.
496    binders: Binders<'a>,
497}
498
499/// #1819: what is bound between a [`Site`]'s insertion point and its
500/// selection, so out of scope where the `let` goes.
501#[derive(Default)]
502struct Binders<'a> {
503    names: Vec<&'a str>,
504    /// Inside an observation's `with` predicate, whose names are the observed
505    /// operation's parameters: declared on the capability, not in the tree,
506    /// so every name read there is treated as bound (#1880 review).
507    opaque: bool,
508}
509
510impl<'a> Binders<'a> {
511    fn extend(&mut self, names: impl IntoIterator<Item = &'a str>) {
512        self.names.extend(names);
513    }
514
515    fn binds(&self, name: &str) -> bool {
516        self.opaque || self.names.contains(&name)
517    }
518}
519
520/// The names an `is` test binds for the operand to its right: `r is Ok(n)`
521/// binds `n` on the right of `&&` / `implies`, through a chain of them and
522/// parentheses, as the checker scopes them (#1880 review).
523fn is_bindings(e: &Expr) -> Vec<&str> {
524    match &e.kind {
525        ExprKind::Is { pattern, .. } => pattern
526            .bound_names()
527            .into_iter()
528            .map(|id| id.name.as_str())
529            .collect(),
530        ExprKind::BinOp(BinOp::And | BinOp::Implies, l, r) => {
531            let mut names = is_bindings(l);
532            names.extend(is_bindings(r));
533            names
534        }
535        ExprKind::Paren(inner) => is_bindings(inner),
536        _ => Vec::new(),
537    }
538}
539
540/// Closed containment over half-open spans: `outer` fully contains `inner`.
541fn contains(outer: Span, inner: Span) -> bool {
542    outer.start <= inner.start && inner.end <= outer.end
543}
544
545/// Finds the body (fn / handler / provider op / test case) whose span
546/// contains `target`, then hands off to [`find_in_block`]. `None` when the
547/// selection sits outside any body (a header, or a file that doesn't parse).
548///
549/// #2010: a selection whose smallest enclosing expression is the `match` a
550/// `let … else` was desugared into — the statement itself, or a span crossing
551/// from it into the rest of its block — has no expression of the author's to
552/// lift, so it is `None` too.
553fn find_site(unit: &SourceUnit, target: Span) -> Option<Site<'_>> {
554    find_site_any(unit, target).filter(|site| !site.expr.is_let_else_match())
555}
556
557fn find_site_any(unit: &SourceUnit, target: Span) -> Option<Site<'_>> {
558    match unit {
559        SourceUnit::Commons(c) => find_in_items(&c.items, target),
560        SourceUnit::Context(c) => find_in_items(&c.items, target),
561        // Adapters carry no Bynk-bodied operations to extract from.
562        SourceUnit::Adapter(_) => None,
563        SourceUnit::Suite(t) => t
564            .cases
565            .iter()
566            .find(|case| contains(case.body.span, target))
567            .and_then(|case| find_in_block(&case.body, target)),
568    }
569}
570
571fn find_in_items(items: &[CommonsItem], target: Span) -> Option<Site<'_>> {
572    for item in items {
573        match item {
574            CommonsItem::Fn(f) if contains(f.body.span, target) => {
575                return find_in_block(&f.body, target);
576            }
577            CommonsItem::Provider(p) => {
578                if let Some(op) = p.ops.iter().find(|op| contains(op.body.span, target)) {
579                    return find_in_block(&op.body, target);
580                }
581            }
582            CommonsItem::Service(s) => {
583                if let Some(h) = s.handlers.iter().find(|h| contains(h.body.span, target)) {
584                    return find_in_block(&h.body, target);
585                }
586            }
587            CommonsItem::Agent(a) => {
588                if let Some(h) = a.handlers.iter().find(|h| contains(h.body.span, target)) {
589                    return find_in_block(&h.body, target);
590                }
591            }
592            _ => {}
593        }
594    }
595    None
596}
597
598/// Finds the statement expression (or the tail) that fully contains `target`,
599/// then narrows within it via [`locate`]. `None` when `target` doesn't sit
600/// fully inside any single statement/tail (e.g. it spans the whole block,
601/// braces included, or crosses a statement boundary).
602fn find_in_block(block: &Block, target: Span) -> Option<Site<'_>> {
603    for stmt in &block.statements {
604        // #1851: whichever of the statement's expressions holds the selection.
605        // Not the first: since #1766 a principal's identity comes before the
606        // value it addresses.
607        let mut exprs = Vec::new();
608        statement_exprs(stmt, &mut exprs);
609        if let Some(e) = exprs.into_iter().find(|e| contains(e.span, target)) {
610            return Some(locate(e, target, stmt.span().start, Binders::default()));
611        }
612    }
613    if contains(block.tail.span, target) {
614        return Some(locate(
615            &block.tail,
616            target,
617            block.tail.span.start,
618            Binders::default(),
619        ));
620    }
621    None
622}
623
624/// Descends into `expr` for the smallest node whose span fully contains
625/// `target`. `Block`/`If`/`Match` carry their own nested statement/tail
626/// slots, so descending into one resets `insertion_offset` to that slot's
627/// start; every other kind bubbles the offset through unchanged, walked via
628/// [`expr_children`] — `bynk_syntax`'s exhaustive-by-construction child
629/// iterator, reused here rather than a second hand-rolled `ExprKind` match.
630/// The remainder is enumerated explicitly rather than wildcarded, so an
631/// `ExprKind` variant this doesn't handle fails to compile here instead of
632/// silently falling through the extraction path — and a variant carrying a
633/// `Block` field needs hand-matching above rather than appending to that
634/// list, for the reason recorded at the arm itself.
635fn locate<'a>(
636    expr: &'a Expr,
637    target: Span,
638    insertion_offset: usize,
639    mut binders: Binders<'a>,
640) -> Site<'a> {
641    match &expr.kind {
642        ExprKind::Block(b) => find_in_block(b, target).unwrap_or(Site {
643            insertion_offset,
644            expr_span: expr.span,
645            expr,
646            binders,
647        }),
648        ExprKind::If {
649            cond,
650            then_block,
651            else_block,
652        } => {
653            if contains(cond.span, target) {
654                return locate(cond, target, insertion_offset, binders);
655            }
656            if contains(then_block.span, target)
657                && let Some(site) = find_in_block(then_block, target)
658            {
659                return site;
660            }
661            if contains(else_block.span, target)
662                && let Some(site) = find_in_block(else_block, target)
663            {
664                return site;
665            }
666            Site {
667                insertion_offset,
668                expr_span: expr.span,
669                expr,
670                binders,
671            }
672        }
673        ExprKind::Match { discriminant, arms } => {
674            if contains(discriminant.span, target) {
675                return locate(discriminant, target, insertion_offset, binders);
676            }
677            // A selection inside a guard deliberately falls through to the
678            // whole `match` below rather than descending (#1800 review): the
679            // extracted `let` goes above the enclosing statement, outside the
680            // arm, and a guard almost always reads the arm's pattern bindings,
681            // which are not in scope there. Extracting the whole `match` is
682            // sound.
683            for arm in arms {
684                if !contains(arm.body.span(), target) {
685                    continue;
686                }
687                return match &arm.body {
688                    MatchBody::Expr(e) => {
689                        // #1819: an expression body has no block to insert
690                        // into, so the arm's bindings stay out of scope at the
691                        // insertion point.
692                        binders.extend(arm.pattern.bound_names().iter().map(|id| id.name.as_str()));
693                        locate(e, target, insertion_offset, binders)
694                    }
695                    MatchBody::Block(b) => find_in_block(b, target).unwrap_or(Site {
696                        insertion_offset,
697                        expr_span: expr.span,
698                        expr,
699                        binders,
700                    }),
701                };
702            }
703            Site {
704                insertion_offset,
705                expr_span: expr.span,
706                expr,
707                binders,
708            }
709        }
710        // No variant below carries a `Block` *field*, so `expr_children`'s
711        // total descent is complete for it and bubbling `insertion_offset`
712        // through unchanged is correct — a block reached through a child (a
713        // braced lambda body, say) comes back as an `Expr` and re-enters this
714        // match at the `Block` arm above, which resets the offset via
715        // `find_in_block`. A *new* variant that holds a `Block` directly must
716        // be hand-matched up there alongside `Block`/`If`/`Match`: appending
717        // it here descends past the block's own statement list *and* bubbles
718        // the outer offset, so the returned `Site` inserts the extracted `fn`
719        // outside the block the selection lives in — a wrong edit, not a
720        // failed one.
721        ExprKind::IntLit { .. }
722        | ExprKind::FloatLit { .. }
723        | ExprKind::DecimalLit { .. }
724        | ExprKind::DurationLit { .. }
725        | ExprKind::StrLit(_)
726        | ExprKind::InterpStr(_)
727        | ExprKind::BoolLit(_)
728        | ExprKind::Ident(_)
729        | ExprKind::Call { .. }
730        | ExprKind::Lambda(_)
731        | ExprKind::BinOp(..)
732        | ExprKind::UnaryOp(..)
733        | ExprKind::Paren(_)
734        | ExprKind::Ok(_)
735        | ExprKind::Err(_)
736        | ExprKind::Question(_)
737        | ExprKind::RecordConstruction { .. }
738        | ExprKind::FieldAccess { .. }
739        | ExprKind::MethodCall { .. }
740        | ExprKind::Is { .. }
741        | ExprKind::Some(_)
742        | ExprKind::None
743        | ExprKind::UnitLit
744        | ExprKind::RecordSpread { .. }
745        | ExprKind::EffectPure(_)
746        | ExprKind::Expect(_)
747        | ExprKind::Val { .. }
748        | ExprKind::Wire(_)
749        | ExprKind::ListLit(..)
750        | ExprKind::Observation(_)
751        | ExprKind::Faults(_)
752        | ExprKind::Trace { .. } => {
753            let children = expr_children(expr);
754            match children.into_iter().find(|c| contains(c.span, target)) {
755                Some(child) => {
756                    // #1819: a lambda's parameters are in scope in its body
757                    // only; an expression body bubbles the outer offset.
758                    if let ExprKind::Lambda(l) = &expr.kind {
759                        binders.extend(l.params.iter().map(|p| p.name.name.as_str()));
760                    }
761                    // #1880 review: an `is` on the left of `&&` / `implies`
762                    // binds for the right operand only.
763                    if let ExprKind::BinOp(BinOp::And | BinOp::Implies, lhs, rhs) = &expr.kind
764                        && std::ptr::eq(child, rhs.as_ref())
765                    {
766                        binders.extend(is_bindings(lhs));
767                    }
768                    if let ExprKind::Observation(o) = &expr.kind
769                        && let ObservationMatcher::Called {
770                            with_pred: Some(pred),
771                            ..
772                        } = &o.matcher
773                        && std::ptr::eq(child, pred.as_ref())
774                    {
775                        binders.opaque = true;
776                    }
777                    locate(child, target, insertion_offset, binders)
778                }
779                None => Site {
780                    insertion_offset,
781                    expr_span: expr.span,
782                    expr,
783                    binders,
784                },
785            }
786        }
787    }
788}
789
790/// `extracted`, `extracted2`, … — the first candidate that doesn't already
791/// appear as a whole word anywhere in the file. A collision-avoiding
792/// placeholder, not a scope-aware binder: the client's rename-on-extract is
793/// the expected next step for a better name.
794fn fresh_name(text: &str) -> String {
795    fresh_word(text, "extracted")
796}
797
798/// Like [`fresh_name`], generalised to any base word — extract-function uses
799/// `extractedFn`/`extractedFn2`/… so its generated name reads distinctly from
800/// extract-variable's `extracted` when both actions are offered on the same
801/// selection.
802fn fresh_word(text: &str, base: &str) -> String {
803    let is_ident_char = |c: char| c.is_alphanumeric() || c == '_';
804    let occurs_as_word = |candidate: &str| {
805        text.match_indices(candidate).any(|(i, _)| {
806            let before_ok = text[..i]
807                .chars()
808                .next_back()
809                .is_none_or(|c| !is_ident_char(c));
810            let after_ok = text[i + candidate.len()..]
811                .chars()
812                .next()
813                .is_none_or(|c| !is_ident_char(c));
814            before_ok && after_ok
815        })
816    };
817    let mut n = 1;
818    loop {
819        let candidate = if n == 1 {
820            base.to_string()
821        } else {
822            format!("{base}{n}")
823        };
824        if !occurs_as_word(&candidate) {
825            return candidate;
826        }
827        n += 1;
828    }
829}
830
831/// The enclosing top-level item's span — where [`find_function_site`] inserts
832/// the new `fn` (immediately above it). `None` for a `CommonsItem` extraction
833/// can never target (a `type`/`context` declaration carries no body).
834fn item_span(item: &CommonsItem) -> Option<Span> {
835    match item {
836        CommonsItem::Fn(f) => Some(f.span),
837        CommonsItem::Provider(p) => Some(p.span),
838        CommonsItem::Service(s) => Some(s.span),
839        CommonsItem::Agent(a) => Some(a.span),
840        _ => None,
841    }
842}
843
844/// Where a [`FunctionSite`]'s selection resolves to. #813 adds [`Stmts`](Self::Stmts)
845/// alongside the original track #800 single-expression shape.
846enum FunctionSelection<'a> {
847    /// The original shape: one AST expression, exactly as [`Site`] finds.
848    Expr(&'a Expr),
849    /// #813: a contiguous run of one or more full statements from a single
850    /// block, optionally including the block's tail. `remainder` is every
851    /// expression after the run within that same block — the tail plus
852    /// nothing else when `tail` is `Some` (nothing follows it), or the tail
853    /// and every later statement's value when `tail` is `None` — checked by
854    /// [`leaks_a_binding`] so a binding the run introduces can't be lifted
855    /// away out from under a live use.
856    Stmts {
857        stmts: &'a [Statement],
858        tail: Option<&'a Expr>,
859        remainder: Vec<&'a Expr>,
860    },
861}
862
863/// How the call site replaces the selection. A tail-excluded statement run
864/// has no expression position to drop a bare call into — Bynk has no
865/// expression-statement form — so it needs a statement wrapper instead; see
866/// [`plan_function`]'s call-site construction.
867enum CallSiteForm {
868    /// The call stands as a bare expression (a single-expression selection,
869    /// or a statement run that includes the tail).
870    Bare,
871    /// A tail-excluded run whose lifted `fn` is pure (`-> ()`).
872    Discard,
873    /// A tail-excluded run whose lifted `fn` performs an effect
874    /// (`-> Effect[()]`).
875    Do,
876}
877
878/// Like [`find_site`], but only within `Commons`/`Context` files, and
879/// additionally records the start of the enclosing top-level item — where the
880/// new `fn` is inserted, immediately above it.
881struct FunctionSite<'a> {
882    item_start: usize,
883    /// The exact selected span — the replacement range, and (for `Stmts`)
884    /// the bound every containment check is stated against.
885    span: Span,
886    selection: FunctionSelection<'a>,
887}
888
889/// #813 tries a statement-run match first (against a whitespace-trimmed
890/// `target`, since a "select these lines" gesture commonly pads onto
891/// surrounding blank space); falling short of an exact statement-boundary
892/// alignment there, this falls back to the original single-expression
893/// algorithm unchanged.
894fn find_function_site<'a>(
895    unit: &'a SourceUnit,
896    target: Span,
897    text: &str,
898) -> Option<FunctionSite<'a>> {
899    let items = match unit {
900        SourceUnit::Commons(c) => &c.items,
901        SourceUnit::Context(c) => &c.items,
902        SourceUnit::Adapter(_) | SourceUnit::Suite(_) => return None,
903    };
904    let item = items
905        .iter()
906        .find(|it| item_span(it).is_some_and(|s| contains(s, target)))?;
907    let item_start = item_span(item)?.start;
908
909    let trimmed = trim_span(text, target);
910    if trimmed.start < trimmed.end
911        && let Some((stmts, tail, remainder)) = find_multi_stmt_in_item(item, trimmed)
912    {
913        return Some(FunctionSite {
914            item_start,
915            span: trimmed,
916            selection: FunctionSelection::Stmts {
917                stmts,
918                tail,
919                remainder,
920            },
921        });
922    }
923
924    let site = find_in_items(std::slice::from_ref(item), target)?;
925    Some(FunctionSite {
926        item_start,
927        span: site.expr_span,
928        selection: FunctionSelection::Expr(site.expr),
929    })
930}
931
932/// Trims leading/trailing whitespace bytes from `span` against `text`: a
933/// real editor selection of "these lines" commonly pads onto the
934/// surrounding blank space, which isn't a partial-statement selection the
935/// way clipping actual statement content would be.
936fn trim_span(text: &str, span: Span) -> Span {
937    let s = &text[span.start..span.end];
938    let start = span.start + (s.len() - s.trim_start().len());
939    let trimmed_len = s.trim().len();
940    Span::new(start, start + trimmed_len)
941}
942
943/// A found statement run: the contiguous statement slice, the block's tail
944/// when the run includes it, and — only populated by [`align_stmt_run`]'s
945/// tail-excluded branch — the remainder [`leaks_a_binding`] scans.
946type StmtRun<'a> = (&'a [Statement], Option<&'a Expr>, Vec<&'a Expr>);
947
948/// Dispatches to the item's body/op/handler containing `target`, then hands
949/// off to [`find_stmt_run`] — the statement-run counterpart of
950/// [`find_in_items`].
951fn find_multi_stmt_in_item(item: &CommonsItem, target: Span) -> Option<StmtRun<'_>> {
952    match item {
953        CommonsItem::Fn(f) if contains(f.body.span, target) => find_stmt_run(&f.body, target),
954        CommonsItem::Provider(p) => p
955            .ops
956            .iter()
957            .find(|op| contains(op.body.span, target))
958            .and_then(|op| find_stmt_run(&op.body, target)),
959        CommonsItem::Service(s) => s
960            .handlers
961            .iter()
962            .find(|h| contains(h.body.span, target))
963            .and_then(|h| find_stmt_run(&h.body, target)),
964        CommonsItem::Agent(a) => a
965            .handlers
966            .iter()
967            .find(|h| contains(h.body.span, target))
968            .and_then(|h| find_stmt_run(&h.body, target)),
969        _ => None,
970    }
971}
972
973/// Descends to the smallest block whose own statement list aligns exactly
974/// with `target` (#813): a nested block fully containing `target` is tried
975/// first via [`find_stmt_run_in_expr`] (mirroring [`locate`]'s
976/// descend-first policy), so a run inside an `if`/`match` branch resolves
977/// there rather than at the outer level; [`align_stmt_run`] does the actual
978/// boundary check once no deeper block matches. Unlike [`locate`], it also
979/// descends into a `match` arm's guard (#1800): a run is lifted into a `fn`
980/// whose parameters carry the guard's bindings, so nothing is hoisted out of
981/// their scope.
982fn find_stmt_run(block: &Block, target: Span) -> Option<StmtRun<'_>> {
983    for stmt in &block.statements {
984        let mut values = Vec::new();
985        statement_exprs(stmt, &mut values);
986        for v in values {
987            if let Some(found) = find_stmt_run_in_expr(v, target) {
988                return Some(found);
989            }
990        }
991    }
992    if let Some(found) = find_stmt_run_in_expr(&block.tail, target) {
993        return Some(found);
994    }
995    align_stmt_run(block, target)
996}
997
998/// Looks for a nested block inside `e` whose statement list aligns with
999/// `target` — `None` unless `e`'s span actually contains `target`. Falls
1000/// through to [`expr_children`] for anything other than `Block`/`If`/`Match`,
1001/// the same exhaustive walk [`locate`] and [`collect_idents`] use.
1002fn find_stmt_run_in_expr(e: &Expr, target: Span) -> Option<StmtRun<'_>> {
1003    if !contains(e.span, target) {
1004        return None;
1005    }
1006    match &e.kind {
1007        ExprKind::Block(b) => find_stmt_run(b, target),
1008        ExprKind::If {
1009            cond,
1010            then_block,
1011            else_block,
1012        } => find_stmt_run_in_expr(cond, target)
1013            .or_else(|| find_stmt_run(then_block, target))
1014            .or_else(|| find_stmt_run(else_block, target)),
1015        // #1800: a guard is searched too, so a run inside one
1016        // (`Some(x) if if x > 0 { … } else { … } =>`) can be extracted.
1017        ExprKind::Match { discriminant, arms } => find_stmt_run_in_expr(discriminant, target)
1018            .or_else(|| {
1019                arms.iter().find_map(|arm| {
1020                    arm.guard
1021                        .as_ref()
1022                        .and_then(|g| find_stmt_run_in_expr(g, target))
1023                        .or_else(|| match &arm.body {
1024                            MatchBody::Expr(e) => find_stmt_run_in_expr(e, target),
1025                            MatchBody::Block(b) => find_stmt_run(b, target),
1026                        })
1027                })
1028            }),
1029        // No variant below carries a `Block` *field*, so `expr_children`'s
1030        // total descent is complete for it — a block reached through a child
1031        // (a braced lambda body, say) comes back as an `Expr` and re-enters
1032        // this match at the `Block` arm above. A *new* variant that holds a
1033        // `Block` directly must be hand-matched up there alongside
1034        // `Block`/`If`/`Match`: appending it here descends past the block's
1035        // own statement list (`expr_children` flattens a block to its
1036        // statements' values), so a run inside it stops being extractable.
1037        ExprKind::IntLit { .. }
1038        | ExprKind::FloatLit { .. }
1039        | ExprKind::DecimalLit { .. }
1040        | ExprKind::DurationLit { .. }
1041        | ExprKind::StrLit(_)
1042        | ExprKind::InterpStr(_)
1043        | ExprKind::BoolLit(_)
1044        | ExprKind::Ident(_)
1045        | ExprKind::Call { .. }
1046        | ExprKind::Lambda(_)
1047        | ExprKind::BinOp(..)
1048        | ExprKind::UnaryOp(..)
1049        | ExprKind::Paren(_)
1050        | ExprKind::Ok(_)
1051        | ExprKind::Err(_)
1052        | ExprKind::Question(_)
1053        | ExprKind::RecordConstruction { .. }
1054        | ExprKind::FieldAccess { .. }
1055        | ExprKind::MethodCall { .. }
1056        | ExprKind::Is { .. }
1057        | ExprKind::Some(_)
1058        | ExprKind::None
1059        | ExprKind::UnitLit
1060        | ExprKind::RecordSpread { .. }
1061        | ExprKind::EffectPure(_)
1062        | ExprKind::Expect(_)
1063        | ExprKind::Val { .. }
1064        | ExprKind::Wire(_)
1065        | ExprKind::ListLit(..)
1066        | ExprKind::Observation(_)
1067        | ExprKind::Faults(_)
1068        | ExprKind::Trace { .. } => expr_children(e)
1069            .into_iter()
1070            .find_map(|c| find_stmt_run_in_expr(c, target)),
1071    }
1072}
1073
1074/// Tries to align `target` exactly against `block`'s own statement list: its
1075/// start must equal some statement's start, and its end must equal either
1076/// another statement's end (the run stops before the tail) or the tail's own
1077/// end (the run includes it). No match — a partial-statement selection, or
1078/// one spanning more than this single block — returns `None`.
1079fn align_stmt_run(block: &Block, target: Span) -> Option<StmtRun<'_>> {
1080    // #2010: a `let … else` is a hidden binding plus the `match` it heads, which
1081    // holds the rest of the block; lifting the binding alone would strand the
1082    // rest of the block, so a run that reaches one is not offered.
1083    if block
1084        .statements
1085        .iter()
1086        .any(|s| matches!(s, Statement::Let(l) | Statement::EffectLet(l) if l.let_else.is_some()))
1087        && block
1088            .statements
1089            .last()
1090            .is_some_and(|s| s.span().end <= target.end)
1091    {
1092        return None;
1093    }
1094    let start_idx = block
1095        .statements
1096        .iter()
1097        .position(|s| s.span().start == target.start)?;
1098    if target.end == block.tail.span.end {
1099        let full = Span::new(
1100            block.statements[start_idx].span().start,
1101            block.tail.span.end,
1102        );
1103        if full == target {
1104            return Some((
1105                &block.statements[start_idx..],
1106                Some(block.tail.as_ref()),
1107                Vec::new(),
1108            ));
1109        }
1110    }
1111    let end_idx = block
1112        .statements
1113        .iter()
1114        .position(|s| s.span().end == target.end)?;
1115    if end_idx < start_idx {
1116        return None;
1117    }
1118    let full = Span::new(
1119        block.statements[start_idx].span().start,
1120        block.statements[end_idx].span().end,
1121    );
1122    if full != target {
1123        return None;
1124    }
1125    let mut remainder = Vec::new();
1126    for s in &block.statements[end_idx + 1..] {
1127        statement_exprs(s, &mut remainder);
1128    }
1129    remainder.push(&block.tail);
1130    Some((&block.statements[start_idx..=end_idx], None, remainder))
1131}
1132
1133/// Whether any `let`/`<-` binding introduced by `stmts` (skipping `_`) is
1134/// still referenced in `remainder` — the expressions after the run within
1135/// the same block. A tail-excluded run whose binding leaks this way can't be
1136/// lifted away: the reference downstream would resolve to nothing once the
1137/// binding moves into the new `fn`.
1138fn leaks_a_binding(
1139    stmts: &[Statement],
1140    remainder: &[&Expr],
1141    locals: &[LocalBinding],
1142    run_span: Span,
1143) -> bool {
1144    let bound_names: Vec<&str> = stmts
1145        .iter()
1146        .filter_map(|s| match s {
1147            Statement::Let(l) | Statement::EffectLet(l) if l.name.name != "_" => {
1148                Some(l.name.name.as_str())
1149            }
1150            _ => None,
1151        })
1152        .collect();
1153    if bound_names.is_empty() {
1154        return false;
1155    }
1156    let mut used = Vec::new();
1157    for e in remainder {
1158        collect_idents(e, &mut used);
1159    }
1160    used.iter().any(|id| {
1161        bound_names.contains(&id.name.as_str())
1162            && locals_at(locals, id.span.start)
1163                .into_iter()
1164                .find(|b| b.name == id.name)
1165                .is_some_and(|b| contains(run_span, b.def_span))
1166    })
1167}
1168
1169/// Whether any of `stmts` matches `pred` — checked on the statement itself
1170/// first, then recursively on every nested statement reachable through its
1171/// value expression's own `if`/`match`/block sub-expressions (arbitrarily
1172/// deep). The shared shape behind [`stmts_contain_effect_stmt`] and
1173/// [`stmts_contain_assign_stmt`]: both need "does this run perform/contain
1174/// X, however deeply nested" and neither can stop at the run's direct
1175/// top-level statements — a `do`/`<-` or a `:=` can equally sit inside
1176/// an `if`/`match` branch that one of the run's own `let`s evaluates.
1177fn stmts_match(stmts: &[Statement], pred: &impl Fn(&Statement) -> bool) -> bool {
1178    stmts.iter().any(|s| pred(s) || stmt_value_matches(s, pred))
1179}
1180
1181fn stmt_value_matches(s: &Statement, pred: &impl Fn(&Statement) -> bool) -> bool {
1182    // #1851: every expression of the statement, a principal's identity
1183    // included.
1184    let mut exprs = Vec::new();
1185    statement_exprs(s, &mut exprs);
1186    exprs.into_iter().any(|e| expr_matches(e, pred))
1187}
1188
1189fn block_matches(b: &Block, pred: &impl Fn(&Statement) -> bool) -> bool {
1190    stmts_match(&b.statements, pred) || expr_matches(&b.tail, pred)
1191}
1192
1193fn expr_matches(e: &Expr, pred: &impl Fn(&Statement) -> bool) -> bool {
1194    match &e.kind {
1195        ExprKind::Block(b) => block_matches(b, pred),
1196        ExprKind::If {
1197            cond,
1198            then_block,
1199            else_block,
1200        } => {
1201            expr_matches(cond, pred)
1202                || block_matches(then_block, pred)
1203                || block_matches(else_block, pred)
1204        }
1205        // #1800: a guard's statements count too. Skipping it let a run whose
1206        // guard held a `<-` be lifted to a `()`-returning fn, and one holding
1207        // a `:=` be lifted at all; neither typechecks.
1208        ExprKind::Match { discriminant, arms } => {
1209            expr_matches(discriminant, pred)
1210                || arms.iter().any(|arm| {
1211                    arm.guard.as_ref().is_some_and(|g| expr_matches(g, pred))
1212                        || match &arm.body {
1213                            MatchBody::Expr(e) => expr_matches(e, pred),
1214                            MatchBody::Block(b) => block_matches(b, pred),
1215                        }
1216                })
1217        }
1218        // No variant below carries a `Block` *field*, so `expr_children`'s
1219        // total descent is complete for it — a block reached through a child
1220        // (a braced lambda body, say) comes back as an `Expr` and re-enters
1221        // this match at the `Block` arm above. A *new* variant that holds a
1222        // `Block` directly must be hand-matched up there alongside
1223        // `Block`/`If`/`Match`: appending it here never reaches the block's
1224        // statement list (`expr_children` flattens a block to its statements'
1225        // values), so `pred` is never asked about the statements inside it.
1226        ExprKind::IntLit { .. }
1227        | ExprKind::FloatLit { .. }
1228        | ExprKind::DecimalLit { .. }
1229        | ExprKind::DurationLit { .. }
1230        | ExprKind::StrLit(_)
1231        | ExprKind::InterpStr(_)
1232        | ExprKind::BoolLit(_)
1233        | ExprKind::Ident(_)
1234        | ExprKind::Call { .. }
1235        | ExprKind::Lambda(_)
1236        | ExprKind::BinOp(..)
1237        | ExprKind::UnaryOp(..)
1238        | ExprKind::Paren(_)
1239        | ExprKind::Ok(_)
1240        | ExprKind::Err(_)
1241        | ExprKind::Question(_)
1242        | ExprKind::RecordConstruction { .. }
1243        | ExprKind::FieldAccess { .. }
1244        | ExprKind::MethodCall { .. }
1245        | ExprKind::Is { .. }
1246        | ExprKind::Some(_)
1247        | ExprKind::None
1248        | ExprKind::UnitLit
1249        | ExprKind::RecordSpread { .. }
1250        | ExprKind::EffectPure(_)
1251        | ExprKind::Expect(_)
1252        | ExprKind::Val { .. }
1253        | ExprKind::Wire(_)
1254        | ExprKind::ListLit(..)
1255        | ExprKind::Observation(_)
1256        | ExprKind::Faults(_)
1257        | ExprKind::Trace { .. } => expr_children(e).into_iter().any(|c| expr_matches(c, pred)),
1258    }
1259}
1260
1261/// Whether any of `stmts` is (or contains, arbitrarily nested through
1262/// `if`/`match`/block sub-expressions) a `do`/`<-` statement — the two
1263/// forms legal only in an effectful body (`ctx.effectful`, gated on the
1264/// enclosing return type being `Effect[_]`). Decides whether a tail-excluded
1265/// run's synthesised `fn` must return `Effect[()]` — so those forms stay
1266/// legal in the lifted body — rather than plain `()`.
1267fn stmts_contain_effect_stmt(stmts: &[Statement]) -> bool {
1268    stmts_match(stmts, &|s| {
1269        matches!(
1270            s,
1271            Statement::EffectLet(_) | Statement::Do(_) | Statement::Par(_)
1272        )
1273    })
1274}
1275
1276/// Whether any of `stmts` is (or contains, arbitrarily nested through
1277/// `if`/`match`/block sub-expressions) a `:=` (`Cell` store write). A lifted
1278/// top-level `fn` has no `store` fields, so a run containing one anywhere —
1279/// not just as a direct top-level statement — would always fail to
1280/// typecheck once extracted.
1281fn stmts_contain_assign_stmt(stmts: &[Statement]) -> bool {
1282    stmts_match(stmts, &|s| matches!(s, Statement::Assign(_)))
1283}
1284
1285/// `expr` and every `Ident` reference nested inside it — walked via
1286/// [`expr_children`], the same exhaustive-by-construction iterator `locate`
1287/// uses, so a future `ExprKind` variant can't silently drop out of either
1288/// walk without the other noticing.
1289///
1290/// #2100 slice 2: a called name (`f(…)`) counts too. It calls whatever `f`
1291/// resolves to, a local closure included, so extract-function threads a
1292/// called local through as a parameter, and the binder and leak checks see
1293/// it.
1294fn collect_idents<'a>(expr: &'a Expr, out: &mut Vec<&'a Ident>) {
1295    match &expr.kind {
1296        ExprKind::Ident(id) => out.push(id),
1297        ExprKind::Call { name, .. } => out.push(name),
1298        _ => {}
1299    }
1300    for child in expr_children(expr) {
1301        collect_idents(child, out);
1302    }
1303}
1304
1305/// The whitespace-only run from `offset`'s line start up to `offset` — empty
1306/// if that run isn't pure whitespace (e.g. a single-line body has no
1307/// indentation to mirror; `bynk fmt` cleans up the result, the same
1308/// tolerance the quick-fix path takes).
1309fn line_indent(text: &str, offset: usize) -> String {
1310    let line_start = text[..offset].rfind('\n').map_or(0, |i| i + 1);
1311    let prefix = &text[line_start..offset];
1312    if prefix.chars().all(|c| c == ' ' || c == '\t') {
1313        prefix.to_string()
1314    } else {
1315        String::new()
1316    }
1317}
1318
1319#[cfg(test)]
1320mod tests {
1321    use super::*;
1322
1323    /// #2100 slice 2: a `?` returns from the enclosing body unless it sits in
1324    /// a lambda, whose body is its own return scope.
1325    #[test]
1326    fn early_return_detection_stops_at_a_lambda() {
1327        let src = "commons c\n\nfn g(r: Result[Int, String]) -> Result[Int, String] {\n  let a = r? + 1\n  let f = (x: Result[Int, String]) => Ok(x? + 1)\n  f(r)\n}\n";
1328        let tokens = tokenize(src).unwrap();
1329        let (Some(SourceUnit::Commons(c)), _) = parse_unit_with_recovery(&tokens, src) else {
1330            panic!("parses");
1331        };
1332        let CommonsItem::Fn(f) = &c.items[0] else {
1333            panic!("a fn");
1334        };
1335        let value = |i: usize| match &f.body.statements[i] {
1336            Statement::Let(l) => &l.value,
1337            _ => panic!("a let"),
1338        };
1339        assert!(has_early_return(value(0)));
1340        assert!(!has_early_return(value(1)));
1341    }
1342
1343    fn actions_for(text: &str, needle: &str) -> Vec<CodeActionOrCommand> {
1344        let start = text.find(needle).expect("needle present");
1345        let requested = Span::new(start, start + needle.len());
1346        let uri = Url::parse("file:///a.bynk").unwrap();
1347        extract_variable(text, requested, &uri, Some(3))
1348    }
1349
1350    fn sole_edit(action: &CodeActionOrCommand) -> Vec<TextEdit> {
1351        let CodeActionOrCommand::CodeAction(a) = action else {
1352            panic!("expected a CodeAction");
1353        };
1354        assert_eq!(a.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
1355        let Some(DocumentChanges::Edits(doc_edits)) = &a.edit.as_ref().unwrap().document_changes
1356        else {
1357            panic!("expected versioned document edits");
1358        };
1359        assert_eq!(doc_edits[0].text_document.version, Some(3));
1360        doc_edits[0]
1361            .edits
1362            .iter()
1363            .map(|e| {
1364                let OneOf::Left(edit) = e else {
1365                    panic!("expected a plain TextEdit")
1366                };
1367                edit.clone()
1368            })
1369            .collect()
1370    }
1371
1372    #[test]
1373    fn extracts_a_sub_expression_of_a_let_value() {
1374        let src = "context c\n\nfn f() -> Int {\n  let y = 1 + 2\n  y\n}\n";
1375        let actions = actions_for(src, "1 + 2");
1376        assert_eq!(actions.len(), 1);
1377        let edits = sole_edit(&actions[0]);
1378        assert_eq!(edits.len(), 2);
1379        assert!(edits[0].new_text.starts_with("let extracted = 1 + 2\n"));
1380        assert_eq!(edits[1].new_text, "extracted");
1381        // The insertion is a zero-length range right at the start of the
1382        // `let y = …` line — same line the replacement (later on that line)
1383        // sits on, since positions are computed against the original text.
1384        assert_eq!(edits[0].range.start, edits[0].range.end);
1385        assert_eq!(edits[0].range.start.line, edits[1].range.start.line);
1386        assert!(edits[0].range.start.character < edits[1].range.start.character);
1387    }
1388
1389    #[test]
1390    fn extracts_the_whole_tail_expression() {
1391        let src = "context c\n\nfn f() -> Int {\n  let x = 1\n  x + 1\n}\n";
1392        let actions = actions_for(src, "x + 1");
1393        let edits = sole_edit(&actions[0]);
1394        assert!(edits[0].new_text.starts_with("let extracted = x + 1\n"));
1395        assert_eq!(edits[1].new_text, "extracted");
1396    }
1397
1398    #[test]
1399    fn resets_the_insertion_point_inside_a_nested_if_block() {
1400        let src = concat!(
1401            "context c\n\n",
1402            "fn f(n: Int) -> Int {\n",
1403            "  if n > 0 {\n",
1404            "    let z = n * 2\n",
1405            "    z\n",
1406            "  } else {\n",
1407            "    0\n",
1408            "  }\n",
1409            "}\n",
1410        );
1411        let actions = actions_for(src, "n * 2");
1412        let edits = sole_edit(&actions[0]);
1413        // Inserted right above `let z = …` inside the `if` branch, not above
1414        // the whole `if` statement.
1415        let insert_line = edits[0].range.start.line;
1416        let let_z_line = crate::position::offset_to_position(src, src.find("let z").unwrap()).line;
1417        assert_eq!(insert_line, let_z_line);
1418    }
1419
1420    #[test]
1421    fn resets_the_insertion_point_inside_a_nested_match_arm_block() {
1422        let src = concat!(
1423            "context c\n\n",
1424            "fn f(n: Int) -> Int {\n",
1425            "  match n {\n",
1426            "    0 => {\n",
1427            "      let z = n * 2\n",
1428            "      z\n",
1429            "    }\n",
1430            "    _ => 0\n",
1431            "  }\n",
1432            "}\n",
1433        );
1434        let actions = actions_for(src, "n * 2");
1435        let edits = sole_edit(&actions[0]);
1436        // Inserted right above `let z = …` inside the arm's block, not above
1437        // the whole `match`.
1438        let insert_line = edits[0].range.start.line;
1439        let let_z_line = crate::position::offset_to_position(src, src.find("let z").unwrap()).line;
1440        assert_eq!(insert_line, let_z_line);
1441    }
1442
1443    /// #1819: the `let` goes above the enclosing statement, where an
1444    /// expression arm's pattern bindings and a lambda's parameters are not in
1445    /// scope, so a selection reading one is declined, not hoisted unbound.
1446    #[test]
1447    fn declines_a_selection_reading_an_arm_or_lambda_binding() {
1448        let arm = concat!(
1449            "context c\n\n",
1450            "fn f(o: Option[Int]) -> Int {\n",
1451            "  let a = match o {\n",
1452            "    Some(x) => x + 1\n",
1453            "    _ => 0\n",
1454            "  }\n",
1455            "  a\n",
1456            "}\n",
1457        );
1458        assert!(actions_for(arm, "x + 1").is_empty(), "arm binding hoisted");
1459        let lambda = concat!(
1460            "context c\n\n",
1461            "fn f(xs: List[Int]) -> List[Int] {\n",
1462            "  let ys = xs.map((v) => v * 2)\n",
1463            "  ys\n",
1464            "}\n",
1465        );
1466        assert!(
1467            actions_for(lambda, "v * 2").is_empty(),
1468            "lambda parameter hoisted"
1469        );
1470        // A guard extracts the whole `match` (#1800 review), never the guard
1471        // alone, so the `let` never reads the arm's binding out of scope.
1472        let guard = concat!(
1473            "context c\n\n",
1474            "fn f(o: Option[Int]) -> Int {\n",
1475            "  let a = match o {\n",
1476            "    Some(x) if x > 1 => 1\n",
1477            "    _ => 0\n",
1478            "  }\n",
1479            "  a\n",
1480            "}\n",
1481        );
1482        let guard_actions = actions_for(guard, "x > 1");
1483        assert_eq!(
1484            guard_actions.len(),
1485            1,
1486            "a guard selection extracts the match"
1487        );
1488        {
1489            let edits = sole_edit(&guard_actions[0]);
1490            assert!(
1491                edits[0].new_text.starts_with("let extracted = match o {"),
1492                "a guard selection must extract the whole match: {:?}",
1493                edits[0].new_text
1494            );
1495        }
1496    }
1497
1498    /// #1819's boundary: inside an arm or a lambda, a selection that reads no
1499    /// binding of theirs still extracts above the statement.
1500    #[test]
1501    fn still_extracts_inside_an_arm_or_lambda_when_no_binding_is_read() {
1502        let arm = concat!(
1503            "context c\n\n",
1504            "fn f(o: Option[Int], n: Int) -> Int {\n",
1505            "  let a = match o {\n",
1506            "    Some(x) => n + 1\n",
1507            "    _ => 0\n",
1508            "  }\n",
1509            "  a\n",
1510            "}\n",
1511        );
1512        let edits = sole_edit(&actions_for(arm, "n + 1")[0]);
1513        assert!(edits[0].new_text.starts_with("let extracted = n + 1\n"));
1514        let lambda = concat!(
1515            "context c\n\n",
1516            "fn f(xs: List[Int], k: Int) -> List[Int] {\n",
1517            "  let ys = xs.map((v) => k * 2)\n",
1518            "  ys\n",
1519            "}\n",
1520        );
1521        let edits = sole_edit(&actions_for(lambda, "k * 2")[0]);
1522        assert!(edits[0].new_text.starts_with("let extracted = k * 2\n"));
1523    }
1524
1525    /// #1880 review: the same scope rule for the other binders. An `is` on the
1526    /// left of `&&` / `implies` binds for the right operand only, and an
1527    /// observation's `with` predicate reads the observed operation's
1528    /// parameters, which the tree doesn't bind.
1529    #[test]
1530    fn declines_a_selection_reading_an_is_binding_or_an_observed_parameter() {
1531        let and = concat!(
1532            "context c\n\n",
1533            "fn f(r: Result[Int, String]) -> Bool {\n",
1534            "  let ok = r is Ok(n) && n > 0\n",
1535            "  ok\n",
1536            "}\n",
1537        );
1538        assert!(actions_for(and, "n > 0").is_empty(), "`&&` binding hoisted");
1539        let implies = concat!(
1540            "context c\n\n",
1541            "fn f(r: Result[Int, String]) -> Bool {\n",
1542            "  let ok = r is Ok(n) implies n > 0\n",
1543            "  ok\n",
1544            "}\n",
1545        );
1546        assert!(
1547            actions_for(implies, "n > 0").is_empty(),
1548            "`implies` binding hoisted"
1549        );
1550        let condition = concat!(
1551            "context c\n\n",
1552            "fn f(r: Result[Int, String]) -> Int {\n",
1553            "  if r is Ok(n) && n > 0 {\n",
1554            "    1\n",
1555            "  } else {\n",
1556            "    0\n",
1557            "  }\n",
1558            "}\n",
1559        );
1560        assert!(
1561            actions_for(condition, "n > 0").is_empty(),
1562            "`if` condition binding hoisted"
1563        );
1564        let observed = concat!(
1565            "suite c {\n",
1566            "  case \"logs\" {\n",
1567            "    expect Logger.log called with msg == \"start\"\n",
1568            "  }\n",
1569            "}\n",
1570        );
1571        assert!(
1572            actions_for(observed, "msg == \"start\"").is_empty(),
1573            "observed parameter hoisted"
1574        );
1575        // The left operand is outside the `is` scope, so it still extracts.
1576        let lhs = concat!(
1577            "context c\n\n",
1578            "fn f(r: Result[Int, String], k: Int) -> Bool {\n",
1579            "  let ok = k > 1 && r is Ok(n)\n",
1580            "  ok\n",
1581            "}\n",
1582        );
1583        let edits = sole_edit(&actions_for(lhs, "k > 1")[0]);
1584        assert!(edits[0].new_text.starts_with("let extracted = k > 1\n"));
1585    }
1586
1587    /// #1880 review: a block body puts the `let` inside the binding's scope,
1588    /// so a selection reading the binding still extracts there.
1589    #[test]
1590    fn still_extracts_a_binding_read_inside_a_block_body() {
1591        let arm = concat!(
1592            "context c\n\n",
1593            "fn f(o: Option[Int]) -> Int {\n",
1594            "  let a = match o {\n",
1595            "    Some(x) => {\n",
1596            "      let b = x + 1\n",
1597            "      b\n",
1598            "    }\n",
1599            "    _ => 0\n",
1600            "  }\n",
1601            "  a\n",
1602            "}\n",
1603        );
1604        let edits = sole_edit(&actions_for(arm, "x + 1")[0]);
1605        assert!(edits[0].new_text.starts_with("let extracted = x + 1\n"));
1606        let lambda = concat!(
1607            "context c\n\n",
1608            "fn f(xs: List[Int]) -> List[Int] {\n",
1609            "  let ys = xs.map((v) => {\n",
1610            "    let w = v * 2\n",
1611            "    w\n",
1612            "  })\n",
1613            "  ys\n",
1614            "}\n",
1615        );
1616        let edits = sole_edit(&actions_for(lambda, "v * 2")[0]);
1617        assert!(edits[0].new_text.starts_with("let extracted = v * 2\n"));
1618    }
1619
1620    #[test]
1621    fn selection_crossing_a_statement_boundary_offers_nothing() {
1622        let src = "context c\n\nfn f() -> Int {\n  let a = 1\n  let b = 2\n  a\n}\n";
1623        // Spans from inside `let a`'s value into the start of `let b` — no
1624        // single statement/tail value fully contains it.
1625        let actions = actions_for(src, "1\n  let b");
1626        assert!(actions.is_empty());
1627    }
1628
1629    #[test]
1630    fn selection_of_the_whole_block_braces_included_offers_nothing() {
1631        let src = "context c\n\nfn f() -> Int {\n  let a = 1\n  a\n}\n";
1632        // The full body span, braces included — larger than any single
1633        // statement/tail value, so no candidate node covers it.
1634        let actions = actions_for(src, "{\n  let a = 1\n  a\n}");
1635        assert!(actions.is_empty());
1636    }
1637
1638    #[test]
1639    fn extracts_a_call_argument() {
1640        let src = "context c\n\nfn f() -> Int {\n  g(1 + 2, 3)\n}\n";
1641        let actions = actions_for(src, "1 + 2");
1642        let edits = sole_edit(&actions[0]);
1643        assert_eq!(edits[1].new_text, "extracted");
1644        assert!(edits[0].new_text.contains("let extracted = 1 + 2"));
1645    }
1646
1647    #[test]
1648    fn bumps_the_suffix_on_a_name_collision() {
1649        let src = "context c\n\nfn f() -> Int {\n  let extracted = 0\n  1 + 2\n}\n";
1650        let actions = actions_for(src, "1 + 2");
1651        let edits = sole_edit(&actions[0]);
1652        assert!(edits[0].new_text.starts_with("let extracted2 = 1 + 2\n"));
1653        assert_eq!(edits[1].new_text, "extracted2");
1654    }
1655
1656    #[test]
1657    fn empty_selection_offers_nothing() {
1658        let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1659        let off = src.find("1 + 2").unwrap();
1660        let uri = Url::parse("file:///a.bynk").unwrap();
1661        let actions = extract_variable(src, Span::new(off, off), &uri, Some(1));
1662        assert!(actions.is_empty());
1663    }
1664
1665    #[test]
1666    fn selection_outside_any_body_offers_nothing() {
1667        let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1668        let actions = actions_for(src, "context c");
1669        assert!(actions.is_empty());
1670    }
1671
1672    #[test]
1673    fn preserves_indentation_on_a_multi_statement_block() {
1674        let src = "context c\n\nfn f() -> Int {\n    let a = 1\n    let b = a + 2\n    b\n}\n";
1675        let actions = actions_for(src, "a + 2");
1676        let edits = sole_edit(&actions[0]);
1677        assert_eq!(edits[0].new_text, "let extracted = a + 2\n    ");
1678    }
1679
1680    mod extract_function_tests {
1681        use super::*;
1682        use bynk_check::locals::LocalKind;
1683        use bynk_check::requirements::RequirementSource;
1684
1685        fn function_actions_for(
1686            text: &str,
1687            needle: &str,
1688            requirements: &[Requirement],
1689            locals: &[LocalBinding],
1690            expr_types: &[(Span, TyId)],
1691        ) -> Vec<CodeActionOrCommand> {
1692            let start = text.find(needle).expect("needle present");
1693            let requested = Span::new(start, start + needle.len());
1694            let uri = Url::parse("file:///a.bynk").unwrap();
1695            extract_function(
1696                text,
1697                requested,
1698                &uri,
1699                Some(3),
1700                requirements,
1701                locals,
1702                expr_types,
1703                &TYS,
1704            )
1705        }
1706
1707        fn nth_offset(text: &str, needle: &str, n: usize) -> usize {
1708            text.match_indices(needle)
1709                .nth(n)
1710                .expect("occurrence present")
1711                .0
1712        }
1713
1714        // Permissive (whole-file) scope: these tests exercise extract_function's
1715        // own gating/free-variable logic, not locals_at's scope resolution
1716        // (already covered in bynk-check::locals's own tests).
1717        fn param(text: &str, name: &str, ty: &str) -> LocalBinding {
1718            let def_start = nth_offset(text, name, 0);
1719            LocalBinding {
1720                name: name.to_string(),
1721                def_span: Span::new(def_start, def_start + name.len()),
1722                kind: LocalKind::Param,
1723                ty: ty.to_string(),
1724                scope: Span::new(0, text.len()),
1725            }
1726        }
1727
1728        use bynk_check::checker::Ty;
1729
1730        /// One table for every fixture in this module — `Types` is
1731        /// `Send + Sync` (T3.6b), so a `LazyLock` static is the least
1732        /// ceremonious way to give the `TyId`s below something to resolve
1733        /// against.
1734        static TYS: std::sync::LazyLock<Types> = std::sync::LazyLock::new(Types::new);
1735
1736        fn int_type(text: &str, needle: &str) -> (Span, TyId) {
1737            let start = text.find(needle).expect("needle present");
1738            (
1739                Span::new(start, start + needle.len()),
1740                TYS.intern(Ty::Base(BaseType::Int)),
1741            )
1742        }
1743
1744        /// A `let`-bound local — its def site is `name`'s first occurrence,
1745        /// same convention as [`param`].
1746        fn let_binding(text: &str, name: &str, ty: &str) -> LocalBinding {
1747            let def_start = nth_offset(text, name, 0);
1748            LocalBinding {
1749                name: name.to_string(),
1750                def_span: Span::new(def_start, def_start + name.len()),
1751                kind: LocalKind::Let,
1752                ty: ty.to_string(),
1753                scope: Span::new(0, text.len()),
1754            }
1755        }
1756
1757        fn capability_use(site_needle_offset: usize, len: usize) -> Requirement {
1758            Requirement {
1759                capability: "Clock".to_string(),
1760                site: Span::new(site_needle_offset, site_needle_offset + len),
1761                source: RequirementSource::DirectCall {
1762                    op: "now".to_string(),
1763                },
1764                covered: false,
1765                materialize: None,
1766            }
1767        }
1768
1769        #[test]
1770        fn extracts_a_free_variable_as_a_parameter() {
1771            let src = "context c\n\nfn f(num: Int) -> Int {\n  num * 2\n}\n";
1772            let locals = vec![param(src, "num", "Int")];
1773            let types = vec![int_type(src, "num * 2")];
1774            let actions = function_actions_for(src, "num * 2", &[], &locals, &types);
1775            assert_eq!(actions.len(), 1);
1776            let edits = sole_edit(&actions[0]);
1777            assert_eq!(
1778                edits[0].new_text,
1779                "fn extractedFn(num: Int) -> Int {\n  num * 2\n}\n\n"
1780            );
1781            // Inserted right above the enclosing `fn f`, not at the selection.
1782            assert_eq!(edits[0].range.start, Position::new(2, 0));
1783            assert_eq!(edits[1].new_text, "extractedFn(num)");
1784        }
1785
1786        /// #1760: a name read only in a match-arm guard is still free in the
1787        /// selection, so it's threaded as a parameter. `expr_children` didn't
1788        /// visit guards, so `lim` was dropped and the extracted `fn` read an
1789        /// unbound name.
1790        #[test]
1791        fn a_name_read_only_in_a_guard_is_a_parameter() {
1792            let src = "context c\n\nfn f(num: Int, lim: Int) -> Int {\n  match num {\n    n if n > lim => 1\n    _ => 0\n  }\n}\n";
1793            let selection = "match num {\n    n if n > lim => 1\n    _ => 0\n  }";
1794            let locals = vec![param(src, "num", "Int"), param(src, "lim", "Int")];
1795            let types = vec![int_type(src, selection)];
1796            let actions = function_actions_for(src, selection, &[], &locals, &types);
1797            assert_eq!(actions.len(), 1);
1798            let edits = sole_edit(&actions[0]);
1799            assert!(
1800                edits[0]
1801                    .new_text
1802                    .starts_with("fn extractedFn(num: Int, lim: Int) -> Int {"),
1803                "{}",
1804                edits[0].new_text
1805            );
1806            assert_eq!(edits[1].new_text, "extractedFn(num, lim)");
1807        }
1808
1809        #[test]
1810        fn no_free_variables_yields_a_nullary_call() {
1811            let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1812            let types = vec![int_type(src, "1 + 2")];
1813            let actions = function_actions_for(src, "1 + 2", &[], &[], &types);
1814            let edits = sole_edit(&actions[0]);
1815            assert_eq!(
1816                edits[0].new_text,
1817                "fn extractedFn() -> Int {\n  1 + 2\n}\n\n"
1818            );
1819            assert_eq!(edits[1].new_text, "extractedFn()");
1820        }
1821
1822        #[test]
1823        fn capability_using_selection_offers_nothing() {
1824            let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1825            let site = src.find("1 + 2").unwrap();
1826            let reqs = vec![capability_use(site, "1 + 2".len())];
1827            let types = vec![int_type(src, "1 + 2")];
1828            let actions = function_actions_for(src, "1 + 2", &reqs, &[], &types);
1829            assert!(actions.is_empty());
1830        }
1831
1832        #[test]
1833        fn bumps_the_suffix_on_a_name_collision() {
1834            let src =
1835                "context c\n\nfn extractedFn() -> Int {\n  0\n}\n\nfn f() -> Int {\n  1 + 2\n}\n";
1836            let types = vec![int_type(src, "1 + 2")];
1837            let actions = function_actions_for(src, "1 + 2", &[], &[], &types);
1838            let edits = sole_edit(&actions[0]);
1839            assert!(edits[0].new_text.starts_with("fn extractedFn2("));
1840            assert_eq!(edits[1].new_text, "extractedFn2()");
1841        }
1842
1843        #[test]
1844        fn selection_outside_any_body_offers_nothing() {
1845            let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1846            let types = vec![int_type(src, "1 + 2")];
1847            let actions = function_actions_for(src, "context c", &[], &[], &types);
1848            assert!(actions.is_empty());
1849        }
1850
1851        #[test]
1852        fn adapter_files_offer_nothing() {
1853            // An `Adapter` carries no Bynk bodies — `find_function_site` (like
1854            // `find_site`) short-circuits to `None` regardless of the selection.
1855            let src = "adapter tokens {\n  binding \"./b.ts\"\n}\n";
1856            let actions = function_actions_for(src, "binding", &[], &[], &[]);
1857            assert!(actions.is_empty());
1858        }
1859
1860        #[test]
1861        fn suite_test_cases_offer_nothing() {
1862            // Unlike extract-variable (which can extract a `let` inside a test
1863            // case), extract-function needs a top-level item to insert the new
1864            // `fn` above — a `Suite` case has none, so this declines even where
1865            // extract-variable would offer something.
1866            let src = "suite thing\n\ncase \"it works\" {\n  1 + 2\n}\n";
1867            let types = vec![int_type(src, "1 + 2")];
1868            let actions = function_actions_for(src, "1 + 2", &[], &[], &types);
1869            assert!(actions.is_empty());
1870        }
1871
1872        #[test]
1873        fn a_dirty_file_with_no_recorded_type_offers_nothing() {
1874            let src = "context c\n\nfn f() -> Int {\n  1 + 2\n}\n";
1875            // No expr_types entry for the selection — an expression the
1876            // checker never typed.
1877            let actions = function_actions_for(src, "1 + 2", &[], &[], &[]);
1878            assert!(actions.is_empty());
1879        }
1880
1881        #[test]
1882        fn ambiguous_same_name_shadow_from_two_outer_scopes_declines() {
1883            let src = "context c\n\nfn f() -> Int {\n  x + x\n}\n";
1884            let types = vec![int_type(src, "x + x")];
1885            let first_x = nth_offset(src, "x + x", 0); // the first `x`'s offset
1886            let second_x = first_x + "x + ".len(); // the second `x`'s offset
1887            // Two distinct external bindings named `x`, each in scope only at
1888            // one of the two occurrences — an occurrence-position-dependent
1889            // resolution a real program could never actually produce, used
1890            // here purely to force the ambiguous-shadow branch.
1891            let locals = vec![
1892                LocalBinding {
1893                    name: "x".to_string(),
1894                    def_span: Span::new(0, 1),
1895                    kind: LocalKind::Let,
1896                    ty: "Int".to_string(),
1897                    scope: Span::new(first_x, first_x),
1898                },
1899                LocalBinding {
1900                    name: "x".to_string(),
1901                    def_span: Span::new(1, 2),
1902                    kind: LocalKind::Let,
1903                    ty: "Int".to_string(),
1904                    scope: Span::new(second_x, second_x),
1905                },
1906            ];
1907            let actions = function_actions_for(src, "x + x", &[], &locals, &types);
1908            assert!(actions.is_empty());
1909        }
1910
1911        mod multi_statement_tests {
1912            use super::*;
1913
1914            #[test]
1915            fn a_run_including_the_tail_becomes_a_call_expression() {
1916                let src = "context c\n\nfn f(num: Int) -> Int {\n  let a = num + 1\n  let b = a * 2\n  b + num\n}\n";
1917                let locals = vec![
1918                    param(src, "num", "Int"),
1919                    let_binding(src, "a", "Int"),
1920                    let_binding(src, "b", "Int"),
1921                ];
1922                let types = vec![int_type(src, "b + num")];
1923                let needle = "let a = num + 1\n  let b = a * 2\n  b + num";
1924                let actions = function_actions_for(src, needle, &[], &locals, &types);
1925                assert_eq!(actions.len(), 1);
1926                let edits = sole_edit(&actions[0]);
1927                assert_eq!(
1928                    edits[0].new_text,
1929                    format!("fn extractedFn(num: Int) -> Int {{\n  {needle}\n}}\n\n")
1930                );
1931                assert_eq!(edits[1].new_text, "extractedFn(num)");
1932            }
1933
1934            #[test]
1935            fn a_run_excluding_the_tail_yields_a_discard_call() {
1936                let src = "context c\n\nfn f(num: Int) -> Int {\n  let a = num + 1\n  let valC = a * 2\n  num\n}\n";
1937                let locals = vec![
1938                    param(src, "num", "Int"),
1939                    let_binding(src, "a", "Int"),
1940                    let_binding(src, "valC", "Int"),
1941                ];
1942                let needle = "let a = num + 1\n  let valC = a * 2";
1943                let actions = function_actions_for(src, needle, &[], &locals, &[]);
1944                assert_eq!(actions.len(), 1);
1945                let edits = sole_edit(&actions[0]);
1946                assert_eq!(
1947                    edits[0].new_text,
1948                    format!("fn extractedFn(num: Int) -> () {{\n  {needle}\n}}\n\n")
1949                );
1950                assert_eq!(edits[1].new_text, "let _ = extractedFn(num)");
1951            }
1952
1953            #[test]
1954            fn an_effectful_run_excluding_the_tail_yields_an_effect_return_and_a_do_call() {
1955                // `do` is only legal in an effectful body semantically (a
1956                // checker rule), but the parser accepts it regardless of the
1957                // enclosing signature — extract_function does no
1958                // type-checking of its own, so this exercises the
1959                // return-type/call-site choice in isolation.
1960                let src = "context c\n\nfn f() -> Effect[()] {\n  do g()\n  do h()\n  ()\n}\n";
1961                let needle = "do g()\n  do h()";
1962                let actions = function_actions_for(src, needle, &[], &[], &[]);
1963                assert_eq!(actions.len(), 1);
1964                let edits = sole_edit(&actions[0]);
1965                assert_eq!(
1966                    edits[0].new_text,
1967                    format!("fn extractedFn() -> Effect[()] {{\n  {needle}\n}}\n\n")
1968                );
1969                assert_eq!(edits[1].new_text, "do extractedFn()");
1970            }
1971
1972            #[test]
1973            fn a_run_whose_match_guard_binds_an_effect_yields_an_effect_return() {
1974                // #1800 review: the `<-` sits only in an arm's guard, so
1975                // `stmts_contain_effect_stmt` must search guards for the lifted
1976                // `fn` to return `Effect[()]` and the call site to be `do`.
1977                let src = concat!(
1978                    "context c\n\n",
1979                    "fn f(o: Option[Int]) -> Effect[()] {\n",
1980                    "  let a = match o {\n",
1981                    "    Some(n) if if n > 0 {\n",
1982                    "      let _ <- g()\n",
1983                    "      true\n",
1984                    "    } else {\n",
1985                    "      false\n",
1986                    "    } => n\n",
1987                    "    _ => 0\n",
1988                    "  }\n",
1989                    "  ()\n",
1990                    "}\n",
1991                );
1992                let needle = "let a = match o {\n    Some(n) if if n > 0 {\n      let _ <- g()\n      true\n    } else {\n      false\n    } => n\n    _ => 0\n  }";
1993                let actions = function_actions_for(src, needle, &[], &[], &[]);
1994                assert_eq!(actions.len(), 1);
1995                let edits = sole_edit(&actions[0]);
1996                assert!(
1997                    edits[0]
1998                        .new_text
1999                        .starts_with("fn extractedFn() -> Effect[()] {"),
2000                    "{}",
2001                    edits[0].new_text
2002                );
2003                assert_eq!(edits[1].new_text, "do extractedFn()");
2004            }
2005
2006            #[test]
2007            fn a_binding_the_run_introduces_still_used_in_the_tail_declines() {
2008                let src = "context c\n\nfn f(num: Int) -> Int {\n  let a = num + 1\n  let b = a * 2\n  b\n}\n";
2009                let locals = vec![
2010                    param(src, "num", "Int"),
2011                    let_binding(src, "a", "Int"),
2012                    let_binding(src, "b", "Int"),
2013                ];
2014                // Excludes the tail `b`, which reads the run's own `let b` —
2015                // lifting the run away would strand that reference.
2016                let needle = "let a = num + 1\n  let b = a * 2";
2017                let actions = function_actions_for(src, needle, &[], &locals, &[]);
2018                assert!(actions.is_empty());
2019            }
2020
2021            #[test]
2022            fn a_run_containing_a_cell_write_declines() {
2023                // A lifted top-level `fn` has no `store` fields — a `:=`
2024                // inside the run would always fail to resolve its target.
2025                let src = "context c\n\nfn f() -> Int {\n  cell := 1\n  x\n}\n";
2026                let actions = function_actions_for(src, "cell := 1", &[], &[], &[]);
2027                assert!(actions.is_empty());
2028            }
2029
2030            #[test]
2031            fn a_run_containing_a_nested_cell_write_declines() {
2032                // The `:=` is nested inside an `if`-branch within the run's
2033                // own `let`, not a direct top-level statement in the run —
2034                // `stmts_contain_assign_stmt` must recurse to catch it, the
2035                // same way `stmts_contain_effect_stmt` already does for
2036                // `do`/`<-`.
2037                let src = concat!(
2038                    "context c\n\n",
2039                    "fn f(cond: Bool) -> Int {\n",
2040                    "  let a = if cond {\n",
2041                    "    cell := 1\n",
2042                    "    0\n",
2043                    "  } else {\n",
2044                    "    1\n",
2045                    "  }\n",
2046                    "  a\n",
2047                    "}\n",
2048                );
2049                let needle = "let a = if cond {\n    cell := 1\n    0\n  } else {\n    1\n  }";
2050                let actions = function_actions_for(src, needle, &[], &[], &[]);
2051                assert!(actions.is_empty());
2052            }
2053
2054            #[test]
2055            fn a_run_containing_a_cell_write_in_a_match_guard_declines() {
2056                // #1800: the `:=` sits in an arm's guard, which
2057                // `stmts_contain_assign_stmt` must search like an arm body.
2058                let src = concat!(
2059                    "context c\n\n",
2060                    "fn f(o: Option[Int]) -> Int {\n",
2061                    "  let a = match o {\n",
2062                    "    Some(x) if if x > 0 {\n",
2063                    "      cell := x\n",
2064                    "      true\n",
2065                    "    } else {\n",
2066                    "      false\n",
2067                    "    } => x\n",
2068                    "    _ => 0\n",
2069                    "  }\n",
2070                    "  a\n",
2071                    "}\n",
2072                );
2073                let needle = "let a = match o {\n    Some(x) if if x > 0 {\n      cell := x\n      true\n    } else {\n      false\n    } => x\n    _ => 0\n  }";
2074                let actions = function_actions_for(src, needle, &[], &[], &[]);
2075                assert!(actions.is_empty());
2076            }
2077
2078            #[test]
2079            fn a_run_found_inside_a_match_guard() {
2080                // #1800: the run sits in the `then` block of a guard's `if`.
2081                // The guard's tail reads only `num`, so lifting the run
2082                // strands nothing.
2083                let src = concat!(
2084                    "context c\n\n",
2085                    "fn f(o: Option[Int]) -> Int {\n",
2086                    "  match o {\n",
2087                    "    Some(num) if if num > 0 {\n",
2088                    "      let valA = num * 2\n",
2089                    "      let valB = valA + 1\n",
2090                    "      num > 3\n",
2091                    "    } else {\n",
2092                    "      false\n",
2093                    "    } => num\n",
2094                    "    _ => 0\n",
2095                    "  }\n",
2096                    "}\n",
2097                );
2098                let locals = vec![
2099                    param(src, "num", "Int"),
2100                    let_binding(src, "valA", "Int"),
2101                    let_binding(src, "valB", "Int"),
2102                ];
2103                let needle = "let valA = num * 2\n      let valB = valA + 1";
2104                let actions = function_actions_for(src, needle, &[], &locals, &[]);
2105                assert_eq!(actions.len(), 1, "a run in a guard is extractable");
2106            }
2107
2108            #[test]
2109            fn a_run_found_inside_a_nested_if_branch() {
2110                let src = concat!(
2111                    "context c\n\n",
2112                    "fn f(num: Int) -> Int {\n",
2113                    "  if num > 0 {\n",
2114                    "    let valA = num * 2\n",
2115                    "    let valB = valA + 1\n",
2116                    "    valB\n",
2117                    "  } else {\n",
2118                    "    0\n",
2119                    "  }\n",
2120                    "}\n",
2121                );
2122                let locals = vec![
2123                    param(src, "num", "Int"),
2124                    let_binding(src, "valA", "Int"),
2125                    let_binding(src, "valB", "Int"),
2126                ];
2127                let tail_val_b = nth_offset(src, "valB", 1); // skip `let valB`'s own def
2128                let types = vec![(
2129                    Span::new(tail_val_b, tail_val_b + "valB".len()),
2130                    TYS.intern(Ty::Base(BaseType::Int)),
2131                )];
2132                let needle = "let valA = num * 2\n    let valB = valA + 1\n    valB";
2133                let actions = function_actions_for(src, needle, &[], &locals, &types);
2134                assert_eq!(actions.len(), 1);
2135                let edits = sole_edit(&actions[0]);
2136                assert_eq!(
2137                    edits[0].new_text,
2138                    format!("fn extractedFn(num: Int) -> Int {{\n  {needle}\n}}\n\n")
2139                );
2140                // Inserted above the enclosing `fn f`, not inside the `if`.
2141                assert_eq!(edits[0].range.start, Position::new(2, 0));
2142                assert_eq!(edits[1].new_text, "extractedFn(num)");
2143            }
2144
2145            /// #2010: a `let … else` line is the hidden binding that heads the
2146            /// rest of its block, so neither refactoring lifts it — alone or
2147            /// with what follows — while its value is still extractable.
2148            #[test]
2149            fn a_let_else_statement_is_not_extracted() {
2150                let src = "context c\n\nfn f(r: Result[Int, String]) -> Int {\n  let Ok(n) = load(r) else { 0 }\n  let m = n + 1\n  m\n}\n";
2151                let uri = Url::parse("file:///a.bynk").unwrap();
2152                let locals = vec![param(src, "r", "Result[Int, String]")];
2153                for sel in [
2154                    "let Ok(n) = load(r) else { 0 }",
2155                    "let Ok(n) = load(r) else { 0 }\n  let m = n + 1",
2156                    "let Ok(n) = load(r) else { 0 }\n  let m = n + 1\n  m",
2157                ] {
2158                    let start = src.find(sel).unwrap();
2159                    let requested = Span::new(start, start + sel.len());
2160                    assert!(
2161                        extract_function(src, requested, &uri, Some(3), &[], &locals, &[], &TYS)
2162                            .is_empty(),
2163                        "extract function must decline {sel:?}"
2164                    );
2165                    assert!(
2166                        extract_variable(src, requested, &uri, Some(3)).is_empty(),
2167                        "extract variable must decline {sel:?}"
2168                    );
2169                }
2170                let start = src.find("load(r)").unwrap();
2171                let requested = Span::new(start, start + "load(r)".len());
2172                let actions = extract_variable(src, requested, &uri, Some(3));
2173                assert_eq!(actions.len(), 1, "the value is the author's expression");
2174                let edits = sole_edit(&actions[0]);
2175                assert!(
2176                    edits
2177                        .iter()
2178                        .any(|e| e.new_text.starts_with("let extracted = load(r)")),
2179                    "{edits:?}"
2180                );
2181            }
2182
2183            /// #2010: statements after a `let … else` live in its pattern's arm
2184            /// and are an ordinary run there.
2185            #[test]
2186            fn statements_after_a_let_else_still_extract() {
2187                let src = "context c\n\nfn f(r: Result[Int, String]) -> Int {\n  let Ok(n) = load(r) else { 0 }\n  let m = n + 1\n  let k = m * 2\n  k\n}\n";
2188                let uri = Url::parse("file:///a.bynk").unwrap();
2189                let sel = "let m = n + 1\n  let k = m * 2\n  k";
2190                let start = src.find(sel).unwrap();
2191                let requested = Span::new(start, start + sel.len());
2192                let locals = vec![
2193                    param(src, "r", "Result[Int, String]"),
2194                    let_binding(src, "m", "Int"),
2195                    let_binding(src, "k", "Int"),
2196                    LocalBinding {
2197                        name: "n".to_string(),
2198                        def_span: Span::new(nth_offset(src, "n)", 0), nth_offset(src, "n)", 0) + 1),
2199                        kind: LocalKind::Let,
2200                        ty: "Int".to_string(),
2201                        scope: Span::new(0, src.len()),
2202                    },
2203                ];
2204                // The run includes the tail, whose type becomes the lifted
2205                // `fn`'s return type.
2206                let tail = src.find("  k\n}").unwrap() + 2;
2207                let types = vec![(
2208                    Span::new(tail, tail + 1),
2209                    TYS.intern(Ty::Base(BaseType::Int)),
2210                )];
2211                let actions =
2212                    extract_function(src, requested, &uri, Some(3), &[], &locals, &types, &TYS);
2213                assert_eq!(actions.len(), 1, "{actions:#?}");
2214            }
2215
2216            #[test]
2217            fn a_selection_extending_past_a_statement_boundary_declines() {
2218                let src = "context c\n\nfn f(num: Int) -> Int {\n  let a = num + 1\n  let valC = a * 2\n  num\n}\n";
2219                let start = src.find("let a = num + 1").unwrap();
2220                // One byte short of a full second statement — doesn't align
2221                // with any statement/tail boundary in either direction, so
2222                // neither the multi-statement nor the single-expression
2223                // algorithm matches.
2224                let end = start + "let a = num + 1\n  let valC = a * 2".len() - 1;
2225                let requested = Span::new(start, end);
2226                let uri = Url::parse("file:///a.bynk").unwrap();
2227                let actions = extract_function(src, requested, &uri, Some(3), &[], &[], &[], &TYS);
2228                assert!(actions.is_empty());
2229            }
2230
2231            #[test]
2232            fn a_selection_padded_with_surrounding_whitespace_still_aligns() {
2233                let src = "context c\n\nfn f(num: Int) -> Int {\n  let a = num + 1\n  let valC = a * 2\n  num\n}\n";
2234                let inner = "let a = num + 1\n  let valC = a * 2";
2235                let start = src.find(inner).unwrap();
2236                // Pads onto the leading two-space indent and the trailing
2237                // newline — a common "select whole lines" editor gesture.
2238                let requested = Span::new(start - 2, start + inner.len() + 1);
2239                let locals = vec![
2240                    param(src, "num", "Int"),
2241                    let_binding(src, "a", "Int"),
2242                    let_binding(src, "valC", "Int"),
2243                ];
2244                let uri = Url::parse("file:///a.bynk").unwrap();
2245                let actions =
2246                    extract_function(src, requested, &uri, Some(3), &[], &locals, &[], &TYS);
2247                assert_eq!(actions.len(), 1);
2248                let edits = sole_edit(&actions[0]);
2249                assert_eq!(edits[1].new_text, "let _ = extractedFn(num)");
2250            }
2251        }
2252
2253        /// Fixtures run through the real analysis rather than hand-built
2254        /// tables, so `expr_types`/`locals` carry exactly what the
2255        /// `code_action` handler sees — real `FileId`s on every span, and
2256        /// (ADR 0094) best-effort partial types for a file with errors, where
2257        /// an expression whose typing failed is recorded as `Ty::Error`.
2258        mod analysed_fixtures {
2259            use super::*;
2260            use std::path::Path;
2261            use std::sync::Arc;
2262
2263            /// `src`'s `(expr_types, locals, tys)` as the single-file context
2264            /// `c.bynk` of a fresh on-disk project, asserting the file's
2265            /// diagnostic categories are exactly `expected`.
2266            fn analysed(
2267                test_name: &str,
2268                src: &str,
2269                expected: &[&str],
2270            ) -> (Vec<(Span, TyId)>, Vec<LocalBinding>, Arc<Types>) {
2271                let root = std::env::temp_dir().join(format!(
2272                    "bynk-lsp-extract-{test_name}-{}",
2273                    std::process::id()
2274                ));
2275                let _ = std::fs::remove_dir_all(&root);
2276                std::fs::create_dir_all(&root).expect("create test root");
2277                std::fs::write(root.join("c.bynk"), src).expect("write file");
2278                let root = root.canonicalize().expect("canonical root");
2279                let overlay = HashMap::from([(root.join("c.bynk"), src.to_string())]);
2280                let result = bynk_ide::diagnose_project(&root, &overlay);
2281                let _ = std::fs::remove_dir_all(&root);
2282                let rel = Path::new("c.bynk");
2283                let categories: Vec<&str> = result
2284                    .files
2285                    .iter()
2286                    .filter(|f| f.source_path == rel)
2287                    .flat_map(|f| f.diagnostics.iter().map(|d| d.error.category))
2288                    .collect();
2289                assert_eq!(categories, expected);
2290                (
2291                    result.expr_types.get(rel).cloned().unwrap_or_default(),
2292                    result.locals.get(rel).cloned().unwrap_or_default(),
2293                    Arc::clone(&result.ty_intern),
2294                )
2295            }
2296
2297            /// The new `fn` each offered action would insert.
2298            fn offered(test_name: &str, src: &str, needle: &str, expected: &[&str]) -> Vec<String> {
2299                let (types, locals, tys) = analysed(test_name, src, expected);
2300                let start = src.find(needle).expect("needle present");
2301                let uri = Url::parse("file:///c.bynk").unwrap();
2302                extract_function(
2303                    src,
2304                    Span::new(start, start + needle.len()),
2305                    &uri,
2306                    Some(3),
2307                    &[],
2308                    &locals,
2309                    &types,
2310                    &tys,
2311                )
2312                .iter()
2313                .map(|a| sole_edit(a)[0].new_text.clone())
2314                .collect()
2315            }
2316
2317            /// The handler reparses the buffer (spans with no file identity)
2318            /// but the analysis's spans carry the file's real `FileId` (T3.5),
2319            /// so matching a recorded type must compare positions only — an
2320            /// exact `Span` match never found one, and the action was never
2321            /// offered against real analysis output.
2322            #[test]
2323            fn a_clean_file_offers_the_action() {
2324                let src = "context c\n\nfn f(num: Int) -> Int {\n  num * 2\n}\n";
2325                assert_eq!(
2326                    offered("clean", src, "num * 2", &[]),
2327                    ["fn extractedFn(num: Int) -> Int {\n  num * 2\n}\n\n"]
2328                );
2329            }
2330
2331            /// The selection itself failed to type: its recorded type is
2332            /// `Ty::Error`, which must decline, not render `-> <type error>`.
2333            #[test]
2334            fn an_error_typed_selection_declines() {
2335                let src = "context c\n\nfn f(num: Int) -> Int {\n  num + \"s\"\n}\n";
2336                let offered = offered(
2337                    "error-typed-selection",
2338                    src,
2339                    "num + \"s\"",
2340                    &["bynk.types.type_mismatch"],
2341                );
2342                assert!(offered.is_empty(), "expected no action; got {offered:?}");
2343            }
2344
2345            /// A well-typed selection that reads an error-typed binding: the
2346            /// checker records no local for a `let` whose value failed to
2347            /// type, so `z` would not be threaded as a parameter and the
2348            /// lifted `fn` would read an unbound name.
2349            #[test]
2350            fn a_selection_reading_an_error_typed_binding_declines() {
2351                let src = "context c\n\nfn f(num: Int) -> Int {\n  let z = num + \"s\"\n  let w = if num > 0 {\n    let q = z\n    1\n  } else {\n    2\n  }\n  w\n}\n";
2352                let offered = offered(
2353                    "error-typed-binding",
2354                    src,
2355                    "if num > 0 {\n    let q = z\n    1\n  } else {\n    2\n  }",
2356                    &["bynk.types.type_mismatch"],
2357                );
2358                assert!(offered.is_empty(), "expected no action; got {offered:?}");
2359            }
2360
2361            /// A tail-less statement run synthesises its `()` return type and
2362            /// never looks one up, so the `Ty::Error` gate is its only guard:
2363            /// `z`'s `let` is unrecorded in `locals`, so without the gate the
2364            /// run would lift with `z` unbound.
2365            #[test]
2366            fn a_statement_run_reading_an_error_typed_binding_declines() {
2367                let src = "context c\n\nfn f(num: Int) -> Int {\n  let z = num + \"s\"\n  let q = z\n  num\n}\n";
2368                let offered = offered(
2369                    "error-typed-stmts",
2370                    src,
2371                    "let q = z",
2372                    &["bynk.types.type_mismatch"],
2373                );
2374                assert!(offered.is_empty(), "expected no action; got {offered:?}");
2375            }
2376
2377            /// An error elsewhere in the file doesn't block a selection that
2378            /// typed cleanly (ADR 0094's partial map).
2379            #[test]
2380            fn an_error_elsewhere_still_offers_the_action() {
2381                let src = "context c\n\nfn f(num: Int) -> Int {\n  num * 2\n}\n\nfn g(num: Int) -> Int {\n  num + \"s\"\n}\n";
2382                assert_eq!(
2383                    offered(
2384                        "error-elsewhere",
2385                        src,
2386                        "num * 2",
2387                        &["bynk.types.type_mismatch"]
2388                    ),
2389                    ["fn extractedFn(num: Int) -> Int {\n  num * 2\n}\n\n"]
2390                );
2391            }
2392        }
2393    }
2394
2395    #[test]
2396    fn extracts_inside_the_value_of_a_let_with_a_call_site_principal() {
2397        // #1766 put a principal's identity first in `statement_exprs`; the
2398        // value is the statement's last expression, not its first.
2399        let src = "suite demo.s {\n  case \"c\" {\n    let who = \"alice\"\n    let item <- api.get(1 + 2) by User(who)\n    expect item\n  }\n}\n";
2400        assert_eq!(actions_for(src, "1 + 2").len(), 1);
2401    }
2402}