Skip to content

Silent wrong value: recursing through a Box payload bound from a &Enum match subject (sum over a Box list returns the head only) #1443

Closed

Description

@ehartford

Summary

Recursing through a Box payload bound by matching a reference to a recursive enum reads the wrong value — silent wrong code — or crashes.

Repro (origin/main 1c76062)

use std.box.Box

enum L:
    Cons(v: i64, next: Box[L])
    Nil

fn sum(l: &L) -> i64:
    match l:
        L.Cons(v, next) => v + sum(next.as_ref())
        L.Nil => 0

fn main:
    let l = L.Cons(1, Box.new(L.Cons(2, Box.new(L.Nil))))
    print(f"sum={sum(&l)}")

Prints sum=1; expected sum=3. The variant

enum Expr:
    Num(n: i64)
    Neg(e: Box[Expr])

fn eval(e: &Expr) -> i64:
    match e:
        Expr.Num(n) => n
        Expr.Neg(inner) => 0 - eval(inner.as_ref())

fn main:
    print(f"eval={eval(&Expr.Neg(Box.new(Expr.Num(5))))}")

prints nothing and exits 139. Matching the owned value and recursing with next.into_inner() gives the right answer, as does matching an owned value and calling next.as_ref() on the binding — the failure is the &L subject with a Box field binding (a D22 view projection through the Box).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions