1use 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
35pub(crate) struct NotOrd {
37 pub part: String,
39 pub decl: Option<Arc<TypeDecl>>,
41}
42
43fn base_is_ord(b: BaseType) -> bool {
45 !matches!(b, BaseType::Bool)
46}
47
48pub(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
88pub(crate) enum OrdSite<'a> {
90 Operator(&'a str),
92 Key(&'a str),
94 Element(&'a str),
97 Call { callee: &'a str, param: &'a str },
99}
100
101pub(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 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
170pub(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 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
216pub(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 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, ¶ms) {
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, ¶ms, 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, ¶ms, 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 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 let names = &decl.derives;
344 let edit = if names.len() == 1 {
345 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
371pub 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
405fn 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}