From e9ee120383b8e370f8fee18642ddbf0341534fca Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 16 Oct 2026 15:26:31 +0300 Subject: [PATCH] refuse a comparison of other than two operands (< a b c) reached C as C's own chain, which compares a boolean with c. --- fmt-c-writer.scm | 12 +++++++++++- tests/codegen.scm | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 6511f6e5..00f337f8 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -283,7 +283,17 @@ forms, and what remains." (('default . body) (cons 'default (walk-case-body body))) ;; Drop comments so they will not generate additional comma - (else (map walk-expr (remove comment-form? form))))) + (else + (check-arity form) + (map walk-expr (remove comment-form? form))))) + +;;; Operands past what an operator takes were written as they came: +;;; (< a b c) as C's own chain, which compares a boolean with c +(define (check-arity form) + (when (and (memq (car form) '(< > <= >= == !=)) + (not (= (count (lambda (part) (not (comment-form? part))) (cdr form)) 2))) + (sex-error form "a comparison takes two operands; chain them with &&" + (car form)))) ;;; #(a b c) is a brace initializer. A `:' inside one ends a type and ;;; turns the whole thing into a C99 compound literal: diff --git a/tests/codegen.scm b/tests/codegen.scm index 5e9b4c1f..3e223499 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -706,6 +706,18 @@ (test-assert "and negation beside a binary operator" (emits? (in-fn "(var n int (+ (- a) b))") "-a + b"))) + ;; Operands past what an operator takes were written as they came: + ;; (< a b c) as C's own chain, which compares a boolean with c + (test-group "operator arity" + (test-assert "a comparison takes two operands" + (reports? (in-fn "(var x bool (< a b a))") "a comparison takes two operands")) + (test-assert "equality too" + (reports? (in-fn "(var x bool (== a b a))") "a comparison takes two operands")) + (test-assert "and not one" + (reports? (in-fn "(var x bool (>= a))") "a comparison takes two operands")) + (test-assert "two is a comparison" + (emits? (in-fn "(var x bool (<= a b))") "x = a <= b;"))) + ;; An array bound was taken only when it was an integer literal, so a ;; symbolic one fell into the type: `[int N]' came out `int N a[]'. (test-group "array bounds"