Skip to main content

bynk_check/checker/
collections.rs

1//! #3961: the `Map` and `Set` methods that bring them level with `List` (ADR
2//! 0116): `remove`, `contains`, `getOrElse`, `isEmpty`, `entries`, `filter`,
3//! `mapValues` and `fold` on a `Map`, `Map.of`, and the set algebra plus
4//! `isEmpty`, `filter`, `map` and `fold` on a `Set`. Kept apart from
5//! `kernels.rs` so that file does not grow.
6
7use super::calls::check_arg;
8use super::kernels::check_kernel_fn_arg;
9use super::keying::{KeySite, check_key};
10use super::*;
11use crate::kernel_op::{MapOp, SetOp};
12
13/// A wrong argument count: reports `bynk.types.method_arity` and types the
14/// arguments for their own diagnostics. `true` when the count is right.
15fn arity(what: &str, name: &str, n: usize, args: &[Expr], span: Span, ctx: &mut Ctx) -> bool {
16    if args.len() == n {
17        return true;
18    }
19    ctx.errors.push(CompileError::new(
20        "bynk.types.method_arity",
21        span,
22        format!(
23            "`{what}.{name}` takes {n} argument{}, got {}",
24            if n == 1 { "" } else { "s" },
25            args.len()
26        ),
27    ));
28    for a in args {
29        let _ = type_of(a, None, ctx);
30    }
31    false
32}
33
34/// The `Map` methods #3961 adds; `None` for one it does not own.
35pub(super) fn check_map_more(
36    method: &Ident,
37    op: MapOp,
38    args: &[Expr],
39    key: TyId,
40    val: TyId,
41    span: Span,
42    ctx: &mut Ctx,
43) -> Option<Option<TyId>> {
44    let tys = ctx.tys;
45    let name = method.name.as_str();
46    let n = match op {
47        MapOp::IsEmpty | MapOp::Entries => 0,
48        MapOp::Remove | MapOp::Contains | MapOp::Filter | MapOp::MapValues => 1,
49        MapOp::GetOrElse | MapOp::Fold => 2,
50        _ => return None,
51    };
52    if !arity("Map", name, n, args, span, ctx) {
53        return Some(None);
54    }
55    let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
56    // `?` inside returns from this closure only: a failed argument is reported
57    // already and types as `None`, which is still one of our methods.
58    let typed = |ctx: &mut Ctx| -> Option<TyId> {
59        match op {
60            MapOp::IsEmpty => Some(bool_ty),
61            MapOp::Entries => Some(tys.intern(Ty::List(map_entry_ty(key, val, tys)))),
62            MapOp::Remove => {
63                check_arg(&args[0], key, "the `Map.remove` key", ctx);
64                Some(tys.intern(Ty::Map(key, val)))
65            }
66            MapOp::Contains => {
67                check_arg(&args[0], key, "the `Map.contains` key", ctx);
68                Some(bool_ty)
69            }
70            MapOp::GetOrElse => {
71                check_arg(&args[0], key, "the `Map.getOrElse` key", ctx);
72                check_arg(&args[1], val, "the `Map.getOrElse` default", ctx);
73                Some(val)
74            }
75            MapOp::Filter => {
76                let p = Ty::Fn {
77                    params: vec![key, val],
78                    ret: bool_ty,
79                };
80                check_arg(&args[0], tys.intern(p), "the `Map.filter` predicate", ctx);
81                Some(tys.intern(Ty::Map(key, val)))
82            }
83            MapOp::MapValues => {
84                let u =
85                    check_kernel_fn_arg(&args[0], vec![val], "the `Map.mapValues` function", ctx)?;
86                Some(tys.intern(Ty::Map(key, u)))
87            }
88            MapOp::Fold => {
89                let acc = type_of(&args[0], None, ctx)?;
90                let step = Ty::Fn {
91                    params: vec![acc, key, val],
92                    ret: acc,
93                };
94                check_arg(
95                    &args[1],
96                    tys.intern(step),
97                    "the `Map.fold` step function",
98                    ctx,
99                );
100                Some(acc)
101            }
102            _ => unreachable!("filtered above"),
103        }
104    };
105    Some(typed(ctx))
106}
107
108/// The `Set` methods #3961 adds; `None` for one it does not own.
109pub(super) fn check_set_more(
110    method: &Ident,
111    op: SetOp,
112    args: &[Expr],
113    elem: TyId,
114    span: Span,
115    ctx: &mut Ctx,
116) -> Option<Option<TyId>> {
117    let tys = ctx.tys;
118    let name = method.name.as_str();
119    let n = match op {
120        SetOp::IsEmpty => 0,
121        SetOp::Union
122        | SetOp::Intersect
123        | SetOp::Difference
124        | SetOp::IsSubsetOf
125        | SetOp::Filter
126        | SetOp::Map => 1,
127        SetOp::Fold => 2,
128        _ => return None,
129    };
130    if !arity("Set", name, n, args, span, ctx) {
131        return Some(None);
132    }
133    let set = tys.intern(Ty::Set(elem));
134    let bool_ty = tys.intern(Ty::Base(BaseType::Bool));
135    // `?` inside returns from this closure only: a failed argument is reported
136    // already and types as `None`, which is still one of our methods.
137    let typed = |ctx: &mut Ctx| -> Option<TyId> {
138        match op {
139            SetOp::IsEmpty => Some(bool_ty),
140            SetOp::Union | SetOp::Intersect | SetOp::Difference => {
141                check_arg(&args[0], set, &format!("the `Set.{name}` argument"), ctx);
142                Some(set)
143            }
144            SetOp::IsSubsetOf => {
145                check_arg(&args[0], set, "the `Set.isSubsetOf` argument", ctx);
146                Some(bool_ty)
147            }
148            SetOp::Filter => {
149                let p = Ty::Fn {
150                    params: vec![elem],
151                    ret: bool_ty,
152                };
153                check_arg(&args[0], tys.intern(p), "the `Set.filter` predicate", ctx);
154                Some(set)
155            }
156            SetOp::Map => {
157                let u = check_kernel_fn_arg(&args[0], vec![elem], "the `Set.map` function", ctx)?;
158                check_key(ctx, u, args[0].span, &KeySite::SetElement);
159                Some(tys.intern(Ty::Set(u)))
160            }
161            SetOp::Fold => {
162                let acc = type_of(&args[0], None, ctx)?;
163                let step = Ty::Fn {
164                    params: vec![acc, elem],
165                    ret: acc,
166                };
167                check_arg(
168                    &args[1],
169                    tys.intern(step),
170                    "the `Set.fold` step function",
171                    ctx,
172                );
173                Some(acc)
174            }
175            _ => unreachable!("filtered above"),
176        }
177    };
178    Some(typed(ctx))
179}
180
181/// `Map.of(entries: List[MapEntry[K, V]]) -> Map[K, V]`: a later entry for a key
182/// replaces the value and keeps the first position. An inferred key type never
183/// passes the resolver's `Map[K, V]` check, so the key rule is applied here.
184pub(super) fn check_map_of(
185    args: &[Expr],
186    span: Span,
187    expected: Option<TyId>,
188    ctx: &mut Ctx,
189) -> Option<TyId> {
190    let tys = ctx.tys;
191    if !arity("Map", "of", 1, args, span, ctx) {
192        return None;
193    }
194    let expected_list = expected
195        .and_then(|t| peel_to_map(t, tys))
196        .filter(|(k, v)| !contains_var(*k, tys) && !contains_var(*v, tys))
197        .map(|(k, v)| tys.intern(Ty::List(map_entry_ty(k, v, tys))));
198    let list = type_of(&args[0], expected_list, ctx)?;
199    let entry = peel_to_list(list, tys).and_then(|e| match &*tys.get(e) {
200        Ty::Named { name, args, .. } if name == MAP_ENTRY && args.len() == 2 => {
201            Some((args[0], args[1]))
202        }
203        _ => None,
204    });
205    let Some((key, val)) = entry else {
206        ctx.errors.push(CompileError::new(
207            "bynk.types.type_mismatch",
208            args[0].span,
209            format!(
210                "the `Map.of` argument has type `{}`, but a `List[MapEntry[K, V]]` is required",
211                list.display(tys)
212            ),
213        ));
214        return None;
215    };
216    check_key(ctx, key, args[0].span, &KeySite::MapKey);
217    Some(tys.intern(Ty::Map(key, val)))
218}
219
220/// The `bynk.map` and `bynk.set` free functions and the method form each rewrites
221/// to: `(module, function, method, arity)`. One table, read by the warning below and by
222/// the wasm `bynk_reference` catalogue so the two cannot drift.
223pub const BYNK_COLLECTION_DEPRECATED: &[(&str, &str, &str, usize)] = &[
224    ("bynk.map", "values", "values", 1),
225    ("bynk.map", "contains", "contains", 2),
226    ("bynk.map", "getOr", "getOrElse", 3),
227    ("bynk.set", "union", "union", 2),
228    ("bynk.set", "intersect", "intersect", 2),
229    ("bynk.set", "difference", "difference", 2),
230    ("bynk.set", "isSubsetOf", "isSubsetOf", 2),
231    ("bynk.set", "filterSet", "filter", 2),
232    ("bynk.set", "mapSet", "map", 2),
233];
234
235/// A call to a deprecated `bynk.map`/`bynk.set` function: a non-failing warning
236/// (ADR 0117) with a machine-applicable rewrite to the method form,
237/// `union(a, b)` to `a.union(b)` and `getOr(m, k, d)` to `m.getOrElse(k, d)`.
238pub(super) fn warn_deprecated_collection_fn(
239    name: &Ident,
240    args: &[Expr],
241    call_span: Span,
242    ctx: &mut Ctx,
243) {
244    let Some(module) = ctx.input.imported_from.get(&name.name).cloned() else {
245        return;
246    };
247    let Some(&(_, _, method, arity)) = BYNK_COLLECTION_DEPRECATED
248        .iter()
249        .find(|(m, f, _, _)| *m == module && *f == name.name)
250    else {
251        return;
252    };
253    let code = if module == "bynk.map" {
254        "bynk.map.deprecated_function"
255    } else {
256        "bynk.set.deprecated_function"
257    };
258    let mut err = CompileError::new(
259        code,
260        name.span,
261        format!(
262            "`{module}.{}` is deprecated: use the `{}` method `.{method}(…)`",
263            name.name,
264            if module == "bynk.map" { "Map" } else { "Set" }
265        ),
266    )
267    .with_note(format!(
268        "the `{module}` free functions are superseded by the `{}` methods (#3961); the method form reads left to right and chains",
269        if module == "bynk.map" { "Map" } else { "Set" }
270    ));
271    // The rewrite needs the function's own shape; a wrong-arity call is reported
272    // elsewhere and gets no fix.
273    if args.len() == arity {
274        let mut edits = vec![(
275            Span::new(name.span.start, args[0].span.start),
276            String::new(),
277        )];
278        edits.push(if args.len() == 1 {
279            (
280                Span::new(args[0].span.end, call_span.end),
281                format!(".{method}()"),
282            )
283        } else {
284            (
285                Span::new(args[0].span.end, args[1].span.start),
286                format!(".{method}("),
287            )
288        });
289        err = err.with_suggestion(
290            format!("rewrite to the `.{method}(…)` method form"),
291            edits,
292            Applicability::MachineApplicable,
293        );
294    }
295    ctx.errors.push(err);
296}