convert enumerators written with a value

(wire-varint 0) is a pair, and both the writer and map-fields only
expected a name: the writer passed it out unconverted, and a macro
mapping over the enum was handed the pair.

Fixes #46.
This commit is contained in:
2026-10-09 15:59:16 +03:00
parent 816c1db9ed
commit c06845a80a
4 changed files with 26 additions and 4 deletions

View File

@@ -450,11 +450,17 @@ forms, and what remains."
(('enum (? symbol? name))
`(enum ,(atom-to-fmt-c name)))
(('enum (values ...))
`(enum ,(map atom-to-fmt-c values)))
`(enum ,(map walk-enumerator values)))
(('enum name (values ...))
`(enum ,(atom-to-fmt-c name) ,(map atom-to-fmt-c values)))
`(enum ,(atom-to-fmt-c name) ,(map walk-enumerator values)))
(else (sex-error form "malformed enum" form))))
;;; red -> red, (wire-varint 0) -> wire_varint = 0
(define (walk-enumerator value)
(match value
((name expr) (list (atom-to-fmt-c name) (walk-expr expr)))
(_ (atom-to-fmt-c value))))
(define (walk-extern form)
(match form
(('fn . _)

View File

@@ -200,6 +200,16 @@ compiles."
(emits? "(pub enum color (red green blue))" "enum color"))
(test-assert "with its values"
(emits? "(pub enum color (red green blue))" "red"))
;; A value made the enumerator a pair, which went out unconverted
(test-assert "explicit values"
(emits? "(pub enum wire ((wire-varint 0) (wire-fixed64 1)))"
"wire_varint = 0, wire_fixed64 = 1"))
(test-assert "a value is an expression"
(emits? "(enum wire ((wire-last (+ WIRE-BASE 1))))"
"wire_last = WIRE_BASE + 1"))
(test-assert "and an anonymous enum takes them too"
(emits? "(fn f () void (var e (enum ((up-one 1) down)) up-one))"
"up_one = 1, down"))
(test-assert "and a non-pub enum still is too"
(emits? "(enum color (red green blue))" "enum color"))
;; Naming an enum as a type, rather than defining it, had no

View File

@@ -139,6 +139,10 @@
(test "enum values are fields whose type is the enum"
'((red (enum t-color)) (green (enum t-color)) (blue (enum t-color)))
(map-fields 't-color (lambda (name type) (list name type))))
(add-enum 't-wire '(enum t-wire ((t-varint 0) (t-fixed64 1) t-bytes)))
(test "an enumerator with a value is still named by its name"
'(t-varint t-fixed64 t-bytes)
(map-fields 't-wire (lambda (name type) name)))
(test "a typedef has no fields to map"
#f
(map-fields 't-u8 (lambda (name type) name)))

View File

@@ -334,7 +334,8 @@
(else (equal? pattern type))))
;;; Map function to each field/value of a structure/union/enum
;;; For enums, field-type is the type of the enum (since C 23)
;;; For enums, field-type is the type of the enum (since C 23), and
;;; field-name the enumerator's name, (wire-varint 0) or not
;;; (map-fields type-name
;;; (lambda (field-name field-type) ...))
;;;
@@ -350,7 +351,8 @@
;; declared, since `enum some-typedef' is not a C type.
((enum)
(let ((type (list 'enum (cadr info))))
(map (lambda (value) (fn value type))
(map (lambda (value)
(fn (if (pair? value) (car value) value) type))
(caddr info))))
(else #f)))))