Skip to main content

bynk_check/checker/
keying.rs

1//! Which types are `Key`, and the checks that need it. Constrained generics
2//! slice 2 (#2684; the model is the track's Q6 in
3//! `design/archive/retired-tracks.md`).
4//!
5//! `Key` admits a type as a value `Map` key or `Set` member (and as a `distinct`,
6//! `groupBy` or join key). It is automatic, never derived: a type is `Key` when it
7//! is one of:
8//!
9//! - `String`, `Int`, `Bool`, `Instant`, `Duration`, `Bytes` or `Decimal`, or a refined or
10//!   opaque type over one of them;
11//! - `Option[T]` or `List[T]` with `T` `Key`;
12//! - a record, sum or enum whose every field and payload is `Key`, and, when it is
13//!   generic, whose type arguments are `Key`;
14//! - a type parameter declared `K: Key` (checked separately: see
15//!   `super::equality::require_key_vars`).
16//!
17//! `Float` is not `Key` at any depth (`NaN` is not equal to itself), nor are
18//! `Map` and `Set` (an order-independent encoding is possible but nothing needs
19//! one yet), functions, `Effect`, `Query`, streams, held resources, actors and
20//! the boundary-only types.
21//!
22//! The runtime holds a composite key under a canonical encoding
23//! (`__bynkKeyEncode`); `Key` needs no witness, so it adds no hidden argument.
24//!
25//! The store rule (`store m: Map[K, V]`, `Cache`, `@indexed`) keeps its own
26//! `String`/`Int` predicate: those keys persist through `String(k)`.
27
28use std::collections::{HashMap, HashSet};
29use std::sync::Arc;
30
31use bynk_syntax::ast::{BaseType, TypeBody, TypeDecl, TypeRef};
32use bynk_syntax::error::CompileError;
33use bynk_syntax::span::Span;
34
35use super::equality::{EqScope, require_key_vars, require_key_vars_in};
36use super::{Ctx, NamedKind, Ty, TyId, Types};
37
38/// Why a type is not `Key`: the first offending part found.
39pub(crate) struct NotKey {
40    /// The offending part, as the author would write it.
41    pub part: String,
42    /// Whether the part is (or contains) a `Float`.
43    pub float: bool,
44}
45
46fn base_is_key(b: BaseType) -> bool {
47    !matches!(b, BaseType::Float)
48}
49
50/// The first part of `ty` that is not `Key`, or `None` when `ty` is `Key` all the
51/// way down. A type variable counts as `Key` here: whether the enclosing function
52/// declared the bound is `require_key_vars`'s question.
53pub(crate) fn not_keyable(ty: TyId, ctx: &Ctx) -> Option<NotKey> {
54    let mut visited = HashSet::new();
55    walk_ty(ty, ctx, &mut visited)
56}
57
58fn walk_ty(ty: TyId, ctx: &Ctx, visited: &mut HashSet<String>) -> Option<NotKey> {
59    let tys = ctx.tys;
60    match &*tys.get(ty) {
61        Ty::Base(b) if base_is_key(*b) => None,
62        Ty::Base(_) => Some(NotKey {
63            part: tys.display(ty),
64            float: true,
65        }),
66        // A type that already failed to resolve was reported where it failed.
67        Ty::Var(_) | Ty::Error => None,
68        Ty::Option(t) | Ty::List(t) => walk_ty(*t, ctx, visited),
69        Ty::Named {
70            name, kind, args, ..
71        } => {
72            if let NamedKind::Refined(b) | NamedKind::Opaque(b) = kind
73                && !base_is_key(*b)
74            {
75                return Some(NotKey {
76                    part: tys.display(ty),
77                    float: true,
78                });
79            }
80            let args = args.clone();
81            let name = name.clone();
82            for a in &args {
83                if let Some(found) = walk_ty(*a, ctx, visited) {
84                    return Some(found);
85                }
86            }
87            walk_decl(&name, &ctx.input.types, visited)
88        }
89        _ => Some(NotKey {
90            part: tys.display(ty),
91            float: false,
92        }),
93    }
94}
95
96/// Walk a named type's declared fields. Each name is walked once per check, which
97/// keeps recursive types finite.
98fn walk_decl(
99    name: &str,
100    types: &HashMap<String, Arc<TypeDecl>>,
101    visited: &mut HashSet<String>,
102) -> Option<NotKey> {
103    if !visited.insert(name.to_string()) {
104        return None;
105    }
106    let decl = types.get(name)?;
107    let params: Vec<&str> = decl
108        .type_params
109        .iter()
110        .map(|p| p.name.name.as_str())
111        .collect();
112    match &decl.body {
113        TypeBody::Record(r) => r
114            .fields
115            .iter()
116            .find_map(|f| walk_ref(&f.type_ref, &params, types, visited)),
117        TypeBody::Sum(s) => s
118            .variants
119            .iter()
120            .flat_map(|v| v.payload.iter())
121            .find_map(|p| walk_ref(&p.type_ref, &params, types, visited)),
122        TypeBody::Opaque { base, .. } | TypeBody::Refined { base, .. } => (!base_is_key(*base))
123            .then(|| NotKey {
124                part: base.name().to_string(),
125                float: true,
126            }),
127    }
128}
129
130/// The declaration-side walk: the first part of a declared type that is not `Key`,
131/// with the declaring type's own parameters (`params`) taken as `Key`.
132pub(crate) fn typeref_not_key(
133    t: &TypeRef,
134    params: &[&str],
135    types: &HashMap<String, Arc<TypeDecl>>,
136) -> Option<NotKey> {
137    walk_ref(t, params, types, &mut HashSet::new())
138}
139
140fn walk_ref(
141    t: &TypeRef,
142    params: &[&str],
143    types: &HashMap<String, Arc<TypeDecl>>,
144    visited: &mut HashSet<String>,
145) -> Option<NotKey> {
146    match t {
147        TypeRef::Base(b, _) => (!base_is_key(*b)).then(|| NotKey {
148            part: b.name().to_string(),
149            float: true,
150        }),
151        TypeRef::Option(a, _) | TypeRef::List(a, _) => walk_ref(a, params, types, visited),
152        TypeRef::Named(id) if params.contains(&id.name.as_str()) => None,
153        // An unresolved name is reported by the resolver, not here.
154        TypeRef::Named(id) => walk_decl(&id.name, types, visited),
155        TypeRef::App { name, args, .. } => args
156            .iter()
157            .find_map(|a| walk_ref(a, params, types, visited))
158            .or_else(|| walk_decl(&name.name, types, visited)),
159        _ => Some(NotKey {
160            part: super::equality::render(t),
161            float: false,
162        }),
163    }
164}
165
166/// What a use of `Key` is for, which decides the diagnostic's wording.
167pub(crate) enum KeySite<'a> {
168    /// A `Map` key.
169    MapKey,
170    /// A `Set` member.
171    SetElement,
172    /// A `List` or `Query` kernel's element or key (`distinct`, `distinctBy`, `groupBy`,
173    /// `joinOn`, `leftJoin`).
174    Kernel(&'a str),
175    /// A call to a `Key`-bounded callee: `callee` requires `param: Key`.
176    Call { callee: &'a str, param: &'a str },
177}
178
179/// Check that `ty` can key a collection at `span`: every concrete part is `Key`
180/// ([`not_keyable`]) and every type parameter in it is declared `Key`
181/// ([`require_key_vars`]). Reports and returns `false` otherwise.
182pub(crate) fn check_key(ctx: &mut Ctx, ty: TyId, span: Span, site: &KeySite) -> bool {
183    if let Some(blocker) = not_keyable(ty, ctx) {
184        report_not_keyable(ctx, ty, span, site, blocker);
185        return false;
186    }
187    let clause = match site {
188        KeySite::MapKey => "a `Map` key must be `Key`".to_string(),
189        KeySite::SetElement => "a `Set` element must be `Key`".to_string(),
190        KeySite::Kernel(method) => format!("`{method}` keys by this type"),
191        KeySite::Call { callee, param } => format!("`{callee}` requires `{param}: Key`"),
192    };
193    require_key_vars(ctx, ty, span, &clause)
194}
195
196/// The note every `not_keyable` diagnostic carries.
197pub(crate) fn key_note(blocker: &NotKey) -> String {
198    let mut note = format!(
199        "`{}` is not `Key`; key types are `String`, `Int`, `Bool`, `Instant`, `Duration`, `Bytes`, `Option` and `List` of a key type, refined and opaque types over them, and records, sums and enums made only of key types",
200        blocker.part
201    );
202    if blocker.float {
203        note.push_str(". A `Float` is never a key: `NaN` is not equal to itself, so a key holding one could never be found again");
204    }
205    note
206}
207
208/// The tail of a `not_keyable` message when the blocker is a `Float`.
209pub(crate) fn float_clause(blocker: &NotKey) -> &'static str {
210    if blocker.float {
211        " (a `Float` is never a key: `NaN` is not equal to itself)"
212    } else {
213        ""
214    }
215}
216
217fn report_not_keyable(ctx: &mut Ctx, ty: TyId, span: Span, site: &KeySite, blocker: NotKey) {
218    let shown = ty.display(ctx.tys);
219    let message = match site {
220        KeySite::MapKey => format!("a `Map` key must be `Key`, but `{shown}` is not"),
221        KeySite::SetElement => format!("a `Set` element must be `Key`, but `{shown}` is not"),
222        KeySite::Kernel(method) => {
223            format!("`{method}` needs a `Key` element or key, but got `{shown}`")
224        }
225        KeySite::Call { callee, param } => {
226            format!("`{callee}` requires `{param}: Key`, but this call makes `{param}` `{shown}`")
227        }
228    };
229    let message = format!("{message}{}", float_clause(&blocker));
230    let note = key_note(&blocker);
231    ctx.errors
232        .push(CompileError::new("bynk.types.not_keyable", span, message).with_note(note));
233}
234
235/// At a call, check each `Key`-bounded type parameter of the callee (`params`)
236/// against its instantiation (`subst`): a `Key` type, or a type parameter the
237/// caller declares `Key`. Returns `false` after reporting the first violation.
238pub(crate) fn check_declared_key_args(
239    callee: &str,
240    call_span: Span,
241    params: &[String],
242    subst: &HashMap<String, TyId>,
243    ctx: &mut Ctx,
244) -> bool {
245    for param in params {
246        let Some(&arg_ty) = subst.get(param) else {
247            continue;
248        };
249        if !check_key(ctx, arg_ty, call_span, &KeySite::Call { callee, param }) {
250            return false;
251        }
252    }
253    true
254}
255
256/// The type parameters of `f` declared `Key`: its own (inline or in `where`) and
257/// its receiver type's.
258pub fn key_params(
259    f: &bynk_syntax::ast::FnDecl,
260    types: &HashMap<String, Arc<TypeDecl>>,
261) -> Vec<String> {
262    use super::equality::has_key;
263    let where_key = |name: &str| {
264        f.where_bounds
265            .iter()
266            .any(|wb| wb.param.name == name && has_key(&wb.bounds))
267    };
268    let mut out = Vec::new();
269    if let bynk_syntax::ast::FnName::Method { type_name, .. } = &f.name
270        && let Some(decl) = types.get(&type_name.name)
271    {
272        for tp in &decl.type_params {
273            if has_key(&tp.bounds) || where_key(&tp.name.name) {
274                out.push(tp.name.name.clone());
275            }
276        }
277    }
278    for tp in &f.type_params {
279        if has_key(&tp.bounds) || where_key(&tp.name.name) {
280            out.push(tp.name.name.clone());
281        }
282    }
283    out
284}
285
286/// Walk `ty` for `Map` keys and `Set` members that mention a type parameter, and
287/// require each to be declared `Key`. Used on a signature, where a bound is
288/// declared rather than discovered (DECISION F): without it
289/// `fn mk[K](k: K) -> Map[K, Int]` could key a map by a function.
290pub(crate) fn require_key_positions(
291    tys: &Types,
292    type_vars: &HashSet<String>,
293    eq: &EqScope,
294    errors: &mut Vec<CompileError>,
295    ty: TyId,
296    span: Span,
297) {
298    let go = |t: TyId, errors: &mut Vec<CompileError>| {
299        require_key_positions(tys, type_vars, eq, errors, t, span)
300    };
301    match &*tys.get(ty) {
302        Ty::Map(k, v) => {
303            require_key_vars_in(
304                tys,
305                type_vars,
306                eq,
307                errors,
308                *k,
309                span,
310                "a `Map` key must be `Key`",
311            );
312            go(*k, errors);
313            go(*v, errors);
314        }
315        Ty::Set(e) => {
316            require_key_vars_in(
317                tys,
318                type_vars,
319                eq,
320                errors,
321                *e,
322                span,
323                "a `Set` element must be `Key`",
324            );
325            go(*e, errors);
326        }
327        Ty::Option(a)
328        | Ty::List(a)
329        | Ty::Effect(a)
330        | Ty::HttpResult(a)
331        | Ty::HttpOutcome(a)
332        | Ty::Query(a)
333        | Ty::Stream(a)
334        | Ty::TestConnection(a)
335        | Ty::Connection(a) => go(*a, errors),
336        Ty::Result(a, b) => {
337            go(*a, errors);
338            go(*b, errors);
339        }
340        Ty::Fn { params, ret } => {
341            for p in params {
342                go(*p, errors);
343            }
344            go(*ret, errors);
345        }
346        Ty::Named { args, .. } => {
347            for a in args {
348                go(*a, errors);
349            }
350        }
351        _ => {}
352    }
353}