make a declaring case body a block

A case body shared the switch's scope, so two cases could not each
declare `bits', and a label could not be followed by a declaration
before C23; inference shared the scope too, and typed a later case's
read of an outer name as the earlier case's local.

Fixes #51.
This commit is contained in:
2026-10-09 17:23:42 +03:00
parent 52228e6fc6
commit 3e01fe41e8
4 changed files with 46 additions and 14 deletions

View File

@@ -53,6 +53,15 @@ compiles."
(let ((m (error-message source)))
(and m (string-contains m fragment) #t)))
(define (followed-by? source first then)
"Is FIRST in the C compiled from SOURCE, and the next thing past it,
whitespace aside, THEN?"
(let* ((c (silently (lambda () (sex->c source))))
(at (string-contains c first)))
(and at
(let ((next (string-skip c char-whitespace? (+ at (string-length first)))))
(and next (string-prefix? then (substring c next)))))))
(define (in-fn body)
(string-append "(fn f ((a int) (b int)) void " body ")"))
@@ -78,6 +87,22 @@ compiles."
;; c-switch handed its scrutinee straight to `cat', which only works
;; when it is an atom. Anything else was displayed as a raw
;; s-expression: `switch ((%. e type))'.
;; A case body shared the switch's scope, so two cases could not
;; declare one name, and a label could not be followed by a
;; declaration before C23. Only a body that declares needs a block
(test-group "case bodies"
(test-assert "are blocks"
(followed-by? (in-fn "(switch a (case 1 (var x int 1) (g x)))")
"case 1:" "{"))
(test-assert "so is a default"
(followed-by? (in-fn "(switch a (default (var x int 1) (g x)))")
"default:" "{"))
(test-assert "where they declare"
(followed-by? (in-fn "(switch a (case 1 (g a)))") "case 1:" "g(a)"))
(test-assert "and one already a block is not wrapped again"
(not (followed-by? (in-fn "(switch a (case 1 (do (var x int 1) (g x))))")
"{" "{"))))
(test-group "switch scrutinee"
(test-assert "member access"
(emits? "(struct s ((type int))) (fn f ((e (struct s))) void (switch (. e type) (case 1 (g))))"