; Fieldtest raw-buf comprehensive .2 (Axes 1+2+3 — Bool element width
; through a fill loop, then counted via a borrow helper).
;
; Task an LLM author is naturally given: "mark which of the numbers
; 0..N are even in a flag buffer, then count how many flags are set."
; A flat Bool RawBuf is the natural storage for a flag/bitset array.
;
; The prior field test only stored a single Bool at a literal index
; (rawbuf_3_sensor_pair). This drives the i1/i8 Bool packing edge
; through a (loop ...)/recur FILL of runtime length N (one RawBuf.set
; per slot, the stored value being a *computed* Bool — the result of
; `eq (i % 2) 0`), and reads the flags back through a `borrow` helper
; (`count_set`) that drives off RawBuf.size and accumulates an Int.
;
; This stresses:
;   - Bool stored/loaded across a loop, not a literal set — does the
;     i1/i8 round-trip hold when the value is computed, not a `true`
;     literal?
;   - A borrow-receiver helper over a Bool buffer (the #46 fix on the
;     Bool width).
;   - `RawBuf.get` of a Bool used directly as an `if` condition inside
;     the count loop.
;
; N = 6 -> flags for 0,1,2,3,4,5 -> even at 0,2,4 -> 3 set.
; Expected stdout: "3".

(module rbx_2_bool_sieve

  (fn mark_even
    (doc "Set slot i to (i is even) for i in 0..n. Linear own->own.")
    (type (fn-type (params (own (con RawBuf (con Bool))) (own (con Int))) (ret (own (con RawBuf (con Bool))))))
    (params buf n)
    (body
      (loop (b (con RawBuf (con Bool)) buf) (i (con Int) 0)
        (if (app ge i n)
            b
            (recur (app RawBuf.set b i (app eq (app % i 2) 0))
                   (app + i 1))))))

  (fn count_set
    (doc "Count the set flags, reading the Bool buffer through a borrow.")
    (type (fn-type (params (borrow (con RawBuf (con Bool)))) (ret (own (con Int)))))
    (params buf)
    (body
      (loop (acc (con Int) 0) (i (con Int) 0)
        (if (app ge i (app RawBuf.size buf))
            acc
            (recur (if (app RawBuf.get buf i) (app + acc 1) acc)
                   (app + i 1))))))

  (fn main
    (type (fn-type (params) (ret (own (con Unit))) (effects IO)))
    (params)
    (body
      (let buf (new RawBuf (con Bool) 6)
        (let buf (app mark_even buf 6)
          (app print (app count_set buf)))))))
