From 566e8326a343598d2ae8d2cb7a1c11a0c8b14c9e Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 16:05:03 +0300 Subject: [PATCH] read -NAME as the negation of NAME The reader took -INFINITY as one symbol, and the leading dash was then mangled like any other: _INFINITY. -1 was always a number, so a name gets the same reading. Fixes #63. --- reader.scm | 9 +++++++++ tests/codegen.scm | 2 ++ tests/reader.scm | 9 +++++++++ 3 files changed, 20 insertions(+) diff --git a/reader.scm b/reader.scm index 566fd10..d1dd55f 100644 --- a/reader.scm +++ b/reader.scm @@ -179,8 +179,17 @@ (cond ((string=? s ".") dot-token) ((string->number s) => identity) + ((negated-name? s) (list '- (string->symbol (substring s 1)))) (else (string->symbol s)))) +;;; -INFINITY is (- INFINITY), as -1 is minus one. No name begins with +;;; a dash, and an operator that does goes on with a non-letter: -> -- +(define (negated-name? s) + (and (> (string-length s) 1) + (char=? #\- (string-ref s 0)) + (let ((c (string-ref s 1))) + (or (char-alphabetic? c) (char=? c #\_))))) + ;;; #-dispatch: booleans, characters, vectors, block/datum comments, ;;; feature expressions (define (read-hash port) diff --git a/tests/codegen.scm b/tests/codegen.scm index 6155234..476ae95 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -735,6 +735,8 @@ compiles." (test-assert "an expression is walked and parenthesised" (emits? "(define K (/ (cast 255 float) (cast 60 float)))" "#define K ((float)255 / (float)60)")) + (test-assert "and a negated name" + (emits? "(define LOWEST -INFINITY)" "#define LOWEST (-INFINITY)")) (test-assert "so is a negative literal" (emits? "(define NEG -1)" "#define NEG (-1)")) (test-assert "a function-like one is converted too" diff --git a/tests/reader.scm b/tests/reader.scm index 7367b48..23627f7 100644 --- a/tests/reader.scm +++ b/tests/reader.scm @@ -38,6 +38,15 @@ ;; a `.'-prefixed symbol is an ordinary symbol, not dot-access (reader-test '((.field obj)) "(.field obj)") + ;; a leading `-' on a name is negation, the way it is on a number: + ;; no name is spelled with one, and -INFINITY otherwise mangled into + ;; _INFINITY. The operators that start with one are left alone + (reader-test '((- INFINITY)) "-INFINITY") + (reader-test '((var best double (- INFINITY))) "(var best double -INFINITY)") + (reader-test '((- _x)) "-_x") + (reader-test '(-1 -1.5) "-1 -1.5") + (reader-test '(- -> ->> -- -=) "- -> ->> -- -=") + ;; `;' comments are preserved as (comment "...") forms (reader-test '((comment " hi")) "; hi") (reader-test '((comment ";; Prototypes")) ";;; Prototypes")