; Iter 18d.1 — `(reuse-as xs (term-ctor List Cons ...))` schema floor
; demo. The `(reuse-as ...)` wrapper is identity at codegen in 18d.1
; (the `body` is lowered, the `source` is dropped); 18d.2 will lower
; this as in-place rewrite under `--alloc=rc`.
;
; The fixture exercises:
;   - parser + printer round-trip for `Term::ReuseAs`
;   - typecheck of an all-explicit-mode fn whose body returns a
;     `(reuse-as <var> <ctor>)` form (body is allocating: Term::Ctor)
;   - linearity check: `xs` is consumed exactly once via reuse-as in
;     the Cons arm; the Nil arm doesn't consume `xs`. Merge across
;     arms is consistent.
;   - codegen under `--alloc=rc`: program prints `9`
;     (1+1 + 2+1 + 3+1 = 9), the same value the non-reuse-as
;     `map_inc` would print.
;
; Expected stdout:
;   9

(module reuse_as_demo

  (data List
    (doc "Monomorphic singly-linked Int list — boxed, recursive.")
    (ctor Nil)
    (ctor Cons (con Int) (con List)))

  (fn map_inc
    (doc "Increment each Int in xs. The Cons arm uses (reuse-as xs ...) — author asserts that the freshly-allocated Cons cell should reuse xs's slot. In 18d.1 codegen treats this as identity.")
    (type
      (fn-type
        (params (own (con List)))
        (ret (own (con List)))))
    (params xs)
    (body
      (match xs
        (case (pat-ctor Nil) (term-ctor List Nil))
        (case (pat-ctor Cons h t)
          (reuse-as xs
            (term-ctor List Cons (app + h 1) (app map_inc t)))))))

  (fn sum_list
    (doc "Consume xs, sum its elements.")
    (type
      (fn-type
        (params (own (con List)))
        (ret (own (con Int)))))
    (params xs)
    (body
      (match xs
        (case (pat-ctor Nil) 0)
        (case (pat-ctor Cons h t)
          (app + h (app sum_list t))))))

  (fn main
    (doc "Build [1,2,3]; map_inc → [2,3,4]; sum_list → 9. Print 9.")
    (type (fn-type (params) (ret (own (con Unit))) (effects IO)))
    (params)
    (body
      (let xs
        (term-ctor List Cons 1
          (term-ctor List Cons 2
            (term-ctor List Cons 3
              (term-ctor List Nil))))
        (app print (app sum_list (app map_inc xs)))))))
