Skip to main content

bynk_check/checker/
ordering.rs

1//! Which types are `Ord`, and the checks that need it. Constrained generics
2//! slice 1 (#2660; the model is the track's Q2/Q5 in
3//! `design/archive/retired-tracks.md`).
4//!
5//! `Ord` is a declared, structural property. A type is `Ord` when it is one of:
6//!
7//! - `Int`, `Float`, `String`, `Duration`, `Instant` or `Bytes`, or a refined type
8//!   over one of them (a refinement is visible everywhere, so it needs no
9//!   declaration);
10//! - `Option[T]` or `List[T]` with `T` `Ord`;
11//! - a record, sum, enum or opaque type that declares `derives Ord`, and, when it
12//!   is generic, whose type arguments are `Ord`;
13//! - a type parameter declared `T: Ord` (checked separately: see
14//!   `super::equality::require_ord_vars`).
15//!
16//! `Bool`, `Result`, `Map`, `Set`, functions and held resources are not `Ord`.
17//!
18//! `derives Ord` makes declaration order meaningful: a record orders by its fields
19//! in declaration order, a sum by variant declaration order and then by payload.
20//! That is why `Ord` is opt-in (Q2) while `Eq` is automatic.
21//!
22//! `Query`'s `sortBy`/`min`/`max` take any `Ord` key too (#2787); a `Query` is
23//! evaluated in memory, so there is no storage path that needs a base-type key.
24
25use std::collections::HashMap;
26use std::sync::Arc;
27
28use bynk_syntax::ast::{BaseType, FnDecl, FnName, Ident, TypeBody, TypeDecl, TypeRef};
29use bynk_syntax::error::{Applicability, CompileError};
30use bynk_syntax::span::Span;
31
32use super::equality::{has_ord, require_ord_vars};
33use super::{Ctx, NamedKind, Ty, TyId};
34
35/// Why a type is not `Ord`: the first offending part found.
36pub(crate) struct NotOrd {
37    /// The offending part, as the author would write it.
38    pub part: String,
39    /// The user-declared type that lacks `derives Ord`, when that is the cause.
40    pub decl: Option<Arc<TypeDecl>>,
41}
42
43/// Whether a base type is `Ord`.
44fn base_is_ord(b: BaseType) -> bool {
45    !matches!(b, BaseType::Bool)
46}
47
48/// The first part of `ty` that is not `Ord`, or `None` when `ty` is `Ord` all the
49/// way down. A type variable counts as `Ord` here: whether the enclosing
50/// function declared the bound is `require_ord_vars`'s question.
51pub(crate) fn not_orderable(ty: TyId, ctx: &Ctx) -> Option<NotOrd> {
52    let tys = ctx.tys;
53    match &*tys.get(ty) {
54        Ty::Base(b) if base_is_ord(*b) => None,
55        Ty::Var(_) => None,
56        Ty::Option(t) | Ty::List(t) => not_orderable(*t, ctx),
57        Ty::Named {
58            name, kind, args, ..
59        } => {
60            match kind {
61                NamedKind::Refined(b) => {
62                    if !base_is_ord(*b) {
63                        return Some(NotOrd {
64                            part: tys.display(ty),
65                            decl: None,
66                        });
67                    }
68                }
69                NamedKind::Record | NamedKind::Sum | NamedKind::Opaque(_) => {
70                    let decl = ctx.input.types.get(name);
71                    if !decl.is_some_and(|d| has_ord(&d.derives)) {
72                        return Some(NotOrd {
73                            part: tys.display(ty),
74                            decl: decl.cloned(),
75                        });
76                    }
77                }
78            }
79            args.iter().find_map(|a| not_orderable(*a, ctx))
80        }
81        _ => Some(NotOrd {
82            part: tys.display(ty),
83            decl: None,
84        }),
85    }
86}
87
88/// What a use of `Ord` is for, which decides the diagnostic's wording and code.
89pub(crate) enum OrdSite<'a> {
90    /// A comparison operator (`<`, `<=`, `>`, `>=`).
91    Operator(&'a str),
92    /// A `List` or `Query` ordering kernel's key (`sortBy`, `min`, `max`).
93    Key(&'a str),
94    /// #3962: a keyless `List` ordering kernel (`sort()`, `min()`, `max()`), which
95    /// orders the element itself.
96    Element(&'a str),
97    /// A call to an `Ord`-bounded callee: `callee` requires `param: Ord`.
98    Call { callee: &'a str, param: &'a str },
99}
100
101/// Check that `ty` can be ordered at `span`: every concrete part is `Ord`
102/// ([`not_orderable`]) and every type parameter in it is declared `Ord`
103/// (`require_ord_vars`). Reports and returns `false` otherwise.
104pub(crate) fn check_ord(ctx: &mut Ctx, ty: TyId, span: Span, site: &OrdSite) -> bool {
105    if let Some(blocker) = not_orderable(ty, ctx) {
106        report_not_orderable(ctx, ty, span, site, blocker);
107        return false;
108    }
109    let clause = match site {
110        OrdSite::Operator(op) => format!("operator `{op}` orders values of this type"),
111        OrdSite::Key(method) => format!("`{method}` orders by this key"),
112        OrdSite::Element(method) => format!("`{method}` orders the elements"),
113        OrdSite::Call { callee, param } => format!("`{callee}` requires `{param}: Ord`"),
114    };
115    require_ord_vars(ctx, ty, span, &clause)
116}
117
118fn report_not_orderable(ctx: &mut Ctx, ty: TyId, span: Span, site: &OrdSite, blocker: NotOrd) {
119    let tys = ctx.tys;
120    let shown = ty.display(tys);
121    let (code, message) = match site {
122        OrdSite::Operator(op) => (
123            "bynk.types.not_orderable",
124            format!("operator `{op}` needs an orderable type, but `{shown}` is not"),
125        ),
126        OrdSite::Key(method) => (
127            "bynk.types.key_not_orderable",
128            format!("`{method}` needs an orderable key, but the key function returns `{shown}`"),
129        ),
130        OrdSite::Element(method) => (
131            "bynk.types.not_orderable",
132            format!("`{method}` needs an orderable element type, but `{shown}` is not"),
133        ),
134        OrdSite::Call { callee, param } => (
135            "bynk.types.not_orderable",
136            format!("`{callee}` requires `{param}: Ord`, but this call makes `{param}` `{shown}`"),
137        ),
138    };
139    let mut err = CompileError::new(code, span, message);
140    match &blocker.decl {
141        Some(decl) => {
142            err = err.with_note(format!(
143                "`{}` does not declare `derives Ord`; declaring it orders the type by declaration order (fields, then variants), so reordering the declaration changes the order",
144                decl.name.name
145            ));
146            // The edit lands in the declaring file; a suggestion for a type
147            // declared elsewhere would render against the wrong source.
148            if decl.span.file == span.file {
149                let end = decl.span.end;
150                err = err.with_suggestion(
151                    format!("add `derives Ord` to `{}`", decl.name.name),
152                    vec![(
153                        Span::new_in(decl.span.file, end, end),
154                        " derives Ord".to_string(),
155                    )],
156                    Applicability::MaybeIncorrect,
157                );
158            }
159        }
160        None => {
161            err = err.with_note(format!(
162                "`{}` is not orderable; orderable types are `Int`, `Float`, `Decimal`, `String`, `Duration`, `Instant`, `Bytes`, `Option` and `List` of an orderable type, refined types over them, and types that declare `derives Ord`",
163                blocker.part
164            ));
165        }
166    }
167    ctx.errors.push(err);
168}
169
170// -- `derives` validation (declaration side) --
171
172/// Whether a declared field type is `Ord`, with the declaring type's own
173/// parameters `params` taken as `Ord`.
174/// Returns the first offending part, rendered as written.
175pub(crate) fn typeref_not_ord(
176    t: &TypeRef,
177    params: &[&str],
178    types: &HashMap<String, Arc<TypeDecl>>,
179) -> Option<String> {
180    match t {
181        TypeRef::Base(b, _) => (!base_is_ord(*b)).then(|| super::equality::render(t)),
182        TypeRef::Option(a, _) | TypeRef::List(a, _) => typeref_not_ord(a, params, types),
183        TypeRef::Named(id) if params.contains(&id.name.as_str()) => None,
184        TypeRef::Named(id) => named_not_ord(&id.name, &[], t, params, types),
185        TypeRef::App { name, args, .. } => named_not_ord(&name.name, args, t, params, types),
186        _ => Some(super::equality::render(t)),
187    }
188}
189
190fn named_not_ord(
191    name: &str,
192    args: &[TypeRef],
193    whole: &TypeRef,
194    params: &[&str],
195    types: &HashMap<String, Arc<TypeDecl>>,
196) -> Option<String> {
197    let Some(decl) = types.get(name) else {
198        // An unresolved name is reported by the resolver, not here.
199        return None;
200    };
201    match &decl.body {
202        TypeBody::Refined { base, .. } => {
203            if !base_is_ord(*base) {
204                return Some(super::equality::render(whole));
205            }
206        }
207        _ => {
208            if !has_ord(&decl.derives) {
209                return Some(super::equality::render(whole));
210            }
211        }
212    }
213    args.iter().find_map(|a| typeref_not_ord(a, params, types))
214}
215
216/// `derives` validation for one type declaration: unknown names, the automatic
217/// ones, and, for `Ord`, that every field and payload is `Ord`.
218pub(crate) fn check_derives(
219    decl: &TypeDecl,
220    types: &HashMap<String, Arc<TypeDecl>>,
221    errors: &mut Vec<CompileError>,
222) {
223    for (i, d) in decl.derives.iter().enumerate() {
224        match d.name.as_str() {
225            "Ord" => {}
226            "Eq" | "Key" | "Codable" => errors.push(derives_automatic(decl, i, d)),
227            other => errors.push(
228                CompileError::new(
229                    "bynk.generics.unknown_constraint",
230                    d.span,
231                    format!(
232                        "`{other}` is not a constraint a type can derive (type `{}`)",
233                        decl.name.name
234                    ),
235                )
236                .with_note("a type can derive `Ord`; `Eq`, `Key` and `Codable` hold automatically"),
237            ),
238        }
239    }
240    if !has_ord(&decl.derives) {
241        return;
242    }
243    let params: Vec<&str> = decl
244        .type_params
245        .iter()
246        .map(|p| p.name.name.as_str())
247        .collect();
248    // A recursive reference with different arguments (`Nest[List[T]]` inside
249    // `Nest[T]`) would need a comparator per nesting depth, so it has none.
250    let all_fields: Vec<(&str, &TypeRef, Span)> = match &decl.body {
251        TypeBody::Record(r) => r
252            .fields
253            .iter()
254            .map(|f| (f.name.name.as_str(), &f.type_ref, f.type_ref.span()))
255            .collect(),
256        TypeBody::Sum(s) => s
257            .variants
258            .iter()
259            .flat_map(|v| v.payload.iter())
260            .map(|p| (p.name.name.as_str(), &p.type_ref, p.type_ref.span()))
261            .collect(),
262        _ => Vec::new(),
263    };
264    for (field, t, span) in all_fields {
265        if irregular_self_reference(t, decl, &params) {
266            errors.push(
267                CompileError::new(
268                    "bynk.types.derives_field_not_orderable",
269                    span,
270                    format!(
271                        "`{}` derives `Ord`, but field `{field}` refers to `{}` with different type arguments",
272                        decl.name.name, decl.name.name
273                    ),
274                )
275                .with_note("a recursive reference in a type that derives `Ord` must repeat the type's own parameters unchanged"),
276            );
277        }
278    }
279    let mut fail = |what: String, part: String, span: Span| {
280        errors.push(
281            CompileError::new(
282                "bynk.types.derives_field_not_orderable",
283                span,
284                format!(
285                    "`{}` derives `Ord`, but {what} has type `{part}`, which is not orderable",
286                    decl.name.name
287                ),
288            )
289            .with_note("every field and payload of a type that derives `Ord` must itself be `Ord`"),
290        );
291    };
292    match &decl.body {
293        TypeBody::Record(r) => {
294            for f in &r.fields {
295                if let Some(part) = typeref_not_ord(&f.type_ref, &params, types) {
296                    fail(format!("field `{}`", f.name.name), part, f.type_ref.span());
297                }
298            }
299        }
300        TypeBody::Sum(s) => {
301            for v in &s.variants {
302                for p in &v.payload {
303                    if let Some(part) = typeref_not_ord(&p.type_ref, &params, types) {
304                        fail(
305                            format!(
306                                "`{}.{}`'s field `{}`",
307                                decl.name.name, v.name.name, p.name.name
308                            ),
309                            part,
310                            p.type_ref.span(),
311                        );
312                    }
313                }
314            }
315        }
316        TypeBody::Opaque {
317            base, base_span, ..
318        } => {
319            if !base_is_ord(*base) {
320                fail(
321                    "its representation".to_string(),
322                    base.name().to_string(),
323                    *base_span,
324                );
325            }
326        }
327        // A refined type is `Ord` over an orderable base without declaring it.
328        TypeBody::Refined { .. } => {}
329    }
330}
331
332fn derives_automatic(decl: &TypeDecl, index: usize, d: &Ident) -> CompileError {
333    let mut err = CompileError::new(
334        "bynk.types.derives_automatic",
335        d.span,
336        format!(
337            "`{}` holds for `{}` automatically; there is nothing to derive",
338            d.name, decl.name.name
339        ),
340    )
341    .with_note("only `Ord` is opted into with `derives`");
342    // Remove the name; when it is the only one, the whole clause goes too.
343    let names = &decl.derives;
344    let edit = if names.len() == 1 {
345        // `<body> derives Eq` -> `<body>`: the keyword through the name, and the
346        // one separator before it.
347        let kw = decl.derives_kw.unwrap_or(d.span);
348        (
349            Span::new_in(d.span.file, kw.start.saturating_sub(1), d.span.end),
350            String::new(),
351        )
352    } else if index + 1 < names.len() {
353        (
354            Span::new_in(d.span.file, d.span.start, names[index + 1].span.start),
355            String::new(),
356        )
357    } else {
358        (
359            Span::new_in(d.span.file, names[index - 1].span.end, d.span.end),
360            String::new(),
361        )
362    };
363    err = err.with_suggestion(
364        format!("remove `{}`", d.name),
365        vec![edit],
366        Applicability::MachineApplicable,
367    );
368    err
369}
370
371// -- witnesses --
372
373/// The type parameters of `f` that take a comparator witness, in witness order
374/// (DECISION D): the receiver type's parameters first, in the type's declaration
375/// order, then the function's own, in declaration order. A parameter is a witness
376/// parameter when declared `Ord` inline (`T: Ord`), in a `where` entry, or, for
377/// a receiver parameter, on the type (`type Sorted[T: Ord]`). The emitter adds
378/// one trailing parameter per name, and every call site passes one argument per
379/// name, so this order is the contract between them; it is not part of the
380/// published ABI.
381pub fn witness_params(f: &FnDecl, types: &HashMap<String, Arc<TypeDecl>>) -> Vec<String> {
382    let where_ord = |name: &str| {
383        f.where_bounds
384            .iter()
385            .any(|wb| wb.param.name == name && has_ord(&wb.bounds))
386    };
387    let mut out = Vec::new();
388    if let FnName::Method { type_name, .. } = &f.name
389        && let Some(decl) = types.get(&type_name.name)
390    {
391        for tp in &decl.type_params {
392            if has_ord(&tp.bounds) || where_ord(&tp.name.name) {
393                out.push(tp.name.name.clone());
394            }
395        }
396    }
397    for tp in &f.type_params {
398        if has_ord(&tp.bounds) || where_ord(&tp.name.name) {
399            out.push(tp.name.name.clone());
400        }
401    }
402    out
403}
404
405/// Whether `t` mentions the declaration's own name applied to anything but its
406/// own parameters, in order.
407fn irregular_self_reference(t: &TypeRef, decl: &TypeDecl, params: &[&str]) -> bool {
408    match t {
409        TypeRef::Option(a, _) | TypeRef::List(a, _) => irregular_self_reference(a, decl, params),
410        TypeRef::App { name, args, .. } => {
411            let same = args.len() == params.len()
412                && args
413                    .iter()
414                    .zip(params)
415                    .all(|(a, p)| matches!(a, TypeRef::Named(id) if id.name == *p));
416            (name.name == decl.name.name && !same)
417                || args
418                    .iter()
419                    .any(|a| irregular_self_reference(a, decl, params))
420        }
421        _ => false,
422    }
423}