Skip to main content

bynk_ide/
signature_help.rs

1//! v0.32 (ADR 0065): signature help — `textDocument/signatureHelp`.
2//!
3//! While typing a call's arguments, show the callee's signature with the active
4//! parameter highlighted. **Call-context detection is lexical** (the innermost
5//! unclosed `(` before the cursor, the callee before it, the active parameter
6//! from a bracket-aware comma count); **signatures are semantic**, resolved from
7//! the recovery parse + the static registries — the same name-vs-value split as
8//! completion. This slice covers **name callees**: free functions, capability
9//! operations, refined/opaque `of`/`unsafe`, built-in type statics
10//! (`Int.parse`/`Json.decode`), and the `Ok`/`Err`/`Some` constructors. Value
11//! receivers (`xs.fold(`) need the receiver typed → a later slice.
12//!
13//! The signature is rendered with `symbols::type_ref_str` — the same Bynk-syntax
14//! renderer hover uses — so the two never diverge.
15
16use bynk_syntax::ast::{BaseType, CommonsItem, FnName, SourceUnit, TypeBody};
17use std::collections::{BTreeSet, HashMap};
18use std::path::PathBuf;
19
20use crate::completion::{BUILTIN_STATICS, for_each_unit};
21use crate::symbols::type_ref_str;
22
23/// The call under the cursor: the callee text, the active-parameter index, and
24/// the byte offset of the call's opening `(`.
25#[derive(Debug, PartialEq, Eq)]
26pub struct CallContext {
27    pub callee: String,
28    pub active_param: usize,
29    pub open_paren: usize,
30}
31
32/// The innermost unclosed `(` before `offset`, its callee, and the active
33/// parameter (top-level commas between that `(` and the cursor). `None` when the
34/// cursor is not inside a call's argument list.
35pub fn call_context(text: &str, offset: usize) -> Option<CallContext> {
36    let prefix = text.get(..offset)?;
37    let open = innermost_unclosed_paren(prefix)?;
38    let callee = callee_before(&prefix[..open])?;
39    let active = top_level_commas(&prefix[open + 1..]);
40    Some(CallContext {
41        callee,
42        active_param: active,
43        open_paren: open,
44    })
45}
46
47/// A value-receiver method callee — `recv.method` where `recv` is a single
48/// lowercase-initial identifier (a value, not a type/capability name). The
49/// signature comes from typing the receiver (a later slice's path).
50pub fn value_receiver_method(callee: &str) -> Option<(&str, &str)> {
51    let (recv, method) = callee.rsplit_once('.')?;
52    let first = recv.chars().next()?;
53    if (first.is_ascii_lowercase() || first == '_') && !recv.contains('.') {
54        Some((recv, method))
55    } else {
56        None
57    }
58}
59
60/// For a value-receiver callee `recv.method(` whose `(` is at `open_paren`,
61/// rewrite the buffer so `recv` is a complete expression (the `.method(args`
62/// dropped) and return it with the receiver byte offset to type — the same
63/// mid-edit trick value-member completion uses.
64pub fn value_receiver_rewrite(
65    text: &str,
66    callee: &str,
67    open_paren: usize,
68    cursor: usize,
69) -> Option<(String, usize)> {
70    let (recv, _) = value_receiver_method(callee)?;
71    let before = strip_type_args(text.get(..open_paren)?).trim_end();
72    let callee_start = before.len().checked_sub(callee.len())?;
73    let dot = callee_start + recv.len();
74    let rewritten = format!("{}{}", &text[..dot], &text[cursor..]);
75    Some((rewritten, dot.saturating_sub(1)))
76}
77
78/// The kernel-method signature for `method` on receiver type `ty`, if any.
79pub fn kernel_method_signature(
80    ty: bynk_check::checker::TyId,
81    tys: &bynk_check::checker::Types,
82    method: &str,
83) -> Option<String> {
84    bynk_check::kernel_methods::methods_for(ty, tys)
85        .iter()
86        .find(|m| m.name == method)
87        .map(|m| m.signature.to_string())
88}
89
90/// Scan back for the `(` that is open at the cursor. A depth-0 `[` or `{` means
91/// the cursor sits in a type-argument list / list literal / block, not a call.
92fn innermost_unclosed_paren(prefix: &str) -> Option<usize> {
93    let b = prefix.as_bytes();
94    let mut depth = 0i32;
95    for i in (0..b.len()).rev() {
96        match b[i] {
97            b')' | b']' | b'}' => depth += 1,
98            b'(' => {
99                if depth == 0 {
100                    return Some(i);
101                }
102                depth -= 1;
103            }
104            b'[' | b'{' => {
105                if depth == 0 {
106                    return None;
107                }
108                depth -= 1;
109            }
110            _ => {}
111        }
112    }
113    None
114}
115
116/// Top-level (bracket-depth-0) commas in `s`.
117fn top_level_commas(s: &str) -> usize {
118    let mut depth = 0i32;
119    let mut n = 0;
120    for c in s.chars() {
121        match c {
122            '(' | '[' | '{' => depth += 1,
123            ')' | ']' | '}' => depth -= 1,
124            ',' if depth == 0 => n += 1,
125            _ => {}
126        }
127    }
128    n
129}
130
131/// #2795: drop a trailing explicit type-argument list — `b.map[String]` →
132/// `b.map` — so `name[T](` finds the same callee as `name(`. The list's commas
133/// are inside the brackets and never counted as argument separators.
134fn strip_type_args(s: &str) -> &str {
135    let t = s.trim_end();
136    if !t.ends_with(']') {
137        return s;
138    }
139    let mut depth = 0i32;
140    for (i, c) in t.char_indices().rev() {
141        match c {
142            ']' => depth += 1,
143            '[' => {
144                depth -= 1;
145                if depth == 0 {
146                    return &t[..i];
147                }
148            }
149            _ => {}
150        }
151    }
152    s
153}
154
155/// The callee immediately before the `(` — a bare `name` or `Recv.member`.
156fn callee_before(s: &str) -> Option<String> {
157    let s = strip_type_args(s).trim_end();
158    // Advance past the matched char by its UTF-8 length; a multi-byte
159    // non-identifier char (`"`, `€`, `—`, …) would make `i + 1` land
160    // mid-codepoint and panic the slice.
161    let start = s
162        .char_indices()
163        .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_' || c == '.'))
164        .map_or(0, |(i, c)| i + c.len_utf8());
165    let callee = &s[start..];
166    if callee.is_empty() || callee.starts_with('.') || callee.ends_with('.') {
167        return None;
168    }
169    Some(callee.to_string())
170}
171
172/// Render the signature *label* for a name callee — `name(p: T, …) -> R`.
173/// `None` if the callee can't be resolved (or is a value receiver — slice 2).
174pub fn resolve_label(
175    callee: &str,
176    doc_text: &str,
177    files: Option<&HashMap<PathBuf, String>>,
178) -> Option<String> {
179    if let Some((recv, member)) = callee.rsplit_once('.') {
180        // #3446: `Record.field.cookie` / `Record.field.expire` on a cookie record.
181        if let Some((record, field)) = recv.split_once('.') {
182            return cookie_field_label(record, field, member, doc_text, files);
183        }
184        // #3147: `D1.peek(…)`, a case's handle on a participant's database.
185        if callee == "D1.peek" {
186            return Some(crate::completion::D1_PEEK_SIGNATURE.to_string());
187        }
188        // Built-in type statics — already display-ready signature strings.
189        if let Some((_, statics)) = BUILTIN_STATICS.iter().find(|(n, _)| *n == recv)
190            && let Some((_, sig)) = statics.iter().find(|(n, _)| *n == member)
191        {
192            return Some((*sig).to_string());
193        }
194        // A refined/opaque type's `of`/`unsafe`, or a capability op.
195        return resolve_qualified(recv, member, doc_text, files);
196    }
197    // Built-in constructors.
198    match callee {
199        "Ok" => return Some("Ok(value: T) -> Result[T, E]".to_string()),
200        "Err" => return Some("Err(error: E) -> Result[T, E]".to_string()),
201        "Some" => return Some("Some(value: T) -> Option[T]".to_string()),
202        _ => {}
203    }
204    // A free function.
205    let mut found = None;
206    for_each_unit(doc_text, files, |unit| {
207        if found.is_some() {
208            return;
209        }
210        // #2834: a suite's helper `fn`s are callable from its own cases.
211        let suite_fns: Vec<CommonsItem> = match unit {
212            SourceUnit::Suite(s) => s.fns.iter().cloned().map(CommonsItem::Fn).collect(),
213            _ => Vec::new(),
214        };
215        let items = match unit {
216            SourceUnit::Commons(c) => &c.items,
217            SourceUnit::Context(c) => &c.items,
218            SourceUnit::Adapter(a) => &a.items,
219            SourceUnit::Suite(_) => &suite_fns,
220        };
221        for item in items {
222            if let CommonsItem::Fn(f) = item
223                && let FnName::Free(id) = &f.name
224                && id.name == callee
225            {
226                let params: Vec<String> = f
227                    .params
228                    .iter()
229                    .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
230                    .collect();
231                found = Some(format!(
232                    "{callee}{}({}) -> {}{}{}",
233                    crate::symbols::fn_type_params_str(f),
234                    params.join(", "),
235                    type_ref_str(&f.return_type),
236                    crate::symbols::fn_given_str(f),
237                    crate::symbols::fn_where_str(f)
238                ));
239                return;
240            }
241        }
242    });
243    // #2620: the ambient fault built-ins, unless a `fn` of that name shadows them.
244    found.or_else(|| match callee {
245        "unreachable" | "todo" => Some(format!("{callee}(message: String) -> never returns")),
246        _ => None,
247    })
248}
249
250/// #3446: the signature of `Record.field.cookie(value)` and `Record.field.expire()`.
251fn cookie_field_label(
252    record: &str,
253    field: &str,
254    member: &str,
255    doc_text: &str,
256    files: Option<&HashMap<PathBuf, String>>,
257) -> Option<String> {
258    let fields = crate::completion::cookie_record_fields_of(record, doc_text, files)?;
259    let (_, ty, _) = fields.into_iter().find(|(n, _, _)| n == field)?;
260    match member {
261        "cookie" => {
262            let value = match &ty {
263                bynk_syntax::ast::TypeRef::Option(inner, _) => type_ref_str(inner),
264                other => type_ref_str(other),
265            };
266            Some(format!("cookie(value: {value}) -> Cookie"))
267        }
268        "expire" => Some("expire() -> Cookie".to_string()),
269        _ => None,
270    }
271}
272
273fn resolve_qualified(
274    recv: &str,
275    member: &str,
276    doc_text: &str,
277    files: Option<&HashMap<PathBuf, String>>,
278) -> Option<String> {
279    resolve_qualified_from(recv, member, doc_text, files, &mut BTreeSet::new())
280}
281
282/// [`resolve_qualified`], with the derived capabilities already followed
283/// (S4a, #1966). Signature help reads unchecked source, so a derivation cycle
284/// (`capability A = B`, `capability B = A`) can be on screen: each receiver
285/// is followed once.
286fn resolve_qualified_from(
287    recv: &str,
288    member: &str,
289    doc_text: &str,
290    files: Option<&HashMap<PathBuf, String>>,
291    followed: &mut BTreeSet<String>,
292) -> Option<String> {
293    followed.insert(recv.to_string());
294    let mut out = None;
295    // S4a (#1966): a derived capability's (`capability Sessions = Kv`) base,
296    // whose operations it has.
297    let mut derived_base: Option<String> = None;
298    for_each_unit(doc_text, files, |unit| {
299        if out.is_some() {
300            return;
301        }
302        let items = match unit {
303            SourceUnit::Commons(c) => &c.items,
304            SourceUnit::Context(c) => &c.items,
305            SourceUnit::Adapter(a) => &a.items,
306            _ => return,
307        };
308        for item in items {
309            match item {
310                // `Type.of` / `Type.unsafe` for a refined/opaque type.
311                CommonsItem::Type(t)
312                    if t.name.name == recv && (member == "of" || member == "unsafe") =>
313                {
314                    let (base, total) = match &t.body {
315                        TypeBody::Refined {
316                            base, refinement, ..
317                        } => (
318                            base_name(*base),
319                            bynk_syntax::ast::of_is_total(*base, refinement.as_ref(), false),
320                        ),
321                        TypeBody::Opaque { base, .. } => (base_name(*base), false),
322                        _ => return,
323                    };
324                    out = Some(if member == "of" && total {
325                        // #3946: a named type with no predicate cannot fail.
326                        format!("of(value: {base}) -> {recv}")
327                    } else if member == "of" {
328                        format!("of(value: {base}) -> Result[{recv}, ValidationError]")
329                    } else {
330                        format!("unsafe(value: {base}) -> {recv}")
331                    });
332                    return;
333                }
334                CommonsItem::Capability(c) if c.name.name == recv && c.derived.is_some() => {
335                    derived_base = c.derived.as_ref().map(|d| d.base.name.clone());
336                }
337                // #3386: `User.issue(identity)` / `User.expire()` on a `SignedCookie` actor.
338                CommonsItem::Actor(a)
339                    if a.name.name == recv && crate::completion::is_signed_cookie_actor(a) =>
340                {
341                    out = crate::completion::signed_cookie_members(a)
342                        .into_iter()
343                        .find(|(label, _)| *label == member)
344                        .map(|(_, sig)| sig);
345                    return;
346                }
347                // `Cap.op` — a capability operation.
348                CommonsItem::Capability(c) if c.name.name == recv => {
349                    if let Some(op) = c.ops.iter().find(|o| o.name.name == member) {
350                        let params: Vec<String> = op
351                            .params
352                            .iter()
353                            .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
354                            .collect();
355                        // #926: `[T, …]` type parameters on the op itself.
356                        let type_params = if op.type_params.is_empty() {
357                            String::new()
358                        } else {
359                            let names: Vec<&str> = op
360                                .type_params
361                                .iter()
362                                .map(|tp| tp.name.name.as_str())
363                                .collect();
364                            format!("[{}]", names.join(", "))
365                        };
366                        out = Some(format!(
367                            "{member}{type_params}({}) -> {}",
368                            params.join(", "),
369                            type_ref_str(&op.return_type)
370                        ));
371                        return;
372                    }
373                }
374                _ => {}
375            }
376        }
377    });
378    match (out, derived_base) {
379        // #2865: a derived `D1`'s typed reads are lowered by the compiler, so
380        // `D1` declares no operation for them.
381        (None, Some(base)) if typed_read(&base, member).is_some() => {
382            typed_read(&base, member).map(str::to_string)
383        }
384        (None, Some(base)) if !followed.contains(&base) => {
385            resolve_qualified_from(&base, member, doc_text, files, followed)
386        }
387        (out, _) => out,
388    }
389}
390
391/// #2865: the signature of `D1.select[T]` / `D1.firstAs[T]`, compiler-lowered
392/// over `all`/`first` (so not declared operations of the capability).
393/// Hyperdrive H3 (#3320): and of `Postgres`' (`base`), whose parameters are
394/// `PgValue`s and whose failure is a `PgReadError`; H5 (#3322): and of
395/// `MySql`'s, with `MySqlValue`s and a `MySqlReadError`.
396pub(crate) fn typed_read(base: &str, member: &str) -> Option<&'static str> {
397    match (base, member) {
398        ("D1", "select") => Some(
399            "select[T](tail: String, params: List[SqlValue]) -> Effect[Result[List[T], SqlReadError]]",
400        ),
401        ("D1", "firstAs") => Some(
402            "firstAs[T](tail: String, params: List[SqlValue]) -> Effect[Result[Option[T], SqlReadError]]",
403        ),
404        ("Postgres", "select") => Some(
405            "select[T](tail: String, params: List[PgValue]) -> Effect[Result[List[T], PgReadError]]",
406        ),
407        ("Postgres", "firstAs") => Some(
408            "firstAs[T](tail: String, params: List[PgValue]) -> Effect[Result[Option[T], PgReadError]]",
409        ),
410        ("MySql", "select") => Some(
411            "select[T](tail: String, params: List[MySqlValue]) -> Effect[Result[List[T], MySqlReadError]]",
412        ),
413        ("MySql", "firstAs") => Some(
414            "firstAs[T](tail: String, params: List[MySqlValue]) -> Effect[Result[Option[T], MySqlReadError]]",
415        ),
416        _ => None,
417    }
418}
419
420/// The bases whose derived instances have the compiler-lowered typed reads.
421pub(crate) const TYPED_READ_BASES: [&str; 3] = ["D1", "Postgres", "MySql"];
422
423/// Whether `label` is the typed-read signature of the member `callee` names, so a
424/// user's own `select` operation is never taken for one.
425pub(crate) fn is_typed_read_label(callee: &str, label: &str) -> bool {
426    callee.rsplit_once('.').is_some_and(|(_, m)| {
427        TYPED_READ_BASES
428            .iter()
429            .any(|b| typed_read(b, m) == Some(label))
430    })
431}
432
433fn base_name(b: BaseType) -> &'static str {
434    match b {
435        BaseType::Int => "Int",
436        BaseType::Float => "Float",
437        BaseType::String => "String",
438        BaseType::Bool => "Bool",
439        BaseType::Duration => "Duration",
440        BaseType::Instant => "Instant",
441        BaseType::Bytes => "Bytes",
442        BaseType::Decimal => "Decimal",
443    }
444}
445
446/// The byte ranges of each top-level parameter within a signature `label`
447/// (`name(p0, p1, …) -> R`) — for the LSP `ParameterInformation` offsets.
448pub fn param_ranges(label: &str) -> Vec<(usize, usize)> {
449    let Some(open) = label.find('(') else {
450        return Vec::new();
451    };
452    let mut ranges = Vec::new();
453    let mut depth = 0i32;
454    let mut seg_start = open + 1;
455    let bytes = label.as_bytes();
456    let mut i = open;
457    while i < bytes.len() {
458        match bytes[i] {
459            b'(' | b'[' | b'{' => depth += 1,
460            b')' | b']' | b'}' => {
461                depth -= 1;
462                if depth == 0 {
463                    push_trimmed(label, seg_start, i, &mut ranges);
464                    break;
465                }
466            }
467            b',' if depth == 1 => {
468                push_trimmed(label, seg_start, i, &mut ranges);
469                seg_start = i + 1;
470            }
471            _ => {}
472        }
473        i += 1;
474    }
475    ranges
476}
477
478fn push_trimmed(label: &str, start: usize, end: usize, out: &mut Vec<(usize, usize)>) {
479    let seg = &label[start..end];
480    let trimmed = seg.trim();
481    if trimmed.is_empty() {
482        return;
483    }
484    let s = start + (seg.len() - seg.trim_start().len());
485    out.push((s, s + trimmed.len()));
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    /// Constrained generics slice 0: the label shows a generic's bounds.
493    #[test]
494    fn free_fn_label_shows_bounds() {
495        let doc = "commons m\n\nfn same[T: Eq](a: T, b: T) -> Bool { a == b }\n\nfn pick[T](a: T) -> T { a }\n";
496        assert_eq!(
497            resolve_label("same", doc, None).as_deref(),
498            Some("same[T: Eq](a: T, b: T) -> Bool")
499        );
500        assert_eq!(
501            resolve_label("pick", doc, None).as_deref(),
502            Some("pick[T](a: T) -> T")
503        );
504        let label = resolve_label("same", doc, None).unwrap();
505        let ranges = param_ranges(&label);
506        assert_eq!(&label[ranges[0].0..ranges[0].1], "a: T");
507    }
508
509    /// #2868: the label shows a context function's `given`, ahead of any `where`;
510    /// the hidden `deps` parameter is not in the AST, so it is never offered.
511    #[test]
512    fn free_fn_label_shows_given() {
513        let doc = "context m\n\nfn warn(what: String) -> Effect[()] given Logger, B.Orders {\n  Logger.error(what)\n}\n";
514        let label = resolve_label("warn", doc, None).expect("warn resolves");
515        assert_eq!(
516            label,
517            "warn(what: String) -> Effect[()] given Logger, B.Orders"
518        );
519        assert_eq!(param_ranges(&label).len(), 1);
520    }
521
522    /// Constrained generics slice 1: the label shows `Ord` bounds. The hidden
523    /// comparator-witness parameters the emitter adds are not in the AST, so
524    /// they are never offered as a parameter or in the label.
525    #[test]
526    fn free_fn_label_shows_ord_bounds_and_never_the_witness() {
527        let doc = "commons m\n\nfn top[T: Ord](xs: List[T], n: Int) -> List[T] { xs }\n\nfn both[A: Eq + Ord, B: Ord](a: A, b: B) -> A { a }\n";
528        let label = resolve_label("top", doc, None).unwrap();
529        assert_eq!(label, "top[T: Ord](xs: List[T], n: Int) -> List[T]");
530        let ranges = param_ranges(&label);
531        let params: Vec<&str> = ranges.iter().map(|&(s, e)| &label[s..e]).collect();
532        assert_eq!(params, ["xs: List[T]", "n: Int"]);
533        let both = resolve_label("both", doc, None).unwrap();
534        assert_eq!(both, "both[A: Eq + Ord, B: Ord](a: A, b: B) -> A");
535        for l in [&label, &both] {
536            let lower = l.to_lowercase();
537            assert!(
538                !lower.contains("witness") && !lower.contains("cmp") && !lower.contains("compar"),
539                "{l}"
540            );
541        }
542        assert_eq!(param_ranges(&both).len(), 2);
543    }
544
545    #[test]
546    fn call_context_finds_callee_and_active_param() {
547        let t = "  let x = f(a, b";
548        let ctx = call_context(t, t.len()).unwrap();
549        assert_eq!(ctx.callee, "f");
550        assert_eq!(ctx.active_param, 1); // after one comma
551    }
552
553    #[test]
554    fn an_explicit_type_argument_list_is_not_the_callee_or_an_argument() {
555        // #2795: `b.map[String](` resolves like `b.map(`, and the list's comma
556        // is not an argument separator.
557        let t = "  b.map[String](f, ";
558        let ctx = call_context(t, t.len()).unwrap();
559        assert_eq!(ctx.callee, "b.map");
560        assert_eq!(ctx.active_param, 1);
561        let t = "  b.pair[Int, String](";
562        let ctx = call_context(t, t.len()).unwrap();
563        assert_eq!(ctx.callee, "b.pair");
564        assert_eq!(ctx.active_param, 0);
565        let (rw, _) = value_receiver_rewrite(t, &ctx.callee, ctx.open_paren, t.len()).unwrap();
566        assert_eq!(rw, "  b");
567    }
568
569    #[test]
570    fn innermost_call_wins_in_nested_calls() {
571        let t = "  outer(g(x";
572        let ctx = call_context(t, t.len()).unwrap();
573        assert_eq!(ctx.callee, "g");
574        assert_eq!(ctx.active_param, 0);
575        // back out to the outer call's second arg
576        let t2 = "  outer(g(x), ";
577        let ctx2 = call_context(t2, t2.len()).unwrap();
578        assert_eq!(ctx2.callee, "outer");
579        assert_eq!(ctx2.active_param, 1);
580    }
581
582    #[test]
583    fn commas_inside_nested_brackets_dont_count() {
584        let t = "  f(g(a, b), ";
585        assert_eq!(call_context(t, t.len()).unwrap().active_param, 1);
586    }
587
588    #[test]
589    fn qualified_callee_and_no_call_context() {
590        let t = "    Clock.now(";
591        assert_eq!(call_context(t, t.len()).unwrap().callee, "Clock.now");
592        assert!(call_context("  let x = 1", 11).is_none()); // not in a call
593        assert!(call_context("  xs[", 4).is_none()); // a list index, not a call
594    }
595
596    #[test]
597    fn callee_extraction_survives_a_multibyte_char_before_the_callee() {
598        // A multi-byte non-identifier char before the callee used to make the
599        // `i + 1` byte offset land mid-codepoint → panic on slice (#715). `(`
600        // is a trigger char, so this fired on signature help inside a string.
601        assert_eq!(callee_before("\"Foo.bar"), Some("Foo.bar".to_string()));
602        assert_eq!(callee_before("€f"), Some("f".to_string()));
603        // The whole path: a call context whose prefix opens a string literal.
604        let t = "  \"€greet(";
605        let _ = call_context(t, t.len());
606    }
607
608    /// S4a (#1966): a derived capability's operation has its base's signature.
609    #[test]
610    fn a_derived_capability_op_has_its_bases_signature() {
611        const DERIVED_DOC: &str =
612            "context a\n\nconsumes bynk.cloudflare { Kv }\n\ncapability Sessions = Kv\n";
613        assert_eq!(
614            resolve_label("Sessions.put", DERIVED_DOC, None).as_deref(),
615            Some("put(key: String, value: String) -> Effect[()]")
616        );
617    }
618
619    /// #2865: a derived `D1` has the compiler-lowered typed reads.
620    #[test]
621    fn a_derived_d1_has_the_typed_reads() {
622        const DOC: &str =
623            "context a\n\nconsumes bynk.cloudflare { D1 }\n\ncapability Orders = D1\n";
624        assert_eq!(
625            resolve_label("Orders.select", DOC, None).as_deref(),
626            Some(
627                "select[T](tail: String, params: List[SqlValue]) -> Effect[Result[List[T], SqlReadError]]"
628            )
629        );
630        assert!(resolve_label("Orders.firstAs", DOC, None).is_some());
631        // #3147: and the case-only `D1.peek`, which is no operation.
632        assert!(
633            resolve_label("D1.peek", DOC, None)
634                .is_some_and(|l| l.starts_with("peek(<participant>"))
635        );
636        assert!(resolve_label("Orders.all", DOC, None).is_some());
637    }
638
639    /// Hyperdrive H3 (#3320): a derived `Postgres` has them too, over `PgValue`
640    /// and `PgReadError`, and `transaction` is its declared operation.
641    #[test]
642    fn a_derived_postgres_has_the_typed_reads_and_transaction() {
643        const DOC: &str =
644            "context a\n\nconsumes bynk.cloudflare { Postgres }\n\ncapability Main = Postgres\n";
645        assert_eq!(
646            resolve_label("Main.select", DOC, None).as_deref(),
647            Some(
648                "select[T](tail: String, params: List[PgValue]) -> Effect[Result[List[T], PgReadError]]"
649            )
650        );
651        assert_eq!(
652            resolve_label("Main.firstAs", DOC, None).as_deref(),
653            Some(
654                "firstAs[T](tail: String, params: List[PgValue]) -> Effect[Result[Option[T], PgReadError]]"
655            )
656        );
657        assert_eq!(
658            resolve_label("Main.transaction", DOC, None).as_deref(),
659            Some(
660                "transaction(statements: List[PgStatement]) -> Effect[Result[List[PgRun], PgError]]"
661            )
662        );
663    }
664
665    /// Review of #1968: a derivation cycle in unchecked source resolves
666    /// nothing rather than recursing without end.
667    #[test]
668    fn a_derivation_cycle_has_no_signature() {
669        let doc = "context a\n\ncapability A = B\ncapability B = A\n";
670        assert_eq!(resolve_label("A.put", doc, None), None);
671    }
672
673    #[test]
674    fn fault_builtins_have_a_signature_a_user_fn_shadows() {
675        // #2620
676        assert_eq!(
677            resolve_label("unreachable", "context a.b\n", None).as_deref(),
678            Some("unreachable(message: String) -> never returns")
679        );
680        let doc = "commons m {\n  fn todo(n: Int) -> Int { n }\n}\n";
681        assert_eq!(
682            resolve_label("todo", doc, None).as_deref(),
683            Some("todo(n: Int) -> Int")
684        );
685    }
686
687    #[test]
688    fn builtin_static_and_constructor_labels() {
689        assert_eq!(
690            resolve_label("Int.parse", "context a.b\n", None).as_deref(),
691            Some("parse(s: String) -> Option[Int]")
692        );
693        assert!(
694            resolve_label("Ok", "context a.b\n", None)
695                .unwrap()
696                .starts_with("Ok(value")
697        );
698    }
699
700    #[test]
701    fn yaml_decode_has_a_signature() {
702        // #3214: `Yaml.decode` reads the same table as `Json.decode`.
703        assert_eq!(
704            resolve_label("Yaml.decode", "context a.b\n", None).as_deref(),
705            Some("decode[T](s: String) -> Result[T, DecodeError]")
706        );
707        assert_eq!(resolve_label("Yaml.encode", "context a.b\n", None), None);
708    }
709
710    #[test]
711    fn a_signed_cookie_actor_has_issue_and_expire_signatures() {
712        let doc = "context a\n\ntype UserId = String where NonEmpty\n\nactor User { auth = SignedCookie(secret = \"K\", ttl = 1.hour), identity = UserId }\n";
713        assert_eq!(
714            resolve_label("User.issue", doc, None).as_deref(),
715            Some("issue(identity: UserId) -> Effect[Cookie]")
716        );
717        assert_eq!(
718            resolve_label("User.expire", doc, None).as_deref(),
719            Some("expire() -> Cookie")
720        );
721        let other =
722            "context a\n\nactor Admin { auth = Bearer(secret = \"K\"), identity = String }\n";
723        assert_eq!(resolve_label("Admin.issue", other, None), None);
724    }
725
726    #[test]
727    fn a_cookie_record_field_has_cookie_and_expire_signatures() {
728        let doc = "context a.b\ntype Prefs = { visits: Option[Int] }\nservice s from http {\n  on GET(\"/p\") (cookies: Prefs) -> Effect[HttpResult[String]] by v: Visitor { Ok(\"x\") }\n}\n";
729        assert_eq!(
730            resolve_label("Prefs.visits.cookie", doc, None).as_deref(),
731            Some("cookie(value: Int) -> Cookie")
732        );
733        assert_eq!(
734            resolve_label("Prefs.visits.expire", doc, None).as_deref(),
735            Some("expire() -> Cookie")
736        );
737        assert_eq!(resolve_label("Prefs.nope.cookie", doc, None), None);
738        // a record no handler takes as `cookies` has no cookie signatures
739        let plain = "context a.b\ntype P = { x: Int }\n";
740        assert_eq!(resolve_label("P.x.cookie", plain, None), None);
741        // the call context names the whole chain as the callee
742        let call = "  Ok(\"x\").withCookie(Prefs.visits.cookie(";
743        let ctx = call_context(call, call.len()).expect("a call");
744        assert_eq!(ctx.callee, "Prefs.visits.cookie");
745    }
746
747    #[test]
748    fn free_fn_and_capability_op_and_refined_labels() {
749        let doc = "commons m {\n  fn add(a: Int, b: Int) -> Int { a }\n}\n";
750        assert_eq!(
751            resolve_label("add", doc, None).as_deref(),
752            Some("add(a: Int, b: Int) -> Int")
753        );
754        let cap = "context a.b\n  capability Timer { fn after(label: String) -> Effect[Int] }\n";
755        assert_eq!(
756            resolve_label("Timer.after", cap, None).as_deref(),
757            Some("after(label: String) -> Effect[Int]")
758        );
759        let refined = "commons m {\n  type Email = String where NonEmpty\n}\n";
760        assert_eq!(
761            resolve_label("Email.of", refined, None).as_deref(),
762            Some("of(value: String) -> Result[Email, ValidationError]")
763        );
764    }
765
766    #[test]
767    fn value_receiver_callee_detection_and_rewrite() {
768        assert_eq!(value_receiver_method("xs.fold"), Some(("xs", "fold")));
769        assert_eq!(value_receiver_method("Int.parse"), None); // uppercase = name callee
770        assert_eq!(value_receiver_method("a.b.fold"), None); // multi-segment
771        assert_eq!(value_receiver_method("bar"), None); // no receiver
772
773        let text = "  let r = xs.fold(0, ";
774        let open = text.find('(').unwrap();
775        let (rw, off) = value_receiver_rewrite(text, "xs.fold", open, text.len()).unwrap();
776        assert_eq!(rw, "  let r = xs", "the `.fold(0, ` is dropped");
777        assert_eq!(&text[off..=off], "s", "offset lands inside `xs`");
778    }
779
780    #[test]
781    fn kernel_method_signature_lookup() {
782        use bynk_check::checker::{Ty, Types};
783        use bynk_syntax::ast::BaseType;
784        let tys = &Types::new();
785        let list = tys.intern(Ty::List(tys.intern(Ty::Base(BaseType::Int))));
786        assert!(
787            kernel_method_signature(list, tys, "fold")
788                .unwrap()
789                .starts_with("fold(")
790        );
791        let string = tys.intern(Ty::Base(BaseType::String));
792        assert!(
793            kernel_method_signature(string, tys, "split")
794                .unwrap()
795                .starts_with("split(")
796        );
797        assert!(kernel_method_signature(string, tys, "nope").is_none());
798    }
799
800    #[test]
801    fn param_ranges_split_top_level_only() {
802        let label = "fold(init: U, step: (U, T) -> U) -> U";
803        let r = param_ranges(label);
804        assert_eq!(r.len(), 2, "two params, not split inside (U, T): {r:?}");
805        assert_eq!(&label[r[0].0..r[0].1], "init: U");
806        assert_eq!(&label[r[1].0..r[1].1], "step: (U, T) -> U");
807    }
808}