Skip to main content

bynk_ide/
completion.rs

1//! Completion for the cursor, keyed off the line up to it.
2//!
3//! The surface is the canonical *cursor context × candidate-kind* matrix fixed
4//! by ADR 0093 (`design/decisions/0093-completion-surface-contract.md`), spec'd
5//! at `design/bynk-lsp-spec.md` §3.15. [`complete`] dispatches the six contexts
6//! it can serve purely (no analysis cache):
7//!
8//! - `consumes <prefix>` / `consumes U { … }` / `given …` — consumable units and
9//!   in-scope capabilities (v0.17);
10//! - **type position** (`: T`, `-> T`, inside `[ … ]` type args) — built-in
11//!   types, the `bynk`-surface transparent types, and project `type` decls;
12//! - **keyword position** (a bare word at a declaration/statement start) — the
13//!   reserved keywords (with registry docs) and declaration snippets;
14//! - **name-receiver `UpperIdent.`** — sum variants (project + built-in
15//!   `HttpResult`/`QueueResult`), refined/opaque `of`/`unsafe`, capability ops,
16//!   and built-in type statics (`Int.parse`/`List.empty`/`Effect.pure`/…);
17//! - **expression position** (after `=`/`(`/`,`/`=>`/an operator) — the value
18//!   constructors (`Ok`/`Some`/`true`/…), in-scope type names, and in-scope free
19//!   functions (the current unit's own `fn`s + `uses`-imported stdlib/project
20//!   combinators, gated on the `uses` set) (ADR 0093 D3).
21//!
22//! Two further contexts need the analysis overlay and so live handler-side
23//! (`main.rs`): **value-receiver `lower.`** members (kernel methods + record
24//! fields) and **in-scope locals/params**. They depend on the analysis overlay
25//! (the boundary is ADR 0093 D4), but since slice 4 (ADR 0094) it is
26//! error-tolerant: best-effort partial types are recorded even on a broken
27//! buffer, so they no longer go silent on an unrelated error. Items also carry a
28//! one-line `detail` eagerly; the richer `documentation` is filled in lazily by
29//! `completionItem/resolve`, handler-side (slice 5).
30//!
31//! Context detection is lexical (it must work mid-edit, when the buffer rarely
32//! parses); candidates are semantic. Unit/type/capability/member enumeration
33//! parses the project's `.bynk` files (and the embedded `bynk` surface) with
34//! recovery, so it works even while the file the cursor sits in is mid-edit.
35//! Built-ins, keywords, and constructors come from the static `bynk` registries
36//! (`keywords`/`builtin_names`/`firstparty`/`ast`), never the index — first-party
37//! symbols aren't indexed (the v0.28 finding); the project parse supplies only
38//! *project* symbols.
39
40use std::borrow::Cow;
41use std::collections::{BTreeMap, BTreeSet, HashMap};
42use std::path::{Path, PathBuf};
43use std::sync::{Arc, LazyLock};
44
45use bynk_check::checker::{NamedKind, Ty, TyId, Types};
46use bynk_check::kernel_methods;
47use bynk_check::locals::LocalBinding;
48use bynk_check::store_ops;
49use bynk_syntax::ast::{CommonsItem, ExportKind, FnName, SourceUnit, TypeBody, TypeRef, UsesDecl};
50use bynk_syntax::{keywords, lexer, parser};
51
52use crate::symbols::type_ref_str;
53
54/// What a candidate refers to — maps to an LSP `CompletionItemKind`.
55#[derive(Clone, Copy, PartialEq, Eq)]
56pub enum CompletionKind {
57    Unit,
58    Capability,
59    Type,
60    Keyword,
61    Snippet,
62    /// A sum-type variant (`Color.Red`).
63    Variant,
64    /// A name-receiver member: a refined/opaque `of`/`unsafe` constructor, a
65    /// capability operation, or a built-in type static (`Int.parse`).
66    Member,
67    /// A record field on a value receiver (`order.total`).
68    Field,
69    /// A value constructor at expression position (`Ok`/`Some`/`true`).
70    Constructor,
71    /// A free function in scope at expression position — the current unit's own
72    /// top-level `fn`s and the `uses`-imported stdlib/project combinators.
73    Function,
74    /// A named constant value at expression position — an `asset` (#1883),
75    /// in scope by the same rule as a free function.
76    Constant,
77    /// A constraint name after `T:` or `where A:` (constrained generics
78    /// slice 0).
79    Constraint,
80}
81
82pub struct Completion {
83    pub label: String,
84    pub kind: CompletionKind,
85    pub detail: Option<String>,
86    /// LSP snippet text (with `${n:…}`/`$0` tab stops) for `Snippet` items;
87    /// `None` means insert the label verbatim.
88    pub insert_text: Option<String>,
89    /// #1888: the candidate's doc, as Markdown: a record field's or a
90    /// variant's own doc, in either form.
91    pub documentation: Option<String>,
92}
93
94impl Completion {
95    pub fn item(label: impl Into<String>, kind: CompletionKind, detail: Option<String>) -> Self {
96        Completion {
97            label: label.into(),
98            kind,
99            detail,
100            insert_text: None,
101            documentation: None,
102        }
103    }
104
105    /// #1888: this candidate with `doc` as its documentation.
106    fn with_doc(mut self, doc: Option<&str>) -> Self {
107        self.documentation = doc.map(str::to_owned);
108        self
109    }
110
111    fn snippet(label: &str, body: &str) -> Self {
112        Completion {
113            label: label.to_string(),
114            kind: CompletionKind::Snippet,
115            detail: Some(format!("{label} scaffold")),
116            insert_text: Some(body.to_string()),
117            documentation: None,
118        }
119    }
120}
121
122/// #2841: the text typed so far of a `fixture name = "…` path, when the cursor
123/// is inside that string.
124fn fixture_path_prefix(line_prefix: &str) -> Option<&str> {
125    let rest = line_prefix.trim_start().strip_prefix("fixture ")?;
126    let (name, after) = rest.split_once('=')?;
127    if name.trim().is_empty() || !name.trim().chars().all(|c| c.is_alphanumeric() || c == '_') {
128        return None;
129    }
130    let partial = after.trim_start().strip_prefix('"')?;
131    (!partial.contains('"')).then_some(partial)
132}
133
134/// Produce completions for the cursor, given the text of the line up to the
135/// cursor, the current document text, and the project source root (if any).
136/// Without a project root, a project's dependencies are found from the
137/// manifest in `files` ([`crate::packages::DependencyView::from_files`]);
138/// the language server calls [`complete_in`] with the root it knows.
139pub fn complete(
140    line_prefix: &str,
141    doc_text: &str,
142    files: Option<&HashMap<PathBuf, String>>,
143) -> Vec<Completion> {
144    complete_in(None, line_prefix, doc_text, files)
145}
146
147/// [`complete`] for the project rooted at `project_root`, whose path
148/// dependencies decide which unit names are offered (#2223).
149pub fn complete_in(
150    project_root: Option<&Path>,
151    line_prefix: &str,
152    doc_text: &str,
153    files: Option<&HashMap<PathBuf, String>>,
154) -> Vec<Completion> {
155    // #2223: the project's own files and its dependencies' reachable units,
156    // resolved once per request and only by the branches that name units.
157    let split = || split_dependency_files(files, project_root);
158    // 0. #2841: inside a suite's `fixture name = "<cursor>` — the files in the
159    //    project's `fixtures/` folder.
160    if let Some(partial) = fixture_path_prefix(line_prefix) {
161        let files = project_root
162            .and_then(|root| bynk_project::assets::list_fixture_files(root).ok())
163            .unwrap_or_default();
164        return files
165            .into_iter()
166            .filter(|f| f.starts_with(partial.trim_start_matches("./")))
167            .map(|f| {
168                Completion::item(
169                    f,
170                    CompletionKind::Constant,
171                    Some("fixture file — test-only, never deployed".to_string()),
172                )
173            })
174            .collect();
175    }
176    // 0b. #2686: `@<cursor>` after a `Matches(…)` / `IsoDate` refinement — the
177    //     `@example` annotation, the only one valid there.
178    if in_refinement_annotation_position(line_prefix) {
179        return vec![Completion::item(
180            "example",
181            CompletionKind::Keyword,
182            Some(
183                "@example(<literal>) — the value `Val` uses for this pattern; checked against it"
184                    .to_string(),
185            ),
186        )];
187    }
188    // 1. Inside `consumes U { … <cursor>` — the capabilities U exports.
189    if let Some(unit) = consumes_brace_unit(line_prefix) {
190        // #2887: after `T as` the next word is the alias, a name of the user's
191        // own: nothing to suggest.
192        if names_a_brace_alias(line_prefix) {
193            return Vec::new();
194        }
195        return capabilities_of_unit(&unit, doc_text, &split())
196            .into_iter()
197            .map(|c| {
198                let detail = format!(
199                    "capability exported by `{unit}`{}",
200                    stability_suffix(experimental(&format!("{unit}.{c}")))
201                );
202                Completion::item(c, CompletionKind::Capability, Some(detail))
203            })
204            .collect();
205    }
206    // 2. After `consumes <prefix>` — consumable unit names.
207    if is_consumes_target(line_prefix) {
208        return consumable_units(doc_text, &split());
209    }
210    // 2a. #2223: after `uses <prefix>` — the commons a `uses` can name: the
211    //     project's own, and each dependency's exported ones as
212    //     `<alias>.<unit>`.
213    if is_uses_target(line_prefix) {
214        return usable_commons(doc_text, &split());
215    }
216    // 3. After `given …` — in-scope capabilities.
217    if is_given_position(line_prefix) {
218        return in_scope_capabilities(doc_text, &split());
219    }
220    // 3b. #3386: `auth = <cursor>` — the actor schemes, and inside `SignedCookie(` its keys.
221    if let Some(keys) = signed_cookie_key_candidates(line_prefix) {
222        return keys;
223    }
224    if auth_scheme_position(line_prefix) {
225        return auth_scheme_candidates();
226    }
227    // 3c. #3446: `Record.field.<cursor>` on a cookie record — the typed cookie write and deletion.
228    if let Some((record, field)) = cookie_field_receiver(line_prefix) {
229        return cookie_field_members(&record, &field, doc_text, files);
230    }
231    // 3d. #3947: `<int>.<cursor>` — the `Duration` units that agree with the number.
232    if let Some(units) = crate::duration_completion::duration_unit_candidates(line_prefix) {
233        return units;
234    }
235    // 4. `UpperIdent.<cursor>` — name-receiver members: sum variants, refined/
236    //    opaque `of`/`unsafe`, capability ops, or built-in type statics.
237    if let Some(receiver) = member_receiver(line_prefix) {
238        let mut items = member_candidates(&receiver, doc_text, files);
239        items.extend(cookie_record_fields(&receiver, doc_text, files));
240        return items;
241    }
242    // v0.124 (slice 3): the non-keyword clause/construction contexts, before the
243    // generic type/keyword/expression cells they would otherwise fall into.
244    // 4a-pre. #2641: `Type { <cursor>` in a *pattern* — the fields not yet
245    //     listed, then `..` (a record pattern always ends with it).
246    if let Some((recv, listed)) = record_pattern_receiver(line_prefix) {
247        let mut fields = record_field_names(&recv, doc_text, files);
248        if !fields.is_empty() {
249            fields.retain(|c| !listed.contains(&c.label));
250            fields.push(Completion::item(
251                "..",
252                CompletionKind::Keyword,
253                Some("the rest of the fields — a record pattern is always open".to_string()),
254            ));
255            return fields;
256        }
257    }
258    // 4a. `Type { <cursor>` — record field names on construction.
259    if let Some(recv) = record_construction_receiver(line_prefix) {
260        let fields = record_field_names(&recv, doc_text, files);
261        if !fields.is_empty() {
262            return fields;
263        }
264    }
265    // 4b. `from <cursor>` — the service protocols.
266    if after_clause_keyword(line_prefix, "from") {
267        return protocol_candidates();
268    }
269    // 4c. `on <cursor>` — the handler kinds.
270    if after_clause_keyword(line_prefix, "on") {
271        return handler_kind_candidates();
272    }
273    // 4d. `by <cursor>` — the project's actor names, where `by` is the clause
274    //     word. #3191: `by` is also an ordinary name, so a variable named `by`
275    //     followed by an operator is not offered actors.
276    if is_by_clause_position(line_prefix) {
277        return actor_candidates(doc_text, files);
278    }
279    // 4e. `exports <cursor>` — the export kinds (adapter).
280    if after_clause_keyword(line_prefix, "exports") {
281        return export_kind_candidates();
282    }
283    // 4f. `provides <cursor>` — the in-scope capabilities to implement.
284    if after_clause_keyword(line_prefix, "provides") {
285        return in_scope_capabilities(doc_text, &split());
286    }
287    // 4f''. Constrained generics slice 1: `… derives <cursor>` / `derives Ord + <cursor>`
288    //      — the derivable constraint; and `derives` itself after a type's body.
289    if is_derives_list_position(line_prefix) {
290        return derivable_candidates();
291    }
292    if is_after_type_body(line_prefix, doc_text) {
293        return vec![derives_keyword_candidate()];
294    }
295    // 4f'. Constrained generics slice 0: `fn f[T: <cursor>` / `where A: <cursor>`
296    //      — the constraint names.
297    if is_constraint_position(line_prefix) {
298        return constraint_candidates();
299    }
300    // 4g'. #3890: `actor A = Caller where <cursor>` — the `Caller` predicate.
301    if is_caller_refinement_where(line_prefix) {
302        return vec![Completion::snippet("IsContext", "IsContext(${1:context})")];
303    }
304    // 4g. `where <cursor>` — the closed refinement-predicate vocabulary.
305    // Shared by a type declaration's `type X = Base where <cursor>` and
306    // (#472) a match arm's `_ where <cursor>`; both reuse the same closed
307    // predicate catalogue, so one branch serves both surfaces. Excludes a
308    // `for all x: T, … where <cursor>` binder's clause, which takes an
309    // arbitrary `Bool` expression, not the predicate catalogue — that case
310    // falls through to expression-position candidates below.
311    if after_clause_keyword(line_prefix, "where") && !is_for_all_where(line_prefix) {
312        return predicate_name_candidates();
313    }
314    // 4i. #2842: `expect <value> <cursor>` — the snapshot claim.
315    if is_snapshot_clause_position(line_prefix) {
316        return vec![Completion::snippet(
317            "matches snapshot",
318            "matches snapshot \"${1:name}\"",
319        )];
320    }
321    // 5. Type position (`: T`, `-> T`, `[ … ]` type args) — built-ins, the
322    //    `bynk`-surface transparent types, and project type declarations.
323    if is_type_position(line_prefix) {
324        return type_candidates(doc_text, files);
325    }
326    // 6. Keyword position (a bare word at a declaration/statement start) — the
327    //    reserved keywords plus declaration snippets.
328    if is_keyword_position(line_prefix) {
329        return keyword_and_snippet_candidates();
330    }
331    // 7. Expression position (after `=`/`(`/`,`/`=>`/a binary operator) — a value
332    //    starts here: the constructor keywords + in-scope type names. In-scope
333    //    locals/params (and, from slice 3, free functions) are appended
334    //    handler-side, where the analysis cache lives (ADR 0093 D3).
335    if is_expression_position(line_prefix) {
336        return expression_candidates(doc_text, files);
337    }
338    Vec::new()
339}
340
341// -- Cursor-context detection (line-prefix scanning) --
342
343/// #2842: the cursor follows a complete-looking `expect <value> ` on its line, or
344/// a start of `matches` there, and no snapshot clause is written yet: where
345/// `matches snapshot "<name>"` can go. Lexical, like its neighbours: the value is
346/// taken to end at a name, a closing bracket, a quote or a digit.
347fn is_snapshot_clause_position(line: &str) -> bool {
348    let rest = line.trim_start();
349    let Some(body) = rest.strip_prefix("expect") else {
350        return false;
351    };
352    if !body.starts_with(char::is_whitespace) || body.contains("matches") {
353        return false;
354    }
355    // The word being typed after the value, if any, must begin `matches`.
356    let typed = body
357        .rsplit(char::is_whitespace)
358        .next()
359        .filter(|w| !w.is_empty() && body.ends_with(*w));
360    let value = match typed {
361        Some(word) if "matches".starts_with(word) => body[..body.len() - word.len()].trim_end(),
362        Some(_) => return false,
363        None if body.ends_with(char::is_whitespace) => body.trim_end(),
364        None => return false,
365    };
366    let Some(last) = value.chars().last() else {
367        return false;
368    };
369    let ends_a_value = last.is_alphanumeric() || matches!(last, '_' | ')' | ']' | '}' | '"');
370    // A trailing keyword or word operator is not the end of a value.
371    let last_word = value
372        .rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
373        .next();
374    ends_a_value
375        && !matches!(
376            last_word,
377            Some("and" | "or" | "not" | "is" | "if" | "else" | "match" | "faults" | "called")
378        )
379}
380
381/// `consumes U { … ` with the brace still open at the cursor → `Some(U)`.
382fn consumes_brace_unit(line: &str) -> Option<String> {
383    let idx = line.rfind("consumes")?;
384    let after = &line[idx + "consumes".len()..];
385    let open = after.find('{')?;
386    // The brace must still be open up to the cursor (no closing brace after it).
387    if after[open + 1..].contains('}') {
388        return None;
389    }
390    let unit = after[..open].trim();
391    if unit.is_empty() || !is_qualified_name(unit) {
392        return None;
393    }
394    Some(unit.to_string())
395}
396
397/// #2887: the open `consumes U { … T as <partial>` ends at the alias being
398/// written: its last whole word before the partial one is `as`.
399fn names_a_brace_alias(line: &str) -> bool {
400    let tail = line.rsplit(['{', ',']).next().unwrap_or("");
401    let mut words = tail.split_whitespace().collect::<Vec<_>>();
402    if !tail.ends_with(char::is_whitespace) {
403        // The alias is partly typed; the word before it decides.
404        words.pop();
405    }
406    words.last() == Some(&"as")
407}
408
409/// `consumes <partial>` with no brace or `as` yet → completing the target name.
410fn is_consumes_target(line: &str) -> bool {
411    let Some(idx) = line.rfind("consumes") else {
412        return false;
413    };
414    // `consumes` must be a standalone keyword (preceded by start/whitespace).
415    if !line[..idx]
416        .chars()
417        .last()
418        .map(|c| c.is_whitespace())
419        .unwrap_or(true)
420    {
421        return false;
422    }
423    let after = &line[idx + "consumes".len()..];
424    // Need at least one separating space, and no `{`, `}`, or `as` yet.
425    after.starts_with(char::is_whitespace)
426        && !after.contains('{')
427        && !after.contains('}')
428        && !after.split_whitespace().any(|w| w == "as")
429}
430
431/// #2223: `uses <partial>` as a unit header clause → completing the target.
432fn is_uses_target(line: &str) -> bool {
433    let trimmed = line.trim_start();
434    let Some(after) = trimmed.strip_prefix("uses") else {
435        return false;
436    };
437    after.starts_with(char::is_whitespace) && after.split_whitespace().count() <= 1
438}
439
440/// Constrained generics slice 0: the cursor follows the `:` (or a `+`) of a
441/// bound — inside a `fn`/`type` type-parameter list (`fn f[T: <cursor>`), or in
442/// a method's `where` clause (`-> Bool where A: <cursor>`). The partial
443/// constraint name being typed is stripped first.
444fn is_constraint_position(line: &str) -> bool {
445    let head = line
446        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
447        .trim_end();
448    if !(head.ends_with(':') && !head.ends_with("::") || head.ends_with('+')) {
449        return false;
450    }
451    // Inside a still-open `[ … ]` that a `fn name` / `type Name` opened.
452    if let Some(open) = head.rfind('[')
453        && !head[open..].contains(']')
454    {
455        let before = head[..open].trim_end();
456        let name_start = before
457            .rfind(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '.')))
458            .map_or(0, |i| i + 1);
459        let decl = before[..name_start].trim_end();
460        return decl.ends_with("fn") || decl.ends_with("type");
461    }
462    // A `where` clause after a return type: only names, `:`, `,`, `+` since it.
463    if let Some(w) = head.rfind("where")
464        && line[..w].contains("->")
465        && head[..w].chars().last().is_none_or(char::is_whitespace)
466    {
467        return head[w + "where".len()..]
468            .chars()
469            .all(|c| c.is_alphanumeric() || matches!(c, '_' | ':' | ',' | '+' | ' ' | '\t'));
470    }
471    false
472}
473
474/// The constraints a bound may name: `Eq`, `Ord`, `Key` and `Codable`. Mirrors the checker's
475/// `CONSTRAINTS`; `constraint_names_match_the_checker` pins the two together.
476const BOUND_CONSTRAINTS: &[(&str, &str)] = &[
477    ("Eq", "constraint: values of the type compare with `==`"),
478    (
479        "Ord",
480        "constraint: values of the type are ordered (`<`, `<=`, `>`, `>=`); implies `Eq`",
481    ),
482    (
483        "Key",
484        "constraint: values of the type key a `Map` or `Set`; implies `Eq`",
485    ),
486    (
487        "Codable",
488        "constraint: values of the type encode and decode with `Json`, and cross a capability operation as JSON",
489    ),
490];
491
492/// The constraint names a bound offers.
493fn constraint_candidates() -> Vec<Completion> {
494    BOUND_CONSTRAINTS
495        .iter()
496        .map(|(name, doc)| {
497            Completion::item(*name, CompletionKind::Constraint, Some((*doc).to_string()))
498        })
499        .collect()
500}
501
502/// What `derives` accepts: `Ord` only — `Eq`, `Key` and `Codable` are automatic.
503fn derivable_candidates() -> Vec<Completion> {
504    vec![Completion::item(
505        "Ord",
506        CompletionKind::Constraint,
507        Some("derive `Ord`: order the type by declaration order".to_string()),
508    )]
509}
510
511fn derives_keyword_candidate() -> Completion {
512    Completion::item(
513        "derives",
514        CompletionKind::Keyword,
515        Some(
516            "opt the type into a constraint (`derives Ord`): ordered by declaration order"
517                .to_string(),
518        ),
519    )
520}
521
522/// Constrained generics slice 1: the cursor follows `derives` or a `+` in a
523/// `derives` list (a partial name being typed is stripped first).
524fn is_derives_list_position(line: &str) -> bool {
525    let head = line.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
526    let before = head.trim_end();
527    // A gap before the cursor, so `derives` / `Ord` is a finished word.
528    if !(head.ends_with(char::is_whitespace) || before.ends_with('+')) {
529        return false;
530    }
531    let Some(at) = before.rfind("derives") else {
532        return false;
533    };
534    // `derives` must be a whole word (not `redrives`).
535    if !before[..at].chars().last().is_none_or(char::is_whitespace) {
536        return false;
537    }
538    let after = &before[at + "derives".len()..];
539    after
540        .chars()
541        .all(|c| c.is_alphanumeric() || matches!(c, '_' | '+' | ' ' | '\t'))
542        && (after.trim().is_empty() || after.trim_end().ends_with('+'))
543}
544
545/// Constrained generics slice 1: the cursor sits after a type declaration's
546/// body, where an optional `derives` clause may follow — after a record's or
547/// enum's `}`, a pipe-sum's last variant, or a refined/opaque base. The line
548/// prefix alone is read, so a multi-line body is recognised by its closing
549/// `}` at the start of a line when the document has an unclosed `type … {`.
550fn is_after_type_body(line: &str, doc_text: &str) -> bool {
551    let head = line.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
552    // A separating space, or a bare `}` straight before the cursor.
553    if !head.ends_with(char::is_whitespace) && !head.ends_with('}') {
554        return false;
555    }
556    let rest = head.trim_end();
557    if rest.is_empty() || line.split_whitespace().any(|w| w == "derives") {
558        return false;
559    }
560    let balanced = |s: &str| {
561        s.matches('{').count() == s.matches('}').count()
562            && s.matches('(').count() == s.matches(')').count()
563            && s.matches('[').count() == s.matches(']').count()
564    };
565    let trimmed = rest.trim_start();
566    if trimmed.starts_with("type ") || trimmed.starts_with("type\t") {
567        // `type X[..] = <body>`: a non-empty body that ends like a complete one.
568        let Some(eq) = trimmed.find('=') else {
569            return false;
570        };
571        let body = trimmed[eq + 1..].trim();
572        if body.is_empty() || !balanced(trimmed) {
573            return false;
574        }
575        let last_word = body
576            .rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
577            .next()
578            .unwrap_or("");
579        let ends_open = body
580            .ends_with(['=', '|', ',', '+', ':', '.', '>', '<', '(', '{', '[', '&'])
581            || matches!(
582                last_word,
583                "where" | "enum" | "opaque" | "and" | "or" | "implies"
584            );
585        return !ends_open && !body.ends_with("->");
586    }
587    // A multi-line body's closing `}` on its own line.
588    if rest == "}" && !line.starts_with(char::is_whitespace) {
589        return doc_text.lines().any(|l| {
590            l.starts_with("type ")
591                && l.matches('{').count() > l.matches('}').count()
592                && !l.contains("derives")
593        });
594    }
595    false
596}
597
598/// The cursor is inside a `given` list (after `given`, before the `{` body).
599fn is_given_position(line: &str) -> bool {
600    let Some(idx) = line.rfind("given") else {
601        return false;
602    };
603    if !line[..idx]
604        .chars()
605        .last()
606        .map(|c| c.is_whitespace())
607        .unwrap_or(true)
608    {
609        return false;
610    }
611    let after = &line[idx + "given".len()..];
612    if !after.starts_with(char::is_whitespace) {
613        return false;
614    }
615    // Still in the given list while only capability names, dots, commas and
616    // whitespace follow — a `{` opens the handler body.
617    after
618        .chars()
619        .all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | ',' | ' ' | '\t'))
620}
621
622fn is_qualified_name(s: &str) -> bool {
623    !s.is_empty()
624        && s.split('.').all(|seg| {
625            !seg.is_empty()
626                && seg.chars().all(|c| c.is_alphanumeric() || c == '_')
627                && !seg.chars().next().unwrap().is_ascii_digit()
628        })
629}
630
631/// The cursor sits in a type position: a return type (`-> T`), a type
632/// annotation/field type (`: T`), or inside a `[ … ]` type-argument list. The
633/// partial type name being typed is stripped before inspecting the preceding
634/// token, so `: Optio` and `-> Eff` both qualify.
635///
636/// Conservative by construction: a list literal `[1, 2` is excluded (its `[` is
637/// not preceded by a type constructor). The one accepted false positive is a
638/// record *construction* value (`Order { id: <cursor>`), lexically identical to
639/// a record field-type declaration — offering type names there is mild noise.
640fn is_type_position(line: &str) -> bool {
641    let head = line
642        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
643        .trim_end();
644    head.ends_with("->") || (head.ends_with(':') && !head.ends_with("::")) || in_type_arg_list(head)
645}
646
647/// `head` ends inside an unclosed `[ … ` whose opening bracket immediately
648/// follows an identifier (a type constructor, e.g. `Option[`, `Result[Int, `) —
649/// as opposed to a bare list-literal `[`.
650fn in_type_arg_list(head: &str) -> bool {
651    let chars: Vec<char> = head.chars().collect();
652    let mut depth = 0i32;
653    let mut opener_after_ident = false;
654    for (i, &c) in chars.iter().enumerate() {
655        match c {
656            '[' => {
657                depth += 1;
658                if depth == 1 {
659                    opener_after_ident =
660                        i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_');
661                }
662            }
663            ']' => depth -= 1,
664            _ => {}
665        }
666    }
667    depth > 0 && opener_after_ident
668}
669
670/// A bare word at a declaration/statement start: the line up to the cursor is
671/// only leading whitespace plus an optional partial identifier (no operators,
672/// colons, or brackets). Fires on an empty line too. Disjoint from
673/// `is_type_position` (an internal helper), whose triggers (`:`/`->`/`[`) make
674/// this false.
675pub fn is_keyword_position(line: &str) -> bool {
676    line.trim().chars().all(|c| c.is_alphanumeric() || c == '_')
677}
678
679/// The cursor sits where a **value** expression is expected — after `=`/`(`/`,`,
680/// a `=>` lambda arrow, or a binary operator — so in-scope locals are offered
681/// (v0.31, ADR 0064). Conservative: covers the common positions, excludes the
682/// type arrow `->`. (The handler also offers locals at keyword position.)
683pub fn is_expression_position(line: &str) -> bool {
684    let head = line
685        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
686        .trim_end();
687    if head.ends_with("->") {
688        return false; // a return/param type, not a value
689    }
690    if head.ends_with("=>") {
691        return true; // a lambda body
692    }
693    matches!(
694        head.chars().last(),
695        Some('=' | '(' | ',' | '[' | '+' | '-' | '*' | '/' | '<' | '>' | '&' | '|')
696    )
697}
698
699/// `UpperIdent.<partial>` at the cursor → `Some("UpperIdent")` — a name
700/// receiver whose members are statically enumerable (a sum/refined/opaque
701/// type or a capability). Conservative: the receiver is a **single**
702/// uppercase-initial identifier, not itself a `.`-qualified segment (so
703/// `bynk.cloudflare.` and `a.B.` are excluded) and not a number (so the
704/// decimal `1.` is excluded). A lowercase `x.` is a *value* receiver — deferred
705/// to slice 3 — and yields `None`.
706fn member_receiver(line: &str) -> Option<String> {
707    // Drop the partial member name being typed, then require a trailing dot.
708    let head = line
709        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
710        .strip_suffix('.')?;
711    // The receiver is the identifier immediately before that dot. Advance past
712    // the matched char by its UTF-8 length: a multi-byte non-identifier char
713    // (`"`, `€`, `—`, …) would make `i + 1` land mid-codepoint and panic.
714    let start = head
715        .char_indices()
716        .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
717        .map_or(0, |(i, c)| i + c.len_utf8());
718    let recv = &head[start..];
719    let first = recv.chars().next()?;
720    if !first.is_ascii_uppercase() {
721        return None;
722    }
723    // Reject a `.`-qualified receiver (`a.B.`): the char before it is a dot.
724    if head[..start].ends_with('.') {
725        return None;
726    }
727    Some(recv.to_string())
728}
729
730/// #3446: `Record.field.<partial>` at the cursor → `Some(("Record", "field"))`: an uppercase-initial
731/// record name, a lowercase field, then the dot being completed.
732fn cookie_field_receiver(line: &str) -> Option<(String, String)> {
733    let head = line
734        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
735        .strip_suffix('.')?;
736    let is_ident = |c: char| c.is_alphanumeric() || c == '_';
737    let field_start = head
738        .char_indices()
739        .rfind(|&(_, c)| !is_ident(c))
740        .map_or(0, |(i, c)| i + c.len_utf8());
741    let field = &head[field_start..];
742    if field.is_empty() || !field.starts_with(|c: char| c.is_ascii_lowercase()) {
743        return None;
744    }
745    let before = head[..field_start].strip_suffix('.')?;
746    let record = member_receiver(&format!("{before}."))?;
747    Some((record, field.to_string()))
748}
749
750/// #3446: the records of this source that some `on http` handler takes as its `cookies` parameter,
751/// with each one's fields as `(name, type, wire name)`.
752pub(crate) fn cookie_record_fields_of(
753    record: &str,
754    doc_text: &str,
755    files: Option<&HashMap<PathBuf, String>>,
756) -> Option<Vec<(String, bynk_syntax::ast::TypeRef, String)>> {
757    use bynk_syntax::ast::{HandlerKind, TypeBody};
758    let mut decl: Option<Vec<(String, bynk_syntax::ast::TypeRef, String)>> = None;
759    let mut taken_as_cookies = false;
760    for_each_unit(doc_text, files, |unit| {
761        let items = match unit {
762            SourceUnit::Commons(c) => &c.items,
763            SourceUnit::Context(c) => &c.items,
764            _ => return,
765        };
766        for item in items {
767            match item {
768                CommonsItem::Type(t) if t.name.name == record => {
769                    if let TypeBody::Record(r) = &t.body {
770                        decl = Some(
771                            r.fields
772                                .iter()
773                                .map(|f| {
774                                    (
775                                        f.name.name.clone(),
776                                        f.type_ref.clone(),
777                                        f.wire_name().unwrap_or_else(|| f.name.name.clone()),
778                                    )
779                                })
780                                .collect(),
781                        );
782                    }
783                }
784                CommonsItem::Service(svc) => {
785                    taken_as_cookies |= svc.handlers.iter().any(|h| {
786                        matches!(h.kind, HandlerKind::Http { .. })
787                            && h.params.iter().any(|p| {
788                                p.name.name == "cookies"
789                                    && matches!(&p.type_ref,
790                                        bynk_syntax::ast::TypeRef::Named(id) if id.name == record)
791                            })
792                    });
793                }
794                _ => {}
795            }
796        }
797    });
798    decl.filter(|_| taken_as_cookies)
799}
800
801/// #3446: after `Record.` on a cookie record, its fields: each is written with `.cookie(v)` or
802/// removed with `.expire()`.
803fn cookie_record_fields(
804    record: &str,
805    doc_text: &str,
806    files: Option<&HashMap<PathBuf, String>>,
807) -> Vec<Completion> {
808    cookie_record_fields_of(record, doc_text, files)
809        .unwrap_or_default()
810        .into_iter()
811        .map(|(name, ty, wire)| {
812            Completion::item(
813                name,
814                CompletionKind::Field,
815                Some(format!(
816                    "{} — cookie `{wire}` of `{record}`; `.cookie(v)` writes it, `.expire()` removes it",
817                    crate::symbols::type_ref_str(&ty)
818                )),
819            )
820        })
821        .collect()
822}
823
824/// #3446: after `Record.field.`, `cookie(value)` and `expire()`.
825fn cookie_field_members(
826    record: &str,
827    field: &str,
828    doc_text: &str,
829    files: Option<&HashMap<PathBuf, String>>,
830) -> Vec<Completion> {
831    let Some(fields) = cookie_record_fields_of(record, doc_text, files) else {
832        return Vec::new();
833    };
834    let Some((_, ty, wire)) = fields.into_iter().find(|(n, _, _)| n == field) else {
835        return Vec::new();
836    };
837    let value = match &ty {
838        bynk_syntax::ast::TypeRef::Option(inner, _) => crate::symbols::type_ref_str(inner),
839        other => crate::symbols::type_ref_str(other),
840    };
841    vec![
842        Completion::item(
843            "cookie".to_string(),
844            CompletionKind::Member,
845            Some(format!(
846                "cookie(value: {value}) -> Cookie — the cookie `{wire}`, valued as `{record}`'s decoder reads it"
847            )),
848        ),
849        Completion::item(
850            "expire".to_string(),
851            CompletionKind::Member,
852            Some(format!("expire() -> Cookie — deletes the cookie `{wire}`")),
853        ),
854    ]
855}
856
857/// v0.124 (slice 3): the cursor is at a field-*name* position of a record
858/// construction — inside an unclosed `{` opened immediately after an
859/// uppercase-initial type name (`Order { <cursor>` / `Order { id: 1, <cursor>`),
860/// with the current field segment not yet past its `:` (a field *type*
861/// position, left to [`is_type_position`]). Returns the record type name.
862fn record_construction_receiver(line: &str) -> Option<String> {
863    // The innermost `{` still open at the cursor.
864    let bytes = line.as_bytes();
865    let mut depth = 0i32;
866    let mut open = None;
867    for i in (0..bytes.len()).rev() {
868        match bytes[i] {
869            b'}' => depth += 1,
870            b'{' => {
871                if depth == 0 {
872                    open = Some(i);
873                    break;
874                }
875                depth -= 1;
876            }
877            _ => {}
878        }
879    }
880    let open = open?;
881    // Only at a name position: the current field (since the last comma) has no
882    // `:` yet — else the cursor is in that field's type.
883    let current = line[open + 1..].rsplit(',').next().unwrap_or("");
884    if current.contains(':') {
885        return None;
886    }
887    // The receiver is the uppercase-initial identifier immediately before `{`.
888    let head = line[..open].trim_end();
889    let start = head
890        .char_indices()
891        .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
892        .map_or(0, |(i, c)| i + c.len_utf8());
893    let recv = &head[start..];
894    if recv.chars().next()?.is_ascii_uppercase() {
895        Some(recv.to_string())
896    } else {
897        None
898    }
899}
900
901/// #2712: `head` (the text before a record type name) ends inside a lambda's
902/// parameter list — `items.map((`, `items.fold(0, (total, ` — so a record type
903/// name there opens a pattern parameter. The lambda's `(` must itself be a call
904/// argument (preceded by `(` or `,`), which keeps a parenthesised record
905/// construction (`let o = (Order {`) out; the parameters before the cursor must
906/// each be a name or a braced pattern.
907fn lambda_param_position(head: &str) -> bool {
908    let mut depth = 0i32;
909    let mut open = None;
910    for (i, c) in head.char_indices().rev() {
911        match c {
912            ')' => depth += 1,
913            '(' if depth == 0 => {
914                open = Some(i);
915                break;
916            }
917            '(' => depth -= 1,
918            _ => {}
919        }
920    }
921    let Some(open) = open else { return false };
922    let before = head[..open].trim_end();
923    if !(before.ends_with('(') || before.ends_with(',')) {
924        return false;
925    }
926    let mut segments = Vec::new();
927    let mut depth = 0i32;
928    let mut segment = String::new();
929    for c in head[open + 1..].chars() {
930        match c {
931            '(' | '{' | '[' => depth += 1,
932            ')' | '}' | ']' => depth -= 1,
933            ',' if depth == 0 => {
934                segments.push(std::mem::take(&mut segment));
935                continue;
936            }
937            _ => {}
938        }
939        segment.push(c);
940    }
941    let current = segment.trim().is_empty();
942    current
943        && segments.iter().all(|seg| {
944            let seg = seg.trim();
945            let name = seg.split(':').next().unwrap_or("").trim();
946            seg.ends_with('}')
947                || (!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_'))
948        })
949}
950
951/// #2641: the cursor is at a field-name position of a record *pattern* —
952/// `Type { <cursor>` where the text before `Type` is only pattern syntax (a
953/// match arm's start, `Some(`, `is (`, `let `, `field: `, `|`), never an
954/// expression (`let o = Type {`). Returns the type name and the fields already listed.
955fn record_pattern_receiver(line: &str) -> Option<(String, Vec<String>)> {
956    let recv = record_construction_receiver(line)?;
957    let open = line.rfind('{')?;
958    // Only the segment after `is` (the pattern) or the whole line (a match arm).
959    let head = line[..open].trim_end();
960    let head = head.strip_suffix(recv.as_str())?;
961    let after_is = head
962        .rsplit_once(" is ")
963        .map_or(head, |(_, pattern)| pattern);
964    // What precedes the type name must be pattern syntax only: separators, an
965    // uppercase constructor before `(`, or a field name before `:`.
966    let mut rest = after_is.trim_start();
967    // #2654: a `let` opens a pattern too — `let Item { <cursor>`. An ordinary
968    // `let o = Item {` leaves the `o =` behind, which is not pattern syntax.
969    if let Some(after_let) = rest.strip_prefix("let ") {
970        rest = after_let;
971    }
972    loop {
973        let before = rest;
974        rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '(' || c == '|');
975        let ident_end = rest
976            .find(|c: char| !(c.is_alphanumeric() || c == '_'))
977            .unwrap_or(rest.len());
978        let (ident, tail) = rest.split_at(ident_end);
979        let tail_trim = tail.trim_start();
980        if !ident.is_empty()
981            && ((tail_trim.starts_with('(') && ident.starts_with(|c: char| c.is_ascii_uppercase()))
982                || (tail_trim.starts_with(':') && !tail_trim.starts_with("::")))
983        {
984            rest = &tail_trim[1..];
985        }
986        if rest == before {
987            break;
988        }
989    }
990    if !rest.trim().is_empty() && !lambda_param_position(head) {
991        return None;
992    }
993    // The fields already listed at this brace's top level.
994    let mut listed = Vec::new();
995    let mut depth = 0i32;
996    let mut segment = String::new();
997    for c in line[open + 1..].chars() {
998        match c {
999            '(' | '{' | '[' => depth += 1,
1000            ')' | '}' | ']' => depth -= 1,
1001            ',' if depth == 0 => {
1002                let name = segment.split(':').next().unwrap_or("").trim();
1003                if !name.is_empty() {
1004                    listed.push(name.to_string());
1005                }
1006                segment.clear();
1007                continue;
1008            }
1009            _ => {}
1010        }
1011        segment.push(c);
1012    }
1013    Some((recv, listed))
1014}
1015
1016/// v0.131: the CORS policy fields, offered at a field-name position inside a
1017/// `cors { }` block. `Allow-Methods` is deliberately absent (derived from the
1018/// routes), so the closed set is these four.
1019pub const CORS_FIELDS: &[(&str, &str)] = &[
1020    (
1021        "origins",
1022        "the allowed origins — an exact allowlist, or `[\"*\"]`",
1023    ),
1024    (
1025        "headers",
1026        "the `Access-Control-Allow-Headers` a preflight advertises",
1027    ),
1028    (
1029        "credentials",
1030        "whether credentialed requests are allowed (`true`/`false`)",
1031    ),
1032    (
1033        "maxAge",
1034        "how long a browser may cache the preflight (a `Duration`)",
1035    ),
1036];
1037
1038/// v0.141 (ADR 0164): the security-headers policy fields, offered at a field-name
1039/// position inside a `security { }` block. The closed set is these two.
1040pub const SECURITY_FIELDS: &[(&str, &str)] = &[
1041    (
1042        "nosniff",
1043        "stamp `X-Content-Type-Options: nosniff` (`true`/`false`, default `true`)",
1044    ),
1045    (
1046        "hsts",
1047        "opt in to `Strict-Transport-Security` — the `max-age` as a `Duration`",
1048    ),
1049];
1050
1051/// v0.142 (ADR 0165): the request-limits policy fields, offered at a field-name
1052/// position inside a `limits { }` block. The closed set is this one.
1053pub const LIMITS_FIELDS: &[(&str, &str)] = &[
1054    (
1055        "maxBody",
1056        "the maximum request body size in bytes (a positive `Int`)",
1057    ),
1058    (
1059        "maxFile",
1060        "the maximum size in bytes of one file part of a `@multipart` body (a positive `Int`)",
1061    ),
1062    (
1063        "maxParts",
1064        "the maximum number of parts of a `@multipart` body (a positive `Int`; default 64)",
1065    ),
1066];
1067
1068/// #2858: the response-JSON policy fields, offered at a field-name position
1069/// inside a `json { }` block (and as `@json( … )` arguments). The closed set is
1070/// this one.
1071pub const JSON_FIELDS: &[(&str, &str)] = &[(
1072    "options",
1073    "how `Option` is written in response bodies: `tagged` (Bynk's `{\"kind\": …}` form) or `plain` (`v` / `null`)",
1074)];
1075
1076/// #2858: the values of a `json` / `@json` `options`.
1077pub const JSON_OPTIONS_VALUES: &[(&str, &str)] = &[
1078    (
1079        "tagged",
1080        "Bynk's tagged form: `{\"kind\": \"Some\", \"value\": v}` / `{\"kind\": \"None\"}` (the default)",
1081    ),
1082    (
1083        "plain",
1084        "plain JSON for non-Bynk clients: `Some(v)` is `v`, `None` is `null`",
1085    ),
1086];
1087
1088/// #2686: whether the cursor follows `@` (and any partial name) after a
1089/// `where … Matches(…)` / `IsoDate` refinement on the line: a type declaration
1090/// or a record field, where `@example` may go.
1091pub fn in_refinement_annotation_position(line_prefix: &str) -> bool {
1092    let Some(at) = line_prefix.rfind('@') else {
1093        return false;
1094    };
1095    let partial = &line_prefix[at + 1..];
1096    if !partial.chars().all(|c| c.is_alphanumeric() || c == '_') {
1097        return false;
1098    }
1099    let before = &line_prefix[..at];
1100    before.contains(" where ")
1101        && (before.contains("Matches(") || before.contains("IsoDate") || before.contains("Cron"))
1102        && !before.contains("@example")
1103}
1104
1105/// v0.140 (ADR 0163): the `@cache` handler-annotation arguments, offered at an
1106/// argument-name position inside `@cache( … )`. `maxAge` is required (the freshness
1107/// window); `scope` is optional (`public`/`private`, default `private`), as is
1108/// `immutable` (caching raw responses; default `false`). The conditional
1109/// `ETag`/`304` half is automatic and has no surface.
1110pub const CACHE_ARGS: &[(&str, &str)] = &[
1111    (
1112        "maxAge",
1113        "the freshness window — a whole-second `Duration` (e.g. `5.minutes`) lowered to `Cache-Control: max-age`",
1114    ),
1115    (
1116        "scope",
1117        "`public` or `private` (default `private` — a shared cache stores only on `public`)",
1118    ),
1119    (
1120        "immutable",
1121        "`true` promises the response never changes (a content-addressed path) — appends `immutable` to `Cache-Control`; purge it through `EdgeCache` if it can change; default `false`",
1122    ),
1123];
1124
1125/// v0.142 (ADR 0165): the `@limit` handler-annotation arguments, offered at an
1126/// argument-name position inside `@limit( … )`. Its one arg is `maxBody`, the
1127/// request-body byte ceiling above which a `413` is synthesised before the body
1128/// is read.
1129pub const LIMIT_ARGS: &[(&str, &str)] = &[
1130    (
1131        "maxBody",
1132        "the maximum request body size in bytes (a positive `Int`) — a `413` is synthesised past it",
1133    ),
1134    (
1135        "maxFile",
1136        "on a `@multipart` route, the maximum size in bytes of one file part — a `413` past it",
1137    ),
1138    (
1139        "maxParts",
1140        "on a `@multipart` route, the maximum number of parts — a `413` past it",
1141    ),
1142];
1143
1144/// The `@raw` handler-annotation arguments, offered at an argument-name position
1145/// inside `@raw( … )`. Its one arg is `contentType`, the media type the route accepts
1146/// (`"*/*"` for any).
1147pub const RAW_ARGS: &[(&str, &str)] = &[(
1148    "contentType",
1149    "the media type the route accepts, a string literal (`\"*/*\"` for any) — another `Content-Type` is a `415`",
1150)];
1151
1152/// #2854: the special parameter names an `on http` handler may declare beside
1153/// its `:name` path parameters, offered at a parameter-*name* position, with the
1154/// type each takes.
1155pub const HTTP_PARAMS: &[(&str, &str, &str)] = &[
1156    (
1157        "query",
1158        "RequestQuery",
1159        "the query string: a record `T` decoded and validated before the handler runs (`400` on a violation), or a raw `RequestQuery` view",
1160    ),
1161    (
1162        "headers",
1163        "RequestHeaders",
1164        "the request's headers, read-only",
1165    ),
1166    (
1167        "cookies",
1168        "T",
1169        "the request's cookies: a record `T` decoded from the `Cookie` header and validated before the handler runs (`400` on a violation), or a raw `RequestCookies` view",
1170    ),
1171    (
1172        "cf",
1173        "RequestCf",
1174        "what Cloudflare derived about the connection (country, colo, ASN, …); every field is optional (Cloudflare only: `consumes bynk.cloudflare { RequestCf }`)",
1175    ),
1176    (
1177        "body",
1178        "T",
1179        "the request body, parsed and validated before the handler runs (not on `GET` or `DELETE`)",
1180    ),
1181];
1182
1183/// #2854: the cursor is at a parameter-*name* position in the parameter list of an
1184/// `on <METHOD>("…") ( … )` HTTP handler header: the innermost open paren follows
1185/// the route's closing `)`, itself opened by an HTTP method after `on`, and the
1186/// current parameter (since the last `,`) has no `:` yet.
1187pub fn in_http_param_name_position(text: &str, offset: usize) -> bool {
1188    let Some(open) = innermost_open_paren(text, offset) else {
1189        return false;
1190    };
1191    let head = text[..open].trim_end();
1192    if !head.ends_with(')') {
1193        return false;
1194    }
1195    let Some(route_open) = innermost_open_paren(head, head.len() - 1) else {
1196        return false;
1197    };
1198    let before = text[..route_open].trim_end();
1199    let Some(method_start) = before
1200        .rfind(|c: char| !c.is_ascii_alphanumeric())
1201        .map(|i| i + 1)
1202    else {
1203        return false;
1204    };
1205    if !matches!(
1206        &before[method_start..],
1207        "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
1208    ) {
1209        return false;
1210    }
1211    if !before[..method_start].trim_end().ends_with("on") {
1212        return false;
1213    }
1214    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1215        return false;
1216    };
1217    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1218    !current.contains(':')
1219}
1220
1221/// The byte index of the innermost `{` still open at `offset` (a naive scan that,
1222/// like [`record_construction_receiver`], does not skip braces inside strings or
1223/// comments — acceptable for a completion heuristic).
1224fn innermost_open_brace(text: &str, offset: usize) -> Option<usize> {
1225    let bytes = text.as_bytes();
1226    let end = offset.min(bytes.len());
1227    let mut depth = 0i32;
1228    for i in (0..end).rev() {
1229        match bytes[i] {
1230            b'}' => depth += 1,
1231            b'{' => {
1232                if depth == 0 {
1233                    return Some(i);
1234                }
1235                depth -= 1;
1236            }
1237            _ => {}
1238        }
1239    }
1240    None
1241}
1242
1243/// The bare word immediately before byte index `open` (skipping trailing
1244/// whitespace), e.g. the `cors` before a `cors {`.
1245fn word_before_brace(text: &str, open: usize) -> &str {
1246    let head = text[..open].trim_end();
1247    let start = head
1248        .char_indices()
1249        .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
1250        .map_or(0, |(i, c)| i + c.len_utf8());
1251    &head[start..]
1252}
1253
1254/// #2640: the cursor is directly inside a `par { … }` block — the innermost open
1255/// brace is opened by the word `par`.
1256pub fn in_par_block_position(text: &str, offset: usize) -> bool {
1257    innermost_open_brace(text, offset).is_some_and(|open| word_before_brace(text, open) == "par")
1258}
1259
1260/// #2640: what a `par { … }` block can hold, so nothing else is offered there:
1261/// the effectful binding and the unit effect (DECISION B).
1262pub fn par_block_candidates() -> Vec<Completion> {
1263    vec![
1264        Completion::snippet("let x <-", "let ${1:name} <- ${2:effect}"),
1265        Completion::item(
1266            "do",
1267            CompletionKind::Keyword,
1268            Some("run a unit effect alongside the others in this `par` block".to_string()),
1269        ),
1270    ]
1271}
1272
1273/// #2640: whether `offset` sits in an effectful body, the only place a `par`
1274/// block is legal. Lexical, like the other position cells: walk the enclosing
1275/// braces outwards; the first one whose header declares a return type decides —
1276/// effectful when that type is `Effect[…]`. A brace with no `->` (an `if`, a
1277/// `match` arm, a bare block) defers to the one around it.
1278pub fn in_effectful_body_position(text: &str, offset: usize) -> bool {
1279    let mut at = offset.min(text.len());
1280    while let Some(open) = innermost_open_brace(text, at) {
1281        let before = &text[..open];
1282        let header_start = before.rfind(['{', '}']).map_or(0, |i| i + 1);
1283        let header = &before[header_start..];
1284        if let Some(arrow) = header.rfind("->") {
1285            return header[arrow + 2..].trim_start().starts_with("Effect[");
1286        }
1287        at = open;
1288    }
1289    false
1290}
1291
1292/// #2640: the `par` block snippet, offered at statement position in an
1293/// effectful body.
1294pub fn par_snippet() -> Completion {
1295    Completion::snippet(
1296        "par",
1297        "par {\n\tlet ${1:first} <- ${2:effect}\n\tlet ${3:second} <- ${4:effect}\n}",
1298    )
1299}
1300
1301/// v0.131: the cursor is at a field-*name* position inside a `cors { … }` block —
1302/// the innermost open brace is opened by `cors`, and the current field segment
1303/// (since the last `,` or newline) has no `:` yet (a value position).
1304pub fn in_cors_field_position(text: &str, offset: usize) -> bool {
1305    let Some(open) = innermost_open_brace(text, offset) else {
1306        return false;
1307    };
1308    if word_before_brace(text, open) != "cors" {
1309        return false;
1310    }
1311    // `offset` arrives on a char boundary from the position converter, but
1312    // slice defensively — a mid-codepoint offset must degrade, not panic.
1313    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1314        return false;
1315    };
1316    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1317    !current.contains(':')
1318}
1319
1320/// v0.141: the cursor is at a field-*name* position inside a `security { … }`
1321/// block — the innermost open brace is opened by `security`, and the current
1322/// field segment has no `:` yet. Mirrors [`in_cors_field_position`].
1323pub fn in_security_field_position(text: &str, offset: usize) -> bool {
1324    let Some(open) = innermost_open_brace(text, offset) else {
1325        return false;
1326    };
1327    if word_before_brace(text, open) != "security" {
1328        return false;
1329    }
1330    // `offset` arrives on a char boundary from the position converter, but
1331    // slice defensively — a mid-codepoint offset must degrade, not panic.
1332    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1333        return false;
1334    };
1335    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1336    !current.contains(':')
1337}
1338
1339/// v0.142 (ADR 0165): the cursor is at a field-*name* position inside a
1340/// `limits { … }` block — the innermost open brace is opened by `limits`, and the
1341/// current field segment has no `:` yet. Mirrors [`in_security_field_position`].
1342pub fn in_limits_field_position(text: &str, offset: usize) -> bool {
1343    let Some(open) = innermost_open_brace(text, offset) else {
1344        return false;
1345    };
1346    if word_before_brace(text, open) != "limits" {
1347        return false;
1348    }
1349    // `offset` arrives on a char boundary from the position converter, but
1350    // slice defensively — a mid-codepoint offset must degrade, not panic.
1351    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1352        return false;
1353    };
1354    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1355    !current.contains(':')
1356}
1357
1358/// #2858: the cursor is at a field-*name* position inside a `json { … }` block.
1359/// Mirrors [`in_limits_field_position`].
1360pub fn in_json_field_position(text: &str, offset: usize) -> bool {
1361    let Some(open) = innermost_open_brace(text, offset) else {
1362        return false;
1363    };
1364    if word_before_brace(text, open) != "json" {
1365        return false;
1366    }
1367    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1368        return false;
1369    };
1370    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1371    !current.contains(':')
1372}
1373
1374/// #2858: the cursor is at the value of `options:` — inside `json { … }` or
1375/// `@json( … )` — where `tagged` / `plain` are offered.
1376pub fn in_json_options_value_position(text: &str, offset: usize) -> bool {
1377    let Some(head) = text.get(..offset.min(text.len())) else {
1378        return false;
1379    };
1380    let in_block = innermost_open_brace(text, offset)
1381        .is_some_and(|open| word_before_brace(text, open) == "json");
1382    let in_annotation = innermost_open_paren(text, offset).is_some_and(|open| {
1383        word_before_brace(text, open) == "json"
1384            && text[..open]
1385                .trim_end()
1386                .trim_end_matches("json")
1387                .trim_end()
1388                .ends_with('@')
1389    });
1390    if !in_block && !in_annotation {
1391        return false;
1392    }
1393    let line = head.rsplit(['\n', ',', '(', '{']).next().unwrap_or("");
1394    line.trim_start()
1395        .strip_prefix("options")
1396        .and_then(|rest| rest.trim_start().strip_prefix(':'))
1397        .is_some_and(|value| {
1398            value
1399                .chars()
1400                .all(|c| c.is_alphabetic() || c.is_whitespace())
1401        })
1402}
1403
1404/// #2858: the cursor is at an argument-*name* position inside a `@json( … )`
1405/// annotation. Mirrors [`in_cache_arg_position`].
1406pub fn in_json_arg_position(text: &str, offset: usize) -> bool {
1407    let Some(open) = innermost_open_paren(text, offset) else {
1408        return false;
1409    };
1410    if word_before_brace(text, open) != "json" {
1411        return false;
1412    }
1413    let head = text[..open].trim_end();
1414    let before = head[..head.len() - "json".len()].trim_end();
1415    if !before.ends_with('@') {
1416        return false;
1417    }
1418    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1419        return false;
1420    };
1421    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1422    !current.contains(':')
1423}
1424
1425/// #2134: the cursor is at an entry-*name* position inside a suite's or case's
1426/// `env { … }` block — the innermost open brace is opened by `env`, and the
1427/// current entry (since the last newline or `,`) has no `=` yet.
1428pub fn in_env_name_position(text: &str, offset: usize) -> bool {
1429    let Some(open) = innermost_open_brace(text, offset) else {
1430        return false;
1431    };
1432    if word_before_brace(text, open) != "env" {
1433        return false;
1434    }
1435    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1436        return false;
1437    };
1438    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1439    !current.contains('=')
1440}
1441
1442/// #2134: the names an `env` block can usefully give — each secret an actor
1443/// declares (`secret = "…"`, a Bearer, Signature or Foreign scheme) and each
1444/// literal name a `Secrets.get("…")` reads, across the buffer and the project's
1445/// files. A lexical scan, so it works mid-edit; sorted and deduplicated.
1446pub fn env_name_candidates(
1447    doc_text: &str,
1448    files: Option<&HashMap<PathBuf, String>>,
1449) -> Vec<Completion> {
1450    let mut names: BTreeMap<String, &'static str> = BTreeMap::new();
1451    let mut scan = |src: &str| {
1452        for (marker, detail) in [
1453            ("secret = \"", "a secret an actor declares"),
1454            ("Secrets.get(\"", "a name `Secrets.get` reads"),
1455        ] {
1456            let mut rest = src;
1457            while let Some(i) = rest.find(marker) {
1458                rest = &rest[i + marker.len()..];
1459                if let Some(end) = rest.find('"') {
1460                    let name = &rest[..end];
1461                    if !name.is_empty() && !name.contains(char::is_whitespace) {
1462                        names.entry(name.to_string()).or_insert(detail);
1463                    }
1464                }
1465            }
1466        }
1467    };
1468    scan(doc_text);
1469    if let Some(files) = files {
1470        for src in files.values() {
1471            scan(src);
1472        }
1473    }
1474    names
1475        .into_iter()
1476        .map(|(name, detail)| {
1477            let mut c = Completion::item(name.clone(), CompletionKind::Field, Some(detail.into()));
1478            c.insert_text = Some(format!("{name} = \"\""));
1479            c
1480        })
1481        .collect()
1482}
1483
1484/// v0.131: the cursor is at a service-body item start — a bare word inside a
1485/// `service … {` block (not a nested block) — where `cors` may begin, alongside
1486/// the `on` handler kinds. Gated on `is_keyword_position` so it only fires at a
1487/// fresh item start, and on the enclosing brace's header line naming `service`.
1488pub fn in_service_body_item_position(text: &str, offset: usize, line_prefix: &str) -> bool {
1489    if !is_keyword_position(line_prefix) {
1490        return false;
1491    }
1492    let Some(open) = innermost_open_brace(text, offset) else {
1493        return false;
1494    };
1495    let header_start = text[..open].rfind('\n').map_or(0, |i| i + 1);
1496    text[header_start..open].contains("service ")
1497}
1498
1499/// The byte index of the innermost `(` still open at `offset` — the paren analogue
1500/// of [`innermost_open_brace`], for `@cache( … )` argument-position detection.
1501fn innermost_open_paren(text: &str, offset: usize) -> Option<usize> {
1502    let bytes = text.as_bytes();
1503    let end = offset.min(bytes.len());
1504    let mut depth = 0i32;
1505    for i in (0..end).rev() {
1506        match bytes[i] {
1507            b')' => depth += 1,
1508            b'(' => {
1509                if depth == 0 {
1510                    return Some(i);
1511                }
1512                depth -= 1;
1513            }
1514            _ => {}
1515        }
1516    }
1517    None
1518}
1519
1520/// v0.140 (ADR 0163): the cursor is at an argument-*name* position inside a
1521/// `@cache( … )` — the innermost open paren is opened by the `cache` annotation
1522/// (`@cache`, not a bare `cache(` call), and the current argument segment (since
1523/// the last `,`) has no `:` yet (a name position, not a value one).
1524pub fn in_cache_arg_position(text: &str, offset: usize) -> bool {
1525    let Some(open) = innermost_open_paren(text, offset) else {
1526        return false;
1527    };
1528    if word_before_brace(text, open) != "cache" {
1529        return false;
1530    }
1531    // Distinguish the `@cache` annotation from any ordinary `cache(...)` call: the
1532    // word must be immediately preceded by `@`.
1533    let head = text[..open].trim_end();
1534    let before_cache = head[..head.len() - "cache".len()].trim_end();
1535    if !before_cache.ends_with('@') {
1536        return false;
1537    }
1538    // `offset` arrives on a char boundary from the position converter, but
1539    // slice defensively — a mid-codepoint offset must degrade, not panic.
1540    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1541        return false;
1542    };
1543    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1544    !current.contains(':')
1545}
1546
1547/// v0.142 (ADR 0165): the cursor is at an argument-*name* position inside a
1548/// `@limit( … )` — the innermost open paren is opened by the `limit` annotation
1549/// (`@limit`, not a bare `limit(` call), and the current argument segment has no
1550/// `:` yet. Mirrors [`in_cache_arg_position`].
1551pub fn in_limit_arg_position(text: &str, offset: usize) -> bool {
1552    let Some(open) = innermost_open_paren(text, offset) else {
1553        return false;
1554    };
1555    if word_before_brace(text, open) != "limit" {
1556        return false;
1557    }
1558    // Distinguish the `@limit` annotation from any ordinary `limit(...)` call: the
1559    // word must be immediately preceded by `@`.
1560    let head = text[..open].trim_end();
1561    let before_limit = head[..head.len() - "limit".len()].trim_end();
1562    if !before_limit.ends_with('@') {
1563        return false;
1564    }
1565    // P3 (#2342): `capability X = RateLimit @limit(…)` is an instance option,
1566    // not the handler annotation, so `maxBody` doesn't belong there.
1567    if on_capability_declaration(text, open) {
1568        return false;
1569    }
1570    // `offset` arrives on a char boundary from the position converter, but
1571    // slice defensively — a mid-codepoint offset must degrade, not panic.
1572    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1573        return false;
1574    };
1575    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1576    !current.contains(':')
1577}
1578
1579/// Whether the `(` at `open` is on a `capability X = Base @opt(…)` line: an
1580/// instance option, not a handler annotation.
1581fn on_capability_declaration(text: &str, open: usize) -> bool {
1582    let line_start = text[..open].rfind('\n').map_or(0, |i| i + 1);
1583    let line = text[line_start..open].trim_start();
1584    line.starts_with("capability ") && line.contains('=')
1585}
1586
1587/// P3 (#2342): the values offered for an instance option at its value
1588/// position, `capability X = RateLimit @period(▮`: the rate limiting windows.
1589/// Empty anywhere else.
1590pub fn instance_option_values(
1591    text: &str,
1592    offset: usize,
1593) -> &'static [(&'static str, &'static str)] {
1594    let Some(open) = innermost_open_paren(text, offset) else {
1595        return &[];
1596    };
1597    if !on_capability_declaration(text, open) {
1598        return &[];
1599    }
1600    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1601        return &[];
1602    };
1603    if !seg.trim().is_empty() {
1604        return &[];
1605    }
1606    let head = text[..open].trim_end();
1607    let before = head[..head.len() - word_before_brace(text, open).len()].trim_end();
1608    if !before.ends_with('@') {
1609        return &[];
1610    }
1611    match word_before_brace(text, open) {
1612        "period" => RATELIMIT_PERIODS,
1613        _ => &[],
1614    }
1615}
1616
1617/// P3 (#2342): the instance completions on a `capability X = …` line, as
1618/// `(label, detail, insert text)`: after the `=`, each instantiable platform
1619/// capability; after `= <Base> `, a snippet of the base's required options
1620/// (`@limit(${1:100}) @period(${2:60.seconds})`), when it has any. Empty
1621/// anywhere else.
1622pub fn instance_declaration_completions(line: &str) -> Vec<(String, String, String)> {
1623    let line = line.trim_start();
1624    let Some(rest) = line.strip_prefix("capability ") else {
1625        return Vec::new();
1626    };
1627    let Some((_, after)) = rest.split_once('=') else {
1628        return Vec::new();
1629    };
1630    let kinds = || {
1631        bynk_check::firstparty::UNITS
1632            .iter()
1633            .flat_map(|u| u.instantiable.iter().map(move |i| (u.name, i)))
1634    };
1635    let typed = after.trim_start();
1636    if !typed.contains(char::is_whitespace) {
1637        // The base being typed (or not yet begun).
1638        return kinds()
1639            .filter(|(_, i)| i.capability.starts_with(typed))
1640            .map(|(unit, i)| {
1641                (
1642                    i.capability.to_string(),
1643                    format!("an instance of `{unit}`'s `{}`", i.capability),
1644                    i.capability.to_string(),
1645                )
1646            })
1647            .collect();
1648    }
1649    let (base, tail) = typed.split_once(char::is_whitespace).unwrap_or((typed, ""));
1650    if !tail.trim().is_empty() {
1651        return Vec::new();
1652    }
1653    let Some((_, kind)) = kinds().find(|(_, i)| i.capability == base) else {
1654        return Vec::new();
1655    };
1656    if kind.required.is_empty() {
1657        return Vec::new();
1658    }
1659    let snippet: Vec<String> = kind
1660        .required
1661        .iter()
1662        .enumerate()
1663        .map(|(n, o)| format!("@{o}(${{{}:{}}})", n + 1, option_sample(o)))
1664        .collect();
1665    let label: Vec<String> = kind.required.iter().map(|o| format!("@{o}(…)")).collect();
1666    vec![(
1667        label.join(" "),
1668        format!("the options every `{base}` instance needs"),
1669        snippet.join(" "),
1670    )]
1671}
1672
1673/// A sample value of instance option `option`, as a snippet offers it.
1674fn option_sample(option: &str) -> &'static str {
1675    match option {
1676        "limit" => "100",
1677        "period" => "60.seconds",
1678        "jurisdiction" => "\"eu\"",
1679        "name" => "\"order-events\"",
1680        "store" => "\"payments\"",
1681        "secret" => "\"stripe-live\"",
1682        "to" => "\"[email protected]\"",
1683        "allowedRecipients" | "allowedSenders" => "[\"[email protected]\"]",
1684        _ => "\"legacy-billing\"",
1685    }
1686}
1687
1688/// The windows a `RateLimit` instance's `@period` takes.
1689pub const RATELIMIT_PERIODS: &[(&str, &str)] = &[
1690    (
1691        "10.seconds",
1692        "a 10-second window — one of the two the platform offers",
1693    ),
1694    (
1695        "60.seconds",
1696        "a 60-second window — one of the two the platform offers",
1697    ),
1698];
1699
1700/// The cursor is at an argument-*name* position inside a `@raw( … )` annotation.
1701/// Mirrors [`in_limit_arg_position`].
1702pub fn in_raw_arg_position(text: &str, offset: usize) -> bool {
1703    let Some(open) = innermost_open_paren(text, offset) else {
1704        return false;
1705    };
1706    if word_before_brace(text, open) != "raw" {
1707        return false;
1708    }
1709    let head = text[..open].trim_end();
1710    let before_raw = head[..head.len() - "raw".len()].trim_end();
1711    if !before_raw.ends_with('@') {
1712        return false;
1713    }
1714    let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1715        return false;
1716    };
1717    let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1718    !current.contains(':')
1719}
1720
1721/// #3890: the cursor follows `where` in an `actor <Name> = Caller where …`
1722/// refinement, whose predicate is `IsContext(…)` (not the type predicates).
1723fn is_caller_refinement_where(line_prefix: &str) -> bool {
1724    let t = line_prefix.trim_start();
1725    t.starts_with("actor ") && t.contains("= Caller where")
1726}
1727
1728/// v0.124 (slice 3): the cursor is completing the argument to a leading clause
1729/// keyword — `from`/`on`/`by`/`exports`/`provides <cursor>` — with only a
1730/// partial identifier typed after the keyword. `kw` must be a standalone word
1731/// (line start or whitespace before it), so a field named `from` or the `on`
1732/// inside `session` does not trigger it.
1733fn after_clause_keyword(line: &str, kw: &str) -> bool {
1734    let Some(idx) = line.rfind(kw) else {
1735        return false;
1736    };
1737    if !line[..idx]
1738        .chars()
1739        .last()
1740        .map(char::is_whitespace)
1741        .unwrap_or(true)
1742    {
1743        return false;
1744    }
1745    let after = &line[idx + kw.len()..];
1746    after.starts_with(char::is_whitespace)
1747        && after
1748            .trim_start()
1749            .chars()
1750            .all(|c| c.is_alphanumeric() || c == '_')
1751}
1752
1753/// #3191: the cursor is completing the actor after a `by` that is the clause
1754/// word rather than a name: after a handler's return type (`-> T by`), a
1755/// service header (`service s from http by`), an effect-let value
1756/// (`let r <- call by`) or an `expect` subject (`expect call by`). Anywhere else
1757/// on the line `by` is an ordinary name (a parameter, a binding), and
1758/// `advance Clock by` takes a duration, not an actor.
1759pub(crate) fn is_by_clause_position(line: &str) -> bool {
1760    if !after_clause_keyword(line, "by") {
1761        return false;
1762    }
1763    let Some(idx) = line.rfind("by") else {
1764        return false;
1765    };
1766    let before = line[..idx].trim_start();
1767    // The clause follows a value or a type: a `)`, `]`, an identifier or a
1768    // closing literal. After `(`, `,` or an operator `by` is an argument or a
1769    // parameter name (`f(a, by`, `g: (Int) -> Int, by`).
1770    if !before
1771        .trim_end()
1772        .chars()
1773        .last()
1774        .is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | ')' | ']' | '"' | '\''))
1775    {
1776        return false;
1777    }
1778    // A handler's `by` follows its return type, before the body's `{`.
1779    let after_return_type = before
1780        .rfind("->")
1781        .is_some_and(|i| !before[i..].contains('{'));
1782    after_return_type
1783        || before.contains("<-")
1784        || before.starts_with("service ")
1785        || before.starts_with("expect ")
1786}
1787
1788/// #472 (finding 2, PR #827 review): `for all x: T, y: U where <cursor>` — a
1789/// generative-test binder's clause. Unlike a type declaration's or a refined
1790/// pattern's `where`, this one takes an arbitrary `Bool` expression over the
1791/// bound names, not the closed predicate catalogue; `after_clause_keyword`
1792/// only matches the keyword text, so this excludes that one `where` position
1793/// from the predicate-vocabulary branch. `line`'s last `where` is checked
1794/// against the text immediately before it, ignoring the binding list, since
1795/// `for`/`all` are contextual (not lexer) keywords only meaningful in this
1796/// exact `for all` sequence.
1797fn is_for_all_where(line: &str) -> bool {
1798    let Some(idx) = line.rfind("where") else {
1799        return false;
1800    };
1801    let head = line[..idx].trim_start();
1802    let Some(after_for) = head.strip_prefix("for") else {
1803        return false;
1804    };
1805    // `for` must be a standalone word (a whitespace boundary), not a prefix
1806    // of a longer identifier (`format(...)`).
1807    if !after_for.starts_with(char::is_whitespace) {
1808        return false;
1809    }
1810    let Some(after_all) = after_for.trim_start().strip_prefix("all") else {
1811        return false;
1812    };
1813    // Likewise `all` — `allocate` is not the `for all` keyword.
1814    after_all.is_empty() || after_all.starts_with(char::is_whitespace)
1815}
1816
1817/// v0.124 (slice 3): the cursor sits in a contract-clause predicate —
1818/// `requires <name>: <cursor>` or `ensures <name>: <cursor>` — where the
1819/// enclosing function's parameters (and, for an `ensures`, `result`) are in
1820/// scope. Returns `Some(is_ensures)`; the parameters themselves are resolved
1821/// handler-side from the enclosing `fn` (needs the cursor offset).
1822pub fn contract_clause_kind(line: &str) -> Option<bool> {
1823    let colon = line.rfind(':')?;
1824    let clause = line[..colon].trim();
1825    for (kw, is_ensures) in [("requires", false), ("ensures", true)] {
1826        if let Some(rest) = clause.strip_prefix(kw) {
1827            let rest = rest.trim();
1828            if !rest.is_empty() && rest.chars().all(|c| c.is_alphanumeric() || c == '_') {
1829                return Some(is_ensures);
1830            }
1831        }
1832    }
1833    None
1834}
1835
1836/// The record fields of a project (or embedded-surface) type named `name`, as
1837/// field-name completions — the construction-position half of what
1838/// [`value_member_candidates`] offers on a value receiver.
1839///
1840/// Finding #62: stops at the first unit declaring `name` rather than unioning
1841/// fields across every matching unit — `for_each_unit` can otherwise yield
1842/// the live buffer *and* that same file's stale on-disk copy, and a name
1843/// removed from the buffer's declaration must not resurface from the disk
1844/// copy's fields.
1845fn record_field_names(
1846    name: &str,
1847    doc_text: &str,
1848    files: Option<&HashMap<PathBuf, String>>,
1849) -> Vec<Completion> {
1850    let mut out: Vec<Completion> = Vec::new();
1851    let mut found = false;
1852    for_each_unit(doc_text, files, |unit| {
1853        if found {
1854            return;
1855        }
1856        // #3066: a suite's own types are in scope in its cases.
1857        let suite_types: Vec<CommonsItem> = match unit {
1858            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
1859            _ => Vec::new(),
1860        };
1861        let items = match unit {
1862            SourceUnit::Commons(c) => &c.items,
1863            SourceUnit::Context(c) => &c.items,
1864            SourceUnit::Adapter(a) => &a.items,
1865            SourceUnit::Suite(_) => &suite_types,
1866        };
1867        for item in items {
1868            if let CommonsItem::Type(t) = item
1869                && t.name.name == name
1870                && let TypeBody::Record(r) = &t.body
1871            {
1872                found = true;
1873                // #2607: the fields a literal must give come first; a field
1874                // with a default follows, its default in the detail, since a
1875                // literal may leave it out.
1876                let (required, defaulted): (Vec<_>, Vec<_>) =
1877                    r.fields.iter().partition(|f| f.init.is_none());
1878                for f in required.into_iter().chain(defaulted) {
1879                    let detail = match &f.init {
1880                        Some(init) => format!(
1881                            "field of `{name}`, default `{}`",
1882                            bynk_fmt::expr_to_string(init)
1883                        ),
1884                        None => format!("field of `{name}`"),
1885                    };
1886                    out.push(
1887                        Completion::item(f.name.name.clone(), CompletionKind::Field, Some(detail))
1888                            .with_doc(f.documentation.as_deref()),
1889                    );
1890                }
1891                return;
1892            }
1893        }
1894    });
1895    out
1896}
1897
1898/// v0.124 (slice 3): the variants of a project (or embedded-surface) sum type
1899/// named `name`, as pattern completions — the `is`/`match` candidate set once
1900/// the scrutinee's type is known (resolved handler-side from `expr_types`).
1901/// `pub` so the completion handler can offer them at an `is` position.
1902///
1903/// Finding #62: stops at the first unit declaring `name`, for the same
1904/// buffer-vs-stale-disk-copy reason as `record_field_names` above.
1905pub fn sum_type_variants(
1906    name: &str,
1907    doc_text: &str,
1908    files: Option<&HashMap<PathBuf, String>>,
1909) -> Vec<Completion> {
1910    let mut out: Vec<Completion> = Vec::new();
1911    let mut found = false;
1912    for_each_unit(doc_text, files, |unit| {
1913        if found {
1914            return;
1915        }
1916        // #3066: a suite's own types are in scope in its cases.
1917        let suite_types: Vec<CommonsItem> = match unit {
1918            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
1919            _ => Vec::new(),
1920        };
1921        let items = match unit {
1922            SourceUnit::Commons(c) => &c.items,
1923            SourceUnit::Context(c) => &c.items,
1924            SourceUnit::Adapter(a) => &a.items,
1925            SourceUnit::Suite(_) => &suite_types,
1926        };
1927        for item in items {
1928            if let CommonsItem::Type(t) = item
1929                && t.name.name == name
1930                && let TypeBody::Sum(s) = &t.body
1931            {
1932                found = true;
1933                for v in &s.variants {
1934                    out.push(
1935                        Completion::item(
1936                            v.name.name.clone(),
1937                            CompletionKind::Variant,
1938                            Some(format!("variant of `{name}`")),
1939                        )
1940                        .with_doc(v.documentation.as_deref()),
1941                    );
1942                }
1943                return;
1944            }
1945        }
1946    });
1947    out
1948}
1949
1950/// v0.145 (ADR 0169, base gap for #565): the variants offerable for a scrutinee
1951/// `Ty` at a pattern position. A user-declared sum's variants come from source
1952/// (`sum_type_variants`); the built-in `Result`/`Option` variants do not (they
1953/// are not declared types, so `sum_type_variants` can't see them) and are
1954/// intrinsic here. This is why match-arm / `is` completion now fires for a
1955/// `Result`/`Option` scrutinee, not only a user sum.
1956pub fn variants_for_ty(
1957    ty: TyId,
1958    tys: &Types,
1959    doc_text: &str,
1960    files: Option<&HashMap<PathBuf, String>>,
1961) -> Vec<Completion> {
1962    match &*tys.get(ty) {
1963        Ty::Named { name, .. } => sum_type_variants(name, doc_text, files),
1964        Ty::Result(..) => built_in_variants(&["Ok", "Err"], "Result"),
1965        Ty::Option(..) => built_in_variants(&["Some", "None"], "Option"),
1966        _ => Vec::new(),
1967    }
1968}
1969
1970/// v0.145 (ADR 0169, nested-variant completion for #565): the variants offerable
1971/// inside `OuterVariant(‸` within a match arm — the payload field type's
1972/// variants. Resolves the single-field payload type of `outer_variant` on the
1973/// scrutinee `ty` (the same shape as `bynk-emit`'s `payload_field_ty`):
1974/// `Result`/`Option`/`HttpResult` generic args come straight off the `Ty`, and a
1975/// user-declared sum's field type is walked from source. `Ok`/`Err` inside
1976/// `Some(‸)` on an `Option[Result[…]]` is the headline case.
1977pub fn nested_variant_completions(
1978    ty: TyId,
1979    tys: &Types,
1980    outer_variant: &str,
1981    doc_text: &str,
1982    files: Option<&HashMap<PathBuf, String>>,
1983) -> Vec<Completion> {
1984    match &*tys.get(ty) {
1985        Ty::Result(t, e) => match outer_variant {
1986            "Ok" => variants_for_ty(*t, tys, doc_text, files),
1987            "Err" => variants_for_ty(*e, tys, doc_text, files),
1988            _ => Vec::new(),
1989        },
1990        Ty::HttpResult(t) if outer_variant == "Ok" => variants_for_ty(*t, tys, doc_text, files),
1991        Ty::Option(t) if outer_variant == "Some" => variants_for_ty(*t, tys, doc_text, files),
1992        Ty::Named {
1993            kind: NamedKind::Sum,
1994            name,
1995            ..
1996        } => payload_type_ref_variants(name, outer_variant, doc_text, files),
1997        _ => Vec::new(),
1998    }
1999}
2000
2001/// The built-in variant names of `Result`/`Option` as `Variant` completions.
2002fn built_in_variants(names: &[&str], of: &str) -> Vec<Completion> {
2003    names
2004        .iter()
2005        .map(|v| {
2006            Completion::item(
2007                (*v).to_string(),
2008                CompletionKind::Variant,
2009                Some(format!("variant of `{of}`")),
2010            )
2011        })
2012        .collect()
2013}
2014
2015/// The variants of the payload field type of `variant` on the user-declared sum
2016/// `sum_name`, walked from source (the LSP holds no resolved type map, so it
2017/// reads the field's `TypeRef` off the parsed decl — the source-side analogue of
2018/// `payload_field_ty`'s `commons.types` lookup).
2019fn payload_type_ref_variants(
2020    sum_name: &str,
2021    variant: &str,
2022    doc_text: &str,
2023    files: Option<&HashMap<PathBuf, String>>,
2024) -> Vec<Completion> {
2025    let mut field_ty: Option<TypeRef> = None;
2026    for_each_unit(doc_text, files, |unit| {
2027        // #3066: a suite's own types are in scope in its cases.
2028        let suite_types: Vec<CommonsItem> = match unit {
2029            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2030            _ => Vec::new(),
2031        };
2032        let items = match unit {
2033            SourceUnit::Commons(c) => &c.items,
2034            SourceUnit::Context(c) => &c.items,
2035            SourceUnit::Adapter(a) => &a.items,
2036            SourceUnit::Suite(_) => &suite_types,
2037        };
2038        for item in items {
2039            if let CommonsItem::Type(t) = item
2040                && t.name.name == sum_name
2041                && let TypeBody::Sum(s) = &t.body
2042                && let Some(v) = s.variants.iter().find(|v| v.name.name == variant)
2043                && let Some(f) = v.payload.first()
2044            {
2045                field_ty = Some(f.type_ref.clone());
2046            }
2047        }
2048    });
2049    match field_ty {
2050        Some(tr) => variants_for_type_ref(&tr, doc_text, files),
2051        None => Vec::new(),
2052    }
2053}
2054
2055/// `variants_for_ty` over an unresolved `TypeRef` (a user-sum payload field). A
2056/// named type's variants come from source; `Result`/`Option` are intrinsic.
2057fn variants_for_type_ref(
2058    tr: &TypeRef,
2059    doc_text: &str,
2060    files: Option<&HashMap<PathBuf, String>>,
2061) -> Vec<Completion> {
2062    match tr {
2063        TypeRef::Named(id) => sum_type_variants(&id.name, doc_text, files),
2064        TypeRef::Result(..) => built_in_variants(&["Ok", "Err"], "Result"),
2065        TypeRef::Option(..) => built_in_variants(&["Some", "None"], "Option"),
2066        _ => Vec::new(),
2067    }
2068}
2069
2070/// The service protocols offerable after `from`.
2071fn protocol_candidates() -> Vec<Completion> {
2072    ["http", "cron", "queue", "websocket", "email"]
2073        .into_iter()
2074        .map(|p| Completion::item(p, CompletionKind::Keyword, Some("service protocol".into())))
2075        .collect()
2076}
2077
2078/// The handler kinds offerable after `on`.
2079fn handler_kind_candidates() -> Vec<Completion> {
2080    [
2081        "call", "GET", "POST", "PUT", "PATCH", "DELETE", "schedule", "message", "open", "close",
2082        "rejected",
2083    ]
2084    .into_iter()
2085    .map(|k| Completion::item(k, CompletionKind::Keyword, Some("handler kind".into())))
2086    .collect()
2087}
2088
2089/// The export kinds offerable after `exports` (adapter).
2090fn export_kind_candidates() -> Vec<Completion> {
2091    ["capability", "transparent", "opaque"]
2092        .into_iter()
2093        .map(|k| Completion::item(k, CompletionKind::Keyword, Some("export kind".into())))
2094        .collect()
2095}
2096
2097/// The closed refinement-predicate vocabulary offerable after `where` —
2098/// shared by a type declaration's refinement and (#472) a match arm's
2099/// `_ where <predicate>`. Mirrors `PredKind::name()`.
2100fn predicate_name_candidates() -> Vec<Completion> {
2101    [
2102        "Matches",
2103        "InRange",
2104        "MinLength",
2105        "MaxLength",
2106        "Length",
2107        "NonNegative",
2108        "Positive",
2109        "NonEmpty",
2110        "IsoDate",
2111        "Cron",
2112    ]
2113    .into_iter()
2114    .map(|k| {
2115        Completion::item(
2116            k,
2117            CompletionKind::Keyword,
2118            Some("refinement predicate".into()),
2119        )
2120    })
2121    .collect()
2122}
2123
2124/// The project's `actor` names, offerable after `by`.
2125fn actor_candidates(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<Completion> {
2126    let mut out: Vec<Completion> = Vec::new();
2127    // #2135: in a suite, a call-site `by` may also name a reserved principal
2128    // (`Nobody`, `Forged`, `Stale`, `Expired`, `WrongIssuer`, `WrongAudience`,
2129    // `WrongAlgorithm`, `NoSubject`), which drives the seam to a `401`.
2130    // A lexical test, so it holds mid-edit, when the suite does not parse.
2131    let in_suite = lexer::tokenize(doc_text).ok().is_some_and(|toks| {
2132        toks.iter()
2133            .find(|t| !matches!(t.kind, lexer::TokenKind::Comment))
2134            .is_some_and(|t| t.kind == lexer::TokenKind::Suite)
2135    });
2136    if in_suite {
2137        for (name, doc) in crate::symbols::RESERVED_PRINCIPALS {
2138            out.push(
2139                Completion::item(
2140                    *name,
2141                    CompletionKind::Type,
2142                    Some("reserved test principal".into()),
2143                )
2144                .with_doc(Some(doc)),
2145            );
2146        }
2147    }
2148    let mut seen: BTreeSet<String> = BTreeSet::new();
2149    for_each_unit(doc_text, files, |unit| {
2150        // #3066: a suite's own types are in scope in its cases.
2151        let suite_types: Vec<CommonsItem> = match unit {
2152            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2153            _ => Vec::new(),
2154        };
2155        let items = match unit {
2156            SourceUnit::Commons(c) => &c.items,
2157            SourceUnit::Context(c) => &c.items,
2158            SourceUnit::Adapter(a) => &a.items,
2159            SourceUnit::Suite(_) => &suite_types,
2160        };
2161        for item in items {
2162            if let CommonsItem::Actor(a) = item
2163                && seen.insert(a.name.name.clone())
2164            {
2165                out.push(Completion::item(
2166                    a.name.name.clone(),
2167                    CompletionKind::Type,
2168                    Some("actor".into()),
2169                ));
2170            }
2171        }
2172    });
2173    out
2174}
2175
2176/// Built-in type statics — real language statics that are not user-declared, so
2177/// they come from this small table rather than the project parse. Covers the
2178/// numeric parse statics and the JSON codec (v0.22, ADRs 0048/0049), the
2179/// collection `empty` constructors (v0.20b), and `Effect.pure` (v0.5). The full
2180/// real set per ADR 0093 D2 — kept complete and drift-tested
2181/// (`builtin_statics_are_reachable`).
2182pub const BUILTIN_STATICS: &[(&str, &[(&str, &str)])] = &[
2183    ("Int", &[("parse", "parse(s: String) -> Option[Int]")]),
2184    (
2185        "Float",
2186        &[
2187            ("parse", "parse(s: String) -> Option[Float]"),
2188            ("pi", "pi: Float"),
2189            ("e", "e: Float"),
2190        ],
2191    ),
2192    // #2698: `Duration.`/`Instant.` completed to nothing; both have statics.
2193    ("Duration", &[("millis", "millis(n: Int) -> Duration")]),
2194    (
2195        "Instant",
2196        &[
2197            ("fromEpochMillis", "fromEpochMillis(n: Int) -> Instant"),
2198            ("fromIso", "fromIso(s: String) -> Option[Instant]"),
2199        ],
2200    ),
2201    (
2202        "Decimal",
2203        &[
2204            ("parse", "parse(s: String) -> Option[Decimal]"),
2205            ("fromInt", "fromInt(n: Int) -> Decimal"),
2206        ],
2207    ),
2208    // #2854: the test-side constructors of a handler's raw `query`.
2209    (
2210        "RequestQuery",
2211        &[
2212            ("of", "of(pairs: List[String]) -> RequestQuery"),
2213            ("empty", "empty() -> RequestQuery"),
2214        ],
2215    ),
2216    // #3277: the test-side constructors of a handler's raw `cookies`.
2217    (
2218        "RequestCookies",
2219        &[
2220            ("of", "of(pairs: List[String]) -> RequestCookies"),
2221            ("empty", "empty() -> RequestCookies"),
2222        ],
2223    ),
2224    (
2225        "RoundingMode",
2226        &[
2227            ("Down", "RoundingMode.Down - toward zero"),
2228            ("Up", "RoundingMode.Up - away from zero"),
2229            ("Floor", "RoundingMode.Floor - toward negative infinity"),
2230            ("Ceiling", "RoundingMode.Ceiling - toward positive infinity"),
2231            (
2232                "HalfUp",
2233                "RoundingMode.HalfUp - nearest, a tie away from zero",
2234            ),
2235            (
2236                "HalfDown",
2237                "RoundingMode.HalfDown - nearest, a tie toward zero",
2238            ),
2239            (
2240                "HalfEven",
2241                "RoundingMode.HalfEven - nearest, a tie to the even neighbour",
2242            ),
2243        ],
2244    ),
2245    (
2246        "Json",
2247        &[
2248            ("encode", "encode(value) -> String"),
2249            (
2250                "encodePlain",
2251                "encodePlain(value) -> String - Option as `v` / `null`",
2252            ),
2253            ("decode", "decode[T](s: String) -> Result[T, DecodeError]"),
2254            (
2255                "decodeSql",
2256                "decodeSql[T](s: String) -> Result[T, DecodeError]",
2257            ),
2258        ],
2259    ),
2260    (
2261        "Yaml",
2262        &[("decode", "decode[T](s: String) -> Result[T, DecodeError]")],
2263    ),
2264    (
2265        "Form",
2266        &[
2267            ("decode", "decode[T](s: String) -> Result[T, DecodeError]"),
2268            ("encode", "encode(v: T) -> String"),
2269        ],
2270    ),
2271    ("List", &[("empty", "empty() -> List[T]")]),
2272    ("Map", &[("empty", "empty() -> Map[K, V]")]),
2273    (
2274        "Set",
2275        &[
2276            ("empty", "empty() -> Set[T]"),
2277            ("of", "of(xs: List[T]) -> Set[T]"),
2278        ],
2279    ),
2280    ("Effect", &[("pure", "pure(value) -> Effect[T]")]),
2281    (
2282        "Bytes",
2283        &[
2284            ("fromUtf8", "fromUtf8(s: String) -> Bytes"),
2285            ("fromBase64", "fromBase64(s: String) -> Option[Bytes]"),
2286            ("fromHex", "fromHex(s: String) -> Option[Bytes]"),
2287            ("fromBase64Url", "fromBase64Url(s: String) -> Option[Bytes]"),
2288            ("empty", "empty() -> Bytes"),
2289        ],
2290    ),
2291];
2292
2293/// Variants of a built-in sum type (`HttpResult`/`QueueResult`), sourced from
2294/// the AST variant registries so a new variant surfaces in completion for free
2295/// (ADR 0093 D2/G3). Empty for any other receiver.
2296fn builtin_sum_variants(receiver: &str) -> Vec<(String, String)> {
2297    match receiver {
2298        "HttpResult" => bynk_syntax::ast::HTTP_VARIANTS
2299            .iter()
2300            .map(|v| {
2301                (
2302                    v.name.to_string(),
2303                    if v.status == bynk_syntax::ast::AUTHOR_CHOSEN_STATUS {
2304                        "variant of `HttpResult` (4xx/5xx, author-chosen)".to_string()
2305                    } else {
2306                        format!("variant of `HttpResult` ({})", v.status)
2307                    },
2308                )
2309            })
2310            .collect(),
2311        "QueueResult" => bynk_syntax::ast::QUEUE_VARIANTS
2312            .iter()
2313            .map(|v| (v.name.to_string(), "variant of `QueueResult`".to_string()))
2314            .collect(),
2315        // #3328: the first-party verdict of a `from email` handler. Declared in
2316        // `bynk.cloudflare` rather than hard-wired like `QueueResult`, but
2317        // offered the same way so the decision's four names are one keystroke
2318        // away wherever the receiver is written out.
2319        "EmailVerdict" => [
2320            (
2321                "Accept",
2322                "variant of `EmailVerdict`: handled, nothing else happens",
2323            ),
2324            (
2325                "Reject",
2326                "variant of `EmailVerdict`: refuse with an SMTP rejection",
2327            ),
2328            (
2329                "Forward",
2330                "variant of `EmailVerdict`: pass to a verified destination",
2331            ),
2332            ("Reply", "variant of `EmailVerdict`: answer the sender"),
2333        ]
2334        .into_iter()
2335        .map(|(n, d)| (n.to_string(), d.to_string()))
2336        .collect(),
2337        _ => Vec::new(),
2338    }
2339}
2340
2341/// Members of a name receiver: built-in type statics, then built-in sum-type
2342/// variants, then — from the project and embedded-surface parse — project sum
2343/// variants, refined/opaque `of`/`unsafe`, or capability operations. Yields `[]`
2344/// when the receiver resolves to none of these (e.g. a plain `type X = Int`
2345/// alias or a record).
2346/// #3386: whether the cursor is on the scheme of an `auth = <cursor>` entry.
2347fn auth_scheme_position(line_prefix: &str) -> bool {
2348    let Some(i) = line_prefix.rfind("auth") else {
2349        return false;
2350    };
2351    line_prefix[i + "auth".len()..]
2352        .trim_start()
2353        .strip_prefix('=')
2354        .is_some_and(|r| {
2355            r.trim_start()
2356                .chars()
2357                .all(|c| c.is_alphanumeric() || c == '_')
2358        })
2359}
2360
2361/// #3386: the actor authentication schemes `auth =` takes.
2362fn auth_scheme_candidates() -> Vec<Completion> {
2363    [
2364        ("None", "anonymous: no credential"),
2365        ("Bearer", "a signed JWT in `Authorization: Bearer …`"),
2366        (
2367            "SignedCookie",
2368            "a signed, expiring session cookie that Bynk issues and verifies",
2369        ),
2370        ("Oidc", "an OIDC/JWKS provider token"),
2371        ("Signature", "a webhook HMAC signature"),
2372        ("Internal", "an in-system caller"),
2373        ("Foreign", "a caller that is not Bynk, signing the call"),
2374    ]
2375    .into_iter()
2376    .map(|(label, detail)| {
2377        Completion::item(
2378            label,
2379            CompletionKind::Keyword,
2380            Some(format!("auth scheme — {detail}")),
2381        )
2382    })
2383    .collect()
2384}
2385
2386/// #3386: inside the parentheses of `auth = SignedCookie(…`, the config keys not yet written.
2387fn signed_cookie_key_candidates(line_prefix: &str) -> Option<Vec<Completion>> {
2388    let open = line_prefix.rfind("SignedCookie(")? + "SignedCookie(".len();
2389    let args = &line_prefix[open..];
2390    if args.contains(')') {
2391        return None;
2392    }
2393    // The key being typed starts after the last comma; a value (after `=`) completes nothing.
2394    let current = args.rsplit(',').next().unwrap_or(args);
2395    if current.contains('=') {
2396        return Some(Vec::new());
2397    }
2398    let written: Vec<&str> = args
2399        .split(',')
2400        .filter_map(|part| part.split('=').next().map(str::trim))
2401        .collect();
2402    Some(
2403        [
2404            (
2405                "secret",
2406                "the environment variable holding the signing key (required)",
2407            ),
2408            (
2409                "ttl",
2410                "how long an issued cookie is valid, e.g. `12.hours` (required)",
2411            ),
2412            ("cookie", "the cookie's name; defaults to `__Host-session`"),
2413            (
2414                "previous",
2415                "the key being rotated out, accepted for verification only",
2416            ),
2417            (
2418                "sameSite",
2419                "`Lax` (the default), `Strict` or `Unrestricted`",
2420            ),
2421        ]
2422        .into_iter()
2423        .filter(|(key, _)| !written.contains(key))
2424        .map(|(key, detail)| {
2425            Completion::item(
2426                key,
2427                CompletionKind::Field,
2428                Some(format!("SignedCookie key — {detail}")),
2429            )
2430        })
2431        .collect(),
2432    )
2433}
2434
2435/// #3386: whether an actor authenticates with a signed session cookie.
2436pub fn is_signed_cookie_actor(a: &bynk_syntax::ast::ActorDecl) -> bool {
2437    a.auth.as_ref().is_some_and(|s| s.name == "SignedCookie")
2438}
2439
2440/// #3386: the members a `SignedCookie` actor has inside its context, as `(name, signature)`.
2441pub fn signed_cookie_members(a: &bynk_syntax::ast::ActorDecl) -> [(&'static str, String); 2] {
2442    let identity = a
2443        .identity
2444        .as_ref()
2445        .map_or_else(|| "identity".to_string(), crate::symbols::type_ref_str);
2446    [
2447        (
2448            "issue",
2449            format!("issue(identity: {identity}) -> Effect[Cookie]"),
2450        ),
2451        ("expire", "expire() -> Cookie".to_string()),
2452    ]
2453}
2454
2455/// #3147: the signature of `D1.peek`, a built-in of an `integration` or
2456/// `system` case that is no operation of the capability.
2457pub(crate) const D1_PEEK_SIGNATURE: &str = "peek(<participant>.<Capability>) -> D1Peek - a read-only handle on a participant's test database";
2458
2459fn member_candidates(
2460    receiver: &str,
2461    doc_text: &str,
2462    files: Option<&HashMap<PathBuf, String>>,
2463) -> Vec<Completion> {
2464    let mut out = member_candidates_from(receiver, doc_text, files, &mut BTreeSet::new());
2465    if receiver == "D1" && !out.iter().any(|c| c.label == "peek") {
2466        out.push(Completion::item(
2467            "peek",
2468            CompletionKind::Member,
2469            Some(D1_PEEK_SIGNATURE.to_string()),
2470        ));
2471    }
2472    out
2473}
2474
2475/// [`member_candidates`], with the derived capabilities already followed
2476/// (S4a, #1966). Completion reads unchecked source, so a derivation cycle
2477/// (`capability A = B`, `capability B = A`) can be on screen: each receiver
2478/// is followed once.
2479fn member_candidates_from(
2480    receiver: &str,
2481    doc_text: &str,
2482    files: Option<&HashMap<PathBuf, String>>,
2483    followed: &mut BTreeSet<String>,
2484) -> Vec<Completion> {
2485    followed.insert(receiver.to_string());
2486    if let Some((_, statics)) = BUILTIN_STATICS.iter().find(|(name, _)| *name == receiver) {
2487        return statics
2488            .iter()
2489            .map(|(label, sig)| {
2490                Completion::item(*label, CompletionKind::Member, Some(sig.to_string()))
2491            })
2492            .collect();
2493    }
2494    let mut out: Vec<Completion> = Vec::new();
2495    let mut seen: BTreeSet<String> = BTreeSet::new();
2496    // Built-in sum types (`HttpResult`/`QueueResult`) — variants from the AST
2497    // registry, on the same name-receiver path as project sums (ADR 0093 G3).
2498    // S4a (#1966): a derived capability's (`capability Sessions = Kv`) base,
2499    // whose operations it has.
2500    let mut derived_base: Option<String> = None;
2501    for (label, detail) in builtin_sum_variants(receiver) {
2502        if seen.insert(label.clone()) {
2503            out.push(Completion::item(
2504                label,
2505                CompletionKind::Variant,
2506                Some(detail),
2507            ));
2508        }
2509    }
2510    for_each_unit(doc_text, files, |unit| {
2511        // #3066: a suite's own types are in scope in its cases.
2512        let suite_types: Vec<CommonsItem> = match unit {
2513            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2514            _ => Vec::new(),
2515        };
2516        let items = match unit {
2517            SourceUnit::Commons(c) => &c.items,
2518            SourceUnit::Context(c) => &c.items,
2519            SourceUnit::Adapter(a) => &a.items,
2520            SourceUnit::Suite(_) => &suite_types,
2521        };
2522        for item in items {
2523            match item {
2524                CommonsItem::Type(t) if t.name.name == receiver => match &t.body {
2525                    bynk_syntax::ast::TypeBody::Sum(s) => {
2526                        for v in &s.variants {
2527                            if seen.insert(v.name.name.clone()) {
2528                                out.push(
2529                                    Completion::item(
2530                                        v.name.name.clone(),
2531                                        CompletionKind::Variant,
2532                                        Some(format!("variant of `{receiver}`")),
2533                                    )
2534                                    .with_doc(v.documentation.as_deref()),
2535                                );
2536                            }
2537                        }
2538                    }
2539                    bynk_syntax::ast::TypeBody::Refined { .. }
2540                    | bynk_syntax::ast::TypeBody::Opaque { .. } => {
2541                        let of_sig = match &t.body {
2542                            // #3946: a named type with no predicate cannot fail.
2543                            bynk_syntax::ast::TypeBody::Refined {
2544                                base, refinement, ..
2545                            } if bynk_syntax::ast::of_is_total(
2546                                *base,
2547                                refinement.as_ref(),
2548                                false,
2549                            ) =>
2550                            {
2551                                format!("of(value) -> {receiver}")
2552                            }
2553                            _ => format!("of(value) -> Result[{receiver}, ValidationError]"),
2554                        };
2555                        for (label, sig) in [
2556                            ("of", of_sig),
2557                            ("unsafe", format!("unsafe(value) -> {receiver}")),
2558                        ] {
2559                            if seen.insert(label.to_string()) {
2560                                out.push(Completion::item(
2561                                    label,
2562                                    CompletionKind::Member,
2563                                    Some(sig),
2564                                ));
2565                            }
2566                        }
2567                    }
2568                    // A plain alias (`type X = Int`) or a record has no
2569                    // name-receiver members — record fields are value-receiver
2570                    // (slice 3).
2571                    _ => {}
2572                },
2573                CommonsItem::Capability(c) if c.name.name == receiver && c.derived.is_some() => {
2574                    derived_base = c.derived.as_ref().map(|d| d.base.name.clone());
2575                }
2576                // Constrained generics slice 4: a user static (`fn Box.of(…)`, no
2577                // `self`) completes after `Box.`, generic type or not. The type's
2578                // parameters are written in the signature as declared; the hidden
2579                // witnesses are not.
2580                CommonsItem::Fn(f) => {
2581                    if let FnName::Method {
2582                        type_name,
2583                        method_name,
2584                    } = &f.name
2585                        && !f.has_self
2586                        && type_name.name == receiver
2587                        && seen.insert(method_name.name.clone())
2588                    {
2589                        out.push(
2590                            Completion::item(
2591                                method_name.name.clone(),
2592                                CompletionKind::Member,
2593                                Some(free_fn_signature(&method_name.name, f)),
2594                            )
2595                            .with_doc(f.documentation.as_deref()),
2596                        );
2597                    }
2598                }
2599                // #3386: a `SignedCookie` actor issues and deletes its own session cookie.
2600                CommonsItem::Actor(a) if a.name.name == receiver && is_signed_cookie_actor(a) => {
2601                    for (label, sig) in signed_cookie_members(a) {
2602                        if seen.insert(label.to_string()) {
2603                            out.push(Completion::item(
2604                                label,
2605                                CompletionKind::Member,
2606                                Some(format!("{sig} — session cookie of `{receiver}`")),
2607                            ));
2608                        }
2609                    }
2610                }
2611                CommonsItem::Capability(c) if c.name.name == receiver => {
2612                    for op in &c.ops {
2613                        if seen.insert(op.name.name.clone()) {
2614                            // Typed signature (params + return), the same
2615                            // `type_ref_str` rendering hover/signature help use —
2616                            // not bare param names (slice 5 detail polish).
2617                            out.push(Completion::item(
2618                                op.name.name.clone(),
2619                                CompletionKind::Member,
2620                                Some(format!(
2621                                    "{} — operation of `{receiver}`",
2622                                    capability_op_signature(op)
2623                                )),
2624                            ));
2625                        }
2626                    }
2627                }
2628                _ => {}
2629            }
2630        }
2631    });
2632    // #2865: a derived `D1`'s typed reads, which the compiler lowers.
2633    // Hyperdrive H3 (#3320): and a derived `Postgres`'s.
2634    if let Some(base) = derived_base
2635        .as_deref()
2636        .filter(|b| crate::signature_help::TYPED_READ_BASES.contains(b))
2637    {
2638        for member in ["select", "firstAs"] {
2639            if let Some(sig) = crate::signature_help::typed_read(base, member)
2640                && seen.insert(member.to_string())
2641            {
2642                out.push(Completion::item(
2643                    member.to_string(),
2644                    CompletionKind::Member,
2645                    Some(format!("{sig} — operation of `{receiver}`")),
2646                ));
2647            }
2648        }
2649    }
2650    if let Some(base) = derived_base.filter(|b| !followed.contains(b)) {
2651        for c in member_candidates_from(&base, doc_text, files, followed) {
2652            if seen.insert(c.label.clone()) {
2653                out.push(c);
2654            }
2655        }
2656    }
2657    out
2658}
2659
2660// -- Positional candidate sources (static registries + project parse) --
2661
2662/// Built-in type names not declared in any parseable source. Base and generic
2663/// types from the language core; collection types from `builtin_names`. Docs
2664/// are drawn from the `keywords` registry where present (one source of truth).
2665const BUILTIN_TYPES: &[&str] = &[
2666    bynk_check::builtin_names::types::INT,
2667    "Bool",
2668    bynk_check::builtin_names::types::FLOAT,
2669    "String",
2670    "Option",
2671    "Result",
2672    "Effect",
2673    bynk_check::builtin_names::types::LIST,
2674    bynk_check::builtin_names::types::MAP,
2675    bynk_check::builtin_names::types::SET,
2676];
2677
2678/// Declaration snippets (`CompletionItemKind::SNIPPET`), as LSP snippet bodies.
2679/// `pub` so `tests/scaffolds_compile.rs` (ADR 0157) can enumerate them.
2680pub const SNIPPETS: &[(&str, &str)] = &[
2681    // -- Units --
2682    ("context", "context ${1:name} {\n\t$0\n}"),
2683    ("commons", "commons ${1:my.lib}\n\n$0"),
2684    (
2685        "adapter",
2686        "adapter ${1:name} {\n\tbinding \"${2:./module}\"\n\t$0\n}",
2687    ),
2688    // -- Unit-header clauses --
2689    ("uses", "uses ${1:module}"),
2690    ("consumes", "consumes ${1:bynk} { ${2:Random} }"),
2691    // -- Types --
2692    (
2693        "type record",
2694        "type ${1:Name} = {\n\t${2:field}: ${3:Int},\n}",
2695    ),
2696    ("type enum", "type ${1:Name} = enum {\n\t${2:Variant},\n}"),
2697    (
2698        "type refined",
2699        "type ${1:Name} = ${2:String} where ${3:MinLength(1)}",
2700    ),
2701    (
2702        "type opaque",
2703        "type ${1:Name} = opaque ${2:Int} where ${3:NonNegative}",
2704    ),
2705    // -- Functions --
2706    (
2707        "fn",
2708        "fn ${1:name}(${2:x}: ${3:Int}) -> ${4:Int} {\n\t$0\n}",
2709    ),
2710    (
2711        "fn contract",
2712        "fn ${1:name}(${2:x}: ${3:Int}) -> ${4:Int}\n\trequires ${5:in_range}: ${6:x >= 0}\n\tensures ${7:non_negative}: ${8:result >= 0}\n{\n\t$0\n}",
2713    ),
2714    // -- Capabilities & providers --
2715    (
2716        "capability",
2717        "capability ${1:Name} {\n\tfn ${2:op}() -> Effect[${3:Unit}]\n}",
2718    ),
2719    (
2720        "provides",
2721        "provides ${1:Cap} = ${2:Impl} {\n\tfn ${3:op}(${4}) -> Effect[${5:()}] {\n\t\tEffect.pure(${6:()})\n\t}\n}",
2722    ),
2723    // -- Actors & agents --
2724    (
2725        "actor",
2726        "actor ${1:Name} { auth = ${2:Bearer(secret = \"AUTH_JWT_SECRET\")}, identity = ${3:UserId} }",
2727    ),
2728    (
2729        "agent",
2730        "agent ${1:Name} {\n\tkey ${2:id}: ${3:String}\n\n\tstore ${4:status}: Cell[${5:Int}] = ${6:0}\n\n\tinvariant ${7:non_negative}: ${8:status >= 0}\n\n\ttransition ${9:monotonic}: ${10:new.status >= old.status}\n\n\ton call ${11:op}(${12}) -> Effect[Result[${13:()}, String]] {\n\t\tOk(${14:()})\n\t}\n}",
2731    ),
2732    // -- Services & handlers --
2733    (
2734        "service",
2735        "service ${1:name} {\n\ton call(${2}) -> Effect[${3:Unit}] by Caller {\n\t\t$0\n\t}\n}",
2736    ),
2737    (
2738        "on call",
2739        "on call(${1}) -> Effect[${2:Unit}] by Caller {\n\t$0\n}",
2740    ),
2741    (
2742        "on http",
2743        "on ${1|GET,POST,PUT,DELETE,PATCH|}(\"${2:/path}\") (${3:body}: ${4:Req}) -> Effect[HttpResult[${5:Res}]] given ${6:Cap} {\n\t$0\n}",
2744    ),
2745    (
2746        "on cron",
2747        "on schedule(\"${1:0 * * * *}\") () -> Effect[Result[(), String]] {\n\t$0\n\tOk(())\n}",
2748    ),
2749    // -- Tests --
2750    (
2751        "suite",
2752        "suite ${1:target}\n\ncase \"${2:it works}\" {\n\tlet ${3:actual} = ${4:0}\n\texpect ${5:actual == 0}\n}",
2753    ),
2754    (
2755        "property",
2756        "property \"${1:invariant holds}\" {\n\tfor all ${2:x}: ${3:Int} {\n\t\texpect ${4:x == x}\n\t}\n}",
2757    ),
2758    // #2137: move the test harness's clock (a `case` body statement).
2759    ("advance Clock by", "advance Clock by ${1:15.minutes}"),
2760];
2761
2762/// The value constructors offered at expression position (ADR 0093 D3) — the
2763/// closed set of `Result`/`Option` variant constructors and the boolean
2764/// literals. A value expression can begin with any of these; their docs reuse
2765/// the `keywords` registry (one source of truth).
2766const CONSTRUCTORS: &[&str] = &["Ok", "Err", "Some", "None", "true", "false"];
2767
2768/// Expression-position candidates: the value constructors plus in-scope type
2769/// names (the entry to a static call like `Int.parse` or a record construction
2770/// like `Order { … }`). In-scope values — locals/params, and from slice 3 free
2771/// functions — are appended by the handler, which owns the analysis cache, so
2772/// they are not produced here (ADR 0093 D3).
2773fn expression_candidates(
2774    doc_text: &str,
2775    files: Option<&HashMap<PathBuf, String>>,
2776) -> Vec<Completion> {
2777    let mut out: Vec<Completion> = CONSTRUCTORS
2778        .iter()
2779        .map(|&name| {
2780            Completion::item(
2781                name,
2782                CompletionKind::Constructor,
2783                keyword_doc(name).map(str::to_string),
2784            )
2785        })
2786        .collect();
2787    // Type names are valid here too (static receiver / record construction); the
2788    // `Type.` member context (slice 1) takes over once the user types the dot.
2789    out.extend(type_candidates(doc_text, files));
2790    // In-scope free functions — the current unit's own `fn`s and the combinators
2791    // of every `uses`-imported module (project + stdlib) — ADR 0093 D3 / G5 —
2792    // plus their assets (#1883), in scope by the same rule.
2793    out.extend(free_function_candidates(doc_text, files));
2794    // #2620: the ambient `unreachable`/`todo`, unless a declaration shadows one.
2795    for info in keywords::BUILTIN_FUNCTIONS {
2796        if !out.iter().any(|c| c.label == info.word) {
2797            out.push(
2798                Completion::item(
2799                    info.word,
2800                    CompletionKind::Function,
2801                    Some(format!("{}(message: String) -> never returns", info.word)),
2802                )
2803                .with_doc(Some(info.meaning)),
2804            );
2805        }
2806    }
2807    out
2808}
2809
2810/// A unit's top-level items and its `uses` clauses, for the kinds that carry
2811/// free functions. Service/other units contribute neither.
2812fn unit_items_and_uses(unit: &SourceUnit) -> (&[CommonsItem], &[UsesDecl]) {
2813    match unit {
2814        SourceUnit::Commons(c) => (&c.items, &c.uses),
2815        SourceUnit::Context(c) => (&c.items, &c.uses),
2816        SourceUnit::Adapter(a) => (&a.items, &a.uses),
2817        _ => (&[], &[]),
2818    }
2819}
2820
2821/// The qualified name of the unit the cursor's document declares, via a recovery
2822/// parse (the header survives a mid-edit body). `None` for a headerless fragment
2823/// that names no unit.
2824fn current_unit_name(doc_text: &str) -> Option<String> {
2825    let tokens = lexer::tokenize(doc_text).ok()?;
2826    let (unit, _errs) = parser::parse_unit_with_recovery(&tokens, doc_text);
2827    Some(unit?.name().joined())
2828}
2829
2830/// Standard-library S3 (#1963): whether a first-party item path is experimental.
2831fn experimental(path: &str) -> bool {
2832    bynk_check::firstparty::stability_of(path)
2833        == Some(bynk_check::firstparty::Stability::Experimental)
2834}
2835
2836/// The completion-detail suffix that marks an experimental item, so it is
2837/// visible before it is used.
2838fn stability_suffix(experimental: bool) -> &'static str {
2839    if experimental {
2840        " — experimental"
2841    } else {
2842        ""
2843    }
2844}
2845
2846/// A capability operation's signature (`now() -> Effect[Instant]`,
2847/// `get[T](key: String) -> …`), typed the way hover and signature help render
2848/// types (`type_ref_str`). Shared with the wasm `bynk_reference` catalogue.
2849pub fn capability_op_signature(op: &bynk_syntax::ast::CapabilityOp) -> String {
2850    let params = op
2851        .params
2852        .iter()
2853        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2854        .collect::<Vec<_>>()
2855        .join(", ");
2856    // #926: `[T, …]` type parameters on the op itself.
2857    let type_params = if op.type_params.is_empty() {
2858        String::new()
2859    } else {
2860        let names: Vec<&str> = op
2861            .type_params
2862            .iter()
2863            .map(|tp| tp.name.name.as_str())
2864            .collect();
2865        format!("[{}]", names.join(", "))
2866    };
2867    format!(
2868        "{}{type_params}({params}) -> {}",
2869        op.name.name,
2870        type_ref_str(&op.return_type)
2871    )
2872}
2873
2874/// Render a free function's signature for the completion detail, the same way
2875/// hover and signature help do (`symbols::type_ref_str`) — one format, never
2876/// divergent. Mirrors signature help, bounds included.
2877pub fn free_fn_signature(name: &str, f: &bynk_syntax::ast::FnDecl) -> String {
2878    let params = f
2879        .params
2880        .iter()
2881        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2882        .collect::<Vec<_>>()
2883        .join(", ");
2884    format!(
2885        "{name}{}({params}) -> {}{}{}",
2886        crate::symbols::fn_type_params_str(f),
2887        type_ref_str(&f.return_type),
2888        crate::symbols::fn_given_str(f),
2889        crate::symbols::fn_where_str(f)
2890    )
2891}
2892
2893/// Free-function candidates at expression position: the current unit's own
2894/// top-level `fn`s plus the free `fn`s of every `uses`-imported module (project
2895/// commons and the embedded stdlib). Gated on the `uses` set so a combinator is
2896/// offered only where it is actually in scope (ADR 0093 D3 / G5). The same
2897/// units' `asset` declarations (#1883) ride the same pass and the same gate —
2898/// an asset name resolves exactly where a free function's would.
2899fn free_function_candidates(
2900    doc_text: &str,
2901    files: Option<&HashMap<PathBuf, String>>,
2902) -> Vec<Completion> {
2903    let Some(current) = current_unit_name(doc_text) else {
2904        return Vec::new();
2905    };
2906    // One parse pass: collect each unit's name, its free `fn`s (name + signature),
2907    // its assets (name + declaration), and its `uses` targets.
2908    struct UnitFns {
2909        name: String,
2910        fns: Vec<(String, String, bool)>,
2911        assets: Vec<(String, String, Option<String>, bool)>,
2912        embeds: Vec<(String, String, Option<String>, bool)>,
2913        uses: Vec<String>,
2914    }
2915    let mut units: Vec<UnitFns> = Vec::new();
2916    for_each_unit(doc_text, files, |unit| {
2917        let (items, uses) = unit_items_and_uses(unit);
2918        // #2618: a `private` item stays out of another unit's candidates, but
2919        // the pass cannot tell yet whether this unit is the current one, so
2920        // each carries its visibility and the filter runs below.
2921        let fns = items
2922            .iter()
2923            .filter_map(|it| match it {
2924                CommonsItem::Fn(f) => match &f.name {
2925                    FnName::Free(id) => Some((
2926                        id.name.clone(),
2927                        free_fn_signature(&id.name, f),
2928                        f.private.is_some(),
2929                    )),
2930                    FnName::Method { .. } => None,
2931                },
2932                _ => None,
2933            })
2934            .collect();
2935        let assets = items
2936            .iter()
2937            .filter_map(|it| match it {
2938                CommonsItem::Asset(a) => Some((
2939                    a.name.name.clone(),
2940                    format!(
2941                        "asset {} = \"{}\"{}",
2942                        a.name.name,
2943                        bynk_fmt::escape_string(&a.path),
2944                        a.at.as_ref()
2945                            .map(|(p, _)| format!(" at \"{}\"", bynk_fmt::escape_string(p)))
2946                            .unwrap_or_default()
2947                    ),
2948                    a.documentation.as_deref().map(str::to_string),
2949                    a.private.is_some(),
2950                )),
2951                _ => None,
2952            })
2953            .collect();
2954        // #2387: an embed rides the same pass and gate as an asset.
2955        let embeds = items
2956            .iter()
2957            .filter_map(|it| match it {
2958                CommonsItem::Embed(e) => Some((
2959                    e.name.name.clone(),
2960                    format!(
2961                        "embed {} = \"{}\"",
2962                        e.name.name,
2963                        bynk_fmt::escape_string(&e.path)
2964                    ),
2965                    e.documentation.as_deref().map(str::to_string),
2966                    e.private.is_some(),
2967                )),
2968                // #2617: a constant rides the same pass and gate as an embed.
2969                CommonsItem::Const(c) => Some((
2970                    c.name.name.clone(),
2971                    format!(
2972                        "const {}: {}",
2973                        c.name.name,
2974                        crate::symbols::type_ref_str(&c.ty)
2975                    ),
2976                    c.documentation.as_deref().map(str::to_string),
2977                    c.private.is_some(),
2978                )),
2979                _ => None,
2980            })
2981            .collect();
2982        units.push(UnitFns {
2983            name: unit.name().joined(),
2984            fns,
2985            assets,
2986            embeds,
2987            uses: uses.iter().map(|u| u.target.joined()).collect(),
2988        });
2989    });
2990    // The import scope: the `uses` targets of every unit sharing the current name
2991    // (a unit may span files, so union them).
2992    let mut imported: BTreeSet<String> = BTreeSet::new();
2993    for u in &units {
2994        if u.name == current {
2995            imported.extend(u.uses.iter().cloned());
2996        }
2997    }
2998    // Offer the current unit's own fns and the fns of each imported module.
2999    let mut out: Vec<Completion> = Vec::new();
3000    let mut seen: BTreeSet<String> = BTreeSet::new();
3001    // #2834: in a suite, its own helper `fn`s lead. Only the buffer's suite
3002    // contributes: a helper is private to the suite that declares it.
3003    if let Some(SourceUnit::Suite(suite)) = parse_source_unit(doc_text) {
3004        for f in &suite.fixtures {
3005            if seen.insert(f.name.name.clone()) {
3006                out.push(
3007                    Completion::item(
3008                        f.name.name.clone(),
3009                        CompletionKind::Constant,
3010                        Some(format!(
3011                            "fixture {} = \"{}\" — `this suite`",
3012                            f.name.name,
3013                            bynk_fmt::escape_string(&f.path)
3014                        )),
3015                    )
3016                    .with_doc(f.documentation.as_deref()),
3017                );
3018            }
3019        }
3020        // #3066: and its own constants (values at expression position).
3021        for c in &suite.consts {
3022            if seen.insert(c.name.name.clone()) {
3023                out.push(
3024                    Completion::item(
3025                        c.name.name.clone(),
3026                        CompletionKind::Constant,
3027                        Some(format!(
3028                            "const {}: {} — `this suite`",
3029                            c.name.name,
3030                            type_ref_str(&c.ty)
3031                        )),
3032                    )
3033                    .with_doc(c.documentation.as_deref()),
3034                );
3035            }
3036        }
3037        for f in &suite.fns {
3038            if let FnName::Free(id) = &f.name
3039                && seen.insert(id.name.clone())
3040            {
3041                out.push(
3042                    Completion::item(
3043                        id.name.clone(),
3044                        CompletionKind::Function,
3045                        Some(format!("{} — `this suite`", free_fn_signature(&id.name, f))),
3046                    )
3047                    .with_doc(f.documentation.as_deref()),
3048                );
3049            }
3050        }
3051    }
3052    for u in &units {
3053        let own = u.name == current;
3054        if !own && !imported.contains(&u.name) {
3055            continue;
3056        }
3057        let origin = if own { "this unit" } else { u.name.as_str() };
3058        for (name, sig, private) in &u.fns {
3059            if *private && !own {
3060                continue;
3061            }
3062            if seen.insert(name.clone()) {
3063                let marked = !own && experimental(&format!("{}.{name}", u.name));
3064                out.push(Completion::item(
3065                    name.clone(),
3066                    CompletionKind::Function,
3067                    Some(format!("{sig} — `{origin}`{}", stability_suffix(marked))),
3068                ));
3069            }
3070        }
3071        for (name, decl, doc, private) in u.assets.iter().chain(&u.embeds) {
3072            if *private && !own {
3073                continue;
3074            }
3075            if seen.insert(name.clone()) {
3076                out.push(
3077                    Completion::item(
3078                        name.clone(),
3079                        CompletionKind::Constant,
3080                        Some(format!("{decl} — `{origin}`")),
3081                    )
3082                    .with_doc(doc.as_deref()),
3083                );
3084            }
3085        }
3086    }
3087    out
3088}
3089
3090/// The one-line doc for a name in the `keywords` registry, if present.
3091/// `pub` so hover's bare-keyword fallback (ADR 0156) can reuse it —
3092/// completion and hover render the same doc, never a parallel copy.
3093pub fn keyword_doc(word: &str) -> Option<&'static str> {
3094    keywords::KEYWORDS
3095        .iter()
3096        .find(|k| k.word == word)
3097        .or_else(|| keywords::BUILTIN_FUNCTIONS.iter().find(|k| k.word == word))
3098        .map(|k| k.meaning)
3099}
3100
3101/// Type-position candidates: built-in types (with registry docs), then every
3102/// `type` declaration found in the project sources and the embedded `bynk`
3103/// surface (so the transparent surface types `Uuid`/`Method`/… come for free).
3104fn type_candidates(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<Completion> {
3105    let mut out: Vec<Completion> = Vec::new();
3106    let mut seen: BTreeSet<String> = BTreeSet::new();
3107    for &name in BUILTIN_TYPES {
3108        if seen.insert(name.to_string()) {
3109            let detail = keyword_doc(name)
3110                .map(str::to_string)
3111                .or_else(|| match name {
3112                    "List" => Some("The built-in list type, `List[T]`.".to_string()),
3113                    "Map" => Some("The built-in map type, `Map[K, V]`.".to_string()),
3114                    "Set" => Some("The built-in set type, `Set[T]`.".to_string()),
3115                    _ => Some("built-in type".to_string()),
3116                });
3117            out.push(Completion::item(name, CompletionKind::Type, detail));
3118        }
3119    }
3120    // #2618: another unit's `private` types are not nameable here.
3121    let current = current_unit_name(doc_text);
3122    for_each_unit(doc_text, files, |unit| {
3123        // #3066: a suite's own types are in scope in its cases.
3124        let suite_types: Vec<CommonsItem> = match unit {
3125            SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
3126            _ => Vec::new(),
3127        };
3128        let items = match unit {
3129            SourceUnit::Commons(c) => &c.items,
3130            SourceUnit::Context(c) => &c.items,
3131            SourceUnit::Adapter(a) => &a.items,
3132            SourceUnit::Suite(_) => &suite_types,
3133        };
3134        let own = current.as_deref() == Some(unit.name().joined().as_str());
3135        for item in items {
3136            if let CommonsItem::Type(t) = item
3137                && (own || t.private.is_none())
3138                && seen.insert(t.name.name.clone())
3139            {
3140                out.push(Completion::item(
3141                    t.name.name.clone(),
3142                    CompletionKind::Type,
3143                    Some("type".to_string()),
3144                ));
3145            }
3146        }
3147    });
3148    out
3149}
3150
3151/// Keyword-position candidates: the lowercase-initial reserved keywords (the
3152/// declaration/statement words — uppercase type/value names like `Int`/`Some`
3153/// belong to type/expression position) with their registry docs, plus the
3154/// declaration snippets.
3155fn keyword_and_snippet_candidates() -> Vec<Completion> {
3156    let mut out: Vec<Completion> = keywords::KEYWORDS
3157        .iter()
3158        .filter(|k| k.word.chars().next().is_some_and(char::is_lowercase))
3159        .map(|k| Completion::item(k.word, CompletionKind::Keyword, Some(k.meaning.to_string())))
3160        .collect();
3161    // #3191: `by` is a contextual keyword (an ordinary name outside its clause
3162    // positions), so it is no longer in `KEYWORDS`; it stays offered here, as a
3163    // clause word after a return type or an effect-let value.
3164    if let Some(by) = keywords::CONTEXTUAL_KEYWORDS
3165        .iter()
3166        .find(|k| k.word == "by")
3167    {
3168        out.push(Completion::item(
3169            by.word,
3170            CompletionKind::Keyword,
3171            Some(by.meaning.to_string()),
3172        ));
3173    }
3174    for &(label, body) in SNIPPETS {
3175        out.push(Completion::snippet(label, body));
3176    }
3177    out
3178}
3179
3180// -- Enumeration (parse project sources + the embedded `bynk` surface) --
3181
3182/// Lex + recovery-parse one source, yielding its primary [`SourceUnit`]
3183/// (`None` when nothing parses — an empty or header-broken file).
3184fn parse_source_unit(src: &str) -> Option<SourceUnit> {
3185    let tokens = lexer::tokenize(src).ok()?;
3186    parser::parse_unit_with_recovery(&tokens, src).0
3187}
3188
3189/// The embedded first-party surface, parsed **once** for the whole process.
3190/// These are compile-time `include_str!` constants, so their parse is fixed;
3191/// re-lexing and re-parsing all five on every keystroke-driven request was
3192/// pure waste (#733). The `bynk` surface, the `bynk.cloudflare` platform
3193/// adapter, and the stdlib commons (`bynk.list`/`bynk.map`/`bynk.string`) whose
3194/// free fns are enumerable for `uses`-imported completion (G5) and signature
3195/// help. Harmless to the other contexts — the commons declare only `fn`s (no
3196/// types/capabilities) and are never a `consumes` target.
3197static EMBEDDED_UNITS: LazyLock<Vec<Arc<SourceUnit>>> = LazyLock::new(|| {
3198    // The single first-party source list (`bynk-check::firstparty`), so a new
3199    // first-party commons is completion-visible without a second edit here
3200    // (#901 — `bynk.locale`/`bynk.locale.types` were missing from this copy).
3201    bynk_check::firstparty::FIRSTPARTY_SOURCES
3202        .iter()
3203        .filter_map(|(_, src)| parse_source_unit(src).map(Arc::new))
3204        .collect()
3205});
3206
3207/// S4a (#1966): the first-party unit `unit` (`bynk.cloudflare`), from the
3208/// embedded surface, when it declares capability `cap`: what a derived
3209/// capability's hover renders its base's operations from.
3210pub(crate) fn embedded_capability(
3211    unit: &str,
3212    cap: &str,
3213) -> Option<bynk_syntax::ast::CapabilityDecl> {
3214    EMBEDDED_UNITS.iter().find_map(|u| {
3215        if u.name().joined() != unit {
3216            return None;
3217        }
3218        let SourceUnit::Adapter(a) = u.as_ref() else {
3219            return None;
3220        };
3221        a.items.iter().find_map(|item| match item {
3222            CommonsItem::Capability(c) if c.name.name == cap => Some(c.clone()),
3223            _ => None,
3224        })
3225    })
3226}
3227
3228/// The parsed unit for a project file's already-read `content`. P8.4
3229/// (#1515): served from `bynk_project::parse_cache`'s own shared, durable
3230/// cache (replacing this module's former `PROJECT_UNIT_CACHE` — one cache
3231/// of the same fact, not two independently-invalidated ones, per ADR
3232/// 0413/[DECISION C]) when the cached/fresh **strict** parse is clean; a
3233/// syntax error elsewhere in the project falls back to a local, uncached
3234/// recovery-parse for that one file ([DECISION E], `bynk-project::
3235/// parse_cache`'s own doc comment) — for clean source (the overwhelming
3236/// common case) the strict and recovery parsers produce the identical AST,
3237/// since there is nothing to recover from.
3238///
3239/// PR #1520's own bot review (finding #4): `parser::
3240/// parse_units_with_warnings_from` (what the shared cache stores) always
3241/// converts an empty unit list into `Err("bynk.parse.unexpected_eof")`
3242/// (`bynk-syntax/src/parser.rs`'s own `parse_units_with_drain_check_from`)
3243/// — `Ok` with zero units is not a real case this parser produces, so
3244/// `units.first()` alone says what is meant without an `is_empty()` guard
3245/// that would otherwise route a (nonexistent) clean-but-empty parse down
3246/// the same uncached recovery-parse fallback as a genuine syntax error,
3247/// permanently, on every request.
3248fn cached_project_unit(path: &Path, content: &str) -> Option<Arc<SourceUnit>> {
3249    let (_file_id, result) = bynk_project::parse_cache::cached_parse(path, content);
3250    match result {
3251        Ok((units, _warnings)) => units.first().cloned().map(Arc::new),
3252        Err(_) => parse_source_unit(content).map(Arc::new),
3253    }
3254}
3255
3256/// Parse every project unit, plus the embedded first-party adapters (the
3257/// `bynk` surface and the `bynk.cloudflare` platform adapter), and call `f`
3258/// for each. Recovery parsing tolerates the in-progress edit at the cursor.
3259///
3260/// The embedded surface is parsed once (`EMBEDDED_UNITS`) and the project's
3261/// other files are served from a per-file parse cache (`cached_project_unit`),
3262/// keyed on content rather than disk metadata (content-ownership track,
3263/// #1086, slice 0+1) — `files` is a pre-read `(path, content)` map the caller
3264/// (`bynk-lsp`) built by overlaying every open buffer over a disk sweep, so
3265/// an unsaved edit to file A is visible here exactly like a saved one. Only
3266/// `doc_text` — the buffer under the cursor, which changes per keystroke — is
3267/// parsed fresh each call (#733), never looked up in `files` (the caller
3268/// excludes the cursor's own file from `files` for exactly this reason).
3269/// Ordering is preserved (embedded, then the buffer, then the other files) so
3270/// a callback's first-name-wins dedup still prefers the live buffer.
3271pub fn for_each_unit(
3272    doc_text: &str,
3273    files: Option<&HashMap<PathBuf, String>>,
3274    mut f: impl FnMut(&SourceUnit),
3275) {
3276    for unit in EMBEDDED_UNITS.iter() {
3277        f(unit);
3278    }
3279    if let Some(unit) = parse_source_unit(doc_text) {
3280        f(&unit);
3281    }
3282    // Slice A: the project's files come from the compiler's own discovery
3283    // (`bynk_ide::discover_files`) — every `include` root, `exclude` honoured.
3284    // This used to walk a single directory by hand, so completion could not see
3285    // a second root and swept `out`/`node_modules` if they sat beneath it.
3286    if let Some(content) = files {
3287        for (path, text) in content {
3288            if let Some(unit) = cached_project_unit(path, text) {
3289                f(&unit);
3290            }
3291        }
3292    }
3293}
3294
3295/// #2223: `files` split into the project's own files and its dependencies'
3296/// files (each with its package), when the project has dependencies. A
3297/// dependency's units are never reachable by their bare names, so completion
3298/// that offers unit names reads only the project's own files, and offers a
3299/// dependency's units as `<alias>.<unit>`.
3300fn split_dependency_files<'f>(
3301    files: Option<&'f HashMap<PathBuf, String>>,
3302    project_root: Option<&Path>,
3303) -> SplitFiles<'f> {
3304    let Some(content) = files else {
3305        return SplitFiles::default();
3306    };
3307    let view = match project_root {
3308        Some(root) => crate::packages::DependencyView::for_root(root, content),
3309        None => crate::packages::DependencyView::from_files(content),
3310    };
3311    let Some(view) = view else {
3312        return SplitFiles {
3313            own: Some(Cow::Borrowed(content)),
3314            deps: Vec::new(),
3315        };
3316    };
3317    let mut own = HashMap::new();
3318    let mut deps = Vec::new();
3319    let mut keys: Vec<&PathBuf> = content.keys().collect();
3320    keys.sort();
3321    for path in keys {
3322        let text = &content[path];
3323        match view.package_of(path) {
3324            None => {
3325                own.insert(path.clone(), text.clone());
3326            }
3327            Some(id) => {
3328                if let Some(unit) = cached_project_unit(path, text) {
3329                    for alias in view.aliases_of(id) {
3330                        let declared = unit.name().joined();
3331                        if view.exports(id, &declared) {
3332                            deps.push((format!("{alias}.{declared}"), (*unit).clone()));
3333                        }
3334                    }
3335                }
3336            }
3337        }
3338    }
3339    SplitFiles {
3340        own: Some(Cow::Owned(own)),
3341        deps,
3342    }
3343}
3344
3345/// [`split_dependency_files`]'s result: the project's own files (borrowed
3346/// unchanged when the project has no dependencies), and each reachable
3347/// dependency unit with the `<alias>.<unit>` label it's written as.
3348#[derive(Default)]
3349struct SplitFiles<'f> {
3350    own: Option<Cow<'f, HashMap<PathBuf, String>>>,
3351    deps: Vec<(String, SourceUnit)>,
3352}
3353
3354impl SplitFiles<'_> {
3355    fn own(&self) -> Option<&HashMap<PathBuf, String>> {
3356        self.own.as_deref()
3357    }
3358}
3359
3360/// #2223: commons a `uses` can name — the project's own, then each
3361/// dependency's exported commons as `<alias>.<unit>`.
3362fn usable_commons(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3363    let mut seen: BTreeSet<String> = BTreeSet::new();
3364    let mut out: Vec<Completion> = Vec::new();
3365    for_each_unit(doc_text, split.own(), |unit| {
3366        if let SourceUnit::Commons(c) = unit {
3367            let name = c.name.joined();
3368            if seen.insert(name.clone()) {
3369                out.push(Completion::item(
3370                    name,
3371                    CompletionKind::Unit,
3372                    Some("commons".to_string()),
3373                ));
3374            }
3375        }
3376    });
3377    for (label, unit) in &split.deps {
3378        if matches!(unit, SourceUnit::Commons(_)) && seen.insert(label.clone()) {
3379            out.push(Completion::item(
3380                label,
3381                CompletionKind::Unit,
3382                Some("commons from a dependency".to_string()),
3383            ));
3384        }
3385    }
3386    out
3387}
3388
3389/// Consumable unit names: contexts and adapters (plus `bynk`), deduplicated.
3390/// #2223: a dependency's adapters are offered as `<alias>.<unit>`, its
3391/// contexts never (a context is never shared).
3392fn consumable_units(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3393    let files = split.own();
3394    let mut seen: BTreeSet<String> = BTreeSet::new();
3395    let mut out: Vec<Completion> = Vec::new();
3396    for (label, unit) in &split.deps {
3397        if matches!(unit, SourceUnit::Adapter(_)) && seen.insert(label.clone()) {
3398            out.push(Completion::item(
3399                label.clone(),
3400                CompletionKind::Unit,
3401                Some("adapter from a dependency".to_string()),
3402            ));
3403        }
3404    }
3405    for_each_unit(doc_text, files, |unit| {
3406        let (name, kind) = match unit {
3407            SourceUnit::Context(c) => (c.name.joined(), "context"),
3408            SourceUnit::Adapter(a) => (a.name.joined(), "adapter"),
3409            _ => return,
3410        };
3411        if seen.insert(name.clone()) {
3412            out.push(Completion::item(
3413                name,
3414                CompletionKind::Unit,
3415                Some(kind.to_string()),
3416            ));
3417        }
3418    });
3419    out
3420}
3421
3422/// The capability names a unit `exports capability`.
3423///
3424/// Finding #62: a first-wins guard, for the same buffer-vs-stale-disk-copy
3425/// reason as [`record_field_names`] — the `BTreeSet` still dedups a single
3426/// matching unit's own (possibly repeated) export clauses.
3427fn capabilities_of_unit(unit: &str, doc_text: &str, split: &SplitFiles<'_>) -> Vec<String> {
3428    // #2223: `<alias>.<unit>` names a dependency's adapter, declared there
3429    // under its own name.
3430    if let Some((_, dep)) = split.deps.iter().find(|(label, _)| label == unit) {
3431        let mut out: BTreeSet<String> = BTreeSet::new();
3432        if let SourceUnit::Adapter(a) = dep {
3433            for clause in &a.exports {
3434                if clause.kind == ExportKind::Capability {
3435                    for n in clause.names.iter().map(|e| &e.name) {
3436                        out.insert(n.name.clone());
3437                    }
3438                }
3439            }
3440        }
3441        return out.into_iter().collect();
3442    }
3443    let files = split.own();
3444    let mut out: BTreeSet<String> = BTreeSet::new();
3445    let mut found = false;
3446    for_each_unit(doc_text, files, |u| {
3447        if found {
3448            return;
3449        }
3450        let (name, exports) = match u {
3451            SourceUnit::Context(c) => (c.name.joined(), &c.exports),
3452            SourceUnit::Adapter(a) => (a.name.joined(), &a.exports),
3453            _ => return,
3454        };
3455        if name != unit {
3456            return;
3457        }
3458        found = true;
3459        for clause in exports {
3460            if clause.kind == ExportKind::Capability {
3461                for n in clause.names.iter().map(|e| &e.name) {
3462                    out.insert(n.name.clone());
3463                }
3464            }
3465        }
3466    });
3467    out.into_iter().collect()
3468}
3469
3470/// Capabilities in scope for a `given` clause in the current document: locally
3471/// declared capabilities, bare names flattened by a braced `consumes`, and
3472/// `U.Cap` for each whole-unit `consumes U`.
3473fn in_scope_capabilities(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3474    let mut labels: BTreeSet<String> = BTreeSet::new();
3475    let Ok(tokens) = lexer::tokenize(doc_text) else {
3476        return Vec::new();
3477    };
3478    let (Some(unit), _errs) = parser::parse_unit_with_recovery(&tokens, doc_text) else {
3479        return Vec::new();
3480    };
3481    let (items, consumes) = match &unit {
3482        SourceUnit::Context(c) => (&c.items, &c.consumes),
3483        SourceUnit::Adapter(a) => (&a.items, &EMPTY_CONSUMES),
3484        _ => return Vec::new(),
3485    };
3486    // Locally declared capabilities.
3487    for item in items {
3488        if let bynk_syntax::ast::CommonsItem::Capability(c) = item {
3489            labels.insert(c.name.name.clone());
3490        }
3491    }
3492    // Consumed capabilities: flattened bare names, or qualified `U.Cap`.
3493    for c in consumes {
3494        let unit_name = c.target.joined();
3495        match &c.selected {
3496            Some(names) => {
3497                for n in names {
3498                    labels.insert(n.name.name.clone());
3499                }
3500            }
3501            None => {
3502                let prefix = c
3503                    .alias
3504                    .as_ref()
3505                    .map(|a| a.name.clone())
3506                    .unwrap_or_else(|| unit_name.clone());
3507                for cap in capabilities_of_unit(&unit_name, doc_text, split) {
3508                    labels.insert(format!("{prefix}.{cap}"));
3509                }
3510            }
3511        }
3512    }
3513    labels
3514        .into_iter()
3515        .map(|label| {
3516            Completion::item(
3517                label,
3518                CompletionKind::Capability,
3519                Some("capability in scope".to_string()),
3520            )
3521        })
3522        .collect()
3523}
3524
3525// -- Value-receiver `.method`/`.field` (slice 3, ADR 0063) --
3526
3527/// If the cursor (byte `offset` into `text`) sits just after a **lowercase**
3528/// `receiver.`(`partial`) — a *value* receiver — return the buffer **rewritten**
3529/// so the receiver is a complete expression (the trailing `.partial` dropped,
3530/// so the file parses) and the byte offset of the receiver to type. Returns
3531/// `None` for an uppercase name receiver (slice 2), a decimal `1.`, or a
3532/// `.`-qualified segment.
3533///
3534/// The rewrite is the spike's fix for the mid-edit parse: a bare `email.`
3535/// cascades and loses the receiver, but `email` (dot dropped) types cleanly.
3536pub fn value_receiver_rewrite(text: &str, offset: usize) -> Option<(String, usize)> {
3537    let prefix = text.get(..offset)?;
3538    let head = prefix
3539        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
3540        .strip_suffix('.')?;
3541    let (recv, start) = ident_ending_at(head, head.len())?;
3542    let first = recv.chars().next()?;
3543    if !(first.is_ascii_lowercase() || first == '_') {
3544        return None; // uppercase = name receiver (slice 2); a digit = a decimal
3545    }
3546    if head[..start].ends_with('.') {
3547        return None; // a `.`-qualified segment, not a bare value receiver
3548    }
3549    let dot = head.len(); // the receiver ends here; the dot was the next byte
3550    let rewritten = format!("{}{}", &text[..dot], &text[offset..]);
3551    Some((rewritten, dot.saturating_sub(1)))
3552}
3553
3554/// The identifier run ending at byte `end` in `text` — `(name, start)` — the
3555/// trim-back-to-a-non-identifier-boundary scan shared by every receiver/
3556/// identifier extraction in the LSP: [`value_receiver_rewrite`] above,
3557/// `symbols::receiver_segment_at` (a member's receiver, dot-preceded), and
3558/// `symbols::store_field_kind_at` (a bare receiver's own end offset, no dot).
3559/// Each has different preconditions on what precedes `end`, but the boundary
3560/// scan itself — walk back to the nearest non-identifier char, respecting
3561/// UTF-8 boundaries — is one definition, so it can't drift between them (a
3562/// review flagged the previous three near-identical copies). `None` if
3563/// nothing identifier-shaped precedes `end`.
3564pub fn ident_ending_at(text: &str, end: usize) -> Option<(&str, usize)> {
3565    let before = text.get(..end)?;
3566    let start = before
3567        .char_indices()
3568        .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
3569        .map_or(0, |(i, c)| i + c.len_utf8());
3570    let name = &before[start..];
3571    (!name.is_empty()).then_some((name, start))
3572}
3573
3574/// The members of a typed value receiver: the built-in kernel methods of its
3575/// type (from the enumerable registry) plus, for a record, its fields.
3576pub fn value_member_candidates(
3577    ty: TyId,
3578    tys: &Types,
3579    doc_text: &str,
3580    files: Option<&HashMap<PathBuf, String>>,
3581) -> Vec<Completion> {
3582    let mut out: Vec<Completion> = kernel_methods::methods_for(ty, tys)
3583        .iter()
3584        .map(|km| {
3585            Completion::item(
3586                km.name,
3587                CompletionKind::Member,
3588                Some(km.signature.to_string()),
3589            )
3590        })
3591        .collect();
3592    // An asset's one field (#1883).
3593    if matches!(&*tys.get(ty), Ty::Asset) {
3594        out.push(Completion::item(
3595            "url",
3596            CompletionKind::Field,
3597            Some("String — the URL the platform serves the asset at".to_string()),
3598        ));
3599    }
3600    // `DecodeError`'s three `String` fields (#2863). Compiler-known, so there is
3601    // no declaration to resolve them from.
3602    if matches!(&*tys.get(ty), Ty::DecodeError) {
3603        for (name, doc) in [
3604            (
3605                "kind",
3606                "String — `Malformed`, `StructuralMismatch` or `RefinementViolation`",
3607            ),
3608            ("path", "String — where the decode failed, e.g. `$.qty`"),
3609            ("message", "String — a description of the failure"),
3610        ] {
3611            out.push(Completion::item(
3612                name,
3613                CompletionKind::Field,
3614                Some(doc.to_string()),
3615            ));
3616        }
3617    }
3618    // `ValidationError`'s two `String` fields (#2866); `value` is not exposed.
3619    if matches!(&*tys.get(ty), Ty::ValidationError) {
3620        for (name, doc) in [
3621            (
3622                "field",
3623                "String — the name of the refined type or field that failed validation",
3624            ),
3625            ("message", "String — a description of the failure"),
3626        ] {
3627            out.push(Completion::item(
3628                name,
3629                CompletionKind::Field,
3630                Some(doc.to_string()),
3631            ));
3632        }
3633    }
3634    // Record fields — resolve the receiver's named type to its declaration.
3635    if let Ty::Named { name, .. } = &*tys.get(ty) {
3636        let mut seen: BTreeSet<String> = BTreeSet::new();
3637        for_each_unit(doc_text, files, |unit| {
3638            let items = match unit {
3639                SourceUnit::Commons(c) => &c.items,
3640                SourceUnit::Context(c) => &c.items,
3641                SourceUnit::Adapter(a) => &a.items,
3642                _ => return,
3643            };
3644            for item in items {
3645                if let CommonsItem::Type(t) = item
3646                    && &t.name.name == name
3647                    && let TypeBody::Record(r) = &t.body
3648                {
3649                    for f in &r.fields {
3650                        if seen.insert(f.name.name.clone()) {
3651                            out.push(
3652                                Completion::item(
3653                                    f.name.name.clone(),
3654                                    CompletionKind::Field,
3655                                    Some(format!("field of `{name}`")),
3656                                )
3657                                .with_doc(f.documentation.as_deref()),
3658                            );
3659                        }
3660                    }
3661                }
3662            }
3663        });
3664    }
3665    out
3666}
3667
3668/// #2138: `id` after `run.` in a `case` body that hasn't bound its own
3669/// `run` — the test run's identity. `rewritten`/`recv_offset` are
3670/// [`value_receiver_rewrite`]'s output (`recv_offset` is the receiver's last
3671/// byte). Empty anywhere else.
3672pub fn run_id_member_candidates(rewritten: &str, recv_offset: usize) -> Vec<Completion> {
3673    let Some((name, start)) = ident_ending_at(rewritten, recv_offset + 1) else {
3674        return Vec::new();
3675    };
3676    if name != "run" || !crate::symbols::is_test_run_receiver(rewritten, start) {
3677        return Vec::new();
3678    }
3679    vec![
3680        Completion::item("id", CompletionKind::Field, Some("String".to_string()))
3681            .with_doc(Some(crate::symbols::RUN_ID_DOC)),
3682    ]
3683}
3684
3685/// #596: the entry ops (and, for a `Map`, the `.entries`/`.keys`/`.values`
3686/// query accessors) of a bare `store` field receiver — merged onto
3687/// [`value_member_candidates`] so a store field offers its whole vocabulary,
3688/// not just the `Query` half `kernel_methods::methods_for` covers. A bare
3689/// store `Map` field types (via the checker's ADR 0120 "whole map as a value"
3690/// reading) to plain `Ty::Query`, indistinguishable from an ordinary
3691/// `Query`-typed local — so this reads the receiver's *provenance* instead,
3692/// the same way hover's `describe_store_op_at` does. Empty when the receiver
3693/// isn't a store field of an enclosing agent, or is shadowed by a local.
3694///
3695/// `rewritten`/`recv_offset` are [`value_receiver_rewrite`]'s output; `locals`
3696/// is the current round's locals for the file, best-effort (empty when the
3697/// analysed round doesn't match `rewritten`, in which case the shadowing
3698/// check simply sees no local in scope).
3699pub fn store_field_member_candidates(
3700    rewritten: &str,
3701    recv_offset: usize,
3702    locals: &[LocalBinding],
3703) -> Vec<Completion> {
3704    let Some((kind_head, held)) =
3705        crate::symbols::store_field_kind_at(rewritten, recv_offset + 1, locals)
3706    else {
3707        return Vec::new();
3708    };
3709    let mut out: Vec<Completion> = store_ops::ops_for(&kind_head)
3710        .iter()
3711        .map(|o| {
3712            Completion::item(
3713                o.name,
3714                CompletionKind::Member,
3715                Some(o.signature.to_string()),
3716            )
3717        })
3718        .collect();
3719    if kind_head == "Map" && !held {
3720        out.extend(store_ops::MAP_QUERY_ACCESSORS.iter().map(|a| {
3721            Completion::item(a.name, CompletionKind::Field, Some(a.signature.to_string()))
3722        }));
3723    }
3724    out
3725}
3726
3727static EMPTY_CONSUMES: Vec<bynk_syntax::ast::ConsumesDecl> = Vec::new();
3728
3729#[cfg(test)]
3730mod tests {
3731    #[test]
3732    fn at_after_a_matches_refinement_offers_example() {
3733        let line = r#"type Code = String where Matches("[A-Z]{3}") @"#;
3734        assert!(in_refinement_annotation_position(line));
3735        let got = complete(line, line, None);
3736        assert_eq!(got.len(), 1);
3737        assert_eq!(got[0].label, "example");
3738        assert!(in_refinement_annotation_position(
3739            r#"  code: String where IsoDate @ex"#
3740        ));
3741        assert!(!in_refinement_annotation_position(
3742            r#"type Sku = String where NonEmpty @"#
3743        ));
3744        assert!(!in_refinement_annotation_position(
3745            r#"type C = String where Matches("a") @example("a") @"#
3746        ));
3747    }
3748
3749    use super::*;
3750    use bynk_check::firstparty::BYNK_LIST_SRC;
3751
3752    /// S3 (#1963): an experimental first-party item is marked in its completion
3753    /// detail; nothing ships experimental, so a stable one is unmarked.
3754    #[test]
3755    fn completion_marks_experimental_items() {
3756        assert_eq!(stability_suffix(true), " — experimental");
3757        assert_eq!(stability_suffix(false), "");
3758        assert!(!experimental("bynk.cloudflare.Kv"));
3759        let caps = complete("consumes bynk.cloudflare { ", "context app.probe\n", None);
3760        let kv = caps
3761            .iter()
3762            .find(|c| c.label == "Kv")
3763            .expect("Kv is offered");
3764        assert_eq!(
3765            kv.detail.as_deref(),
3766            Some("capability exported by `bynk.cloudflare`")
3767        );
3768    }
3769
3770    fn labels(line: &str, doc: &str) -> Vec<String> {
3771        complete(line, doc, None)
3772            .into_iter()
3773            .map(|c| c.label)
3774            .collect()
3775    }
3776
3777    /// Constrained generics slice 0: the constraint names are offered after the
3778    /// `:` / `+` of a bound, in a type-parameter list and in a `where` clause,
3779    /// and only there.
3780    #[test]
3781    fn constraint_names_follow_a_bound_colon() {
3782        let doc = "commons m\n";
3783        let eq = |line: &str| {
3784            complete(line, doc, None)
3785                .into_iter()
3786                .filter(|c| c.kind == CompletionKind::Constraint)
3787                .map(|c| c.label)
3788                .collect::<Vec<_>>()
3789        };
3790        assert_eq!(eq("fn same[T: "), ["Eq", "Ord", "Key", "Codable"]);
3791        assert_eq!(eq("fn same[T: E"), ["Eq", "Ord", "Key", "Codable"]);
3792        assert_eq!(eq("fn same[T: Eq + "), ["Eq", "Ord", "Key", "Codable"]);
3793        assert_eq!(eq("fn same[A, T: "), ["Eq", "Ord", "Key", "Codable"]);
3794        assert_eq!(eq("type Pair[T: "), ["Eq", "Ord", "Key", "Codable"]);
3795        assert_eq!(
3796            eq("fn Box.has(self, x: A) -> Bool where A: "),
3797            ["Eq", "Ord", "Key", "Codable"]
3798        );
3799        assert_eq!(
3800            eq("fn f(self) -> Int where A: Eq, B: "),
3801            ["Eq", "Ord", "Key", "Codable"]
3802        );
3803        // A parameter's type annotation and a refinement `where` are not bounds.
3804        assert!(eq("fn f(x: ").is_empty());
3805        assert!(eq("fn f(x: Int) -> ").is_empty());
3806        assert!(eq("type Age = Int where ").is_empty());
3807        assert!(eq("fn f[T](x: ").is_empty());
3808        // `derives` takes only `Ord` (`Eq` is automatic), unlike a bound.
3809        assert_eq!(eq("type P = { a: Int } derives "), ["Ord"]);
3810    }
3811
3812    fn labels_of(line: &str, doc: &str) -> Vec<String> {
3813        complete(line, doc, None)
3814            .into_iter()
3815            .map(|c| c.label)
3816            .collect()
3817    }
3818
3819    /// Constrained generics slice 1: `derives` is offered after a type's body,
3820    /// whatever its shape, and nowhere else.
3821    #[test]
3822    fn derives_follows_a_type_body() {
3823        let doc = "commons m\n";
3824        for line in [
3825            "type P = { a: Int } ",
3826            "type P = { a: Int } de",
3827            "type E = enum { A, B } ",
3828            "type E = A | B(x: Int) ",
3829            "type Age = Int ",
3830            "type Age = Int where self >= 0 ",
3831            "type Id = opaque Int ",
3832            "type Box[T: Ord] = { v: T } ",
3833        ] {
3834            assert!(
3835                labels_of(line, doc).contains(&"derives".to_string()),
3836                "{line:?}"
3837            );
3838        }
3839        // Multi-line body: the closing `}` of an open `type … {`.
3840        let open = "commons m\n\ntype P = {\n  a: Int\n}\n";
3841        assert!(labels_of("} ", open).contains(&"derives".to_string()));
3842        // Not after an incomplete body, a clause already present, a function, or `}` with no type.
3843        for line in [
3844            "type P = ",
3845            "type E = A | ",
3846            "type Age = Int where ",
3847            "type P = { a: Int } derives Ord ",
3848            "fn f() -> Int { 1 } ",
3849        ] {
3850            assert!(
3851                !labels_of(line, doc).contains(&"derives".to_string()),
3852                "{line:?}"
3853            );
3854        }
3855        assert!(!labels_of("} ", doc).contains(&"derives".to_string()));
3856    }
3857
3858    /// Constrained generics slice 1: after `derives` and after `+`, only `Ord`
3859    /// is offered — `Eq`, `Key` and `Codable` are automatic.
3860    #[test]
3861    fn derives_list_offers_only_ord() {
3862        let doc = "commons m\n";
3863        for line in [
3864            "type P = { a: Int } derives ",
3865            "type P = { a: Int } derives O",
3866            "type P = { a: Int } derives Ord + ",
3867            "} derives ",
3868        ] {
3869            assert_eq!(labels_of(line, doc), ["Ord"], "{line:?}");
3870        }
3871        assert!(!labels_of("type P = { a: Int } derives Ord ", doc).contains(&"Ord".to_string()));
3872        assert!(labels_of("let derives = ", doc).iter().all(|l| l != "Ord"));
3873    }
3874
3875    /// The bound-position list mirrors the checker: every offered name is a
3876    /// constraint the checker accepts, and the checker's unknown-constraint
3877    /// diagnostic lists exactly these.
3878    #[test]
3879    fn constraint_names_match_the_checker() {
3880        for c in constraint_candidates() {
3881            let src = format!("commons m\n\nfn f[T: {}](x: T) -> T {{ x }}\n", c.label);
3882            assert!(crate::diagnose(&src).is_empty(), "{}", c.label);
3883        }
3884        let bad = crate::diagnose("commons m\n\nfn f[T: Nope](x: T) -> T { x }\n");
3885        let note = format!("{:?}", bad[0].error);
3886        for c in constraint_candidates() {
3887            assert!(note.contains(&c.label), "{note}");
3888        }
3889    }
3890
3891    #[test]
3892    fn consumes_target_suggests_units_including_bynk() {
3893        // An adapter in the open doc plus the always-available `bynk` surface.
3894        let doc = "adapter tokens {\n  binding \"./b.ts\"\n  capability Jwt { fn f() -> Effect[Int] }\n  provides Jwt = X\n}\n";
3895        let got = labels("  consumes ", doc);
3896        assert!(got.contains(&"bynk".to_string()), "{got:?}");
3897        assert!(got.contains(&"tokens".to_string()), "{got:?}");
3898    }
3899
3900    #[test]
3901    fn consumes_brace_suggests_that_units_capabilities() {
3902        let got = labels("  consumes bynk { ", "context a.b\n");
3903        // The embedded `bynk` surface exports these.
3904        assert!(got.contains(&"Clock".to_string()), "{got:?}");
3905        assert!(got.contains(&"Random".to_string()), "{got:?}");
3906        assert!(got.contains(&"Logger".to_string()), "{got:?}");
3907    }
3908
3909    /// #2868: a context function's `given` completes capability names, as a
3910    /// handler's does.
3911    #[test]
3912    fn a_fn_given_suggests_capabilities() {
3913        let doc = "context a.b\n\
3914                   consumes bynk { Clock }\n\
3915                   capability Local { fn f() -> Effect[Int] }\n\
3916                   fn step() -> Effect[Int] given Clock {\n\
3917                   Clock.now()\n\
3918                   }\n";
3919        let got = labels("fn step() -> Effect[Int] given ", doc);
3920        assert!(got.contains(&"Clock".to_string()), "flattened: {got:?}");
3921        assert!(got.contains(&"Local".to_string()), "local: {got:?}");
3922    }
3923
3924    #[test]
3925    fn given_suggests_local_and_flattened_capabilities() {
3926        let doc = "context a.b\n\
3927                   consumes bynk { Clock }\n\
3928                   capability Local { fn f() -> Effect[Int] }\n\
3929                   service s {\n\
3930                   on call() -> Effect[Int] by Caller given Clock {\n\
3931                   1\n\
3932                   }\n\
3933                   }\n";
3934        let got = labels("    on call() -> Effect[Int] by Caller given ", doc);
3935        assert!(got.contains(&"Clock".to_string()), "flattened: {got:?}");
3936        assert!(got.contains(&"Local".to_string()), "local: {got:?}");
3937    }
3938
3939    #[test]
3940    fn expression_position_offers_constructors_and_types() {
3941        // ADR 0093 D3/D5: a value position (after `=`) yields every constructor
3942        // keyword and in-scope type names — the entry to a static call or a
3943        // record construction. (Locals/params are appended handler-side, not by
3944        // `complete()`.) Registry-driven over CONSTRUCTORS.
3945        let doc = "commons m {\n  type Order = { id: Int }\n}\n";
3946        let items = complete("  let x = ", doc, None);
3947        for &c in CONSTRUCTORS {
3948            assert!(
3949                find(&items, c, CompletionKind::Constructor).is_some(),
3950                "constructor {c}: {:?}",
3951                items.iter().map(|i| &i.label).collect::<Vec<_>>()
3952            );
3953        }
3954        assert!(
3955            find(&items, "Int", CompletionKind::Type).is_some(),
3956            "builtin type"
3957        );
3958        assert!(
3959            find(&items, "Order", CompletionKind::Type).is_some(),
3960            "project type"
3961        );
3962    }
3963
3964    #[test]
3965    fn expression_position_offers_the_fault_builtins_unless_shadowed() {
3966        // #2620: `unreachable`/`todo` are ambient functions at a value position,
3967        // and a `fn` of the same name replaces the built-in rather than doubling it.
3968        let doc = "commons m {\n  fn todo(s: String) -> Int { 1 }\n}\n";
3969        let items = complete("  let x = ", doc, None);
3970        assert!(
3971            find(&items, "unreachable", CompletionKind::Function).is_some(),
3972            "unreachable offered"
3973        );
3974        assert_eq!(
3975            items.iter().filter(|i| i.label == "todo").count(),
3976            1,
3977            "the user's `todo` shadows the built-in"
3978        );
3979    }
3980
3981    #[test]
3982    fn value_receiver_and_decimal_are_not_expression_positions() {
3983        // A trailing `x.` is a member context, not an expression start —
3984        // `complete()` yields nothing (the value-receiver path is handler-side;
3985        // see `record_value_and_decimal_receivers_yield_nothing`). A trailing
3986        // `1.` offers the `Duration` units (#3947), not expressions.
3987        assert!(complete("  let p = q.", "context a.b\n", None).is_empty());
3988        let units = complete("  let n = 1.", "context a.b\n", None);
3989        assert!(
3990            units
3991                .iter()
3992                .all(|c| c.detail.as_deref() == Some("`Duration` unit"))
3993        );
3994        assert_eq!(units.len(), 5);
3995    }
3996
3997    /// Free `fn` names declared in a unit source (registry-driven test helper).
3998    fn free_fn_names(src: &str) -> Vec<String> {
3999        let tokens = lexer::tokenize(src).unwrap();
4000        let (unit, _) = parser::parse_unit_with_recovery(&tokens, src);
4001        let unit = unit.unwrap();
4002        let (items, _) = unit_items_and_uses(&unit);
4003        items
4004            .iter()
4005            .filter_map(|it| match it {
4006                CommonsItem::Fn(f) => match &f.name {
4007                    FnName::Free(id) => Some(id.name.clone()),
4008                    FnName::Method { .. } => None,
4009                },
4010                _ => None,
4011            })
4012            .collect()
4013    }
4014
4015    #[test]
4016    fn free_functions_offered_for_own_unit_and_used_modules() {
4017        // ADR 0093 D3/G5: expression position offers the current unit's own
4018        // free `fn`s and the combinators of every `uses`-imported module.
4019        let doc = "commons app {\n  uses bynk.list\n  fn helper(x: Int) -> Int { x }\n}\n";
4020        let items = complete("  let y = ", doc, None);
4021        // The current unit's own function.
4022        assert!(
4023            find(&items, "helper", CompletionKind::Function).is_some(),
4024            "own fn: {:?}",
4025            items.iter().map(|i| &i.label).collect::<Vec<_>>()
4026        );
4027        // Every combinator of the imported `bynk.list` — registry-driven over the
4028        // embedded source, so a new stdlib combinator must surface or this fails.
4029        for name in free_fn_names(BYNK_LIST_SRC) {
4030            assert!(
4031                find(&items, &name, CompletionKind::Function).is_some(),
4032                "bynk.list.{name}: {:?}",
4033                items.iter().map(|i| &i.label).collect::<Vec<_>>()
4034            );
4035        }
4036        // A module that is not imported does not leak its fns.
4037        assert!(
4038            find(&items, "values", CompletionKind::Function).is_none(),
4039            "bynk.map.values leaked without `uses bynk.map`"
4040        );
4041    }
4042
4043    #[test]
4044    fn locale_functions_offered_when_bynk_locale_is_used() {
4045        // #901: `bynk.locale` was absent from the embedded-source list, so its
4046        // builders/render never surfaced in completion even under `uses
4047        // bynk.locale`. Exercised through the real `complete()` path, not the
4048        // renderer alone.
4049        let doc = "commons app {\n  uses bynk.locale\n}\n";
4050        let items = complete("  let y = ", doc, None);
4051        for name in [
4052            "render",
4053            "message",
4054            "withText",
4055            "withWhole",
4056            "withNum",
4057            "withMoment",
4058        ] {
4059            assert!(
4060                find(&items, name, CompletionKind::Function).is_some(),
4061                "bynk.locale.{name} missing from completion: {:?}",
4062                items.iter().map(|i| &i.label).collect::<Vec<_>>()
4063            );
4064        }
4065    }
4066
4067    #[test]
4068    fn free_functions_require_a_uses_import() {
4069        // Own fns are always in scope; stdlib combinators only with their `uses`.
4070        let doc = "commons app {\n  fn helper(x: Int) -> Int { x }\n}\n";
4071        let items = complete("  let y = ", doc, None);
4072        assert!(find(&items, "helper", CompletionKind::Function).is_some());
4073        for name in ["map", "filter", "reverse"] {
4074            assert!(
4075                find(&items, name, CompletionKind::Function).is_none(),
4076                "bynk.list.{name} offered without `uses bynk.list`"
4077            );
4078        }
4079    }
4080
4081    #[test]
4082    fn another_units_private_items_are_not_offered() {
4083        // #2618: a used commons' `private` fns, assets, types and constants
4084        // are not in scope here, so completion leaves them out; the unit's own
4085        // are.
4086        let doc = "commons app {\n  uses lib\n  private fn mine() -> Int { 1 }\n}\n";
4087        let mut files = HashMap::new();
4088        files.insert(
4089            PathBuf::from("/p/lib.bynk"),
4090            "commons lib {\n  fn open() -> Int { 1 }\n  private fn hidden() -> Int { 2 }\n  private asset secret = \"s.css\"\n  type Shown = Int\n  private type Kept = Int\n  private const Limit: Int = 3\n  const Cap: Int = 4\n}\n"
4091                .to_string(),
4092        );
4093        let items = complete("  let y = ", doc, Some(&files));
4094        let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4095        assert!(
4096            find(&items, "open", CompletionKind::Function).is_some(),
4097            "{:?}",
4098            labels()
4099        );
4100        assert!(
4101            find(&items, "mine", CompletionKind::Function).is_some(),
4102            "{:?}",
4103            labels()
4104        );
4105        assert!(
4106            find(&items, "Shown", CompletionKind::Type).is_some(),
4107            "{:?}",
4108            labels()
4109        );
4110        assert!(items.iter().any(|i| i.label == "Cap"), "{:?}", labels());
4111        for hidden in ["hidden", "secret", "Kept", "Limit"] {
4112            assert!(
4113                !items.iter().any(|i| i.label == hidden),
4114                "a used unit's private `{hidden}` leaked: {:?}",
4115                labels()
4116            );
4117        }
4118    }
4119
4120    #[test]
4121    fn assets_offered_by_the_free_function_scope_rule() {
4122        // #1883: an asset name resolves where a free function's would — the
4123        // unit's own assets, and those of a `uses`-imported unit; never one
4124        // the unit does not import.
4125        let doc = "context app.page {\n  uses app.shared\n  asset logo = \"logo.svg\"\n  asset icon = \"favicon.ico\" at \"/favicon.ico\"\n}\n";
4126        let mut files = HashMap::new();
4127        files.insert(
4128            PathBuf::from("/p/shared.bynk"),
4129            "context app.shared {\n  --- The site stylesheet.\n  asset style = \"site.css\"\n}\n"
4130                .to_string(),
4131        );
4132        files.insert(
4133            PathBuf::from("/p/other.bynk"),
4134            "context app.other {\n  asset banner = \"banner.png\"\n}\n".to_string(),
4135        );
4136        let items = complete("  let y = ", doc, Some(&files));
4137        let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4138        let logo = find(&items, "logo", CompletionKind::Constant);
4139        assert!(logo.is_some(), "own asset: {:?}", labels());
4140        assert_eq!(
4141            logo.unwrap().detail.as_deref(),
4142            Some("asset logo = \"logo.svg\" — `this unit`")
4143        );
4144        assert_eq!(
4145            find(&items, "icon", CompletionKind::Constant).and_then(|c| c.detail.as_deref()),
4146            Some("asset icon = \"favicon.ico\" at \"/favicon.ico\" — `this unit`")
4147        );
4148        let style = find(&items, "style", CompletionKind::Constant);
4149        assert!(style.is_some(), "used unit's asset: {:?}", labels());
4150        assert_eq!(
4151            style.unwrap().documentation.as_deref(),
4152            Some("The site stylesheet.")
4153        );
4154        assert!(
4155            find(&items, "banner", CompletionKind::Constant).is_none(),
4156            "an asset of a unit not in `uses` leaked: {:?}",
4157            labels()
4158        );
4159    }
4160
4161    #[test]
4162    fn embeds_offered_by_the_free_function_scope_rule() {
4163        // #2387: an embed name resolves where a free function's would — the
4164        // unit's own embeds, and those of a `uses`-imported unit; never one
4165        // the unit does not import.
4166        let doc =
4167            "context app.page {\n  uses app.shared\n  embed shell = \"embeds/shell.html\"\n}\n";
4168        let mut files = HashMap::new();
4169        files.insert(
4170            PathBuf::from("/p/shared.bynk"),
4171            "commons app.shared {\n  --| The mail body.\n  embed mail = \"embeds/mail.txt\"\n}\n"
4172                .to_string(),
4173        );
4174        files.insert(
4175            PathBuf::from("/p/other.bynk"),
4176            "context app.other {\n  embed hidden = \"embeds/hidden.txt\"\n}\n".to_string(),
4177        );
4178        let items = complete("  let y = ", doc, Some(&files));
4179        let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4180        assert_eq!(
4181            find(&items, "shell", CompletionKind::Constant).and_then(|c| c.detail.as_deref()),
4182            Some("embed shell = \"embeds/shell.html\" — `this unit`"),
4183            "own embed: {:?}",
4184            labels()
4185        );
4186        let mail = find(&items, "mail", CompletionKind::Constant);
4187        assert!(mail.is_some(), "used unit's embed: {:?}", labels());
4188        assert_eq!(
4189            mail.unwrap().documentation.as_deref(),
4190            Some("The mail body.")
4191        );
4192        assert!(
4193            find(&items, "hidden", CompletionKind::Constant).is_none(),
4194            "an embed of a unit not in `uses` leaked: {:?}",
4195            labels()
4196        );
4197    }
4198
4199    #[test]
4200    fn asset_member_completion_offers_url() {
4201        // #1883: an asset value's one field.
4202        let asset = TYS.intern(Ty::Asset);
4203        let items = value_member_candidates(asset, &TYS, "context a.b\n", None);
4204        assert!(find(&items, "url", CompletionKind::Field).is_some());
4205    }
4206
4207    #[test]
4208    fn member_completion_reaches_inside_an_interpolation_hole() {
4209        // v0.43: a `Type.`/`Cap.` receiver inside a `\(…)` hole completes just
4210        // as it does in bare expression position — context detection is purely
4211        // lexical, so the surrounding string and `\(` do not interfere.
4212        let doc = "context a.b\n  capability Timer { fn now() -> Effect[Int] }\n";
4213        let in_hole = complete("    \"the time is \\(Timer.", doc, None);
4214        assert!(
4215            find(&in_hole, "now", CompletionKind::Member).is_some(),
4216            "capability op not offered inside a hole: {:?}",
4217            in_hole.iter().map(|c| &c.label).collect::<Vec<_>>()
4218        );
4219        // A built-in static receiver works inside a hole too.
4220        let statics = complete("  \"n=\\(Int.", "context a.b\n", None);
4221        assert!(find(&statics, "parse", CompletionKind::Member).is_some());
4222    }
4223
4224    #[test]
4225    fn consumes_brace_alias_position_suggests_nothing() {
4226        // #2887: the name after `as` is the user's own.
4227        for prefix in [
4228            "  consumes bynk.crypto { Crypto, Digest as ",
4229            "  consumes bynk.crypto { Crypto, Digest as Cry",
4230        ] {
4231            let got = labels(prefix, "context a.b\n");
4232            assert!(got.is_empty(), "{prefix}: {got:?}");
4233        }
4234        // The name before `as`, and after the comma, still complete.
4235        assert!(
4236            !labels("  consumes bynk { Clock, ", "context a.b\n").is_empty(),
4237            "capabilities still complete after a comma"
4238        );
4239    }
4240
4241    #[test]
4242    fn consumes_with_as_is_not_a_target_completion() {
4243        // `consumes X as ` is aliasing, not target-name completion.
4244        assert!(!is_consumes_target("consumes platform.time as "));
4245        assert!(is_consumes_target("consumes platform"));
4246    }
4247
4248    fn find<'a>(
4249        items: &'a [Completion],
4250        label: &str,
4251        kind: CompletionKind,
4252    ) -> Option<&'a Completion> {
4253        items.iter().find(|c| c.label == label && c.kind == kind)
4254    }
4255
4256    #[test]
4257    fn type_annotation_suggests_builtins_surface_and_project_types() {
4258        let doc = "commons m {\n  type Order = { id: Int }\n}\n";
4259        let got = labels("  let x: ", doc);
4260        // Built-ins (with registry docs), the `bynk`-surface transparent types,
4261        // and the project's own type declaration.
4262        for want in ["Int", "Option", "Result", "Effect", "List", "Map"] {
4263            assert!(got.contains(&want.to_string()), "built-in {want}: {got:?}");
4264        }
4265        assert!(got.contains(&"Uuid".to_string()), "surface: {got:?}");
4266        assert!(got.contains(&"Order".to_string()), "project: {got:?}");
4267    }
4268
4269    #[test]
4270    fn return_type_and_type_args_are_type_positions() {
4271        assert!(is_type_position("  on call() -> "));
4272        assert!(is_type_position("  let x: Option["));
4273        assert!(is_type_position("  let x: Result[Int, "));
4274        // A partial type name being typed still counts.
4275        assert!(is_type_position("  -> Eff"));
4276    }
4277
4278    #[test]
4279    fn list_literal_is_not_a_type_position() {
4280        // A bare `[` opening a list literal is an expression, not type args…
4281        assert!(!is_type_position("  let xs = ["));
4282        // …so it is an expression position: a list element is a value, and the
4283        // constructor keywords are offered there (ADR 0093 D3) — not a
4284        // type-argument completion.
4285        let items = complete("  let xs = [", "context a.b\n", None);
4286        assert!(
4287            find(&items, "Some", CompletionKind::Constructor).is_some(),
4288            "{:?}",
4289            items.iter().map(|c| &c.label).collect::<Vec<_>>()
4290        );
4291    }
4292
4293    #[test]
4294    fn builtin_type_carries_its_registry_doc() {
4295        let items = complete("  let x: ", "context a.b\n", None);
4296        let int = find(&items, "Int", CompletionKind::Type).expect("Int present");
4297        assert_eq!(int.detail.as_deref(), keyword_doc("Int"));
4298        assert!(int.detail.is_some(), "Int should have a doc");
4299    }
4300
4301    #[test]
4302    fn keyword_position_suggests_keywords_and_snippets() {
4303        let items = complete("  ", "context a.b\n", None);
4304        // Declaration/statement keywords, with docs.
4305        assert!(find(&items, "capability", CompletionKind::Keyword).is_some());
4306        assert!(find(&items, "fn", CompletionKind::Keyword).is_some());
4307        assert!(find(&items, "let", CompletionKind::Keyword).is_some());
4308        // Uppercase type/value names are *not* keyword-position candidates.
4309        assert!(find(&items, "Int", CompletionKind::Keyword).is_none());
4310        assert!(find(&items, "Some", CompletionKind::Keyword).is_none());
4311        // Snippets are offered alongside.
4312        let snip = find(&items, "service", CompletionKind::Snippet).expect("service snippet");
4313        let body = snip.insert_text.as_deref().unwrap_or("");
4314        assert!(body.contains("on call"), "snippet body: {body:?}");
4315        assert!(body.contains("${1"), "snippet tab stop: {body:?}");
4316    }
4317
4318    #[test]
4319    fn keyword_position_fires_on_an_empty_line() {
4320        assert!(is_keyword_position(""));
4321        assert!(is_keyword_position("  cap"));
4322        assert!(!is_keyword_position("  let x ="));
4323        assert!(!is_keyword_position("  x: "));
4324        assert!(!complete("", "context a.b\n", None).is_empty());
4325    }
4326
4327    #[test]
4328    fn a_cookie_record_completes_its_fields_then_cookie_and_expire() {
4329        let src = "context a.b\n\
4330            type Theme = enum { Light, Dark }\n\
4331            type Prefs = { theme: Theme = Light, @name(\"__Host-visits\") visits: Option[Int] }\n\
4332            service s from http {\n\
4333              on GET(\"/p\") (cookies: Prefs) -> Effect[HttpResult[String]] by v: Visitor { Ok(\"x\") }\n\
4334            }\n";
4335        let fields = complete("  Ok(\"x\").withCookie(Prefs.", src, None);
4336        // the ordinary members of the type name are still offered beside its fields
4337        let theme = complete("  Theme.", src, None);
4338        assert!(find(&theme, "Dark", CompletionKind::Variant).is_some());
4339        assert!(find(&fields, "theme", CompletionKind::Field).is_some());
4340        assert!(find(&fields, "visits", CompletionKind::Field).is_some());
4341        let members = complete("  Ok(\"x\").withCookie(Prefs.visits.", src, None);
4342        let cookie = find(&members, "cookie", CompletionKind::Member).expect("cookie");
4343        assert!(
4344            cookie
4345                .detail
4346                .as_deref()
4347                .unwrap_or("")
4348                .contains("value: Int"),
4349            "{:?}",
4350            cookie.detail
4351        );
4352        assert!(
4353            cookie
4354                .detail
4355                .as_deref()
4356                .unwrap_or("")
4357                .contains("__Host-visits"),
4358            "{:?}",
4359            cookie.detail
4360        );
4361        assert!(find(&members, "expire", CompletionKind::Member).is_some());
4362        // a record no handler decodes as `cookies` has no cookie members
4363        let plain = "context a.b\ntype P = { x: Int }\n";
4364        assert!(complete("  P.x.", plain, None).is_empty());
4365    }
4366
4367    #[test]
4368    fn member_receiver_is_a_single_upper_ident_before_a_dot() {
4369        assert_eq!(member_receiver("  Color."), Some("Color".to_string()));
4370        assert_eq!(
4371            member_receiver("  let e = Email.o"),
4372            Some("Email".to_string())
4373        );
4374        assert_eq!(member_receiver("  x."), None); // lowercase = value receiver (slice 3)
4375        assert_eq!(member_receiver("  1."), None); // decimal literal, not a member access
4376        assert_eq!(member_receiver("  a.B."), None); // `.`-qualified segment
4377        assert_eq!(member_receiver("  Color"), None); // no dot yet
4378    }
4379
4380    #[test]
4381    fn receiver_extraction_survives_a_multibyte_char_before_the_receiver() {
4382        // A multi-byte non-identifier char immediately before the receiver used
4383        // to make the `i + 1` byte offset land mid-codepoint → panic on slice
4384        // (#715, hit on every completion/hover keystroke inside a string).
4385        assert_eq!(member_receiver("\"Foo."), Some("Foo".to_string()));
4386        assert_eq!(member_receiver("€Color."), Some("Color".to_string()));
4387        assert_eq!(member_receiver("—Bar."), Some("Bar".to_string()));
4388        assert_eq!(word_before_brace("\"cors {", 6), "cors");
4389        assert_eq!(
4390            record_construction_receiver("\"€Order {"),
4391            Some("Order".to_string())
4392        );
4393        // The reproduction from the issue: a completion request against a buffer
4394        // where the line prefix opens a string literal must not panic.
4395        let _ = complete("let x = \"Foo.", "commons m {}\n", None);
4396        let _ = complete("  \"€42.", "commons m {}\n", None);
4397        assert_eq!(
4398            value_receiver_rewrite("\"email.", 7).map(|(_, r)| r),
4399            Some(5),
4400        );
4401    }
4402
4403    #[test]
4404    fn sum_member_suggests_variants() {
4405        let doc = "commons m {\n  type Color = enum { Red, Green, Blue }\n}\n";
4406        let items = complete("  let c = Color.", doc, None);
4407        for v in ["Red", "Green", "Blue"] {
4408            assert!(
4409                find(&items, v, CompletionKind::Variant).is_some(),
4410                "variant {v}: {:?}",
4411                items.iter().map(|c| &c.label).collect::<Vec<_>>()
4412            );
4413        }
4414    }
4415
4416    #[test]
4417    fn refined_and_plain_alias_members_are_of_and_unsafe() {
4418        // A refinement-bearing type…
4419        let doc = "commons m {\n  type Email = String where NonEmpty\n}\n";
4420        let items = complete("  Email.", doc, None);
4421        assert!(find(&items, "of", CompletionKind::Member).is_some());
4422        assert!(find(&items, "unsafe", CompletionKind::Member).is_some());
4423        // …and a plain alias `type Id = Int` is *also* branded (the emitter
4424        // emits Id.of/Id.unsafe for every Refined body, refinement or not).
4425        let doc = "commons m {\n  type Id = Int\n}\n";
4426        assert!(find(&complete("  Id.", doc, None), "of", CompletionKind::Member).is_some());
4427    }
4428
4429    #[test]
4430    fn auth_completes_the_schemes_and_a_signed_cookie_its_keys() {
4431        let schemes = complete("actor User { auth = Sig", "context a.b\n", None);
4432        assert!(find(&schemes, "SignedCookie", CompletionKind::Keyword).is_some());
4433        assert!(find(&schemes, "Bearer", CompletionKind::Keyword).is_some());
4434        let keys = complete(
4435            "actor User { auth = SignedCookie(secret = \"K\", ",
4436            "context a.b\n",
4437            None,
4438        );
4439        assert!(find(&keys, "ttl", CompletionKind::Field).is_some());
4440        assert!(
4441            find(&keys, "secret", CompletionKind::Field).is_none(),
4442            "already written"
4443        );
4444        let value = complete(
4445            "actor User { auth = SignedCookie(ttl = ",
4446            "context a.b\n",
4447            None,
4448        );
4449        assert!(value.is_empty());
4450        // A closed config offers nothing of its own.
4451        assert!(!auth_scheme_position(
4452            "actor User { auth = Bearer(secret = \"K\"), identity = "
4453        ));
4454    }
4455
4456    #[test]
4457    fn a_signed_cookie_actor_offers_issue_and_expire() {
4458        let doc = "context a.b\n\ntype UserId = String where NonEmpty\n\nactor User { auth = SignedCookie(secret = \"K\", ttl = 1.hour), identity = UserId }\n";
4459        let items = complete("    User.", doc, None);
4460        let issue = find(&items, "issue", CompletionKind::Member).expect("`issue` offered");
4461        assert_eq!(
4462            issue.detail.as_deref(),
4463            Some("issue(identity: UserId) -> Effect[Cookie] — session cookie of `User`")
4464        );
4465        assert!(find(&items, "expire", CompletionKind::Member).is_some());
4466        // Another scheme has neither.
4467        let doc =
4468            "context a.b\n\nactor Admin { auth = Bearer(secret = \"K\"), identity = String }\n";
4469        assert!(
4470            find(
4471                &complete("    Admin.", doc, None),
4472                "issue",
4473                CompletionKind::Member
4474            )
4475            .is_none()
4476        );
4477    }
4478
4479    #[test]
4480    fn capability_member_suggests_ops() {
4481        let doc = "context a.b\n  capability Timer { fn now() -> Effect[Int]\n  fn at(t: Int) -> Effect[()] }\n";
4482        let items = complete("    Timer.", doc, None);
4483        let now = find(&items, "now", CompletionKind::Member).expect("`now` op offered");
4484        // Slice 5 detail polish: a typed signature (params + return), not bare
4485        // param names.
4486        assert_eq!(
4487            now.detail.as_deref(),
4488            Some("now() -> Effect[Int] — operation of `Timer`")
4489        );
4490        let at = find(&items, "at", CompletionKind::Member).expect("`at` op offered");
4491        assert_eq!(
4492            at.detail.as_deref(),
4493            Some("at(t: Int) -> Effect[()] — operation of `Timer`")
4494        );
4495    }
4496
4497    /// #2865: a derived `D1` offers `select` / `firstAs` beside the base's ops.
4498    #[test]
4499    fn a_derived_d1_offers_the_typed_reads() {
4500        let doc = "context a.b\n\nconsumes bynk.cloudflare { D1 }\n\ncapability Orders = D1\n";
4501        let items = complete("    Orders.", doc, None);
4502        for op in ["select", "firstAs", "all", "first"] {
4503            assert!(
4504                find(&items, op, CompletionKind::Member).is_some(),
4505                "`{op}` offered"
4506            );
4507        }
4508    }
4509
4510    /// #3147: `D1.` offers `peek`, the case-only handle on a participant's database.
4511    #[test]
4512    fn the_d1_name_offers_peek() {
4513        let doc = "suite a.b as system {\n  case \"c\" {\n    let db = D1.\n  }\n}\n";
4514        let items = complete("    let db = D1.", doc, None);
4515        let peek = find(&items, "peek", CompletionKind::Member).expect("`peek` offered");
4516        assert_eq!(peek.detail.as_deref(), Some(D1_PEEK_SIGNATURE));
4517    }
4518
4519    /// Hyperdrive H3 (#3320): a derived `Postgres` offers the typed reads and
4520    /// `transaction` beside `all`, `first` and `run`.
4521    #[test]
4522    fn a_derived_postgres_offers_the_typed_reads_and_transaction() {
4523        let doc =
4524            "context a.b\n\nconsumes bynk.cloudflare { Postgres }\n\ncapability Main = Postgres\n";
4525        let items = complete("    Main.", doc, None);
4526        for op in ["select", "firstAs", "transaction", "all", "first", "run"] {
4527            assert!(
4528                find(&items, op, CompletionKind::Member).is_some(),
4529                "`{op}` offered"
4530            );
4531        }
4532        let select = find(&items, "select", CompletionKind::Member).expect("`select`");
4533        assert!(
4534            select
4535                .detail
4536                .as_deref()
4537                .is_some_and(|d| d.contains("PgReadError")),
4538            "{:?}",
4539            select.detail
4540        );
4541    }
4542
4543    #[test]
4544    fn statics_of_a_generic_type_are_offered() {
4545        // Constrained generics slice 4: `Box.` offers the type's statics, with
4546        // the signature as declared, and not its instance methods.
4547        let doc = "commons a.b
4548
4549type Box[T] = { value: T }
4550
4551fn Box.of(value: T) -> Box[T] { Box { value } }
4552
4553fn Box.size(self) -> Int { 1 }
4554";
4555        let items = complete("  Box.", doc, None);
4556        let of = find(&items, "of", CompletionKind::Member).expect("`of` offered");
4557        assert_eq!(of.detail.as_deref(), Some("of(value: T) -> Box[T]"));
4558        assert!(find(&items, "size", CompletionKind::Member).is_none());
4559    }
4560
4561    #[test]
4562    fn builtin_type_statics_are_offered() {
4563        assert!(
4564            find(
4565                &complete("  Int.", "context a.b\n", None),
4566                "parse",
4567                CompletionKind::Member
4568            )
4569            .is_some()
4570        );
4571        let j = complete("  Json.", "context a.b\n", None);
4572        assert!(find(&j, "encode", CompletionKind::Member).is_some());
4573        assert!(find(&j, "decode", CompletionKind::Member).is_some());
4574        // #3214: `Yaml.` offers its one static, `decode`, and no `encode`.
4575        let y = complete("  Yaml.", "context a.b\n", None);
4576        assert!(find(&y, "decode", CompletionKind::Member).is_some());
4577        assert!(find(&y, "encode", CompletionKind::Member).is_none());
4578    }
4579
4580    #[test]
4581    fn decimal_statics_and_rounding_modes_are_offered() {
4582        // #2622: `Decimal.` offers its two statics, and `RoundingMode.` every mode.
4583        let d = complete("  Decimal.", "context a.b\n", None);
4584        assert!(find(&d, "parse", CompletionKind::Member).is_some());
4585        assert!(find(&d, "fromInt", CompletionKind::Member).is_some());
4586        let r = complete("  RoundingMode.", "context a.b\n", None);
4587        for mode in bynk_syntax::ast::RoundingMode::ALL {
4588            assert!(
4589                find(&r, mode.name(), CompletionKind::Member).is_some(),
4590                "RoundingMode.{} missing",
4591                mode.name()
4592            );
4593        }
4594    }
4595
4596    #[test]
4597    fn builtin_sum_variants_are_complete() {
4598        // ADR 0093 D5/G3: every built-in sum variant in the AST registry must
4599        // surface on its name receiver. Registry-driven — adding an
4600        // `HttpResult`/`QueueResult` variant must appear in completion or this
4601        // fails (the standing drift guard, mirroring `kernel_registry`).
4602        let http: Vec<&str> = bynk_syntax::ast::HTTP_VARIANTS
4603            .iter()
4604            .map(|v| v.name)
4605            .collect();
4606        let queue: Vec<&str> = bynk_syntax::ast::QUEUE_VARIANTS
4607            .iter()
4608            .map(|v| v.name)
4609            .collect();
4610        for (recv, names) in [("HttpResult", http), ("QueueResult", queue)] {
4611            let items = complete(&format!("  {recv}."), "context a.b\n", None);
4612            for name in names {
4613                assert!(
4614                    find(&items, name, CompletionKind::Variant).is_some(),
4615                    "{recv}.{name} missing: {:?}",
4616                    items.iter().map(|c| &c.label).collect::<Vec<_>>()
4617                );
4618            }
4619        }
4620    }
4621
4622    #[test]
4623    fn builtin_statics_are_reachable() {
4624        // ADR 0093 D5/G2: every BUILTIN_STATICS entry is reachable through the
4625        // name-receiver context — exercises the member_receiver→member_candidates
4626        // wiring for each receiver (e.g. that `Effect.`/`List.` are recognised).
4627        for &(recv, members) in BUILTIN_STATICS {
4628            let items = complete(&format!("  {recv}."), "context a.b\n", None);
4629            for &(member, _) in members {
4630                assert!(
4631                    find(&items, member, CompletionKind::Member).is_some(),
4632                    "{recv}.{member} unreachable: {:?}",
4633                    items.iter().map(|c| &c.label).collect::<Vec<_>>()
4634                );
4635            }
4636        }
4637        // The slice-1 additions specifically — guards against a table regression
4638        // (the loop above can't catch an entry being deleted).
4639        for (recv, member) in [("List", "empty"), ("Map", "empty"), ("Effect", "pure")] {
4640            let items = complete(&format!("  {recv}."), "context a.b\n", None);
4641            assert!(
4642                find(&items, member, CompletionKind::Member).is_some(),
4643                "{recv}.{member} missing from the statics table"
4644            );
4645        }
4646    }
4647
4648    #[test]
4649    fn record_value_and_decimal_receivers_yield_nothing() {
4650        // A record type has no name-receiver members (fields are value-receiver).
4651        let doc = "commons m {\n  type Point = { x: Int }\n}\n";
4652        assert!(complete("  Point.", doc, None).is_empty(), "record");
4653        // A lowercase value receiver is deferred to slice 3.
4654        assert!(complete("  let p = q.", doc, None).is_empty(), "value");
4655        // An integer literal's `.` is a `Duration` unit (#3947), singular after `1`.
4656        let units: Vec<_> = complete("  let n = 1.", doc, None)
4657            .into_iter()
4658            .map(|c| c.label)
4659            .collect();
4660        assert_eq!(units, ["millisecond", "second", "minute", "hour", "day"]);
4661    }
4662
4663    #[test]
4664    fn value_receiver_rewrite_drops_the_dot_for_lowercase_receivers() {
4665        let text = "  let x = email.\n";
4666        let offset = text.find('.').unwrap() + 1; // just after the dot
4667        let (rewritten, recv) = value_receiver_rewrite(text, offset).expect("value receiver");
4668        assert_eq!(
4669            rewritten, "  let x = email\n",
4670            "the trailing dot is dropped"
4671        );
4672        assert!(
4673            text.get(recv..=recv).is_some_and(|c| c == "l"),
4674            "the receiver offset lands inside `email`"
4675        );
4676        // A partial member is dropped too.
4677        let text2 = "  let x = email.ma\n";
4678        let off2 = text2.find(".ma").unwrap() + 3;
4679        assert_eq!(
4680            value_receiver_rewrite(text2, off2).map(|(r, _)| r),
4681            Some("  let x = email\n".to_string())
4682        );
4683        // Uppercase (name receiver, slice 2), decimal, and no-dot yield None.
4684        assert!(value_receiver_rewrite("  Email.", 8).is_none());
4685        assert!(value_receiver_rewrite("  let n = 1.", 12).is_none());
4686        assert!(value_receiver_rewrite("  email", 7).is_none());
4687    }
4688
4689    /// One table for every fixture in this module — `Types` is `Send + Sync`
4690    /// (T3.6b), so a `LazyLock` static gives the `TyId`s below something to
4691    /// resolve against without threading a value through each helper.
4692    static TYS: std::sync::LazyLock<Types> = std::sync::LazyLock::new(Types::new);
4693
4694    /// #2138: `run.` offers `id` in a case body, not once the case binds its
4695    /// own `run`.
4696    #[test]
4697    fn run_member_offers_id_in_a_case_body() {
4698        let labels = |text: &str| {
4699            let offset = text.find("run.").expect("run.") + "run.".len();
4700            let (rewritten, recv) = value_receiver_rewrite(text, offset).expect("a value receiver");
4701            run_id_member_candidates(&rewritten, recv)
4702                .into_iter()
4703                .map(|c| c.label)
4704                .collect::<Vec<_>>()
4705        };
4706        assert_eq!(
4707            labels("suite rid.orders {\n  case \"a\" {\n    expect run. == \"local\"\n  }\n}\n"),
4708            ["id"]
4709        );
4710        assert!(
4711            labels("suite rid.orders {\n  case \"a\" {\n    let run = 1\n    expect run. == 1\n  }\n}\n")
4712                .is_empty()
4713        );
4714    }
4715
4716    #[test]
4717    fn value_member_candidates_lists_kernel_methods() {
4718        use bynk_syntax::ast::BaseType;
4719        let list = TYS.intern(Ty::List(TYS.intern(Ty::Base(BaseType::Int))));
4720        let items = value_member_candidates(list, &TYS, "context a.b\n", None);
4721        assert!(find(&items, "fold", CompletionKind::Member).is_some());
4722        assert!(find(&items, "get", CompletionKind::Member).is_some());
4723
4724        let string = TYS.intern(Ty::Base(BaseType::String));
4725        let items = value_member_candidates(string, &TYS, "context a.b\n", None);
4726        assert!(find(&items, "split", CompletionKind::Member).is_some());
4727        assert!(find(&items, "trim", CompletionKind::Member).is_some());
4728    }
4729
4730    /// #2683: `within` is offered on every `Effect`, and beside the
4731    /// `Effect[Result]` combinators on one that holds a `Result`.
4732    #[test]
4733    fn value_member_candidates_offers_within_on_any_effect() {
4734        use bynk_syntax::ast::BaseType;
4735        let int = TYS.intern(Ty::Base(BaseType::Int));
4736        let plain = TYS.intern(Ty::Effect(int));
4737        let items = value_member_candidates(plain, &TYS, "context a.b\n", None);
4738        let within = find(&items, "within", CompletionKind::Member).expect("within is offered");
4739        assert_eq!(
4740            within.detail.as_deref(),
4741            Some("within(d: Duration) -> Effect[Result[T, TimedOut]]")
4742        );
4743        assert!(find(&items, "mapOk", CompletionKind::Member).is_none());
4744        // #2711: `race` is offered beside it.
4745        let race = find(&items, "race", CompletionKind::Member).expect("race is offered");
4746        assert_eq!(
4747            race.detail.as_deref(),
4748            Some("race(other: Effect[T]) -> Effect[T]")
4749        );
4750
4751        // #3437: `detach` is offered on every `Effect`.
4752        let detach = find(&items, "detach", CompletionKind::Member).expect("detach is offered");
4753        assert_eq!(detach.detail.as_deref(), Some("detach() -> Effect[()]"));
4754
4755        let result = TYS.intern(Ty::Result(int, int));
4756        let fallible = TYS.intern(Ty::Effect(result));
4757        let items = value_member_candidates(fallible, &TYS, "context a.b\n", None);
4758        assert!(find(&items, "detach", CompletionKind::Member).is_some());
4759        assert!(find(&items, "within", CompletionKind::Member).is_some());
4760        assert!(find(&items, "race", CompletionKind::Member).is_some());
4761        assert!(find(&items, "mapOk", CompletionKind::Member).is_some());
4762    }
4763
4764    #[test]
4765    fn value_member_candidates_lists_refined_inherited_kernel_methods() {
4766        // #561: a refined receiver offers its base type's read-only kernel
4767        // methods in `.`-member completion.
4768        use bynk_check::checker::NamedKind;
4769        use bynk_syntax::ast::BaseType;
4770        let name = TYS.intern(Ty::Named {
4771            name: "Name".to_string(),
4772            kind: NamedKind::Refined(BaseType::String),
4773            args: Vec::new(),
4774        });
4775        let items = value_member_candidates(
4776            name,
4777            &TYS,
4778            "commons m {\n  type Name = String where NonEmpty\n}\n",
4779            None,
4780        );
4781        assert!(find(&items, "toUpper", CompletionKind::Member).is_some());
4782        assert!(find(&items, "length", CompletionKind::Member).is_some());
4783    }
4784
4785    #[test]
4786    fn expression_position_offers_locals() {
4787        // Value-expecting positions (locals offered).
4788        assert!(is_expression_position("  let y = "));
4789        assert!(is_expression_position("  let y = a + lo")); // after a binary op
4790        assert!(is_expression_position("  f("));
4791        assert!(is_expression_position("  g(a, "));
4792        assert!(is_expression_position("  xs.fold(0, (acc, x) => ac")); // lambda body
4793        // `let y = foo` is still a value position (you're typing the value).
4794        assert!(is_expression_position("  let y = foo"));
4795        // Not value positions.
4796        assert!(!is_expression_position("  let y: ")); // type annotation
4797        assert!(!is_expression_position("  on call() -> ")); // return type
4798        assert!(!is_expression_position("  tot")); // bare line start (keyword position covers it)
4799    }
4800
4801    #[test]
4802    fn value_member_candidates_lists_record_fields() {
4803        use bynk_check::checker::NamedKind;
4804        let order = TYS.intern(Ty::Named {
4805            name: "Order".to_string(),
4806            kind: NamedKind::Record,
4807            args: Vec::new(),
4808        });
4809        let doc = "commons m {\n  type Order = { id: Int, total: Int }\n}\n";
4810        let items = value_member_candidates(order, &TYS, doc, None);
4811        assert!(
4812            find(&items, "id", CompletionKind::Field).is_some(),
4813            "{items:?}",
4814            items = items.iter().map(|c| &c.label).collect::<Vec<_>>()
4815        );
4816        assert!(find(&items, "total", CompletionKind::Field).is_some());
4817    }
4818
4819    #[test]
4820    fn value_member_candidates_lists_json_error_fields() {
4821        let err = TYS.intern(Ty::DecodeError);
4822        let items = value_member_candidates(err, &TYS, "commons m {\n}\n", None);
4823        for f in ["kind", "path", "message"] {
4824            assert!(find(&items, f, CompletionKind::Field).is_some(), "{f}");
4825        }
4826    }
4827
4828    #[test]
4829    fn value_member_candidates_lists_validation_error_fields() {
4830        let err = TYS.intern(Ty::ValidationError);
4831        let items = value_member_candidates(err, &TYS, "commons m {\n}\n", None);
4832        for f in ["field", "message"] {
4833            assert!(find(&items, f, CompletionKind::Field).is_some(), "{f}");
4834        }
4835        assert!(find(&items, "value", CompletionKind::Field).is_none());
4836    }
4837
4838    #[test]
4839    fn store_field_member_candidates_offers_entry_ops_and_query_accessors() {
4840        // #596: a bare `store Map` field receiver offers its entry ops
4841        // (put/get/…) AND the `.entries`/`.keys`/`.values` accessors — the
4842        // vocabulary `value_member_candidates` alone can't see, since the
4843        // checker types a bare store map as plain `Ty::Query` (ADR 0120).
4844        let doc = "context shop\n\nagent Inventory {\n  key id: String\n  store items: Map[String, Int]\n\n  on call f() -> Effect[()] {\n    items.\n  }\n}\n";
4845        let offset = doc.find("items.").unwrap() + "items.".len();
4846        let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4847        let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4848        assert!(
4849            find(&items, "put", CompletionKind::Member).is_some(),
4850            "{items:?}",
4851            items = items.iter().map(|c| &c.label).collect::<Vec<_>>()
4852        );
4853        assert!(find(&items, "get", CompletionKind::Member).is_some());
4854        assert!(find(&items, "update", CompletionKind::Member).is_some());
4855        assert!(find(&items, "entries", CompletionKind::Field).is_some());
4856        assert!(find(&items, "keys", CompletionKind::Field).is_some());
4857        assert!(find(&items, "values", CompletionKind::Field).is_some());
4858    }
4859
4860    #[test]
4861    fn store_field_member_candidates_empty_for_ordinary_local() {
4862        // An ordinary local named the same as no store field yields nothing —
4863        // the receiver's provenance, not its name alone, drives this path.
4864        let doc = "context shop\n\nagent Inventory {\n  key id: String\n\n  on call f() -> Effect[()] {\n    let items = 1\n    items.\n  }\n}\n";
4865        let offset = doc.rfind("items.").unwrap() + "items.".len();
4866        let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4867        let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4868        assert!(items.is_empty());
4869    }
4870
4871    #[test]
4872    fn store_field_member_candidates_skips_query_accessors_on_held_map() {
4873        // ADR 0184: a held `Map[K, Connection]` never offers the key-query
4874        // accessors, only its entry ops (`put`/`get`/…).
4875        let doc = "context shop\n\nagent Room {\n  key id: String\n  store conns: Map[String, Connection[String]]\n\n  on call f() -> Effect[()] {\n    conns.\n  }\n}\n";
4876        let offset = doc.find("conns.").unwrap() + "conns.".len();
4877        let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4878        let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4879        assert!(find(&items, "put", CompletionKind::Member).is_some());
4880        assert!(find(&items, "entries", CompletionKind::Field).is_none());
4881        assert!(find(&items, "keys", CompletionKind::Field).is_none());
4882        assert!(find(&items, "values", CompletionKind::Field).is_none());
4883    }
4884
4885    #[test]
4886    fn store_field_member_candidates_offers_set_and_cache_vocabularies() {
4887        // Not every store kind gets the Map-only accessors, but every kind
4888        // gets its own entry ops.
4889        let doc = "context shop\n\nagent Inventory {\n  key id: String\n  store tags: Set[String]\n\n  on call f() -> Effect[()] {\n    tags.\n  }\n}\n";
4890        let offset = doc.find("tags.").unwrap() + "tags.".len();
4891        let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4892        let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4893        assert!(find(&items, "add", CompletionKind::Member).is_some());
4894        assert!(find(&items, "entries", CompletionKind::Field).is_none());
4895    }
4896
4897    // -- v0.124 (slice 3): the non-keyword completion contexts --
4898
4899    #[test]
4900    fn record_construction_offers_field_names() {
4901        let doc = "commons m {\n  type Order = { id: Int, total: Int }\n}\n";
4902        let got = labels("  let o = Order { ", doc);
4903        assert!(got.contains(&"id".to_string()), "{got:?}");
4904        assert!(got.contains(&"total".to_string()), "{got:?}");
4905        // After a comma, still field-name position.
4906        let got2 = labels("  let o = Order { id: 1, ", doc);
4907        assert!(got2.contains(&"total".to_string()), "{got2:?}");
4908        // After a `:`, it is a field *type* position, not a field name.
4909        assert!(record_construction_receiver("  let o = Order { id: ").is_none());
4910        // A lowercase brace context (a block) is not a construction.
4911        assert!(record_construction_receiver("  if x { ").is_none());
4912    }
4913
4914    #[test]
4915    fn record_construction_lists_defaulted_fields_last_with_their_default() {
4916        // #2607: a literal may leave a defaulted field out, so the fields it must
4917        // give come first.
4918        let doc = "commons m\n\ntype Opts = { retries: Int = 3, name: String }\n";
4919        let fields = record_field_names("Opts", doc, None);
4920        let names: Vec<&str> = fields.iter().map(|c| c.label.as_str()).collect();
4921        assert_eq!(names, ["name", "retries"], "{names:?}");
4922        assert_eq!(fields[0].detail.as_deref(), Some("field of `Opts`"));
4923        assert_eq!(
4924            fields[1].detail.as_deref(),
4925            Some("field of `Opts`, default `3`")
4926        );
4927    }
4928
4929    #[test]
4930    fn record_pattern_offers_the_unlisted_fields_then_rest() {
4931        let doc = "commons m {\n  type Order = { id: Int, total: Int, note: String }\n}\n";
4932        for prefix in [
4933            "    Order { ",
4934            "    Some(Order { ",
4935            "  if o is (Order { ",
4936            "    Ok(Order { id: 1, ",
4937            // #2654: a destructuring `let`, plain, parenthesised and under a variant.
4938            "  let Order { ",
4939            "  let Order { id, ",
4940            "  let (Order { ",
4941            "  let Some(Order { ",
4942            // #2712: a lambda's pattern parameter, first or after other parameters.
4943            "  items.map((Order { ",
4944            "  items.map((Order { id, ",
4945            "  items.fold(0, (total, Order { ",
4946            "  items.fold(0, (total, Order { id, ",
4947            "  items.fold(0, (total: Int, Order { ",
4948        ] {
4949            let got = labels(prefix, doc);
4950            assert!(got.contains(&"..".to_string()), "{prefix}: {got:?}");
4951            assert!(got.contains(&"total".to_string()), "{prefix}: {got:?}");
4952        }
4953        // Already-listed fields are not offered again; a nested comma is not a split.
4954        let got = labels("    Order { id: Some(1, 2), total, ", doc);
4955        assert!(!got.contains(&"id".to_string()), "{got:?}");
4956        assert!(!got.contains(&"total".to_string()), "{got:?}");
4957        assert!(got.contains(&"note".to_string()), "{got:?}");
4958        // A construction keeps offering every field, and no `..`.
4959        let got = labels("  let o = Order { ", doc);
4960        assert!(
4961            got.contains(&"id".to_string()) && !got.contains(&"..".to_string()),
4962            "{got:?}"
4963        );
4964        let got = labels("  => Order { id: 1, ", doc);
4965        assert!(!got.contains(&"..".to_string()), "{got:?}");
4966        // A `let` that binds a name and then constructs is a construction.
4967        let got = labels("  let o = Order { ", doc);
4968        assert!(!got.contains(&"..".to_string()), "{got:?}");
4969        let got = labels("  let Order { id, ", doc);
4970        assert!(!got.contains(&"id".to_string()), "{got:?}");
4971        // #2712: a call-argument construction is still a construction, and so is
4972        // a record type after something that is not a parameter list.
4973        let got = labels("  items.map(Order { ", doc);
4974        assert!(!got.contains(&"..".to_string()), "{got:?}");
4975        let got = labels("  items.fold(0, f(1, Order { ", doc);
4976        assert!(!got.contains(&"..".to_string()), "{got:?}");
4977        let got = labels("  let o = (Order { ", doc);
4978        assert!(!got.contains(&"..".to_string()), "{got:?}");
4979    }
4980
4981    #[test]
4982    fn from_offers_protocols() {
4983        let got = labels("  service s from ", "context a.b\n");
4984        assert!(got.contains(&"http".to_string()), "{got:?}");
4985        assert!(got.contains(&"cron".to_string()) && got.contains(&"queue".to_string()));
4986        // #3328: inbound email is the seventh protocol.
4987        assert!(got.contains(&"email".to_string()), "{got:?}");
4988    }
4989
4990    /// #3328: the verdict's four names complete on their type.
4991    #[test]
4992    fn email_verdict_variants_complete() {
4993        let items = complete("  EmailVerdict.", "context a.b\n", None);
4994        for name in ["Accept", "Reject", "Forward", "Reply"] {
4995            assert!(
4996                find(&items, name, CompletionKind::Variant).is_some(),
4997                "{name} missing: {:?}",
4998                items.iter().map(|c| &c.label).collect::<Vec<_>>()
4999            );
5000        }
5001    }
5002
5003    #[test]
5004    fn on_offers_handler_kinds() {
5005        let got = labels("  on ", "context a.b\n");
5006        assert!(got.contains(&"call".to_string()), "{got:?}");
5007        assert!(got.contains(&"GET".to_string()) && got.contains(&"schedule".to_string()));
5008    }
5009
5010    #[test]
5011    fn by_offers_project_actors() {
5012        let doc = "context a.b\n\nactor Caller { auth = Bearer }\n";
5013        let got = labels("  on call f() -> Effect[Int] by ", doc);
5014        assert!(got.contains(&"Caller".to_string()), "{got:?}");
5015    }
5016
5017    #[test]
5018    fn exports_offers_export_kinds() {
5019        let got = labels("  exports ", "adapter t {\n  binding \"./b.ts\"\n}\n");
5020        assert!(got.contains(&"capability".to_string()), "{got:?}");
5021        assert!(got.contains(&"transparent".to_string()));
5022    }
5023
5024    #[test]
5025    fn provides_offers_in_scope_capabilities() {
5026        let doc = "context a.b\n\ncapability Store { fn get() -> Effect[Int] }\n";
5027        let got = labels("  provides ", doc);
5028        assert!(got.contains(&"Store".to_string()), "{got:?}");
5029    }
5030
5031    #[test]
5032    fn where_offers_predicate_names() {
5033        // Type-decl refinement.
5034        let got = labels("  type Code = Int where ", "context a.b\n");
5035        assert!(got.contains(&"InRange".to_string()), "{got:?}");
5036        assert!(got.contains(&"NonNegative".to_string()));
5037        assert!(got.contains(&"IsoDate".to_string()), "{got:?}");
5038        // #472: a match arm's `_ where <predicate>` shares the same catalogue.
5039        let got = labels("      _ where ", "context a.b\n");
5040        assert!(got.contains(&"Matches".to_string()), "{got:?}");
5041        assert!(got.contains(&"NonEmpty".to_string()));
5042    }
5043
5044    #[test]
5045    fn is_for_all_where_matches_only_the_for_all_binder() {
5046        assert!(is_for_all_where("\tfor all x: Int, y: Int where "));
5047        assert!(is_for_all_where("for all x: Int where "));
5048        // `for`/`all` must be standalone words, not prefixes of longer
5049        // identifiers.
5050        assert!(!is_for_all_where("format(x) where "));
5051        assert!(!is_for_all_where("for allocate x where "));
5052        // A type-decl or match-arm `where` isn't a `for all` binder.
5053        assert!(!is_for_all_where("  type Code = Int where "));
5054        assert!(!is_for_all_where("      _ where "));
5055        assert!(!is_for_all_where("no where here"));
5056    }
5057
5058    #[test]
5059    fn for_all_where_falls_through_to_expression_position_not_predicates() {
5060        // #472 (finding 2, PR #827 review): a `for all` binder's `where`
5061        // clause takes an arbitrary `Bool`, not the predicate catalogue —
5062        // it must not offer `InRange`/`NonNegative`/etc.
5063        let got = labels("\tfor all x: Int where ", "context a.b\n");
5064        assert!(!got.contains(&"InRange".to_string()), "{got:?}");
5065        assert!(!got.contains(&"NonNegative".to_string()), "{got:?}");
5066    }
5067
5068    #[test]
5069    fn clause_detectors_do_not_over_fire() {
5070        // `on` inside a larger word, and a field named `from`, must not trigger.
5071        assert!(!after_clause_keyword("  session ", "on"));
5072        assert!(!after_clause_keyword("  let from = ", "from"));
5073        // A standalone keyword does.
5074        assert!(after_clause_keyword("  service s from ", "from"));
5075        assert!(after_clause_keyword("    by ", "by"));
5076    }
5077
5078    #[test]
5079    fn by_offers_actors_only_where_it_is_the_clause_word() {
5080        // The clause positions.
5081        assert!(is_by_clause_position(
5082            "  on GET(\"/\") () -> Effect[Int] by "
5083        ));
5084        assert!(is_by_clause_position("service api from http by "));
5085        assert!(is_by_clause_position("    let r <- svc.POST(\"/h\") by "));
5086        assert!(is_by_clause_position("    expect svc.GET(\"/h\") by "));
5087        // A name: a binding, a parameter, a reference, or `advance`'s amount.
5088        assert!(!is_by_clause_position("    let x = a + by "));
5089        assert!(!is_by_clause_position("  fn shift(xs: List[Int], by "));
5090        assert!(!is_by_clause_position("    advance Clock by "));
5091        // `by` as an argument or a parameter after a comma or an operator.
5092        assert!(!is_by_clause_position("    let r <- f(a, by "));
5093        assert!(!is_by_clause_position("  on call f(g: (Int) -> Int, by "));
5094        assert!(!is_by_clause_position("    let r <- f(by "));
5095        // A reference in a one-line body, after the return type's `->`.
5096        assert!(!is_by_clause_position("  fn f(by: Int) -> Int { by "));
5097        assert!(!is_by_clause_position("    by "));
5098    }
5099
5100    #[test]
5101    fn contract_clause_kind_detects_requires_and_ensures() {
5102        assert_eq!(contract_clause_kind("  requires positive: "), Some(false));
5103        assert_eq!(contract_clause_kind("  ensures never_neg: "), Some(true));
5104        // Not a contract clause.
5105        assert_eq!(contract_clause_kind("  id: Int"), None);
5106        assert_eq!(contract_clause_kind("  let x = 1"), None);
5107    }
5108
5109    #[test]
5110    fn cors_field_position_inside_cors_block() {
5111        // Cursor at a fresh field-name line inside a `cors { }` block.
5112        let doc = "service api from http {\n  cors {\n    ";
5113        assert!(in_cors_field_position(doc, doc.len()));
5114        // After a `:` it is a value position, not a field-name position.
5115        let doc2 = "service api from http {\n  cors {\n    origins: ";
5116        assert!(!in_cors_field_position(doc2, doc2.len()));
5117        // Not inside a `cors` block (an ordinary record construction) — no.
5118        let doc3 = "let x = Order {\n    ";
5119        assert!(!in_cors_field_position(doc3, doc3.len()));
5120    }
5121
5122    /// #2640: inside `par { }` only the two statement forms are offered, and the
5123    /// `par` snippet appears only where a body is effectful.
5124    #[test]
5125    fn par_block_positions_and_candidates() {
5126        let inside = "service s {\n  on call() -> Effect[Int] by Caller {\n    par {\n      ";
5127        assert!(in_par_block_position(inside, inside.len()));
5128        let labels: Vec<String> = par_block_candidates()
5129            .into_iter()
5130            .map(|c| c.label)
5131            .collect();
5132        assert_eq!(labels, ["let x <-", "do"]);
5133        // After the closing brace the statement is an ordinary one again.
5134        let after = "service s {\n  on call() -> Effect[Int] by Caller {\n    par {\n      let a <- f()\n    }\n    ";
5135        assert!(!in_par_block_position(after, after.len()));
5136        assert!(in_effectful_body_position(after, after.len()));
5137    }
5138
5139    #[test]
5140    fn par_snippet_is_for_effectful_bodies_only() {
5141        let effectful = "fn f() -> Effect[Int] {\n  if true {\n    ";
5142        assert!(in_effectful_body_position(effectful, effectful.len()));
5143        let pure = "fn f() -> Int {\n  ";
5144        assert!(!in_effectful_body_position(pure, pure.len()));
5145        let top = "context c\n\n";
5146        assert!(!in_effectful_body_position(top, top.len()));
5147        assert!(par_snippet().insert_text.unwrap().starts_with("par {"));
5148    }
5149
5150    #[test]
5151    fn security_field_position_inside_security_block() {
5152        // Cursor at a fresh field-name line inside a `security { }` block.
5153        let doc = "service api from http {\n  security {\n    ";
5154        assert!(in_security_field_position(doc, doc.len()));
5155        // After a `:` it is a value position, not a field-name position.
5156        let doc2 = "service api from http {\n  security {\n    hsts: ";
5157        assert!(!in_security_field_position(doc2, doc2.len()));
5158        // A `cors { }` block is not a `security` block.
5159        let doc3 = "service api from http {\n  cors {\n    ";
5160        assert!(!in_security_field_position(doc3, doc3.len()));
5161    }
5162
5163    /// Non-ASCII text inside the block (a `-- café` comment) must not break
5164    /// the field-position probes; a mid-codepoint offset degrades to `false`
5165    /// instead of panicking the request handler.
5166    #[test]
5167    fn field_position_probes_survive_non_ascii() {
5168        let doc = "service api from http {\n  cors { // café\n    ";
5169        assert!(in_cors_field_position(doc, doc.len()));
5170        // A raw byte offset that lands inside the `é` must not panic.
5171        let mid = doc.find('é').unwrap() + 1;
5172        assert!(!doc.is_char_boundary(mid));
5173        let _ = in_cors_field_position(doc, mid);
5174        let _ = in_security_field_position(doc, mid);
5175        let _ = in_limits_field_position(doc, mid);
5176        let _ = in_json_field_position(doc, mid);
5177        let _ = in_json_options_value_position(doc, mid);
5178    }
5179
5180    #[test]
5181    fn json_positions_inside_the_section_and_the_annotation() {
5182        // #2858: a field name in `json { }`, the `options:` value in either
5183        // form, and an argument name in `@json( )`.
5184        let name = "service api from http {\n  json {\n    ";
5185        assert!(in_json_field_position(name, name.len()));
5186        assert!(!in_json_options_value_position(name, name.len()));
5187        let value = "service api from http {\n  json {\n    options: ";
5188        assert!(!in_json_field_position(value, value.len()));
5189        assert!(in_json_options_value_position(value, value.len()));
5190        let ann = "service api from http {\n  @json(";
5191        assert!(in_json_arg_position(ann, ann.len()));
5192        let ann_value = "service api from http {\n  @json(options: pl";
5193        assert!(in_json_options_value_position(ann_value, ann_value.len()));
5194        // A `limits { }` block is not a `json` block, nor a bare `json(` call.
5195        let limits = "service api from http {\n  limits {\n    options: ";
5196        assert!(!in_json_options_value_position(limits, limits.len()));
5197        let call = "fn f() { json(";
5198        assert!(!in_json_arg_position(call, call.len()));
5199    }
5200
5201    #[test]
5202    fn by_in_a_suite_offers_the_reserved_principals() {
5203        // #2135, #2864: `Nobody`, `Forged`, `Stale` and `Expired` after `by` in a
5204        // suite only.
5205        let suite = "suite pay.hooks as system {\n  case \"c\" {\n    let r <- webhooks.POST(\"/h\", \"x\") by ";
5206        let labels: Vec<String> =
5207            complete("    let r <- webhooks.POST(\"/h\", \"x\") by ", suite, None)
5208                .into_iter()
5209                .map(|c| c.label)
5210                .collect();
5211        for name in [
5212            "Nobody",
5213            "Forged",
5214            "Stale",
5215            "Expired",
5216            "WrongIssuer",
5217            "WrongAudience",
5218            "WrongAlgorithm",
5219            "NoSubject",
5220        ] {
5221            assert!(labels.iter().any(|l| l == name), "{name}: {labels:?}");
5222        }
5223        let context = "context pay.hooks\n\nservice api from http {\n  on GET(\"/a\") () -> Effect[HttpResult[String]] by ";
5224        let labels: Vec<String> = complete(
5225            "  on GET(\"/a\") () -> Effect[HttpResult[String]] by ",
5226            context,
5227            None,
5228        )
5229        .into_iter()
5230        .map(|c| c.label)
5231        .collect();
5232        assert!(!labels.iter().any(|l| l == "Forged"), "{labels:?}");
5233    }
5234
5235    #[test]
5236    fn env_name_position_and_candidates() {
5237        // #2134: a fresh entry line inside a suite's `env { }` block.
5238        let doc = "suite shop.pay {\n  env {\n    ";
5239        assert!(in_env_name_position(doc, doc.len()));
5240        // After `=` it is a value position.
5241        let doc2 = "suite shop.pay {\n  env {\n    A = ";
5242        assert!(!in_env_name_position(doc2, doc2.len()));
5243        // A case body is not an `env` block.
5244        let doc3 = "suite shop.pay {\n  case \"c\" {\n    ";
5245        assert!(!in_env_name_position(doc3, doc3.len()));
5246        let mut files = HashMap::new();
5247        files.insert(
5248            PathBuf::from("src/pay.bynk"),
5249            "actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = String }\n\
5250             let p <- Secrets.get(\"PAYMENTS_PROCESSOR\")\n"
5251                .to_string(),
5252        );
5253        let labels: Vec<String> = env_name_candidates(doc, Some(&files))
5254            .into_iter()
5255            .map(|c| c.label)
5256            .collect();
5257        assert_eq!(labels, ["AUTH_JWT_SECRET", "PAYMENTS_PROCESSOR"]);
5258    }
5259
5260    #[test]
5261    fn limits_field_position_inside_limits_block() {
5262        // Cursor at a fresh field-name line inside a `limits { }` block.
5263        let doc = "service api from http {\n  limits {\n    ";
5264        assert!(in_limits_field_position(doc, doc.len()));
5265        // After a `:` it is a value position, not a field-name position.
5266        let doc2 = "service api from http {\n  limits {\n    maxBody: ";
5267        assert!(!in_limits_field_position(doc2, doc2.len()));
5268        // A `security { }` block is not a `limits` block.
5269        let doc3 = "service api from http {\n  security {\n    ";
5270        assert!(!in_limits_field_position(doc3, doc3.len()));
5271    }
5272
5273    #[test]
5274    fn service_body_item_position_offers_cors() {
5275        // A bare-word item start inside a `service … {` block.
5276        let doc = "service api from http {\n  ";
5277        assert!(in_service_body_item_position(doc, doc.len(), "  "));
5278        // Inside a nested `cors { }` block the innermost brace is not the
5279        // service brace, so the service-item cell does not fire.
5280        let doc2 = "service api from http {\n  cors {\n    ";
5281        assert!(!in_service_body_item_position(doc2, doc2.len(), "    "));
5282    }
5283
5284    #[test]
5285    fn cache_arg_position_inside_cache_annotation() {
5286        // Cursor at a fresh argument-name position inside `@cache( … )`.
5287        let doc = "service api from http {\n  @cache(";
5288        assert!(in_cache_arg_position(doc, doc.len()));
5289        // After a first arg + comma, still an argument-name position.
5290        let doc2 = "service api from http {\n  @cache(maxAge: 5.minutes, ";
5291        assert!(in_cache_arg_position(doc2, doc2.len()));
5292        // After a `:` it is a value position, not an argument-name position.
5293        let doc3 = "service api from http {\n  @cache(maxAge: ";
5294        assert!(!in_cache_arg_position(doc3, doc3.len()));
5295        // A bare `cache(` call (no `@`) is not the annotation.
5296        let doc4 = "let x = cache(";
5297        assert!(!in_cache_arg_position(doc4, doc4.len()));
5298        // An ordinary handler param list is not a `@cache` position.
5299        let doc5 = "on GET(\"/x\") by v: Visitor (";
5300        assert!(!in_cache_arg_position(doc5, doc5.len()));
5301    }
5302
5303    #[test]
5304    fn a_capability_declaration_completes_its_base_then_its_options() {
5305        // P3 (#2342): the instantiable kinds after `=`, narrowed as typed.
5306        let bases: Vec<String> = instance_declaration_completions("capability LoginLimit = ")
5307            .into_iter()
5308            .map(|(label, ..)| label)
5309            .collect();
5310        assert_eq!(
5311            bases,
5312            [
5313                "Kv",
5314                "Service",
5315                "R2",
5316                "RateLimit",
5317                "Queue",
5318                "Analytics",
5319                "D1",
5320                "EdgeCache",
5321                "StoredSecret",
5322                "Email",
5323                "Postgres",
5324                "MySql",
5325                "Vectorize",
5326                "Container",
5327                "AiSearch",
5328                "MtlsCertificate"
5329            ]
5330        );
5331        let narrowed: Vec<String> = instance_declaration_completions("capability L = Ra")
5332            .into_iter()
5333            .map(|(label, ..)| label)
5334            .collect();
5335        assert_eq!(narrowed, ["RateLimit"]);
5336        // Then the required options, as one snippet.
5337        let options = instance_declaration_completions("capability LoginLimit = RateLimit ");
5338        assert_eq!(options.len(), 1);
5339        assert_eq!(options[0].0, "@limit(…) @period(…)");
5340        assert_eq!(options[0].2, "@limit(${1:100}) @period(${2:60.seconds})");
5341        // P2 (#2578): a `Queue` names its queue.
5342        let options = instance_declaration_completions("capability OrderEvents = Queue ");
5343        assert_eq!(options[0].0, "@name(…)");
5344        assert_eq!(options[0].2, "@name(${1:\"order-events\"})");
5345        // #3301: a `StoredSecret` names its store and its secret.
5346        let options = instance_declaration_completions("capability StripeKey = StoredSecret ");
5347        assert_eq!(options[0].0, "@store(…) @secret(…)");
5348        assert_eq!(
5349            options[0].2,
5350            "@store(${1:\"payments\"}) @secret(${2:\"stripe-live\"})"
5351        );
5352        // A kind with no required option, or a line already carrying them,
5353        // gets nothing; nor does any other line.
5354        assert!(instance_declaration_completions("capability A = R2 ").is_empty());
5355        // #3302: an `Email` has no required option, so offers none.
5356        assert!(instance_declaration_completions("capability Mail = Email ").is_empty());
5357        // #3318: nor does a `Postgres`, which takes no option.
5358        assert!(instance_declaration_completions("capability Main = Postgres ").is_empty());
5359        // #3322: nor does a `MySql`, whose one option, `@tls`, is optional.
5360        assert!(instance_declaration_completions("capability Legacy = MySql ").is_empty());
5361        assert!(instance_declaration_completions("capability Edge = EdgeCache ").is_empty());
5362        assert!(instance_declaration_completions("capability L = RateLimit @limit(1) ").is_empty());
5363        assert!(instance_declaration_completions("let x = R").is_empty());
5364    }
5365
5366    #[test]
5367    fn a_rate_limit_instance_option_is_not_the_limit_annotation() {
5368        // P3 (#2342): `@limit(` on a capability declaration is an instance option.
5369        let doc = "context a\ncapability LoginLimit = RateLimit @limit(";
5370        assert!(!in_limit_arg_position(doc, doc.len()));
5371        // `@period(` offers the platform's two windows, and only at its value.
5372        let doc = "context a\ncapability LoginLimit = RateLimit @limit(100) @period(";
5373        let offered: Vec<&str> = instance_option_values(doc, doc.len())
5374            .iter()
5375            .map(|(v, _)| *v)
5376            .collect();
5377        assert_eq!(offered, ["10.seconds", "60.seconds"]);
5378        assert!(instance_option_values("let x = period(", 15).is_empty());
5379        let doc = "service api from http {\n  @period(";
5380        assert!(instance_option_values(doc, doc.len()).is_empty());
5381    }
5382
5383    #[test]
5384    fn limit_arg_position_inside_limit_annotation() {
5385        // Cursor at a fresh argument-name position inside `@limit( … )`.
5386        let doc = "service api from http {\n  @limit(";
5387        assert!(in_limit_arg_position(doc, doc.len()));
5388        // After a first arg + comma, still an argument-name position.
5389        let doc2 = "service api from http {\n  @limit(maxBody: 1048576, ";
5390        assert!(in_limit_arg_position(doc2, doc2.len()));
5391        // After a `:` it is a value position, not an argument-name position.
5392        let doc3 = "service api from http {\n  @limit(maxBody: ";
5393        assert!(!in_limit_arg_position(doc3, doc3.len()));
5394        // A bare `limit(` call (no `@`) is not the annotation.
5395        let doc4 = "let x = limit(";
5396        assert!(!in_limit_arg_position(doc4, doc4.len()));
5397        // An ordinary handler param list is not a `@limit` position.
5398        let doc5 = "on GET(\"/x\") by v: Visitor (";
5399        assert!(!in_limit_arg_position(doc5, doc5.len()));
5400    }
5401
5402    #[test]
5403    fn http_param_name_position_in_a_handler_header() {
5404        let doc = "service api from http {\n  on GET(\"/x\") (";
5405        assert!(in_http_param_name_position(doc, doc.len()));
5406        let doc2 = "service api from http {\n  on POST(\"/x/:id\") (id: String, ";
5407        assert!(in_http_param_name_position(doc2, doc2.len()));
5408        // After the `:` it is a type position.
5409        let doc3 = "service api from http {\n  on GET(\"/x\") (query: ";
5410        assert!(!in_http_param_name_position(doc3, doc3.len()));
5411        // The route string's own parens, and a call, are not parameter lists.
5412        let doc4 = "service api from http {\n  on GET(";
5413        assert!(!in_http_param_name_position(doc4, doc4.len()));
5414        let doc5 = "fn f(x: Int) -> Int {\n  g(";
5415        assert!(!in_http_param_name_position(doc5, doc5.len()));
5416        // A non-HTTP handler has no such parameters.
5417        let doc6 = "service s from cron {\n  on schedule(\"* * * * *\") (";
5418        assert!(!in_http_param_name_position(doc6, doc6.len()));
5419    }
5420
5421    #[test]
5422    fn raw_arg_position_inside_raw_annotation() {
5423        let doc = "service api from http {\n  @raw(";
5424        assert!(in_raw_arg_position(doc, doc.len()));
5425        let doc2 = "service api from http {\n  @raw(contentType: ";
5426        assert!(!in_raw_arg_position(doc2, doc2.len()));
5427        let doc3 = "let x = raw(";
5428        assert!(!in_raw_arg_position(doc3, doc3.len()));
5429        let doc4 = "service api from http {\n  @limit(";
5430        assert!(!in_raw_arg_position(doc4, doc4.len()));
5431    }
5432
5433    #[test]
5434    fn sum_type_variants_lists_variants() {
5435        let doc = "commons m {\n  type Status = enum { Pending, Shipped }\n}\n";
5436        let got: Vec<String> = sum_type_variants("Status", doc, None)
5437            .into_iter()
5438            .map(|c| c.label)
5439            .collect();
5440        assert!(got.contains(&"Pending".to_string()), "{got:?}");
5441        assert!(got.contains(&"Shipped".to_string()), "{got:?}");
5442    }
5443
5444    /// #1888: a field's and a variant's doc ride on their completion items;
5445    /// an undocumented one has none.
5446    /// Review of #1968: completion reads unchecked source, so a derivation
5447    /// cycle completes nothing rather than recursing without end.
5448    #[test]
5449    fn a_derivation_cycle_completes_nothing() {
5450        let doc = "context a\n\ncapability A = B\ncapability B = C\ncapability C = A\n";
5451        assert!(member_candidates("A", doc, None).is_empty());
5452    }
5453
5454    /// S4a (#1966): a derived capability completes its base's operations.
5455    #[test]
5456    fn a_derived_capability_completes_its_bases_operations() {
5457        const DERIVED_DOC: &str =
5458            "context a\n\nconsumes bynk.cloudflare { Kv }\n\ncapability Sessions = Kv\n";
5459        let labels: Vec<String> = member_candidates("Sessions", DERIVED_DOC, None)
5460            .into_iter()
5461            .map(|c| c.label)
5462            .collect();
5463        for op in ["get", "put", "putTtl", "delete", "list"] {
5464            assert!(labels.iter().any(|l| l == op), "{op} missing: {labels:?}");
5465        }
5466    }
5467
5468    #[test]
5469    fn member_completions_carry_their_docs() {
5470        let doc = "commons m\n\ntype Rec = {\n  --- The id.\n  id: Int,\n  n: Int,\n}\n\ntype Status = enum {\n  ---\n  Waiting.\n  ---\n  Pending,\n  Shipped,\n}\n";
5471        let docs = |items: Vec<Completion>| -> Vec<(String, Option<String>)> {
5472            items
5473                .into_iter()
5474                .map(|c| (c.label, c.documentation.map(|d| d.trim_end().to_string())))
5475                .collect()
5476        };
5477        assert_eq!(
5478            docs(record_field_names("Rec", doc, None)),
5479            [("id".into(), Some("The id.".into())), ("n".into(), None)]
5480        );
5481        assert_eq!(
5482            docs(sum_type_variants("Status", doc, None)),
5483            [
5484                ("Pending".into(), Some("Waiting.".into())),
5485                ("Shipped".into(), None)
5486            ]
5487        );
5488        assert_eq!(
5489            docs(member_candidates("Status", doc, None))
5490                .into_iter()
5491                .filter(|(l, _)| l == "Pending")
5492                .collect::<Vec<_>>(),
5493            [("Pending".into(), Some("Waiting.".into()))]
5494        );
5495    }
5496
5497    #[test]
5498    fn variants_for_ty_offers_built_in_result_and_option() {
5499        // v0.145 (ADR 0169, base gap): a `Result`/`Option` scrutinee offers its
5500        // built-in variants, which are not declared types (`sum_type_variants`
5501        // can't see them). This is what makes match-arm completion fire for a
5502        // Result/Option scrutinee at all.
5503        use bynk_syntax::ast::BaseType;
5504        let result = TYS.intern(Ty::Result(
5505            TYS.intern(Ty::Base(BaseType::Int)),
5506            TYS.intern(Ty::Base(BaseType::String)),
5507        ));
5508        let got: Vec<String> = variants_for_ty(result, &TYS, "", None)
5509            .into_iter()
5510            .map(|c| c.label)
5511            .collect();
5512        assert_eq!(got, vec!["Ok".to_string(), "Err".to_string()]);
5513
5514        let option = TYS.intern(Ty::Option(TYS.intern(Ty::Base(BaseType::Int))));
5515        let got: Vec<String> = variants_for_ty(option, &TYS, "", None)
5516            .into_iter()
5517            .map(|c| c.label)
5518            .collect();
5519        assert_eq!(got, vec!["Some".to_string(), "None".to_string()]);
5520    }
5521
5522    #[test]
5523    fn nested_variant_completions_resolves_the_payload_type() {
5524        use bynk_check::checker::NamedKind;
5525        use bynk_syntax::ast::BaseType;
5526        // Built-in outer: `Some(‸)` on `Option[Result[Int, E]]` offers the
5527        // payload `Result`'s variants.
5528        let payload = TYS.intern(Ty::Result(
5529            TYS.intern(Ty::Base(BaseType::Int)),
5530            TYS.intern(Ty::Named {
5531                name: "E".to_string(),
5532                kind: NamedKind::Sum,
5533                args: Vec::new(),
5534            }),
5535        ));
5536        let scrut = TYS.intern(Ty::Option(payload));
5537        let got: Vec<String> = nested_variant_completions(scrut, &TYS, "Some", "", None)
5538            .into_iter()
5539            .map(|c| c.label)
5540            .collect();
5541        assert_eq!(got, vec!["Ok".to_string(), "Err".to_string()]);
5542
5543        // The other outer variant of a Result payload resolves the error arm.
5544        let opt_int = TYS.intern(Ty::Option(TYS.intern(Ty::Base(BaseType::Int))));
5545        let inner = TYS.intern(Ty::Result(TYS.intern(Ty::Base(BaseType::Int)), opt_int));
5546        let got: Vec<String> = nested_variant_completions(inner, &TYS, "Err", "", None)
5547            .into_iter()
5548            .map(|c| c.label)
5549            .collect();
5550        assert_eq!(got, vec!["Some".to_string(), "None".to_string()]);
5551
5552        // User-sum outer: `Wrap(‸)` on a declared sum offers the payload field
5553        // type's variants, walked from source.
5554        let doc = "commons m {\n  type Inner = enum { A, B }\n  \
5555                   type Outer = | Wrap(inner: Inner) | Bare\n}\n";
5556        let outer = TYS.intern(Ty::Named {
5557            name: "Outer".to_string(),
5558            kind: NamedKind::Sum,
5559            args: Vec::new(),
5560        });
5561        let got: Vec<String> = nested_variant_completions(outer, &TYS, "Wrap", doc, None)
5562            .into_iter()
5563            .map(|c| c.label)
5564            .collect();
5565        assert!(got.contains(&"A".to_string()), "{got:?}");
5566        assert!(got.contains(&"B".to_string()), "{got:?}");
5567    }
5568
5569    #[test]
5570    fn literal_kind_scrutinee_suggests_no_variants() {
5571        // v0.130: a literal-kind `match` (a primitive `Int`/`String`/`Bool`
5572        // scrutinee, or a refinement over one) has no variant names to offer.
5573        // A primitive types to `Ty::Base`, which never reaches this lookup; a
5574        // refined scrutinee types to `Ty::Named` but has no `enum` body, so the
5575        // variant candidate set is empty — no bogus completions.
5576        let doc = "commons m {\n  type Quantity = Int where InRange(1, 99)\n}\n";
5577        assert!(sum_type_variants("Quantity", doc, None).is_empty());
5578        assert!(sum_type_variants("Int", doc, None).is_empty());
5579    }
5580
5581    // -- parse cache (#733) --
5582
5583    /// Collect the enumerated unit names for a buffer + project file set.
5584    fn enumerated_units(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<String> {
5585        let mut names = Vec::new();
5586        for_each_unit(doc_text, files, |u| names.push(u.name().joined()));
5587        names
5588    }
5589
5590    /// Content-ownership track (#1086) slice 0+1: `files` is now a pre-read
5591    /// `(path, content)` map — the caller's job (`bynk-lsp`'s overlay-then-disk
5592    /// sweep) — rather than a bare path list `cached_project_unit` used to
5593    /// read from disk itself. These tests build that map directly; none of
5594    /// them touch the real filesystem any more.
5595    fn synthetic_path(name: &str) -> PathBuf {
5596        PathBuf::from(format!("/synthetic/{name}.bynk"))
5597    }
5598
5599    #[test]
5600    fn for_each_unit_yields_embedded_buffer_and_project_files() {
5601        let sibling = synthetic_path("sibling");
5602        let files = HashMap::from([(
5603            sibling,
5604            "commons proj.sibling {\n  fn s() -> Int { 1 }\n}\n".to_string(),
5605        )]);
5606
5607        let names = enumerated_units(
5608            "commons proj.buffer {\n  fn b() -> Int { 1 }\n}\n",
5609            Some(&files),
5610        );
5611        // The embedded `bynk` surface, the live buffer, and the project file all show.
5612        assert!(names.iter().any(|n| n == "bynk"), "embedded: {names:?}");
5613        assert!(
5614            names.iter().any(|n| n == "proj.buffer"),
5615            "buffer: {names:?}"
5616        );
5617        assert!(
5618            names.iter().any(|n| n == "proj.sibling"),
5619            "project file: {names:?}"
5620        );
5621    }
5622
5623    /// Finding #62: when the buffer and a project file both declare a type
5624    /// under the same name — the buffer's stale copy, or two distinct files
5625    /// that happen to collide — `record_field_names` and `sum_type_variants`
5626    /// must take the first match (the buffer, since `for_each_unit` yields it
5627    /// before `files`) rather than unioning both, so a field/variant removed
5628    /// from the live buffer does not resurface from the stale copy.
5629    #[test]
5630    fn same_named_declarations_do_not_union_across_units() {
5631        let stale = HashMap::from([(
5632            synthetic_path("stale"),
5633            "commons m {\n  \
5634             type Rec = { total: Int, old_field: Int }\n  \
5635             type Status = enum { Pending, Retired }\n\
5636             }\n"
5637            .to_string(),
5638        )]);
5639
5640        let buffer = "commons m {\n  \
5641                       type Rec = { total: Int }\n  \
5642                       type Status = enum { Pending, Shipped }\n\
5643                       }\n";
5644        let files = Some(&stale);
5645
5646        let fields: Vec<String> = record_field_names("Rec", buffer, files)
5647            .into_iter()
5648            .map(|c| c.label)
5649            .collect();
5650        assert_eq!(fields, vec!["total".to_string()], "{fields:?}");
5651
5652        let variants: Vec<String> = sum_type_variants("Status", buffer, files)
5653            .into_iter()
5654            .map(|c| c.label)
5655            .collect();
5656        assert_eq!(
5657            variants,
5658            vec!["Pending".to_string(), "Shipped".to_string()],
5659            "{variants:?}"
5660        );
5661    }
5662
5663    /// Finding #62: `capabilities_of_unit` takes the first unit named `unit`
5664    /// rather than unioning exports across every matching unit — the same
5665    /// buffer-vs-stale-copy reasoning as
5666    /// `same_named_declarations_do_not_union_across_units`.
5667    #[test]
5668    fn capabilities_of_unit_does_not_union_across_units() {
5669        let stale = HashMap::from([(
5670            synthetic_path("stale"),
5671            "adapter tokens {\n  \
5672             exports capability { Jwt, Retired }\n\
5673             }\n"
5674            .to_string(),
5675        )]);
5676
5677        let buffer = "adapter tokens {\n  exports capability { Jwt }\n}\n";
5678        let files = Some(&stale);
5679
5680        let caps = capabilities_of_unit("tokens", buffer, &split_dependency_files(files, None));
5681        assert_eq!(caps, vec!["Jwt".to_string()], "{caps:?}");
5682    }
5683
5684    #[test]
5685    fn project_unit_cache_invalidates_on_change() {
5686        let path = synthetic_path("unit");
5687
5688        let first_files = HashMap::from([(
5689            path.clone(),
5690            "commons proj.first {\n  fn a() -> Int { 1 }\n}\n".to_string(),
5691        )]);
5692        let first = enumerated_units("context a.b\n", Some(&first_files));
5693        assert!(
5694            first.iter().any(|n| n == "proj.first"),
5695            "first read: {first:?}"
5696        );
5697
5698        // Same path, different content — the cache is keyed on content
5699        // equality (not disk metadata, since content is supplied directly
5700        // and an open-buffer overlay has no meaningful mtime at all), so it
5701        // must serve the new parse, not the stale one.
5702        let second_files = HashMap::from([(
5703            path,
5704            "commons proj.second.longer {\n  fn a() -> Int { 1 }\n  fn c() -> Int { 3 }\n}\n"
5705                .to_string(),
5706        )]);
5707        let second = enumerated_units("context a.b\n", Some(&second_files));
5708        assert!(
5709            second.iter().any(|n| n == "proj.second.longer"),
5710            "after change: {second:?}"
5711        );
5712        assert!(
5713            !second.iter().any(|n| n == "proj.first"),
5714            "stale served: {second:?}"
5715        );
5716    }
5717
5718    #[test]
5719    fn unparseable_project_file_is_skipped() {
5720        // Content-ownership track (#1086) slice 0+1: `cached_project_unit` no
5721        // longer reads disk itself, so there is no more "path doesn't exist on
5722        // disk" case to skip — the equivalent today is content that fails to
5723        // parse (the caller's sweep omits an unreadable file from the map
5724        // entirely, so this covers the other unusable case: present but not
5725        // parseable).
5726        let files = HashMap::from([(synthetic_path("broken"), "not bynk source {{{".to_string())]);
5727        let names = enumerated_units("context a.b\n", Some(&files));
5728        let baseline = enumerated_units("context a.b\n", None);
5729        // No panic, and the broken file contributes nothing beyond the same
5730        // embedded surface + buffer a project with no files at all yields —
5731        // not just "the embedded surface is present somewhere", which would
5732        // pass even if a future recovery-parse change made the broken
5733        // content yield a spurious unit alongside it.
5734        assert_eq!(names, baseline, "{names:?}");
5735    }
5736}
5737
5738#[cfg(test)]
5739mod snapshot_completion_tests {
5740    use super::*;
5741
5742    fn labels(line: &str) -> Vec<String> {
5743        complete(line, "", None)
5744            .into_iter()
5745            .map(|c| c.label)
5746            .collect()
5747    }
5748
5749    /// #2842: `matches snapshot` is offered after the value of an `expect`, while
5750    /// the word is being typed, and nowhere else.
5751    #[test]
5752    fn matches_snapshot_follows_an_expect_value() {
5753        let offered = |line: &str| labels(line).contains(&"matches snapshot".to_string());
5754        assert!(offered("  expect read(1) "));
5755        assert!(offered("  expect d.tags "));
5756        assert!(offered("  expect read(1) mat"));
5757        assert!(!offered("  expect read(1) matches snapshot \"x\" "));
5758        assert!(!offered("  expect read(1) =="));
5759        assert!(!offered("  expect read(1) and "));
5760        assert!(!offered("  expect read(1) other"));
5761        assert!(!offered("  let x = read(1) "));
5762    }
5763}