read hex and binary literals

0x80 was not a number to string->number, so it became a symbol the
printer escaped as |0x80|, and #x was rejected outright. Both spellings
now read as the integer, which the C writes in decimal.

Fixes #47.
This commit is contained in:
2026-10-09 16:06:14 +03:00
parent cc0f7f91ec
commit f3d9c95daf
3 changed files with 44 additions and 3 deletions

View File

@@ -179,9 +179,27 @@
(cond
((string=? s ".") dot-token)
((string->number s) => identity)
((radix-number s) => identity)
((negated-name? s) (list '- (string->symbol (substring s 1))))
(else (string->symbol s))))
;;; 0xE0 and 0b101 are C's spelling of 224 and 5, and are read as those
;;; numbers: the C written from them says 224 and 5
(define (radix-number s)
(let* ((negative? (and (> (string-length s) 0) (char=? #\- (string-ref s 0))))
(digits (if negative? (substring s 1) s)))
(and (> (string-length digits) 2)
(char=? #\0 (string-ref digits 0))
(let ((radix (case (string-ref digits 1)
((#\x #\X) 16)
((#\b #\B) 2)
(else #f)))
(body (substring digits 2)))
(and radix
(not (memv (string-ref body 0) '(#\+ #\-)))
(let ((n (string->number body radix)))
(and (exact-integer? n) (if negative? (- n) n))))))))
;;; -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)
@@ -190,8 +208,8 @@
(let ((c (string-ref s 1)))
(or (char-alphabetic? c) (char=? c #\_)))))
;;; #-dispatch: booleans, characters, vectors, block/datum comments,
;;; feature expressions
;;; #-dispatch: booleans, characters, vectors, numbers in a radix,
;;; block/datum comments, feature expressions
(define (read-hash port)
(let ((c (get-ch port)))
(cond
@@ -200,6 +218,9 @@
((or (char=? c #\f) (char=? c #\F)) (read-bool port #f))
((char=? c #\\) (read-char-lit port))
((char=? c #\() (list->vector (read-list port close-paren)))
((memv c '(#\x #\X)) (read-radix port 16))
((memv c '(#\b #\B)) (read-radix port 2))
((memv c '(#\o #\O)) (read-radix port 8))
((char=? c #\|) (skip-block-comment port 1) (next-token port))
((char=? c #\;) (read-datum port) (next-token port)) ; datum comment
((char=? c #\+) (read-conditional port #t))
@@ -253,6 +274,14 @@
((datum-token? guarded) (next-token port))
(else guarded))))
;;; #x80, #b101, #o10
(define (read-radix port radix)
(let* ((digits (read-atom-string port))
(n (string->number digits radix)))
(if (exact-integer? n)
n
(error "Malformed number" digits))))
;;; #t / #true / #f / #false. `val' is the boolean; consume any
;;; trailing name characters and validate
(define (read-bool port val)