Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions conformance/cases/04-expressions/list_rest_exhaustive.pud
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// spec: 4.4
fn classify(xs: List<Int>) -> 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
4 changes: 1 addition & 3 deletions src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down
35 changes: 27 additions & 8 deletions src/elab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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);
Expand Down
44 changes: 18 additions & 26 deletions src/exhaust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -173,25 +183,12 @@ fn specialize(row: &[P], c: &Ctor, n: usize) -> Option<Vec<P>> {
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)
Expand Down Expand Up @@ -228,13 +225,8 @@ fn useful(prog: &Program, m: &[Vec<P>], q: &[P], tys: &[Ty], depth: u32) -> Opti
let column: Vec<&P> = m.iter().filter_map(|r| r.first()).collect();
let used: Vec<Ctor> = 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);
Expand All @@ -255,7 +247,7 @@ fn useful(prog: &Program, m: &[Vec<P>], q: &[P], tys: &[Ty], depth: u32) -> Opti
let d: Vec<Vec<P>> = 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])
Expand Down
1 change: 1 addition & 0 deletions src/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ fn float_impls(s: &mut String, n: &str) {
let _ = writeln!(s, " pub fn pow(self, e: F32) -> F32 {{ __cast<Float, F32>(__fmath(0, self, e)) }}");
let _ = writeln!(s, " pub fn to_float(self) -> Float {{ self }}");
let _ = writeln!(s, " pub fn to_bits(self) -> U32 {{ __reinterpret<F32, U32>(self) }}");
let _ = writeln!(s, " pub fn from_bits(b: U32) -> F32 {{ __reinterpret<U32, F32>(b) }}");
}
for m in IntTy::all() {
let mn = m.name();
Expand Down
8 changes: 8 additions & 0 deletions src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading