Skip to main content

bynk_check/
kernel_methods.rs

1//! v0.30.2 (ADR 0063): the enumerable kernel-method registry.
2//!
3//! The value methods of the built-in kernels (`List`/`Map`/`Option`/`Result`/
4//! `String`/`Int`/`Float`) are dispatched by the checker in
5//! [`crate::checker`]'s `check_*_kernel_method` functions, where the method
6//! names live in `match` arms — authoritative for *typing*, but not
7//! enumerable. This module is the enumerable view the LSP reads for `.`-member
8//! completion: per-kernel `(name, signature)` tables and a [`methods_for`]
9//! mapping from a receiver [`Ty`] to its methods.
10//!
11//! The tables are generated from the typed operations in [`crate::kernel_op`]
12//! (#3164), where each method is declared once with its spelling and signature;
13//! the checker resolves a call to that enum and carries it in
14//! [`crate::checker::Callee::Kernel`].
15//!
16//! The signatures are human-readable Bynk-surface display strings (generic in
17//! the element/key/value type), for completion `detail` — not the checker's
18//! `Ty`-typed signatures. The checker matches on the typed operations
19//! exhaustively, so the table can neither list a method the checker rejects nor
20//! omit one it accepts.
21
22use crate::checker::{NamedKind, Ty, TyId, Types};
23use bynk_syntax::ast::BaseType;
24
25pub use crate::kernel_op::KernelMethod;
26use crate::kernel_op::{
27    BytesOp, DecimalOp, DurationOp, EffectOp, EffectResultOp, FloatOp, HttpResultOp, InstantOp,
28    IntOp, ListOp, MapOp, OptionOp, QueryOp, RequestCookiesOp, RequestHeadersOp, RequestQueryOp,
29    ResultOp, SetOp, StringOp, TestConnectionOp, TokenClaimsOp,
30};
31
32/// `List[T]` (v0.20b; v0.88 adds the ADR 0116 query/collection vocabulary).
33pub const LIST_METHODS: &[KernelMethod] = ListOp::TABLE;
34/// The `Set` kernel (K6a, #2596): what Bynk cannot write over a list. The
35/// combinators (`union`, `intersect`, …) are the `bynk.set` commons.
36pub const SET_METHODS: &[KernelMethod] = SetOp::TABLE;
37/// `Map[K, V]` (v0.20b).
38pub const MAP_METHODS: &[KernelMethod] = MapOp::TABLE;
39/// `Query[T]` (v0.91, ADR 0115; joins/grouping v0.94, ADR 0116/0120): the lazy
40/// storage-query vocabulary a `store` collection lifts into.
41pub const QUERY_METHODS: &[KernelMethod] = QueryOp::TABLE;
42/// `Option[T]` combinators (v0.22a).
43pub const OPTION_METHODS: &[KernelMethod] = OptionOp::TABLE;
44/// `Result[T, E]` combinators (v0.22a).
45pub const RESULT_METHODS: &[KernelMethod] = ResultOp::TABLE;
46/// The methods of every `Effect[T]` (#2683, #2711): `within`, `race` and `detach`.
47pub const EFFECT_METHODS: &[KernelMethod] = EffectOp::TABLE;
48/// The `Effect[Result[T, E]]` combinators (v0.152, ADR 0176): `within` and
49/// `race` (on every `Effect`) alongside the compiler-synthesised combinators.
50pub const EFFECT_RESULT_METHODS: &[KernelMethod] = &[
51    EffectOp::TABLE[0],
52    EffectOp::TABLE[1],
53    EffectOp::TABLE[2],
54    EffectResultOp::TABLE[0],
55    EffectResultOp::TABLE[1],
56    EffectResultOp::TABLE[2],
57    EffectResultOp::TABLE[3],
58];
59/// The `String` kernel (v0.22a; UTF-16 code units, except `chars`).
60pub const STRING_METHODS: &[KernelMethod] = StringOp::TABLE;
61/// The `Int` kernel.
62pub const INT_METHODS: &[KernelMethod] = IntOp::TABLE;
63/// The `Float` kernel.
64pub const FLOAT_METHODS: &[KernelMethod] = FloatOp::TABLE;
65/// The `Duration` kernel (v0.86, ADR 0112).
66pub const DURATION_METHODS: &[KernelMethod] = DurationOp::TABLE;
67/// The `Instant` kernel (v0.90, ADR 0114).
68pub const INSTANT_METHODS: &[KernelMethod] = InstantOp::TABLE;
69/// The `Bytes` kernel (v0.110, ADR 0142).
70pub const BYTES_METHODS: &[KernelMethod] = BytesOp::TABLE;
71/// The `Decimal` kernel (#2622).
72pub const DECIMAL_METHODS: &[KernelMethod] = DecimalOp::TABLE;
73/// An HTTP handler's `headers` (#2341).
74pub const REQUEST_HEADERS_METHODS: &[KernelMethod] = RequestHeadersOp::TABLE;
75/// `HttpResult[T]` (#3277): `withCookie`, `clearCookie`, `cookies`.
76pub const HTTP_RESULT_METHODS: &[KernelMethod] = HttpResultOp::TABLE;
77/// An HTTP handler's `query` (#2854).
78pub const REQUEST_QUERY_METHODS: &[KernelMethod] = RequestQueryOp::TABLE;
79/// An HTTP handler's raw `cookies` (#3277).
80pub const REQUEST_COOKIES_METHODS: &[KernelMethod] = RequestCookiesOp::TABLE;
81/// An `Oidc` binder's claims (#2380).
82pub const TOKEN_CLAIMS_METHODS: &[KernelMethod] = TokenClaimsOp::TABLE;
83/// A case's recording `TestConnection[F]` (#3051).
84pub const TEST_CONNECTION_METHODS: &[KernelMethod] = TestConnectionOp::TABLE;
85
86/// Every method table above, by the type a user writes. The one enumerable
87/// registry (read by the wasm `bynk_reference`); a test pins it against the
88/// `pub const *_METHODS` declarations, so a new table cannot be left out.
89pub const ALL_METHODS: &[(&str, &[KernelMethod])] = &[
90    ("Int", INT_METHODS),
91    ("Float", FLOAT_METHODS),
92    ("Decimal", DECIMAL_METHODS),
93    ("String", STRING_METHODS),
94    ("Bytes", BYTES_METHODS),
95    ("Duration", DURATION_METHODS),
96    ("Instant", INSTANT_METHODS),
97    ("List", LIST_METHODS),
98    ("Map", MAP_METHODS),
99    ("Set", SET_METHODS),
100    ("Query", QUERY_METHODS),
101    ("Option", OPTION_METHODS),
102    ("Result", RESULT_METHODS),
103    ("Effect", EFFECT_METHODS),
104    ("Effect[Result[T, E]]", EFFECT_RESULT_METHODS),
105    ("RequestHeaders", REQUEST_HEADERS_METHODS),
106    ("HttpResult", HTTP_RESULT_METHODS),
107    ("RequestQuery", REQUEST_QUERY_METHODS),
108    ("RequestCookies", REQUEST_COOKIES_METHODS),
109    ("TokenClaims", TOKEN_CLAIMS_METHODS),
110    ("TestConnection", TEST_CONNECTION_METHODS),
111];
112
113/// The value methods of a receiver type, or `&[]` for a type with no kernel
114/// methods (record/sum named types, `Bool`, `Effect`, …). Record *fields* are
115/// resolved separately by the LSP (they need the type declaration).
116pub fn methods_for(ty: TyId, tys: &Types) -> &'static [KernelMethod] {
117    match &*tys.get(ty) {
118        Ty::Base(BaseType::Int) => INT_METHODS,
119        Ty::Base(BaseType::Float) => FLOAT_METHODS,
120        Ty::Base(BaseType::Duration) => DURATION_METHODS,
121        Ty::Base(BaseType::Instant) => INSTANT_METHODS,
122        Ty::Base(BaseType::Bytes) => BYTES_METHODS,
123        Ty::Base(BaseType::Decimal) => DECIMAL_METHODS,
124        Ty::Base(BaseType::String) => STRING_METHODS,
125        Ty::RequestHeaders => REQUEST_HEADERS_METHODS,
126        Ty::HttpResult(_) => HTTP_RESULT_METHODS,
127        Ty::RequestQuery => REQUEST_QUERY_METHODS,
128        Ty::RequestCookies => REQUEST_COOKIES_METHODS,
129        Ty::TokenClaims => TOKEN_CLAIMS_METHODS,
130        Ty::TestConnection(_) => TEST_CONNECTION_METHODS,
131        Ty::List(_) => LIST_METHODS,
132        Ty::Map(_, _) => MAP_METHODS,
133        Ty::Set(_) => SET_METHODS,
134        Ty::Query(_) => QUERY_METHODS,
135        Ty::Option(_) => OPTION_METHODS,
136        Ty::Result(_, _) => RESULT_METHODS,
137        // §2.8.3: an `Effect[Result[T, E]]` receiver offers the cross-context
138        // combinators (and `within`, `race`); any other `Effect[_]` offers those two alone.
139        Ty::Effect(inner) if matches!(&*tys.get(*inner), Ty::Result(_, _)) => EFFECT_RESULT_METHODS,
140        Ty::Effect(_) => EFFECT_METHODS,
141        // #561: a refined receiver inherits its base type's read-only kernel
142        // methods (after its own declared methods, which the completion layer
143        // merges in), so `.`-member completion offers them. `Bool` has no
144        // kernel; opaque types deliberately do not widen, so both surface none.
145        Ty::Named {
146            kind: NamedKind::Refined(base),
147            ..
148        } => match base {
149            BaseType::Int => INT_METHODS,
150            BaseType::Float => FLOAT_METHODS,
151            BaseType::Duration => DURATION_METHODS,
152            BaseType::Instant => INSTANT_METHODS,
153            BaseType::Bytes => BYTES_METHODS,
154            BaseType::Decimal => DECIMAL_METHODS,
155            BaseType::String => STRING_METHODS,
156            BaseType::Bool => &[],
157        },
158        _ => &[],
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn all_methods_lists_every_method_table() {
168        let declared = include_str!("kernel_methods.rs")
169            .lines()
170            .filter(|l| l.starts_with("pub const ") && l.contains("_METHODS: &[KernelMethod]"))
171            .count();
172        assert_eq!(
173            ALL_METHODS.len(),
174            declared,
175            "a *_METHODS table is missing from ALL_METHODS"
176        );
177    }
178
179    fn refined(tys: &Types, base: BaseType) -> TyId {
180        tys.intern(Ty::Named {
181            name: "R".to_string(),
182            kind: NamedKind::Refined(base),
183            args: Vec::new(),
184        })
185    }
186
187    #[test]
188    fn decimal_receiver_offers_its_kernel_and_a_refined_one_inherits_it() {
189        let tys = &Types::new();
190        // #2622: bare and refined `Decimal` receivers both surface the kernel.
191        let names = |ms: &[KernelMethod]| ms.iter().map(|m| m.name).collect::<Vec<_>>();
192        let bare = tys.intern(Ty::Base(BaseType::Decimal));
193        for n in ["scale", "toString", "round", "div", "toInt"] {
194            assert!(names(methods_for(bare, tys)).contains(&n), "{n}");
195        }
196        assert_eq!(
197            methods_for(refined(tys, BaseType::Decimal), tys).len(),
198            DECIMAL_METHODS.len()
199        );
200    }
201
202    #[test]
203    fn refined_receiver_inherits_base_kernel_methods() {
204        let tys = &Types::new();
205        // #561: completion on a refined receiver offers the base kernel.
206        assert_eq!(
207            methods_for(refined(tys, BaseType::String), tys).len(),
208            STRING_METHODS.len()
209        );
210        assert_eq!(
211            methods_for(refined(tys, BaseType::Int), tys).len(),
212            INT_METHODS.len()
213        );
214        assert_eq!(
215            methods_for(refined(tys, BaseType::Float), tys).len(),
216            FLOAT_METHODS.len()
217        );
218        // `Bool` has no kernel, so a `Bool`-based refinement inherits nothing.
219        assert!(methods_for(refined(tys, BaseType::Bool), tys).is_empty());
220        // Opaque types do not widen — no inherited kernel.
221        let opaque = tys.intern(Ty::Named {
222            name: "O".to_string(),
223            kind: NamedKind::Opaque(BaseType::String),
224            args: Vec::new(),
225        });
226        assert!(methods_for(opaque, tys).is_empty());
227    }
228
229    /// #596: a `Query[T]` receiver (a `store Map`'s `.entries`/`.keys`/
230    /// `.values`, or a bare store map used as a value, ADR 0120) offers the
231    /// full lazy query vocabulary — previously unmapped, so `.`-member
232    /// completion on any `Query` offered nothing.
233    #[test]
234    fn query_receiver_offers_the_query_vocabulary() {
235        let tys = &Types::new();
236        let int = tys.intern(Ty::Base(BaseType::Int));
237        let query = tys.intern(Ty::Query(int));
238        assert_eq!(methods_for(query, tys).len(), QUERY_METHODS.len());
239        assert!(methods_for(query, tys).iter().any(|m| m.name == "filter"));
240        assert!(methods_for(query, tys).iter().any(|m| m.name == "collect"));
241    }
242}