diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a908a8..87b7db5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to Puddi are recorded here. The format follows [Keep a Chang ## [Unreleased] +### Added + +- `F32.from_bits` constructs a float from its 32-bit IEEE 754 representation. + +### Fixed + +- Integer literals too large for the compiler's integer representation report an error instead of wrapping. +- List pattern exhaustiveness accounts for the exact lengths covered by rest patterns. + ## [0.1.2] - 2026-11-21 ### Added diff --git a/conformance/cases/04-expressions/list_rest_exhaustive.pud b/conformance/cases/04-expressions/list_rest_exhaustive.pud new file mode 100644 index 0000000..c9944ed --- /dev/null +++ b/conformance/cases/04-expressions/list_rest_exhaustive.pud @@ -0,0 +1,19 @@ +// spec: 4.4 +fn classify(xs: List) -> Str { + match xs { + [] -> "empty" + [_, _] -> "pair" + [_, ..rest] -> "{rest.len()} more" + } +} + +fn main() { + print(classify([])) + print(classify([1])) + print(classify([1, 2])) + print(classify([1, 2, 3])) +} +//> empty +//> 0 more +//> pair +//> 2 more diff --git a/src/codegen.rs b/src/codegen.rs index 0d7dde4..37d1b94 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -1001,9 +1001,7 @@ impl<'a> Cg<'a> { } PatKind::List(ps, rest) => { let Ty::Adt(lid, largs) = &p.ty else { return }; - let fields = self.prog.struct_fields(*lid); - let len_i = fields.iter().position(|f| f.name == "len").unwrap_or(0); - let data_i = fields.iter().position(|f| f.name == "data").unwrap_or(1); + let (len_i, data_i) = self.prog.list_field_indices(*lid); let ln = self.tname(&p.ty); let elem = largs[0].clone(); let arr_ty = Ty::Array(Box::new(elem.clone())); diff --git a/src/elab.rs b/src/elab.rs index bf587d3..051cf9b 100644 --- a/src/elab.rs +++ b/src/elab.rs @@ -492,8 +492,14 @@ impl<'g, 'p> Elab<'g, 'p> { self.vars[*x as usize].0 = Some(t.clone()); true } - (Ty::Tuple(x), Ty::Tuple(y)) => x.len() == y.len() && x.clone().iter().zip(y.clone().iter()).all(|(p, q)| self.unify(p, q)), - (Ty::Adt(i, x), Ty::Adt(j, y)) => i == j && x.clone().iter().zip(y.clone().iter()).all(|(p, q)| self.unify(p, q)), + (Ty::Tuple(x), Ty::Tuple(y)) => { + let (x, y) = (x.clone(), y.clone()); + x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| self.unify(p, q)) + } + (Ty::Adt(i, x), Ty::Adt(j, y)) => { + let (i, j, x, y) = (*i, *j, x.clone(), y.clone()); + i == j && x.iter().zip(y.iter()).all(|(p, q)| self.unify(p, q)) + } (Ty::Array(x), Ty::Array(y)) => { let (x, y) = (x.clone(), y.clone()); self.unify(&x, &y) @@ -798,7 +804,13 @@ impl<'g, 'p> Elab<'g, 'p> { Some(t @ (Ty::Int(_) | Ty::Float(_))) => t, _ => self.fresh_kind(VarKind::Int), }; - mk(ExprKind::Lit(Lit::Int(*n as i128)), ty, span) + match i128::try_from(*n) { + Ok(v) => mk(ExprKind::Lit(Lit::Int(v)), ty, span), + Err(_) => { + self.err(span, "integer literal is too large"); + mk(ExprKind::Lit(Lit::Int(0)), ty, span) + } + } } ast::ExprKind::Float(f) => { let ty = match expect.map(|t| self.resolve(t)) { @@ -1049,8 +1061,7 @@ impl<'g, 'p> Elab<'g, 'p> { es.push(ie); } let n = es.len() as i128; - let fields = self.prog.struct_fields(list_id); - let len_idx = fields.iter().position(|f| f.name == "len").unwrap_or(0); + let (len_idx, _) = self.prog.list_field_indices(list_id); let mut vals = vec![ mk(ExprKind::Lit(Lit::Int(n)), INT, span), mk(ExprKind::ArrayLit(es), Ty::Array(Box::new(elem.clone())), span), @@ -1757,7 +1768,13 @@ impl<'g, 'p> Elab<'g, 'p> { Some(t @ (Ty::Int(_) | Ty::Float(_))) => t, _ => self.fresh_kind(VarKind::Int), }; - return mk(ExprKind::Lit(Lit::Int(-(n as i128))), ty, span); + match i128::try_from(n).ok().and_then(|v| v.checked_neg()) { + Some(v) => return mk(ExprKind::Lit(Lit::Int(v)), ty, span), + None => { + self.err(span, "integer literal is too large"); + return mk(ExprKind::Lit(Lit::Int(0)), ty, span); + } + } } if let ast::ExprKind::Float(f) = inner.kind { let ty = match expect.map(|t| self.resolve(t)) { @@ -2363,8 +2380,10 @@ impl<'g, 'p> Elab<'g, 'p> { }); let lv = self.local_expr(bl, span); let iv = self.local_expr(il, span); - let len = mk(ExprKind::Field(Box::new(lv.clone()), None, 0), int.clone(), span); - let data = mk(ExprKind::Field(Box::new(lv), None, 1), Ty::Array(Box::new(elem.clone())), span); + let list_id = self.prog.known_adt("List"); + let (len_idx, data_idx) = self.prog.list_field_indices(list_id); + let len = mk(ExprKind::Field(Box::new(lv.clone()), None, len_idx), int.clone(), span); + let data = mk(ExprKind::Field(Box::new(lv), None, data_idx), Ty::Array(Box::new(elem.clone())), span); let as_u32 = |e: Expr| mk(ExprKind::Cast(Box::new(e)), u32t.clone(), span); let cond = mk(ExprKind::Prim(PrimOp::Ge, u32t.clone(), vec![as_u32(iv.clone()), as_u32(len.clone())]), Ty::Bool, span); let oob = mk(ExprKind::Call(FnInst { fn_id: self.prog.known_fn("__list_oob"), targs: vec![] }, vec![iv.clone(), len]), Ty::Never, span); diff --git a/src/exhaust.rs b/src/exhaust.rs index ac0a709..cb5e92b 100644 --- a/src/exhaust.rs +++ b/src/exhaust.rs @@ -14,6 +14,16 @@ enum Ctor { ListAtLeast(usize), } +impl Ctor { + /// Whether a pattern with this constructor can match the candidate. + fn covers(&self, candidate: &Self) -> bool { + match (self, candidate) { + (Self::ListAtLeast(min), Self::ListExact(len) | Self::ListAtLeast(len)) => min <= len, + _ => self == candidate, + } + } +} + #[derive(Clone, Debug)] enum P { Wild, @@ -173,25 +183,12 @@ fn specialize(row: &[P], c: &Ctor, n: usize) -> Option> { let (head, rest) = row.split_first()?; let mut out = match head { P::Wild => vec![P::Wild; n], - P::C(k, args) => { - if k == c { - args.clone() - } else { - match (k, c) { - (Ctor::ListAtLeast(m), Ctor::ListExact(e)) if m <= e => { - let mut a = args.clone(); - a.extend(std::iter::repeat_n(P::Wild, e - m)); - a - } - (Ctor::ListAtLeast(m), Ctor::ListAtLeast(e)) if m <= e => { - let mut a = args.clone(); - a.extend(std::iter::repeat_n(P::Wild, e - m)); - a - } - _ => return None, - } - } + P::C(k, args) if k.covers(c) => { + let mut fields = args.clone(); + fields.resize(n, P::Wild); + fields } + P::C(..) => return None, }; out.extend(rest.iter().cloned()); Some(out) @@ -228,13 +225,8 @@ fn useful(prog: &Program, m: &[Vec

], q: &[P], tys: &[Ty], depth: u32) -> Opti let column: Vec<&P> = m.iter().filter_map(|r| r.first()).collect(); let used: Vec = column.iter().filter_map(|p| if let P::C(c, _) = p { Some(c.clone()) } else { None }).collect(); let all = all_ctors(prog, ty, &column); - let complete = match &all { - Some(all) => { - let is_list = all.iter().any(|c| matches!(c, Ctor::ListAtLeast(_))); - if is_list { !used.is_empty() } else { all.iter().all(|c| used.contains(c)) } - } - None => false, - }; + let covered = |c: &Ctor| used.iter().any(|pattern| pattern.covers(c)); + let complete = all.as_ref().is_some_and(|ctors| ctors.iter().all(covered)); if complete { for c in all.unwrap() { let n = arity(prog, ty, &c); @@ -255,7 +247,7 @@ fn useful(prog: &Program, m: &[Vec

], q: &[P], tys: &[Ty], depth: u32) -> Opti let d: Vec> = m.iter().filter(|r| matches!(r.first(), Some(P::Wild))).map(|r| r[1..].to_vec()).collect(); let w = useful(prog, &d, &q[1..], &tys[1..], depth + 1)?; let head = match &all { - Some(all) => match all.iter().find(|c| !used.contains(c)) { + Some(all) => match all.iter().find(|c| !covered(c)) { Some(c) => { let n = arity(prog, ty, c); W::C(c.clone(), ty.clone(), vec![W::Wild; n]) diff --git a/src/numeric.rs b/src/numeric.rs index 8b959fe..b3deadc 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -142,6 +142,7 @@ fn float_impls(s: &mut String, n: &str) { let _ = writeln!(s, " pub fn pow(self, e: F32) -> F32 {{ __cast(__fmath(0, self, e)) }}"); let _ = writeln!(s, " pub fn to_float(self) -> Float {{ self }}"); let _ = writeln!(s, " pub fn to_bits(self) -> U32 {{ __reinterpret(self) }}"); + let _ = writeln!(s, " pub fn from_bits(b: U32) -> F32 {{ __reinterpret(b) }}"); } for m in IntTy::all() { let mn = m.name(); diff --git a/src/program.rs b/src/program.rs index 32d7a8d..e1eca0c 100644 --- a/src/program.rs +++ b/src/program.rs @@ -893,6 +893,14 @@ impl Program { } } + /// Returns `(len_index, data_index)` for the `List` struct. + pub fn list_field_indices(&self, list_id: AdtId) -> (usize, usize) { + let fields = self.struct_fields(list_id); + let len_idx = fields.iter().position(|f| f.name == "len").unwrap_or(0); + let data_idx = fields.iter().position(|f| f.name == "data").unwrap_or(1); + (len_idx, data_idx) + } + /// Whether a trait can be used as `dyn Trait`. pub fn dyn_compatible(&self, tid: TraitId) -> Result<(), String> { for t in self.trait_closure(tid) {