| @@ -0,0 +1,879 @@ |
| 1 | +//! Inference for one function body. |
| 2 | +//! |
| 3 | +//! Bidirectional in the small: `check_expr` pushes an expected type into |
| 4 | +//! lambdas (so callback parameters are known), everything else is inferred |
| 5 | +//! and unified. Local `let`s are not generalized (MonoLocalBinds); only |
| 6 | +//! top-level functions get polymorphic schemes (see lib.rs). |
| 7 | + |
| 8 | +use std::collections::HashMap; |
| 9 | + |
| 10 | +use tilc_diag::Diagnostic; |
| 11 | +use tilc_hir::body::*; |
| 12 | +use tilc_hir::{DefId, DefKind, TypeBody, TypeRef}; |
| 13 | +use tilc_span::{FileId, Span, TextRange}; |
| 14 | + |
| 15 | +use crate::codes; |
| 16 | +use crate::env::{Env, VarMode, VarScope, WellKnown}; |
| 17 | +use crate::ty::{Constraint, InferCtx, Printer, Ty, UnifyError}; |
| 18 | + |
| 19 | +/// A constraint to solve after the body is inferred. |
| 20 | +#[derive(Clone, Debug)] |
| 21 | +pub struct Wanted { |
| 22 | + pub constraint: Constraint, |
| 23 | + pub span: Span, |
| 24 | + /// The expression whose evidence this provides (a reference to a |
| 25 | + /// constrained function, or an operator). |
| 26 | + pub site: Option<ExprId>, |
| 27 | +} |
| 28 | + |
| 29 | +/// Types computed for one body (zonked at the end). |
| 30 | +#[derive(Debug, Default)] |
| 31 | +pub struct BodyTypes { |
| 32 | + pub exprs: Vec<Ty>, |
| 33 | + pub pats: Vec<Ty>, |
| 34 | + pub locals: Vec<Ty>, |
| 35 | +} |
| 36 | + |
| 37 | +pub struct FnInfer<'a, 'h> { |
| 38 | + pub env: &'a mut Env<'h>, |
| 39 | + pub ctx: &'a mut InferCtx, |
| 40 | + pub body: &'h Body, |
| 41 | + pub file: FileId, |
| 42 | + pub diags: &'a mut Vec<Diagnostic>, |
| 43 | + /// Monomorphic types of the functions inferred together (one SCC). |
| 44 | + pub mono: &'a HashMap<DefId, Ty>, |
| 45 | + /// Type variables named in annotations: signature variables (rigid |
| 46 | + /// when checking a signature) and, for new names, flexible ones. |
| 47 | + pub tyvars: VarScope, |
| 48 | + pub types: BodyTypes, |
| 49 | + pub wanted: Vec<Wanted>, |
| 50 | +} |
| 51 | + |
| 52 | +impl<'a, 'h> FnInfer<'a, 'h> { |
| 53 | + pub fn new( |
| 54 | + env: &'a mut Env<'h>, |
| 55 | + ctx: &'a mut InferCtx, |
| 56 | + body: &'h Body, |
| 57 | + file: FileId, |
| 58 | + diags: &'a mut Vec<Diagnostic>, |
| 59 | + mono: &'a HashMap<DefId, Ty>, |
| 60 | + tyvars: VarScope, |
| 61 | + ) -> Self { |
| 62 | + let types = BodyTypes { |
| 63 | + exprs: vec![Ty::Error; body.exprs.len()], |
| 64 | + pats: vec![Ty::Error; body.pats.len()], |
| 65 | + locals: vec![Ty::Error; body.locals.len()], |
| 66 | + }; |
| 67 | + FnInfer { |
| 68 | + env, |
| 69 | + ctx, |
| 70 | + body, |
| 71 | + file, |
| 72 | + diags, |
| 73 | + mono, |
| 74 | + tyvars, |
| 75 | + types, |
| 76 | + wanted: Vec::new(), |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + fn wk(&self) -> WellKnown { |
| 81 | + self.env.wk |
| 82 | + } |
| 83 | + |
| 84 | + fn span(&self, range: TextRange) -> Span { |
| 85 | + Span { |
| 86 | + file: self.file, |
| 87 | + range, |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + fn printer(&self) -> Printer<'_> { |
| 92 | + Printer { |
| 93 | + hir: self.env.hir, |
| 94 | + ctx: Some(self.ctx), |
| 95 | + gen_names: &[], |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + fn show(&self, ty: &Ty) -> String { |
| 100 | + self.printer().ty(ty) |
| 101 | + } |
| 102 | + |
| 103 | + pub fn lower_annotation(&mut self, tref: &TypeRef) -> Ty { |
| 104 | + let file = self.file; |
| 105 | + let mut scope = std::mem::replace(&mut self.tyvars, VarScope::new(VarMode::Flexible)); |
| 106 | + // New names in a body annotation are flexible; signature names |
| 107 | + // already in the scope keep their meaning. |
| 108 | + scope.mode = VarMode::Flexible; |
| 109 | + let ty = self |
| 110 | + .env |
| 111 | + .lower_ty(tref, file, &mut scope, Some(self.ctx), self.diags); |
| 112 | + self.tyvars = scope; |
| 113 | + ty |
| 114 | + } |
| 115 | + |
| 116 | + // ---- unification with reporting --------------------------------------- |
| 117 | + |
| 118 | + /// Require `actual` to fit `expected` at `range`. A `Never` value fits |
| 119 | + /// anywhere (it never produces a value); this is a coercion at checking |
| 120 | + /// sites only, not part of unification. |
| 121 | + pub fn coerce(&mut self, actual: &Ty, expected: &Ty, range: TextRange) { |
| 122 | + if self.is_never(actual) { |
| 123 | + return; |
| 124 | + } |
| 125 | + self.unify_at(expected, actual, range); |
| 126 | + } |
| 127 | + |
| 128 | + fn is_never(&self, ty: &Ty) -> bool { |
| 129 | + matches!(self.ctx.shallow(ty), Ty::Con(d, _) if Some(d) == self.wk().never) |
| 130 | + } |
| 131 | + |
| 132 | + /// Unify, reporting "expected `expected`, found `actual`". |
| 133 | + pub fn unify_at(&mut self, expected: &Ty, actual: &Ty, range: TextRange) { |
| 134 | + if let Err(e) = self.ctx.unify(expected, actual) { |
| 135 | + let (exp, act) = (self.show(expected), self.show(actual)); |
| 136 | + let span = self.span(range); |
| 137 | + let d = match e { |
| 138 | + UnifyError::Mismatch => Diagnostic::error( |
| 139 | + codes::TYPE_MISMATCH, |
| 140 | + format!("type mismatch: expected `{exp}`, found `{act}`"), |
| 141 | + span, |
| 142 | + ) |
| 143 | + .with_primary_label(format!("this has type `{act}`")), |
| 144 | + UnifyError::Occurs => Diagnostic::error( |
| 145 | + codes::INFINITE_TYPE, |
| 146 | + format!("this would need an infinite type: `{exp}` contains itself in `{act}`"), |
| 147 | + span, |
| 148 | + ), |
| 149 | + }; |
| 150 | + self.diags.push(d); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + fn error(&mut self, code: &'static str, message: impl Into<String>, range: TextRange) { |
| 155 | + let span = self.span(range); |
| 156 | + self.diags.push(Diagnostic::error(code, message, span)); |
| 157 | + } |
| 158 | + |
| 159 | + // ---- expressions ----------------------------------------------------- |
| 160 | + |
| 161 | + fn set(&mut self, e: ExprId, ty: Ty) -> Ty { |
| 162 | + self.types.exprs[e.index()] = ty.clone(); |
| 163 | + ty |
| 164 | + } |
| 165 | + |
| 166 | + /// Check `e` against `expected`. The expectation is pushed into |
| 167 | + /// lambdas (so callback parameters are known) and into block tails and |
| 168 | + /// branches (so a mismatch is reported at the offending expression). |
| 169 | + pub fn check_expr(&mut self, e: ExprId, expected: &Ty) { |
| 170 | + match &self.body.exprs[e] { |
| 171 | + Expr::Lambda { params, ret, body } => { |
| 172 | + if let Ty::Fn(eparams, eret, _) = self.ctx.shallow(expected) |
| 173 | + && eparams.len() == params.len() |
| 174 | + { |
| 175 | + let ty = self.lambda(params, ret.as_ref(), *body, Some((&eparams, &eret))); |
| 176 | + self.set(e, ty); |
| 177 | + return; |
| 178 | + } |
| 179 | + } |
| 180 | + Expr::Block { |
| 181 | + stmts, |
| 182 | + tail: Some(tail), |
| 183 | + } => { |
| 184 | + self.stmts(stmts); |
| 185 | + self.check_expr(*tail, expected); |
| 186 | + self.set(e, expected.clone()); |
| 187 | + return; |
| 188 | + } |
| 189 | + Expr::If { |
| 190 | + cond, |
| 191 | + then_branch, |
| 192 | + else_branch: Some(else_branch), |
| 193 | + } => { |
| 194 | + let bool_ty = WellKnown::con(self.wk().bool, vec![]); |
| 195 | + self.check_expr(*cond, &bool_ty); |
| 196 | + self.check_expr(*then_branch, expected); |
| 197 | + self.check_expr(*else_branch, expected); |
| 198 | + self.set(e, expected.clone()); |
| 199 | + return; |
| 200 | + } |
| 201 | + Expr::Match { scrutinee, arms } => { |
| 202 | + self.match_arms(*scrutinee, arms, expected); |
| 203 | + self.set(e, expected.clone()); |
| 204 | + return; |
| 205 | + } |
| 206 | + _ => {} |
| 207 | + } |
| 208 | + let actual = self.infer_expr(e); |
| 209 | + let range = self.body.expr_span(e); |
| 210 | + self.coerce(&actual, expected, range); |
| 211 | + } |
| 212 | + |
| 213 | + pub fn infer_expr(&mut self, e: ExprId) -> Ty { |
| 214 | + let range = self.body.expr_span(e); |
| 215 | + let wk = self.wk(); |
| 216 | + let ty = match &self.body.exprs[e] { |
| 217 | + Expr::Missing => Ty::Error, |
| 218 | + Expr::Lit(Lit::Int(_)) => WellKnown::con(wk.int, vec![]), |
| 219 | + Expr::Lit(Lit::Float(_)) => WellKnown::con(wk.float, vec![]), |
| 220 | + Expr::Lit(Lit::String(_)) => WellKnown::con(wk.string, vec![]), |
| 221 | + Expr::Local(l) => self.types.locals[l.index()].clone(), |
| 222 | + Expr::Def(def) => self.instantiate_def(*def, Some(e), range), |
| 223 | + Expr::Call { |
| 224 | + callee, |
| 225 | + args, |
| 226 | + spread, |
| 227 | + } => self.call(*callee, args, *spread, range), |
| 228 | + Expr::Field { base, name } => self.field(*base, name, range), |
| 229 | + Expr::TupleIndex { base, index } => { |
| 230 | + let base_ty = self.infer_expr(*base); |
| 231 | + match self.ctx.shallow(&base_ty) { |
| 232 | + Ty::Tuple(elems) if (*index as usize) < elems.len() => { |
| 233 | + elems[*index as usize].clone() |
| 234 | + } |
| 235 | + Ty::Tuple(elems) => { |
| 236 | + self.error( |
| 237 | + codes::UNKNOWN_FIELD, |
| 238 | + format!( |
| 239 | + "this tuple has {} elements; there is no `.{index}`", |
| 240 | + elems.len() |
| 241 | + ), |
| 242 | + range, |
| 243 | + ); |
| 244 | + Ty::Error |
| 245 | + } |
| 246 | + Ty::Error => Ty::Error, |
| 247 | + Ty::Var(_) => { |
| 248 | + self.error( |
| 249 | + codes::ANNOTATION_NEEDED, |
| 250 | + "the type of this tuple must be known here; add a type annotation", |
| 251 | + range, |
| 252 | + ); |
| 253 | + Ty::Error |
| 254 | + } |
| 255 | + other => { |
| 256 | + let shown = self.show(&other); |
| 257 | + self.error( |
| 258 | + codes::UNKNOWN_FIELD, |
| 259 | + format!("`.{index}` needs a tuple, but this is `{shown}`"), |
| 260 | + range, |
| 261 | + ); |
| 262 | + Ty::Error |
| 263 | + } |
| 264 | + } |
| 265 | + } |
| 266 | + Expr::Lambda { params, ret, body } => self.lambda(params, ret.as_ref(), *body, None), |
| 267 | + Expr::Block { stmts, tail } => { |
| 268 | + self.stmts(stmts); |
| 269 | + match tail { |
| 270 | + Some(t) => self.infer_expr(*t), |
| 271 | + None => Ty::unit(), |
| 272 | + } |
| 273 | + } |
| 274 | + Expr::If { |
| 275 | + cond, |
| 276 | + then_branch, |
| 277 | + else_branch, |
| 278 | + } => { |
| 279 | + let bool_ty = WellKnown::con(wk.bool, vec![]); |
| 280 | + self.check_expr(*cond, &bool_ty); |
| 281 | + match else_branch { |
| 282 | + Some(else_branch) => { |
| 283 | + let result = self.ctx.fresh(); |
| 284 | + self.check_expr(*then_branch, &result); |
| 285 | + self.check_expr(*else_branch, &result); |
| 286 | + result |
| 287 | + } |
| 288 | + None => { |
| 289 | + self.check_expr(*then_branch, &Ty::unit()); |
| 290 | + Ty::unit() |
| 291 | + } |
| 292 | + } |
| 293 | + } |
| 294 | + Expr::Match { scrutinee, arms } => { |
| 295 | + let result = self.ctx.fresh(); |
| 296 | + self.match_arms(*scrutinee, arms, &result); |
| 297 | + result |
| 298 | + } |
| 299 | + Expr::Binary { op, lhs, rhs } => self.binary(e, *op, *lhs, *rhs, range), |
| 300 | + Expr::Unary { op, expr } => match op { |
| 301 | + UnOp::Not => { |
| 302 | + let bool_ty = WellKnown::con(wk.bool, vec![]); |
| 303 | + self.check_expr(*expr, &bool_ty); |
| 304 | + bool_ty |
| 305 | + } |
| 306 | + UnOp::Neg => { |
| 307 | + let t = self.infer_expr(*expr); |
| 308 | + self.want(wk.num, &t, range, Some(e)); |
| 309 | + t |
| 310 | + } |
| 311 | + }, |
| 312 | + Expr::Tuple(elems) => Ty::Tuple(elems.iter().map(|x| self.infer_expr(*x)).collect()), |
| 313 | + Expr::List { elems, tail } => { |
| 314 | + let elem = self.ctx.fresh(); |
| 315 | + for x in elems { |
| 316 | + self.check_expr(*x, &elem); |
| 317 | + } |
| 318 | + let list = WellKnown::con(wk.list, vec![elem]); |
| 319 | + if let Some(t) = tail { |
| 320 | + self.check_expr(*t, &list); |
| 321 | + } |
| 322 | + list |
| 323 | + } |
| 324 | + Expr::Handle { body, clauses } => self.handle(*body, clauses), |
| 325 | + Expr::Html { holes } => { |
| 326 | + for h in holes { |
| 327 | + self.infer_expr(*h); |
| 328 | + } |
| 329 | + Ty::Error // typed in M8 |
| 330 | + } |
| 331 | + }; |
| 332 | + self.set(e, ty) |
| 333 | + } |
| 334 | + |
| 335 | + fn stmts(&mut self, stmts: &[Stmt]) { |
| 336 | + for stmt in stmts { |
| 337 | + match stmt { |
| 338 | + Stmt::Let { pat, ty, init } => { |
| 339 | + let expected = match ty { |
| 340 | + Some(t) => { |
| 341 | + let ann = self.lower_annotation(t); |
| 342 | + self.check_expr(*init, &ann); |
| 343 | + ann |
| 344 | + } |
| 345 | + None => self.infer_expr(*init), |
| 346 | + }; |
| 347 | + self.check_pat(*pat, &expected); |
| 348 | + } |
| 349 | + Stmt::Expr(e) => { |
| 350 | + self.infer_expr(*e); |
| 351 | + } |
| 352 | + } |
| 353 | + } |
| 354 | + } |
| 355 | + |
| 356 | + fn match_arms(&mut self, scrutinee: ExprId, arms: &[MatchArm], result: &Ty) { |
| 357 | + let scrut_ty = self.infer_expr(scrutinee); |
| 358 | + let bool_ty = WellKnown::con(self.wk().bool, vec![]); |
| 359 | + for arm in arms { |
| 360 | + self.check_pat(arm.pat, &scrut_ty); |
| 361 | + if let Some(g) = arm.guard { |
| 362 | + self.check_expr(g, &bool_ty); |
| 363 | + } |
| 364 | + self.check_expr(arm.body, result); |
| 365 | + } |
| 366 | + } |
| 367 | + |
| 368 | + fn want(&mut self, trait_: Option<DefId>, ty: &Ty, range: TextRange, site: Option<ExprId>) { |
| 369 | + if let Some(trait_) = trait_ { |
| 370 | + let span = self.span(range); |
| 371 | + self.wanted.push(Wanted { |
| 372 | + constraint: Constraint { |
| 373 | + trait_, |
| 374 | + ty: ty.clone(), |
| 375 | + }, |
| 376 | + span, |
| 377 | + site, |
| 378 | + }); |
| 379 | + } |
| 380 | + } |
| 381 | + |
| 382 | + /// The type of a reference to a definition, instantiating its scheme. |
| 383 | + pub fn instantiate_def(&mut self, def: DefId, site: Option<ExprId>, range: TextRange) -> Ty { |
| 384 | + if let Some(mono) = self.mono.get(&def) { |
| 385 | + return mono.clone(); |
| 386 | + } |
| 387 | + let Some(scheme) = self.env.schemes.get(&def).cloned() else { |
| 388 | + return Ty::Error; // its own signature failed to check |
| 389 | + }; |
| 390 | + let (ty, constraints) = self.ctx.instantiate(&scheme); |
| 391 | + for c in constraints { |
| 392 | + let span = self.span(range); |
| 393 | + self.wanted.push(Wanted { |
| 394 | + constraint: c, |
| 395 | + span, |
| 396 | + site, |
| 397 | + }); |
| 398 | + } |
| 399 | + ty |
| 400 | + } |
| 401 | + |
| 402 | + /// Parameter names a named callee accepts as labels. |
| 403 | + fn param_labels(&self, callee: ExprId) -> Option<(Vec<Option<String>>, bool)> { |
| 404 | + let Expr::Def(def) = self.body.exprs[callee] else { |
| 405 | + return None; |
| 406 | + }; |
| 407 | + match &self.env.hir.def(def).kind { |
| 408 | + DefKind::Ctor(c) => Some((c.fields.iter().map(|f| f.label.clone()).collect(), true)), |
| 409 | + DefKind::Fn(f) => Some(( |
| 410 | + f.sig.params.iter().map(|p| Some(p.name.clone())).collect(), |
| 411 | + false, |
| 412 | + )), |
| 413 | + DefKind::Op(o) => Some(( |
| 414 | + o.sig.params.iter().map(|p| Some(p.name.clone())).collect(), |
| 415 | + false, |
| 416 | + )), |
| 417 | + _ => None, |
| 418 | + } |
| 419 | + } |
| 420 | + |
| 421 | + /// Order arguments by position, resolving labels. Returns one slot per |
| 422 | + /// parameter (`None` = not given), or `None` after reporting an error. |
| 423 | + fn order_args( |
| 424 | + &mut self, |
| 425 | + callee: ExprId, |
| 426 | + args: &[Arg], |
| 427 | + range: TextRange, |
| 428 | + ) -> Option<Vec<Option<ExprId>>> { |
| 429 | + if args.iter().all(|a| a.label.is_none()) { |
| 430 | + return Some(args.iter().map(|a| Some(a.expr)).collect()); |
| 431 | + } |
| 432 | + let Some((labels, _)) = self.param_labels(callee) else { |
| 433 | + self.error( |
| 434 | + codes::BAD_LABEL, |
| 435 | + "labelled arguments need a named function or constructor", |
| 436 | + range, |
| 437 | + ); |
| 438 | + return None; |
| 439 | + }; |
| 440 | + let mut slots: Vec<Option<ExprId>> = vec![None; labels.len()]; |
| 441 | + let mut next_positional = 0; |
| 442 | + for arg in args { |
| 443 | + let index = match &arg.label { |
| 444 | + None => { |
| 445 | + let i = next_positional; |
| 446 | + next_positional += 1; |
| 447 | + i |
| 448 | + } |
| 449 | + Some(label) => match labels |
| 450 | + .iter() |
| 451 | + .position(|l| l.as_deref() == Some(label.as_str())) |
| 452 | + { |
| 453 | + Some(i) => i, |
| 454 | + None => { |
| 455 | + self.error( |
| 456 | + codes::BAD_LABEL, |
| 457 | + format!("there is no parameter or field named `{label}`"), |
| 458 | + self.body.expr_span(arg.expr), |
| 459 | + ); |
| 460 | + return None; |
| 461 | + } |
| 462 | + }, |
| 463 | + }; |
| 464 | + match slots.get_mut(index) { |
| 465 | + Some(slot @ None) => *slot = Some(arg.expr), |
| 466 | + Some(Some(_)) => { |
| 467 | + self.error( |
| 468 | + codes::BAD_LABEL, |
| 469 | + "this argument is given twice", |
| 470 | + self.body.expr_span(arg.expr), |
| 471 | + ); |
| 472 | + return None; |
| 473 | + } |
| 474 | + None => { |
| 475 | + self.error( |
| 476 | + codes::ARITY, |
| 477 | + format!("too many arguments: expected {}", labels.len()), |
| 478 | + range, |
| 479 | + ); |
| 480 | + return None; |
| 481 | + } |
| 482 | + } |
| 483 | + } |
| 484 | + Some(slots) |
| 485 | + } |
| 486 | + |
| 487 | + fn call( |
| 488 | + &mut self, |
| 489 | + callee: ExprId, |
| 490 | + args: &[Arg], |
| 491 | + spread: Option<ExprId>, |
| 492 | + range: TextRange, |
| 493 | + ) -> Ty { |
| 494 | + let callee_ty = self.infer_expr(callee); |
| 495 | + let Some(slots) = self.order_args(callee, args, range) else { |
| 496 | + for a in args { |
| 497 | + self.infer_expr(a.expr); |
| 498 | + } |
| 499 | + return Ty::Error; |
| 500 | + }; |
| 501 | + let (params, ret) = match self.ctx.shallow(&callee_ty) { |
| 502 | + Ty::Fn(params, ret, _) => (params, *ret), |
| 503 | + Ty::Var(_) => { |
| 504 | + let params: Vec<Ty> = slots.iter().map(|_| self.ctx.fresh()).collect(); |
| 505 | + let ret = self.ctx.fresh(); |
| 506 | + let f = Ty::func(params.clone(), ret.clone()); |
| 507 | + self.unify_at(&callee_ty, &f, self.body.expr_span(callee)); |
| 508 | + (params, ret) |
| 509 | + } |
| 510 | + Ty::Error => { |
| 511 | + slots.iter().flatten().for_each(|a| { |
| 512 | + self.infer_expr(*a); |
| 513 | + }); |
| 514 | + return Ty::Error; |
| 515 | + } |
| 516 | + other => { |
| 517 | + let shown = self.show(&other); |
| 518 | + self.error( |
| 519 | + codes::NOT_A_FUNCTION, |
| 520 | + format!("this is not a function; it has type `{shown}`"), |
| 521 | + self.body.expr_span(callee), |
| 522 | + ); |
| 523 | + slots.iter().flatten().for_each(|a| { |
| 524 | + self.infer_expr(*a); |
| 525 | + }); |
| 526 | + return Ty::Error; |
| 527 | + } |
| 528 | + }; |
| 529 | + if let Some(base) = spread { |
| 530 | + // Record update: `Ctor(..base, field: value)`. |
| 531 | + let is_ctor = self.param_labels(callee).is_some_and(|(_, ctor)| ctor); |
| 532 | + if !is_ctor || args.iter().any(|a| a.label.is_none()) { |
| 533 | + self.error( |
| 534 | + codes::BAD_LABEL, |
| 535 | + "`..base` updates a record: call its constructor with labelled fields only", |
| 536 | + range, |
| 537 | + ); |
| 538 | + } |
| 539 | + self.check_expr(base, &ret); |
| 540 | + } else if slots.len() != params.len() || slots.iter().any(Option::is_none) { |
| 541 | + let given = slots.iter().flatten().count(); |
| 542 | + self.error( |
| 543 | + codes::ARITY, |
| 544 | + format!( |
| 545 | + "this function takes {} argument{}, but {given} {} given", |
| 546 | + params.len(), |
| 547 | + plural(params.len()), |
| 548 | + if given == 1 { "was" } else { "were" } |
| 549 | + ), |
| 550 | + range, |
| 551 | + ); |
| 552 | + } |
| 553 | + for (slot, param) in slots.iter().zip(¶ms) { |
| 554 | + if let Some(arg) = slot { |
| 555 | + self.check_expr(*arg, param); |
| 556 | + } |
| 557 | + } |
| 558 | + for extra in slots.iter().skip(params.len()).flatten() { |
| 559 | + self.infer_expr(*extra); |
| 560 | + } |
| 561 | + ret |
| 562 | + } |
| 563 | + |
| 564 | + /// `record.field`: the base's type must be known and have a single |
| 565 | + /// constructor with that labelled field. |
| 566 | + fn field(&mut self, base: ExprId, name: &str, range: TextRange) -> Ty { |
| 567 | + let base_ty = self.infer_expr(base); |
| 568 | + let base_ty = self.ctx.shallow(&base_ty); |
| 569 | + let (def, args) = match &base_ty { |
| 570 | + Ty::Error => return Ty::Error, |
| 571 | + Ty::Var(_) => { |
| 572 | + self.error( |
| 573 | + codes::ANNOTATION_NEEDED, |
| 574 | + format!("the type of this value must be known to access `.{name}`; add a type annotation"), |
| 575 | + range, |
| 576 | + ); |
| 577 | + return Ty::Error; |
| 578 | + } |
| 579 | + Ty::Con(def, args) => (*def, args.clone()), |
| 580 | + other => { |
| 581 | + let shown = self.show(other); |
| 582 | + self.error( |
| 583 | + codes::UNKNOWN_FIELD, |
| 584 | + format!("`{shown}` has no fields"), |
| 585 | + range, |
| 586 | + ); |
| 587 | + return Ty::Error; |
| 588 | + } |
| 589 | + }; |
| 590 | + let hir = self.env.hir; |
| 591 | + let type_name = &hir.def(def).name; |
| 592 | + let ctors = match &hir.def(def).kind { |
| 593 | + DefKind::Type(t) => match &t.body { |
| 594 | + TypeBody::Adt(ctors) => ctors.clone(), |
| 595 | + _ => Vec::new(), |
| 596 | + }, |
| 597 | + _ => Vec::new(), |
| 598 | + }; |
| 599 | + let [ctor] = ctors.as_slice() else { |
| 600 | + let msg = if ctors.is_empty() { |
| 601 | + format!("`{type_name}` has no fields") |
| 602 | + } else { |
| 603 | + format!("`{type_name}` has several constructors; use `match` to read `{name}`") |
| 604 | + }; |
| 605 | + self.error(codes::UNKNOWN_FIELD, msg, range); |
| 606 | + return Ty::Error; |
| 607 | + }; |
| 608 | + let DefKind::Ctor(c) = &hir.def(*ctor).kind else { |
| 609 | + return Ty::Error; |
| 610 | + }; |
| 611 | + let Some(index) = c |
| 612 | + .fields |
| 613 | + .iter() |
| 614 | + .position(|f| f.label.as_deref() == Some(name)) |
| 615 | + else { |
| 616 | + self.error( |
| 617 | + codes::UNKNOWN_FIELD, |
| 618 | + format!("`{type_name}` has no field named `{name}`"), |
| 619 | + range, |
| 620 | + ); |
| 621 | + return Ty::Error; |
| 622 | + }; |
| 623 | + match self.env.schemes.get(ctor).map(|s| s.ty.subst_gen(&args)) { |
| 624 | + Some(Ty::Fn(fields, _, _)) => fields[index].clone(), |
| 625 | + _ => Ty::Error, |
| 626 | + } |
| 627 | + } |
| 628 | + |
| 629 | + fn lambda( |
| 630 | + &mut self, |
| 631 | + params: &[(PatId, Option<TypeRef>)], |
| 632 | + ret: Option<&TypeRef>, |
| 633 | + body: ExprId, |
| 634 | + expected: Option<(&[Ty], &Ty)>, |
| 635 | + ) -> Ty { |
| 636 | + let mut param_tys = Vec::new(); |
| 637 | + for (i, (pat, ann)) in params.iter().enumerate() { |
| 638 | + let ty = match (ann, expected) { |
| 639 | + (Some(t), Some((eps, _))) => { |
| 640 | + let ann = self.lower_annotation(t); |
| 641 | + self.unify_at(&eps[i], &ann, self.body.pat_span(*pat)); |
| 642 | + ann |
| 643 | + } |
| 644 | + (Some(t), None) => self.lower_annotation(t), |
| 645 | + (None, Some((eps, _))) => eps[i].clone(), |
| 646 | + (None, None) => self.ctx.fresh(), |
| 647 | + }; |
| 648 | + self.check_pat(*pat, &ty); |
| 649 | + param_tys.push(ty); |
| 650 | + } |
| 651 | + let ret_ty = match (ret, expected) { |
| 652 | + (Some(t), Some((_, eret))) => { |
| 653 | + let ann = self.lower_annotation(t); |
| 654 | + self.unify_at(eret, &ann, self.body.expr_span(body)); |
| 655 | + ann |
| 656 | + } |
| 657 | + (Some(t), None) => self.lower_annotation(t), |
| 658 | + (None, Some((_, eret))) => eret.clone(), |
| 659 | + (None, None) => self.ctx.fresh(), |
| 660 | + }; |
| 661 | + self.check_expr(body, &ret_ty); |
| 662 | + Ty::func(param_tys, ret_ty) |
| 663 | + } |
| 664 | + |
| 665 | + fn binary(&mut self, e: ExprId, op: BinOp, lhs: ExprId, rhs: ExprId, range: TextRange) -> Ty { |
| 666 | + let wk = self.wk(); |
| 667 | + let bool_ty = WellKnown::con(wk.bool, vec![]); |
| 668 | + match op { |
| 669 | + BinOp::And | BinOp::Or => { |
| 670 | + self.check_expr(lhs, &bool_ty); |
| 671 | + self.check_expr(rhs, &bool_ty); |
| 672 | + bool_ty |
| 673 | + } |
| 674 | + BinOp::Concat => { |
| 675 | + let string = WellKnown::con(wk.string, vec![]); |
| 676 | + self.check_expr(lhs, &string); |
| 677 | + self.check_expr(rhs, &string); |
| 678 | + string |
| 679 | + } |
| 680 | + BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => { |
| 681 | + let t = self.infer_expr(lhs); |
| 682 | + self.check_expr(rhs, &t); |
| 683 | + let trait_ = if matches!(op, BinOp::Eq | BinOp::Ne) { |
| 684 | + wk.eq |
| 685 | + } else { |
| 686 | + wk.ord |
| 687 | + }; |
| 688 | + self.want(trait_, &t, range, Some(e)); |
| 689 | + bool_ty |
| 690 | + } |
| 691 | + BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Rem => { |
| 692 | + let t = self.infer_expr(lhs); |
| 693 | + self.check_expr(rhs, &t); |
| 694 | + self.want(wk.num, &t, range, Some(e)); |
| 695 | + t |
| 696 | + } |
| 697 | + } |
| 698 | + } |
| 699 | + |
| 700 | + /// Handlers are typed structurally in M2; effect rows (what the body |
| 701 | + /// may perform, what the handler removes) arrive in M3. |
| 702 | + fn handle(&mut self, body: ExprId, clauses: &[HandlerClause]) -> Ty { |
| 703 | + let body_ty = self.infer_expr(body); |
| 704 | + let result = self.ctx.fresh(); |
| 705 | + let has_return = clauses.iter().any(|c| c.is_return); |
| 706 | + if !has_return { |
| 707 | + self.coerce(&body_ty, &result, self.body.expr_span(body)); |
| 708 | + } |
| 709 | + for clause in clauses { |
| 710 | + if clause.is_return { |
| 711 | + match clause.params.as_slice() { |
| 712 | + [p] => self.check_pat(*p, &body_ty), |
| 713 | + _ => self.error( |
| 714 | + codes::ARITY, |
| 715 | + "`return` takes exactly one parameter: the body's value", |
| 716 | + clause.span, |
| 717 | + ), |
| 718 | + } |
| 719 | + } else if let Some(op) = clause.op { |
| 720 | + let op_ty = self.instantiate_def(op, None, clause.span); |
| 721 | + match self.ctx.shallow(&op_ty) { |
| 722 | + Ty::Fn(params, op_ret, _) => { |
| 723 | + if params.len() != clause.params.len() { |
| 724 | + self.error( |
| 725 | + codes::ARITY, |
| 726 | + format!( |
| 727 | + "this operation takes {} parameter{}", |
| 728 | + params.len(), |
| 729 | + plural(params.len()) |
| 730 | + ), |
| 731 | + clause.span, |
| 732 | + ); |
| 733 | + } |
| 734 | + for (p, t) in clause.params.iter().zip(¶ms) { |
| 735 | + self.check_pat(*p, t); |
| 736 | + } |
| 737 | + if let Some(resume) = clause.resume { |
| 738 | + self.types.locals[resume.index()] = |
| 739 | + Ty::func(vec![*op_ret], result.clone()); |
| 740 | + } |
| 741 | + } |
| 742 | + _ => { |
| 743 | + for p in &clause.params { |
| 744 | + let t = self.ctx.fresh(); |
| 745 | + self.check_pat(*p, &t); |
| 746 | + } |
| 747 | + } |
| 748 | + } |
| 749 | + } |
| 750 | + self.check_expr(clause.body, &result); |
| 751 | + } |
| 752 | + result |
| 753 | + } |
| 754 | + |
| 755 | + // ---- patterns -------------------------------------------------------- |
| 756 | + |
| 757 | + pub fn check_pat(&mut self, p: PatId, expected: &Ty) { |
| 758 | + self.types.pats[p.index()] = expected.clone(); |
| 759 | + let range = self.body.pat_span(p); |
| 760 | + let wk = self.wk(); |
| 761 | + match &self.body.pats[p] { |
| 762 | + Pat::Missing | Pat::Wild => {} |
| 763 | + Pat::Bind(local) => self.types.locals[local.index()] = expected.clone(), |
| 764 | + Pat::Lit { lit, .. } => { |
| 765 | + let t = match lit { |
| 766 | + Lit::Int(_) => WellKnown::con(wk.int, vec![]), |
| 767 | + Lit::Float(_) => WellKnown::con(wk.float, vec![]), |
| 768 | + Lit::String(_) => WellKnown::con(wk.string, vec![]), |
| 769 | + }; |
| 770 | + self.unify_at(expected, &t, range); |
| 771 | + } |
| 772 | + Pat::Ctor { def, args, rest } => self.ctor_pat(*def, args, *rest, expected, range), |
| 773 | + Pat::Tuple(elems) => { |
| 774 | + let tys: Vec<Ty> = elems.iter().map(|_| self.ctx.fresh()).collect(); |
| 775 | + self.unify_at(expected, &Ty::Tuple(tys.clone()), range); |
| 776 | + for (e, t) in elems.iter().zip(&tys) { |
| 777 | + self.check_pat(*e, t); |
| 778 | + } |
| 779 | + } |
| 780 | + Pat::List { elems, rest } => { |
| 781 | + let elem = self.ctx.fresh(); |
| 782 | + let list = WellKnown::con(wk.list, vec![elem.clone()]); |
| 783 | + self.unify_at(expected, &list, range); |
| 784 | + for e in elems { |
| 785 | + self.check_pat(*e, &elem); |
| 786 | + } |
| 787 | + if let Some(Some(local)) = rest { |
| 788 | + self.types.locals[local.index()] = list; |
| 789 | + } |
| 790 | + } |
| 791 | + Pat::Or(alts) => { |
| 792 | + for a in alts { |
| 793 | + self.check_pat(*a, expected); |
| 794 | + } |
| 795 | + } |
| 796 | + Pat::As { pat, local } => { |
| 797 | + self.check_pat(*pat, expected); |
| 798 | + self.types.locals[local.index()] = expected.clone(); |
| 799 | + } |
| 800 | + } |
| 801 | + } |
| 802 | + |
| 803 | + fn ctor_pat( |
| 804 | + &mut self, |
| 805 | + def: DefId, |
| 806 | + args: &[PatArg], |
| 807 | + rest: bool, |
| 808 | + expected: &Ty, |
| 809 | + range: TextRange, |
| 810 | + ) { |
| 811 | + let ty = self.instantiate_def(def, None, range); |
| 812 | + let (fields, result) = match self.ctx.shallow(&ty) { |
| 813 | + Ty::Fn(fields, result, _) => (fields, *result), |
| 814 | + other => (Vec::new(), other), |
| 815 | + }; |
| 816 | + self.unify_at(expected, &result, range); |
| 817 | + let labels: Vec<Option<String>> = match &self.env.hir.def(def).kind { |
| 818 | + DefKind::Ctor(c) => c.fields.iter().map(|f| f.label.clone()).collect(), |
| 819 | + _ => Vec::new(), |
| 820 | + }; |
| 821 | + let mut used = vec![false; fields.len()]; |
| 822 | + let mut next = 0; |
| 823 | + for arg in args { |
| 824 | + let index = match &arg.label { |
| 825 | + None => { |
| 826 | + next += 1; |
| 827 | + next - 1 |
| 828 | + } |
| 829 | + Some(l) => match labels.iter().position(|x| x.as_deref() == Some(l.as_str())) { |
| 830 | + Some(i) => i, |
| 831 | + None => { |
| 832 | + self.error( |
| 833 | + codes::BAD_LABEL, |
| 834 | + format!("`{}` has no field named `{l}`", self.env.hir.def(def).name), |
| 835 | + self.body.pat_span(arg.pat), |
| 836 | + ); |
| 837 | + let t = self.ctx.fresh(); |
| 838 | + self.check_pat(arg.pat, &t); |
| 839 | + continue; |
| 840 | + } |
| 841 | + }, |
| 842 | + }; |
| 843 | + match fields.get(index) { |
| 844 | + Some(t) if !used[index] => { |
| 845 | + used[index] = true; |
| 846 | + let t = t.clone(); |
| 847 | + self.check_pat(arg.pat, &t); |
| 848 | + } |
| 849 | + _ => { |
| 850 | + let t = self.ctx.fresh(); |
| 851 | + self.check_pat(arg.pat, &t); |
| 852 | + } |
| 853 | + } |
| 854 | + } |
| 855 | + let given = used.iter().filter(|u| **u).count(); |
| 856 | + if args.len() > fields.len() || (!rest && given < fields.len()) { |
| 857 | + let name = &self.env.hir.def(def).name; |
| 858 | + self.error( |
| 859 | + codes::ARITY, |
| 860 | + format!( |
| 861 | + "`{name}` has {} field{}, but the pattern gives {}{}", |
| 862 | + fields.len(), |
| 863 | + plural(fields.len()), |
| 864 | + args.len(), |
| 865 | + if rest { |
| 866 | + "" |
| 867 | + } else { |
| 868 | + "; use `..` to ignore the rest" |
| 869 | + } |
| 870 | + ), |
| 871 | + range, |
| 872 | + ); |
| 873 | + } |
| 874 | + } |
| 875 | +} |
| 876 | + |
| 877 | +pub fn plural(n: usize) -> &'static str { |
| 878 | + if n == 1 { "" } else { "s" } |
| 879 | +} |