|
| 1 | +;;; VeloxVM Unit Tests - begin tail-position semantics (R5RS 4.2.3 / 3.5) |
| 2 | +;;; |
| 3 | +;;; Regression for the begin tail-flag bug in core/expr-primitives.c: begin |
| 4 | +;;; used to mark ALL of its sub-expressions as tail calls, not just the |
| 5 | +;;; last. A non-last recursive call inside a begin was therefore wrongly |
| 6 | +;;; tail-folded (its frame reused) and never actually recursed, so the |
| 7 | +;;; expressions after it ran far too few times. Only the FINAL expression |
| 8 | +;;; of a begin is in tail position; the leading ones run for effect. |
| 9 | +;;; |
| 10 | +;;; Depths are kept small so the genuine (non-tail) recursion fits the |
| 11 | +;;; VM context stack; the point is correctness, not depth. |
| 12 | + |
| 13 | +(include "../unit-test-framework.scm") |
| 14 | + |
| 15 | +(test-suite "begin: only the last expression is in tail position") |
| 16 | + |
| 17 | +;; In (begin (recurse) (bump!)) the recursion must run to completion, so |
| 18 | +;; bump! fires once per level on the way back up. Before the fix the |
| 19 | +;; recursive call was tail-folded and bump! fired exactly once. |
| 20 | +(define counter (make-vector 1 0)) |
| 21 | +(define (descend n) |
| 22 | + (when (> n 0) |
| 23 | + (begin (descend (- n 1)) ; non-tail |
| 24 | + (vector-set! counter 0 (+ 1 (vector-ref counter 0)))))) ; tail |
| 25 | +(descend 12) |
| 26 | +(assert-equal 12 (vector-ref counter 0) |
| 27 | + "leading recursive call in begin runs to completion") |
| 28 | + |
| 29 | +;; Three expressions: the first is a non-tail recursive call, the middle |
| 30 | +;; and last run for effect. Each level adds 2, so g(10) yields 20. |
| 31 | +(define c2 (make-vector 1 0)) |
| 32 | +(define (g n) |
| 33 | + (when (> n 0) |
| 34 | + (begin (g (- n 1)) |
| 35 | + (vector-set! c2 0 (+ 1 (vector-ref c2 0))) |
| 36 | + (vector-set! c2 0 (+ 1 (vector-ref c2 0)))))) |
| 37 | +(g 10) |
| 38 | +(assert-equal 20 (vector-ref c2 0) |
| 39 | + "all leading expressions of a begin run, not just the last") |
| 40 | + |
| 41 | +;; Tail recursion through begin's LAST expression must still fold (no |
| 42 | +;; overflow at depth far beyond the context stack). |
| 43 | +(define (countdown n) |
| 44 | + (when (> n 0) (begin 1 (countdown (- n 1))))) |
| 45 | +(countdown 200000) |
| 46 | +(assert-true #t "tail call in begin's last expression still folds (no overflow)") |
| 47 | + |
| 48 | +(test-summary) |
0 commit comments