| @@ -0,0 +1,435 @@ |
| 1 | +//! Exhaustiveness and redundancy of patterns (Maranget, "Warnings for |
| 2 | +//! pattern matching", JFP 2007): a row of patterns is *useful* against a |
| 3 | +//! matrix if some value matches it and no earlier row. A match is |
| 4 | +//! exhaustive iff a wildcard is not useful after all arms; the usefulness |
| 5 | +//! search also yields a witness (a missing pattern) for the message. |
| 6 | + |
| 7 | +use tilc_diag::Diagnostic; |
| 8 | +use tilc_hir::body::{Body, Expr, Lit, Pat, PatId, Stmt}; |
| 9 | +use tilc_hir::{DefId, DefKind, Hir, TypeBody}; |
| 10 | +use tilc_span::{FileId, Span}; |
| 11 | + |
| 12 | +use crate::codes; |
| 13 | +use crate::env::Env; |
| 14 | +use crate::ty::Ty; |
| 15 | + |
| 16 | +#[derive(Clone, PartialEq, Debug)] |
| 17 | +enum Ctor { |
| 18 | + Variant(DefId), |
| 19 | + Tuple(usize), |
| 20 | + /// A literal: one constructor of an infinite type. |
| 21 | + Lit(String), |
| 22 | +} |
| 23 | + |
| 24 | +#[derive(Clone, Debug)] |
| 25 | +enum DPat { |
| 26 | + Wild, |
| 27 | + Ctor(Ctor, Vec<DPat>), |
| 28 | + Or(Vec<DPat>), |
| 29 | +} |
| 30 | + |
| 31 | +/// A missing value, printed for the user. |
| 32 | +#[derive(Clone, Debug)] |
| 33 | +enum Witness { |
| 34 | + Wild, |
| 35 | + Ctor(Ctor, Vec<Witness>), |
| 36 | +} |
| 37 | + |
| 38 | +pub struct Checker<'a, 'h> { |
| 39 | + pub env: &'a Env<'h>, |
| 40 | + pub body: &'a Body, |
| 41 | + pub pat_types: &'a [Ty], |
| 42 | + pub file: FileId, |
| 43 | + nil: Option<DefId>, |
| 44 | + cons: Option<DefId>, |
| 45 | +} |
| 46 | + |
| 47 | +impl<'a, 'h> Checker<'a, 'h> { |
| 48 | + pub fn new(env: &'a Env<'h>, body: &'a Body, pat_types: &'a [Ty], file: FileId) -> Self { |
| 49 | + let values = |name: &str| { |
| 50 | + env.hir |
| 51 | + .prelude |
| 52 | + .and_then(|p| env.hir.exports[p.index()].values.get(name).copied()) |
| 53 | + }; |
| 54 | + Checker { |
| 55 | + env, |
| 56 | + body, |
| 57 | + pat_types, |
| 58 | + file, |
| 59 | + nil: values("Nil"), |
| 60 | + cons: values("Cons"), |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + fn hir(&self) -> &'h Hir { |
| 65 | + self.env.hir |
| 66 | + } |
| 67 | + |
| 68 | + /// Check every match and every irrefutable position in the body. |
| 69 | + pub fn check(&self, diags: &mut Vec<Diagnostic>) { |
| 70 | + for &p in &self.body.params { |
| 71 | + self.irrefutable(p, "function parameter", diags); |
| 72 | + } |
| 73 | + for (_, expr) in self.body.exprs.iter() { |
| 74 | + match expr { |
| 75 | + Expr::Match { scrutinee, arms } => self.check_match(*scrutinee, arms, diags), |
| 76 | + Expr::Block { stmts, .. } => { |
| 77 | + for s in stmts { |
| 78 | + if let Stmt::Let { pat, .. } = s { |
| 79 | + self.irrefutable(*pat, "`let`", diags); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + Expr::Lambda { params, .. } => { |
| 84 | + for (p, _) in params { |
| 85 | + self.irrefutable(*p, "parameter", diags); |
| 86 | + } |
| 87 | + } |
| 88 | + _ => {} |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + fn span(&self, p: PatId) -> Span { |
| 94 | + Span { |
| 95 | + file: self.file, |
| 96 | + range: self.body.pat_span(p), |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + fn ty_of(&self, p: PatId) -> &Ty { |
| 101 | + &self.pat_types[p.index()] |
| 102 | + } |
| 103 | + |
| 104 | + fn irrefutable(&self, p: PatId, what: &str, diags: &mut Vec<Diagnostic>) { |
| 105 | + if self.ty_of(p).contains_error() { |
| 106 | + return; |
| 107 | + } |
| 108 | + let row = vec![self.lower(p)]; |
| 109 | + if let Some(w) = self.useful(&[row], &[DPat::Wild], &[self.ty_of(p).clone()]) { |
| 110 | + diags.push( |
| 111 | + Diagnostic::error( |
| 112 | + codes::REFUTABLE, |
| 113 | + format!( |
| 114 | + "this {what} pattern does not match every value: `{}` is not covered", |
| 115 | + self.show(&w[0]) |
| 116 | + ), |
| 117 | + self.span(p), |
| 118 | + ) |
| 119 | + .with_note("use `match` to handle the other cases"), |
| 120 | + ); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + fn check_match( |
| 125 | + &self, |
| 126 | + scrutinee: tilc_hir::body::ExprId, |
| 127 | + arms: &[tilc_hir::body::MatchArm], |
| 128 | + diags: &mut Vec<Diagnostic>, |
| 129 | + ) { |
| 130 | + let Some(first) = arms.first() else { return }; |
| 131 | + let ty = self.ty_of(first.pat).clone(); |
| 132 | + if ty.contains_error() { |
| 133 | + return; |
| 134 | + } |
| 135 | + let mut rows: Vec<Vec<DPat>> = Vec::new(); |
| 136 | + for arm in arms { |
| 137 | + let row = vec![self.lower(arm.pat)]; |
| 138 | + if self |
| 139 | + .useful(&rows, &row, std::slice::from_ref(&ty)) |
| 140 | + .is_none() |
| 141 | + { |
| 142 | + diags.push(Diagnostic::warning( |
| 143 | + codes::UNREACHABLE, |
| 144 | + "unreachable pattern: earlier arms already match every value it matches", |
| 145 | + self.span(arm.pat), |
| 146 | + )); |
| 147 | + } |
| 148 | + // A guarded arm may not match, so it covers nothing for sure. |
| 149 | + if arm.guard.is_none() { |
| 150 | + rows.push(row); |
| 151 | + } |
| 152 | + } |
| 153 | + if let Some(w) = self.useful(&rows, &[DPat::Wild], &[ty]) { |
| 154 | + let scrutinee_span = Span { |
| 155 | + file: self.file, |
| 156 | + range: self.body.expr_span(scrutinee), |
| 157 | + }; |
| 158 | + let missing = self.show(&w[0]); |
| 159 | + diags.push( |
| 160 | + Diagnostic::error( |
| 161 | + codes::NON_EXHAUSTIVE, |
| 162 | + format!("non-exhaustive `match`: `{missing}` is not covered"), |
| 163 | + scrutinee_span, |
| 164 | + ) |
| 165 | + .with_note(format!( |
| 166 | + "add an arm for `{missing}`, or `_ ->` for the remaining cases" |
| 167 | + )), |
| 168 | + ); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + // ---- lowering HIR patterns ------------------------------------------- |
| 173 | + |
| 174 | + fn lower(&self, p: PatId) -> DPat { |
| 175 | + match &self.body.pats[p] { |
| 176 | + Pat::Missing | Pat::Wild | Pat::Bind(_) => DPat::Wild, |
| 177 | + Pat::As { pat, .. } => self.lower(*pat), |
| 178 | + Pat::Or(alts) => DPat::Or(alts.iter().map(|a| self.lower(*a)).collect()), |
| 179 | + Pat::Lit { lit, .. } => DPat::Ctor(Ctor::Lit(lit_key(lit)), Vec::new()), |
| 180 | + Pat::Tuple(elems) => DPat::Ctor( |
| 181 | + Ctor::Tuple(elems.len()), |
| 182 | + elems.iter().map(|e| self.lower(*e)).collect(), |
| 183 | + ), |
| 184 | + Pat::Ctor { def, args, .. } => { |
| 185 | + let DefKind::Ctor(c) = &self.hir().def(*def).kind else { |
| 186 | + return DPat::Wild; |
| 187 | + }; |
| 188 | + let mut fields = vec![DPat::Wild; c.fields.len()]; |
| 189 | + let mut next = 0; |
| 190 | + for arg in args { |
| 191 | + let index = match &arg.label { |
| 192 | + Some(l) => c |
| 193 | + .fields |
| 194 | + .iter() |
| 195 | + .position(|f| f.label.as_deref() == Some(l.as_str())), |
| 196 | + None => { |
| 197 | + next += 1; |
| 198 | + Some(next - 1) |
| 199 | + } |
| 200 | + }; |
| 201 | + if let Some(slot) = index.and_then(|i| fields.get_mut(i)) { |
| 202 | + *slot = self.lower(arg.pat); |
| 203 | + } |
| 204 | + } |
| 205 | + DPat::Ctor(Ctor::Variant(*def), fields) |
| 206 | + } |
| 207 | + Pat::List { elems, rest } => { |
| 208 | + let (Some(nil), Some(cons)) = (self.nil, self.cons) else { |
| 209 | + return DPat::Wild; |
| 210 | + }; |
| 211 | + let mut list = match rest { |
| 212 | + Some(_) => DPat::Wild, |
| 213 | + None => DPat::Ctor(Ctor::Variant(nil), Vec::new()), |
| 214 | + }; |
| 215 | + for e in elems.iter().rev() { |
| 216 | + list = DPat::Ctor(Ctor::Variant(cons), vec![self.lower(*e), list]); |
| 217 | + } |
| 218 | + list |
| 219 | + } |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + // ---- types of constructors ------------------------------------------- |
| 224 | + |
| 225 | + /// All constructors of `ty`, or `None` if it has infinitely many (or is |
| 226 | + /// unknown), in which case only a wildcard covers it. |
| 227 | + fn all_ctors(&self, ty: &Ty) -> Option<Vec<Ctor>> { |
| 228 | + match ty { |
| 229 | + Ty::Tuple(elems) => Some(vec![Ctor::Tuple(elems.len())]), |
| 230 | + Ty::Con(def, _) => match &self.hir().def(*def).kind { |
| 231 | + DefKind::Type(t) => match &t.body { |
| 232 | + TypeBody::Adt(ctors) => Some(ctors.iter().map(|c| Ctor::Variant(*c)).collect()), |
| 233 | + _ => None, |
| 234 | + }, |
| 235 | + _ => None, |
| 236 | + }, |
| 237 | + _ => None, |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + fn arity(&self, c: &Ctor) -> usize { |
| 242 | + match c { |
| 243 | + Ctor::Tuple(n) => *n, |
| 244 | + Ctor::Lit(_) => 0, |
| 245 | + Ctor::Variant(def) => match &self.hir().def(*def).kind { |
| 246 | + DefKind::Ctor(c) => c.fields.len(), |
| 247 | + _ => 0, |
| 248 | + }, |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + /// Types of a constructor's fields at type `ty`. |
| 253 | + fn field_tys(&self, c: &Ctor, ty: &Ty) -> Vec<Ty> { |
| 254 | + let n = self.arity(c); |
| 255 | + match (c, ty) { |
| 256 | + (Ctor::Tuple(_), Ty::Tuple(elems)) => elems.clone(), |
| 257 | + (Ctor::Variant(def), Ty::Con(_, args)) => { |
| 258 | + match self.env.schemes.get(def).map(|s| s.ty.subst_gen(args)) { |
| 259 | + Some(Ty::Fn(fields, _, _)) => fields, |
| 260 | + _ => vec![Ty::Error; n], |
| 261 | + } |
| 262 | + } |
| 263 | + _ => vec![Ty::Error; n], |
| 264 | + } |
| 265 | + } |
| 266 | + |
| 267 | + // ---- the usefulness algorithm ---------------------------------------- |
| 268 | + |
| 269 | + /// Rows with or-patterns in the first column expanded. |
| 270 | + fn expand(rows: &[Vec<DPat>]) -> Vec<Vec<DPat>> { |
| 271 | + let mut out = Vec::new(); |
| 272 | + for row in rows { |
| 273 | + match row.first() { |
| 274 | + Some(DPat::Or(alts)) => { |
| 275 | + let alt_rows: Vec<Vec<DPat>> = alts |
| 276 | + .iter() |
| 277 | + .map(|a| { |
| 278 | + std::iter::once(a.clone()) |
| 279 | + .chain(row[1..].iter().cloned()) |
| 280 | + .collect() |
| 281 | + }) |
| 282 | + .collect(); |
| 283 | + out.extend(Self::expand(&alt_rows)); |
| 284 | + } |
| 285 | + _ => out.push(row.clone()), |
| 286 | + } |
| 287 | + } |
| 288 | + out |
| 289 | + } |
| 290 | + |
| 291 | + fn specialize(&self, rows: &[Vec<DPat>], c: &Ctor) -> Vec<Vec<DPat>> { |
| 292 | + let arity = self.arity(c); |
| 293 | + rows.iter() |
| 294 | + .filter_map(|row| match &row[0] { |
| 295 | + DPat::Ctor(rc, args) if rc == c => { |
| 296 | + Some(args.iter().chain(&row[1..]).cloned().collect()) |
| 297 | + } |
| 298 | + DPat::Ctor(..) => None, |
| 299 | + DPat::Wild => Some( |
| 300 | + std::iter::repeat_n(DPat::Wild, arity) |
| 301 | + .chain(row[1..].iter().cloned()) |
| 302 | + .collect(), |
| 303 | + ), |
| 304 | + DPat::Or(_) => unreachable!("expanded"), |
| 305 | + }) |
| 306 | + .collect() |
| 307 | + } |
| 308 | + |
| 309 | + fn default_rows(rows: &[Vec<DPat>]) -> Vec<Vec<DPat>> { |
| 310 | + rows.iter() |
| 311 | + .filter(|r| matches!(r[0], DPat::Wild)) |
| 312 | + .map(|r| r[1..].to_vec()) |
| 313 | + .collect() |
| 314 | + } |
| 315 | + |
| 316 | + /// A witness that `v` matches a value no row of `rows` matches. |
| 317 | + fn useful(&self, rows: &[Vec<DPat>], v: &[DPat], tys: &[Ty]) -> Option<Vec<Witness>> { |
| 318 | + let Some(head) = v.first() else { |
| 319 | + return rows.is_empty().then(Vec::new); |
| 320 | + }; |
| 321 | + let rows = Self::expand(rows); |
| 322 | + let (ty, rest_tys) = (&tys[0], &tys[1..]); |
| 323 | + match head { |
| 324 | + DPat::Or(alts) => alts.iter().find_map(|alt| { |
| 325 | + let v2: Vec<DPat> = std::iter::once(alt.clone()) |
| 326 | + .chain(v[1..].iter().cloned()) |
| 327 | + .collect(); |
| 328 | + self.useful(&rows, &v2, tys) |
| 329 | + }), |
| 330 | + DPat::Ctor(c, args) => self.useful_ctor(&rows, c, args, &v[1..], ty, rest_tys), |
| 331 | + DPat::Wild => { |
| 332 | + let used: Vec<Ctor> = rows |
| 333 | + .iter() |
| 334 | + .filter_map(|r| match &r[0] { |
| 335 | + DPat::Ctor(c, _) => Some(c.clone()), |
| 336 | + _ => None, |
| 337 | + }) |
| 338 | + .collect(); |
| 339 | + match self.all_ctors(ty) { |
| 340 | + Some(all) if all.iter().all(|c| used.contains(c)) => all.iter().find_map(|c| { |
| 341 | + let wilds = vec![DPat::Wild; self.arity(c)]; |
| 342 | + self.useful_ctor(&rows, c, &wilds, &v[1..], ty, rest_tys) |
| 343 | + }), |
| 344 | + all => { |
| 345 | + let rest = self.useful(&Self::default_rows(&rows), &v[1..], rest_tys)?; |
| 346 | + let missing = all |
| 347 | + .and_then(|all| all.into_iter().find(|c| !used.contains(c))) |
| 348 | + .map_or(Witness::Wild, |c| { |
| 349 | + Witness::Ctor(c.clone(), vec![Witness::Wild; self.arity(&c)]) |
| 350 | + }); |
| 351 | + Some(std::iter::once(missing).chain(rest).collect()) |
| 352 | + } |
| 353 | + } |
| 354 | + } |
| 355 | + } |
| 356 | + } |
| 357 | + |
| 358 | + fn useful_ctor( |
| 359 | + &self, |
| 360 | + rows: &[Vec<DPat>], |
| 361 | + c: &Ctor, |
| 362 | + args: &[DPat], |
| 363 | + rest: &[DPat], |
| 364 | + ty: &Ty, |
| 365 | + rest_tys: &[Ty], |
| 366 | + ) -> Option<Vec<Witness>> { |
| 367 | + let field_tys = self.field_tys(c, ty); |
| 368 | + let tys: Vec<Ty> = field_tys |
| 369 | + .into_iter() |
| 370 | + .chain(rest_tys.iter().cloned()) |
| 371 | + .collect(); |
| 372 | + let v: Vec<DPat> = args.iter().chain(rest).cloned().collect(); |
| 373 | + let mut w = self.useful(&self.specialize(rows, c), &v, &tys)?; |
| 374 | + let fields: Vec<Witness> = w.drain(..self.arity(c)).collect(); |
| 375 | + Some( |
| 376 | + std::iter::once(Witness::Ctor(c.clone(), fields)) |
| 377 | + .chain(w) |
| 378 | + .collect(), |
| 379 | + ) |
| 380 | + } |
| 381 | + |
| 382 | + // ---- printing witnesses ---------------------------------------------- |
| 383 | + |
| 384 | + fn show(&self, w: &Witness) -> String { |
| 385 | + match w { |
| 386 | + Witness::Wild => "_".into(), |
| 387 | + Witness::Ctor(Ctor::Lit(l), _) => l.clone(), |
| 388 | + Witness::Ctor(Ctor::Tuple(_), fields) => { |
| 389 | + format!( |
| 390 | + "({})", |
| 391 | + fields |
| 392 | + .iter() |
| 393 | + .map(|f| self.show(f)) |
| 394 | + .collect::<Vec<_>>() |
| 395 | + .join(", ") |
| 396 | + ) |
| 397 | + } |
| 398 | + Witness::Ctor(Ctor::Variant(def), fields) => { |
| 399 | + if Some(*def) == self.nil { |
| 400 | + return "[]".into(); |
| 401 | + } |
| 402 | + if Some(*def) == self.cons { |
| 403 | + let head = self.show(&fields[0]); |
| 404 | + return match &fields[1] { |
| 405 | + Witness::Ctor(Ctor::Variant(t), _) if Some(*t) == self.nil => { |
| 406 | + format!("[{head}]") |
| 407 | + } |
| 408 | + _ => format!("[{head}, ..]"), |
| 409 | + }; |
| 410 | + } |
| 411 | + let name = &self.hir().def(*def).name; |
| 412 | + if fields.is_empty() { |
| 413 | + name.clone() |
| 414 | + } else { |
| 415 | + format!( |
| 416 | + "{name}({})", |
| 417 | + fields |
| 418 | + .iter() |
| 419 | + .map(|f| self.show(f)) |
| 420 | + .collect::<Vec<_>>() |
| 421 | + .join(", ") |
| 422 | + ) |
| 423 | + } |
| 424 | + } |
| 425 | + } |
| 426 | + } |
| 427 | +} |
| 428 | + |
| 429 | +fn lit_key(lit: &Lit) -> String { |
| 430 | + match lit { |
| 431 | + Lit::Int(i) => i.to_string(), |
| 432 | + Lit::Float(f) => f.to_string(), |
| 433 | + Lit::String(s) => format!("{s:?}"), |
| 434 | + } |
| 435 | +} |