read a match scrutinee before a binder can shadow it

C has a declaration in scope from its own initializer, so in
(match (* e) ((neg (e)) ...)) the binding read the new, uninitialized e.
A binder named like a part of the scrutinee now has it held in a local.
This commit is contained in:
2026-10-16 13:53:49 +03:00
parent 6f7b28cfa5
commit 0451c6e957
3 changed files with 24 additions and 3 deletions

View File

@@ -959,16 +959,24 @@
(sex-error form "match wants a sum, and this is not one"
(or type 'unknown)))
(check-match form name variants arms)
(if (simple-path? scrutinee)
;; the scrutinee is read once per binding, so anything that could
;; read differently the second time is read into a local first --
;; a binder named like a part of it included, since C has a binder
;; in scope from its own initializer on
(if (and (simple-path? scrutinee)
(not (any (cut mentions? scrutinee <>) (match-binders arms))))
(walk-statement (match-switch name scrutinee variants arms) env)
;; the scrutinee is read once per binding, so anything that
;; could be read twice is read into a local first
(let ((held (aux-name! env make-match-name)))
(walk-statement
`(do (var ,held ,type ,scrutinee)
,(match-switch name held variants arms))
env)))))
(define (match-binders arms)
(append-map (lambda (arm)
(if (eq? (car arm) 'else) '() (delete '_ (second (car arm)))))
arms))
(define (make-match-name fn-name counter)
(string->symbol (string-append "ƛm" (number->string counter))))

View File

@@ -417,6 +417,9 @@ ahead of its pub forms."
(test-assert "a path scrutinee is not copied"
(not (emits? (sum-src "(match s ((circle (r)) (= out r)) (else (= out 0.0)))")
"ƛm0")))
(test-assert "unless a binder is named like a part of it"
(emits? (sum-src "(match s ((circle (s)) (= out s)) (else (= out 0.0)))")
"shape ƛm0 = s"))
(test-assert "a macro scrutinee is typed by what it expands to"
(emits? (string-append "(defmacro (the a) a)"
(sum-src "(match (the s) ((circle (r)) (= out r))"

View File

@@ -2,6 +2,7 @@
(output "3.14 12.00 0.00"
"held once: a 1"
"nested: -(2 + 3) = -5"
"size: 4"
"tagged only: 1"
"rows: 18 5")
(return 0)
@@ -45,6 +46,14 @@
((neg (e)) (printf "-") (show e))
((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")"))))
;;; A binder may take the name the scrutinee is spelled with, and a
;;; later binder still reads the scrutinee, not the earlier binder
(fn size ((e (* const expr))) int
(match (* e)
((lit (v)) (return 1))
((neg (e)) (return (+ 1 (size e))))
((add (e r)) (return (+ 1 (size e) (size r))))))
;;; No fields anywhere: the record is the tag alone, with no union
(sum light ((red ()) (green ())))
@@ -77,6 +86,7 @@
(printf "nested: ")
(show (& e))
(printf " = %g\n" (eval (& e)))
(printf "size: %d\n" (size (& e)))
(var l light (light/green))
(match l