diff --git a/semen.scm b/semen.scm index 429f623..b1c8be0 100644 --- a/semen.scm +++ b/semen.scm @@ -955,16 +955,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)))) diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index 6dcc47a..d7bd86c 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -416,6 +416,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))" diff --git a/tests/sex-programs/sums.sex b/tests/sex-programs/sums.sex index 5eb49db..3ad2b1c 100644 --- a/tests/sex-programs/sums.sex +++ b/tests/sex-programs/sums.sex @@ -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