From 06bbe4b97d89d3863cd7310ce780dfd7747ce4d4 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sat, 17 Oct 2026 17:35:48 +0300 Subject: [PATCH] refuse a malformed enumerator Anything in the list but a name or (name value) was taken apart as if it were the pair: (! 1 2) came out ! = 1. --- fmt-c-writer.scm | 10 ++++++++-- tests/codegen.scm | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index df7f69a8..a40977c3 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -574,8 +574,14 @@ forms, and what remains." ;;; 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)))) + (((? enumerator-name? name) expr) (list (atom-to-fmt-c name) (walk-expr expr))) + ((? enumerator-name?) (atom-to-fmt-c value)) + ;; anything else was taken apart as if it were the pair: (! 1 2) + ;; came out `! = 1' + (_ (sex-error value "an enumerator is a name, or (name value)" value)))) + +(define (enumerator-name? x) + (and (symbol? x) (not (operator-arity x)))) (define (walk-extern form) (match form diff --git a/tests/codegen.scm b/tests/codegen.scm index ad12e28f..5c216c68 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -246,6 +246,14 @@ "enum color m = red")) (test-assert "a malformed enum is rejected with its location" (reports? "(enum)" "codegen.sex:1:")) + ;; anything else in the list was the name its head was and the + ;; value its second element: (! 1 2) came out `! = 1' + (test-assert "an enumerator is a name, or a name and a value" + (reports? "(enum color (red (! 1 2)))" "an enumerator is a name, or (name value)")) + (test-assert "and an operator is no name" + (reports? "(enum color (red (! 1)))" "an enumerator is a name, or (name value)")) + (test-assert "nor a value with no name" + (reports? "(enum color (red 7))" "an enumerator is a name, or (name value)")) ;; c-type handed the declarator's name to c-enum as the enum tag, ;; so this emitted `enum m { up, down }' with no variable at all (test-assert "an anonymous enum keeps the variable"