hold operators to the operands they take

Past them an operator was written as it came: (/ a) as /a, (! a b) as
a ! b. (++ a b) steps each in turn, through a comma operator the writer
lacked: bare in a for header, and in parens wherever else, since bare
it would begin another declarator or argument.
This commit is contained in:
2026-10-16 15:26:49 +03:00
parent cf3363263e
commit 4f3de6b11b
3 changed files with 85 additions and 10 deletions

View File

@@ -294,15 +294,46 @@ forms, and what remains."
;; Drop comments so they will not generate additional comma
(else
(check-arity form)
(map walk-expr (remove comment-form? form)))))
(let ((form (remove comment-form? form)))
(if (and (memq (car form) '(++ --)) (pair? (cdr form)) (pair? (cddr form)))
;; (++ a b) steps each in turn: statements where it is one,
;; C's comma where it is a value
(cons '%comma (map (lambda (operand) (walk-expr (list (car form) operand)))
(cdr form)))
(map walk-expr form))))))
(define +comparisons+ '(< > <= >= == !=))
;;; The operands each operator takes, as (fewest . most), most #f for no
;;; limit. Past them an operator was written as it came: (/ a) as `/a',
;;; (! a b) as `a ! b', (< a b c) as C's own chain, which compares a
;;; boolean with c
(define +operator-arity+
`((,+comparisons+ 2 . 2)
((+= -= *= /= %= &= ^= |\|=| <<= >>=) 2 . 2)
((! ~ bit-not bitwise-not) 1 . 1)
((- + * & ++ --) 1 . #f)
((/ % << >> && |\|\|| ^ |\|| = bit-and bit-or bit-xor
bitwise-and bitwise-ior bitwise-xor)
2 . #f)))
(define (operator-arity head)
(find (lambda (entry) (memq head (car entry))) +operator-arity+))
;;; 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))))
(let ((entry (operator-arity (car form)))
(given (count (lambda (part) (not (comment-form? part))) (cdr form))))
(when entry
(let ((fewest (cadr entry))
(most (cddr entry)))
(unless (and (>= given fewest) (or (not most) (<= given most)))
(sex-error form
(if (eq? (car entry) +comparisons+)
"a comparison takes two operands; chain them with &&"
(string-append "takes "
(if (= fewest 1) "one operand" "two operands")
(if most "" " or more")))
(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: