Skip to content

A read-only walk owns its list when a sum type puts an unboxed field where another constructor has a boxed one #1805

Closed

Description

@viridale

On Bend 2.0.38, a def that only reads a list of a sum type takes the list
(ctr_take) instead of borrowing it (term_peek) whenever two of the
type's constructors put an unboxed word (a Bool, say) and a boxed one at
the same field position. When the list is shared, every cell the walk
passes is then copied out and faded.

import Base

type Ev is Data:
  Hit{key: String, value: String}
  Flag{key: String, on: Bool}

def evs() -> List<&2, Ev>:
  [Hit{"a", "1"}, Flag{"b", True{}}, Hit{"c", "2"}]

# Only reads evs, so it should borrow them.
def hits(evs: List<&2, Ev>, n: Nat) -> Nat:
  match evs:
    case Nil{}: n
    case Hit{k, v} <> tail: hits(tail, 1n+n)
    case Flag{k, on} <> tail: hits(tail, n)

def main() -> IO(Unit):
  +xs = evs()
  a = hits(xs, 0n)
  IO.print(Nat.show(Nat.add(a, List.length(&2, Ev, xs))))

bend mixed.bend -o mixed.c gives hits:

u64 _sp_0 = ctr_take(e, _evs_0, 2, _fb_0);

With on: String in place of on: Bool it gives:

u64 _sp_0 = term_peek(e.mem, _evs_0);

Expected: term_peek in both, since hits stores and returns nothing it
reads.

Cause, as far as I can trace it in the compiler: when val_arms merges the
arms of an unboxed match, each out slot collects one borrow label per arm,
and a word that is not a box pushes "". Field 2 collects "evs…" from
Hit and "" from Flag, so the labels differ, and every non-empty one
goes into FL.own. val_own likewise adds a label for a borrowed word that
is not a box. A non-box word holds no reference, so neither should count.
Two changes make both versions emit term_peek:

  • in val_arms, push a label only for a slot whose kind in that arm is
    "box";
  • in val_own, look up the borrow label only when v.lay.ks[j] === "box".

On a parser that walks a list of such events once per option, the change
made parsing a large argv about 10% faster.

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