1use 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
38pub(crate) struct NotKey {
40 pub part: String,
42 pub float: bool,
44}
45
46fn base_is_key(b: BaseType) -> bool {
47 !matches!(b, BaseType::Float)
48}
49
50pub(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 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
96fn 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, ¶ms, 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, ¶ms, 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
130pub(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 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
166pub(crate) enum KeySite<'a> {
168 MapKey,
170 SetElement,
172 Kernel(&'a str),
175 Call { callee: &'a str, param: &'a str },
177}
178
179pub(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
196pub(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
208pub(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
235pub(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
256pub 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
286pub(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}