Files
sex/reader.scm
alex-eg 52c73cd0ca read a quoted name as the name
'-fields read as (- fields), so (cat name '-fields) built name(- fields).
A quoted list keeps the rule: it is code a macro returns as often as not.
2026-10-19 18:26:12 +03:00

616 lines
24 KiB
Scheme

;;; Sex reader
;;;
;;; A hand-written tokenizer + recursive-descent parser that replaces
;;; CHICKEN's built-in `read'. We need our own reader because the
;;; features Sex requires cannot be expressed on top of `read':
;;; - [ ... ] array/pointer sugar, read as (¤ ...)
;;; - a leading `.' rewritten to the symbol `dot-access'
;;; - `;' comments preserved as (comment "...") forms, so they can be
;;; re-emitted into the generated C (keeping the source mapping)
;;; - #+ / #- feature expressions, which decide at read time what the
;;; compiler gets to see at all
;;; It also records the source location of every form it reads (see
;;; utils' form-source), so the C writer can emit #line directives.
(import
scheme
(scheme base) ; make-parameter
(chicken base)
(chicken condition)
(chicken irregex)
(chicken module)
(chicken pathname)
(chicken platform) ; software-version, machine-type
(only (chicken string) substring-index)
(only srfi-1 every any) ; srfi-1 also has an append-reverse
utils)
(export
read-from-file
read-raw-forms
current-features
platform-features
number-literal?
number-literal-value
number-literal-suffix
;; for the tests
parse-all)
;;; Sentinels for structural tokens
(define close-paren (list '%close-paren))
(define close-bracket (list '%close-bracket))
(define dot-token (list '%dot))
;;; Current source line. Tracked as characters are consumed
(define current-line (make-parameter 1))
(define (get-ch port)
(let ((c (read-char port)))
(when (and (char? c) (char=? c #\newline))
(current-line (+ 1 (current-line))))
c))
(define (peek port)
(peek-char port))
;;; Record where a form started and where it ended. Called with the
;;; line of the opening delimiter, sampled before it is consumed, once
;;; the form itself has been read -- so the current line is the one its
;;; closing delimiter sits on
(define (stamp form line)
(when (pair? form)
(set-form-source! form (current-source-file) line (current-line)))
form)
(define (delimiter? c)
(or (eof-object? c)
(char-whitespace? c)
(memv c '(#\( #\) #\[ #\] #\" #\; #\' #\` #\,))))
;;; Skip whitespace. `;' comments are NOT skipped here: they are read
;;; as (comment "...") forms by the tokenizer. Block comments (#| |#)
;;; and datum comments (#;) are discarded in the tokenizer's `#'
;;; dispatch, since `#' also introduces real data (#t, #f, #\c, #(...))
(define (skip-whitespace port)
(let ((c (peek port)))
(cond
((eof-object? c) #t)
((char-whitespace? c) (get-ch port) (skip-whitespace port))
(else #t))))
;;; A `;' comment, read as (comment "<rest of line>"). The leading `;'
;;; is consumed; the newline is left in the stream so line tracking and
;;; the surrounding parser see it normally
(define (read-comment port)
(get-ch port) ; consume the leading ;
(let loop ((chars (list)))
(let ((c (peek port)))
(if (or (eof-object? c) (char=? c #\newline))
(list 'comment (list->string (reverse chars)))
(begin (get-ch port)
(loop (cons c chars)))))))
;;; Read the next token: a datum, one of the structural sentinels
;;; (close-paren / close-bracket / dot-token), or the eof-object
(define (next-token port)
(skip-whitespace port)
(let ((c (peek port)))
(cond
((eof-object? c) c)
((char=? c #\()
(let ((line (current-line)))
(get-ch port)
(stamp (read-list port close-paren line) line)))
((char=? c #\[)
(let ((line (current-line)))
(get-ch port)
(stamp (cons '¤ (read-list port close-bracket line)) line)))
((char=? c #\)) (get-ch port) close-paren)
((char=? c #\]) (get-ch port) close-bracket)
((char=? c #\;)
(let ((line (current-line)))
(stamp (read-comment port) line)))
((char=? c #\") (read-string-lit port))
((char=? c #\') (get-ch port) (list 'quote (read-quoted port)))
((char=? c #\`) (get-ch port) (list 'quasiquote (read-datum port)))
((char=? c #\,)
(get-ch port)
(if (eqv? (peek port) #\@)
(begin (get-ch port) (list 'unquote-splicing (read-datum port)))
(list 'unquote (read-datum port))))
((char=? c #\#) (get-ch port) (read-hash port))
(else (read-atom port)))))
;;; Like next-token, but a full datum is required: the structural
;;; sentinels and eof are errors here (e.g. after a quote or `.')
(define (read-datum port)
(let ((tok (next-token port)))
(cond
((eof-object? tok) (error "Unexpected end of input"))
((eq? tok close-paren) (error "Unexpected )"))
((eq? tok close-bracket) (error "Unexpected ]"))
((eq? tok dot-token) (error "Unexpected ."))
(else tok))))
;;; A token that stands for a datum
(define (datum-token? tok)
(not (or (eof-object? tok)
(eq? tok close-paren)
(eq? tok close-bracket)
(eq? tok dot-token))))
;;; next-token, sans the comments
(define (next-code-token port)
(let loop ()
(let ((tok (next-token port)))
(if (comment-form? tok)
(loop)
tok))))
;;; Read list elements up to close-paren or close-bracket,
;;; honoring dotted-pair notation (a b . c)
(define (read-list port closer opened)
(let loop ((acc (list)))
(let ((tok (next-token port)))
(cond
((eof-object? tok)
(error (string-append
"Unexpected end of input inside a list opened on line "
(number->string opened))))
((eq? tok close-paren)
(if (eq? closer close-paren)
(reverse acc)
(error "Unmatched closing bracket")))
((eq? tok close-bracket)
(if (eq? closer close-bracket)
(reverse acc)
(error "Unmatched closing bracket")))
((eq? tok dot-token)
(if (null? acc)
;; Leading `.': the member/method access operator. It reads
;; as an ordinary `dot-access' symbol in first position.
(loop (cons 'dot-access acc))
;; Otherwise: ordinary dotted-pair notation (a b . c).
(let ((tail (read-datum port))
(end (next-token port)))
(unless (eq? end closer)
(error "Malformed dotted list"))
(append-reverse acc tail))))
(else (loop (cons tok acc)))))))
;;; Append the reversed list `rev' in front of `tail', producing a
;;; possibly-improper list (used for dotted pairs)
(define (append-reverse rev tail)
(if (null? rev)
tail
(append-reverse (cdr rev) (cons (car rev) tail))))
;;; A bare atom: symbol or number, or the dot token when it is exactly "."
(define (read-atom port)
(let loop ((chars (list)))
(let ((c (peek port)))
(if (delimiter? c)
(finish-atom (list->string (reverse chars)))
(begin (get-ch port) (loop (cons c chars)))))))
;;; ...except quoted, alone: '-fields is a name, as in (cat name '-fields).
;;; A quoted list is code a macro hands back as often as not, and keeps
;;; the rule
(define negating? (make-parameter #t))
(define (read-quoted port)
(if (memv (peek port) '(#\( #\[ #\' #\` #\, #\# #\" #\;))
(read-datum port)
(parameterize ((negating? #f)) (read-datum port))))
(define (finish-atom s)
(let ((digits (if (substring-index "_" s) (or (ungrouped s (or (c-radix s) 10)) s) s)))
;; 017 is 17 to Scheme and 15 to C: whoever reads the Sex and whoever
;; reads the C would each take it for something else
(when (irregex-match "-?0[0-9]+[uUlL]*" digits)
(error
"a leading 0 is octal to C; write the number without it, or #o for octal"
s))
(cond
((string=? s ".") dot-token)
((or (string->number digits) (radix-number digits))
=> (lambda (n) (c-number n s)))
((spelled-number digits s) => identity)
((negated-name? s) (list '- (string->symbol (substring s 1))))
(else (string->symbol s)))))
;;; 1_000_000, 0xFF_FF: `_' between two digits groups them, the way
;;; C23's ' does -- which in Sex is quote. S without them, or #f when a
;;; `_' stands anywhere else, where it is part of a name
(define (ungrouped s radix)
(let ((digit? (lambda (c) (string->number (string c) radix))))
(let loop ((cs (string->list s)) (previous #f) (acc (list)))
(cond ((null? cs) (list->string (reverse acc)))
((char=? (car cs) #\_)
(and previous (digit? previous) (pair? (cdr cs)) (digit? (cadr cs))
(loop (cdr cs) (car cs) acc)))
(else (loop (cdr cs) (car cs) (cons (car cs) acc)))))))
;;; Scheme reads numbers C has no literal for -- 1/2, #e1.5, 1e400,
;;; +nan.0, 1+2i -- and they reached C as written. An integer too wide
;;; for long long is unsigned to C, which says so only by a warning
;;; unless it is written with a `u'; so it is.
(define +llong-min+ (- (expt 2 63)))
(define +llong-max+ (- (expt 2 63) 1))
(define +ullong-max+ (- (expt 2 64) 1))
(define (c-number n s)
(cond ((exact-integer? n)
(cond ((> (abs n) +ullong-max+)
(error "too large for any C integer type" s))
((> n +llong-max+) (make-number-literal n "u" #f))
((< n +llong-min+) (list '- (make-number-literal (- n) "u" #f)))
(else n)))
((and (real? n) (inexact? n) (finite? n)) n)
(else (error "C has no literal for this number" s))))
;;; 1u, 10L, 1ULL, 1.5f, 0.1L, 0x1.8p3: a number with C's suffix, or a
;;; hex float, which the C is written with.
;;;
;;; 0b101u -> 5u in decimal, so C23's 0b never reaches C11
;;; 0.1f -> 0.1f in the digits written: through a double, 0.1f
;;; could round to another float, and 0.1L would
;;; lose all it has over one
;;; -1u -> (- 1u) which is what C reads it as too
(define-record-type <number-literal>
(make-number-literal value suffix digits)
number-literal?
(value number-literal-value)
(suffix number-literal-suffix)
(digits number-literal-digits))
(set-record-printer! <number-literal>
(lambda (literal port)
(display (or (number-literal-digits literal)
(number->string (number-literal-value literal)))
port)
(display (number-literal-suffix literal) port)))
(define suffixed-integer
(irregex "(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9]+)([uU](?:ll|LL|l|L)?|(?:ll|LL|l|L)[uU]?)"))
(define suffixed-float
(irregex "((?:[0-9]+\\.[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)([fFlL])"))
(define hex-float
(irregex "(0[xX]([0-9a-fA-F]*)\\.?([0-9a-fA-F]*)[pP]([+-]?[0-9]+))([fFlL]?)"))
(define (spelled-number digits s)
(let* ((negative? (and (> (string-length digits) 1) (char=? #\- (string-ref digits 0))))
(body (if negative? (substring digits 1) digits))
;; each spelling begins with a digit or a point, and few names do
(literal (and (> (string-length body) 0)
(or (char-numeric? (string-ref body 0))
(char=? #\. (string-ref body 0)))
(or (suffixed-integer-literal body s)
(suffixed-float-literal body s)
(hex-float-literal body s)))))
(and literal (if negative? (list '- literal) literal))))
(define (suffixed-integer-literal body s)
(let ((m (irregex-match suffixed-integer body)))
(and m
(let* ((digits (irregex-match-substring m 1))
(suffix (irregex-match-substring m 2))
(n (or (radix-number digits) (string->number digits)))
(widest (if (irregex-search "[uU]" suffix) +ullong-max+ +llong-max+)))
(when (> n widest)
(error "too large for its suffix" s))
(make-number-literal n suffix #f)))))
;;; 0x1.8p3 is 0x18 sixteenths times 2^3
(define (hex-float-literal body s)
(let ((m (irregex-match hex-float body)))
(and m
(let ((whole (irregex-match-substring m 2))
(fraction (irregex-match-substring m 3))
(exponent (string->number (irregex-match-substring m 4)))
(suffix (irregex-match-substring m 5)))
(and (> (+ (string-length whole) (string-length fraction)) 0)
(float-literal
(if (> (abs exponent) 20000) ; past any C type
(if (> exponent 0) +inf.0 0.)
(exact->inexact
(* (string->number (string-append whole fraction) 16)
(expt 2 (- exponent (* 4 (string-length fraction)))))))
suffix (irregex-match-substring m 1) s))))))
(define (suffixed-float-literal body s)
(let ((m (irregex-match suffixed-float body)))
(and m
(let ((digits (irregex-match-substring m 1)))
(float-literal (string->number digits) (irregex-match-substring m 2)
digits s)))))
(define (float-literal n suffix digits s)
(unless (in-range? n suffix)
(error "C has no literal for this number" s))
(make-number-literal n suffix digits))
;;; A float overflows where it would round past FLT_MAX; a long double
;;; may be wider than any double, so whatever a double holds it does too
(define (in-range? n suffix)
(cond ((string-ci=? suffix "f") (< (abs n) (* (- 2 (expt 2. -24)) (expt 2. 127))))
((string-ci=? suffix "l") #t)
(else (finite? n))))
;;; 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 ((radix (c-radix s)))
(and radix
(let* ((negative? (char=? #\- (string-ref s 0)))
(body (substring s (if negative? 3 2))))
(and (not (memv (string-ref body 0) '(#\+ #\-)))
(let ((n (string->number body radix)))
(and (exact-integer? n) (if negative? (- n) n))))))))
;;; 16 for 0xE0 and 2 for 0b101, a minus aside; #f for any other spelling
(define (c-radix s)
(let ((i (if (and (> (string-length s) 0) (char=? #\- (string-ref s 0))) 1 0)))
(and (> (string-length s) (+ i 2))
(char=? #\0 (string-ref s i))
(case (string-ref s (+ i 1))
((#\x #\X) 16)
((#\b #\B) 2)
(else #f)))))
;;; -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 (negating?)
(> (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, numbers in a radix,
;;; block/datum comments, feature expressions
(define (read-hash port)
(let ((c (get-ch port)))
(cond
((eof-object? c) (error "Unexpected end of input after #"))
((or (char=? c #\t) (char=? c #\T)) (read-bool port #t))
((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 (current-line))))
((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))
((char=? c #\-) (read-conditional port #f))
(else (error "Unsupported # syntax" c)))))
;;; Feature expressions
;;;
;;; #+linux (include GL/gl.h) kept on Linux
;;; #-macosx (foo) kept only on other than macOS
;;; #+(and unix (not macosx)) (bar) and / or / not combine them
;;;
(define (platform-features)
(list (software-version) (software-type) (machine-type)))
;;; The host's features are the default, so anything reading Sex sees
;;; what the compiler would. sexc rebinds this to add --features
(define current-features (make-parameter (platform-features)))
(define (feature-true? test)
(cond
((symbol? test) (and (memq test (current-features)) #t))
((pair? test)
(case (car test)
((and) (every feature-true? (cdr test)))
((or) (any feature-true? (cdr test)))
((not)
(if (and (pair? (cdr test)) (null? (cddr test)))
(not (feature-true? (cadr test)))
(error "Feature expression `not' takes exactly one operand" test)))
(else (error "Unknown operator in feature expression" (car test)))))
(else (error "Malformed feature expression" test))))
;;; The #-/#+ preceded datum is always read -- there is no other way
;;; to know where it ends -- and then either returned or dropped. What
;;; follows a dropped datum is read in its place: `#+x #+y (a) (b)'
;;; with only x is (b).
;;;
;;; That next thing may be nothing: the end of the file, or the
;;; paren closing the list we are in
(define (read-conditional port keep-when)
(let* ((test (next-code-token port))
(keep (begin
(unless (datum-token? test)
(error "Unexpected end of input in feature expression"))
(eq? keep-when (feature-true? test))))
(guarded (next-code-token port)))
(cond
(keep guarded)
;; A datum was dropped, so the next one stands in for it
((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 (or (ungrouped digits radix) 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)
(let ((rest (read-atom-string port)))
(cond
((string=? rest "") val)
((and val (string=? rest "rue")) val)
((and (not val) (string=? rest "alse")) val)
(else (error "Malformed boolean literal" rest)))))
(define (read-atom-string port)
(let loop ((chars (list)))
(let ((c (peek port)))
(if (delimiter? c)
(list->string (reverse chars))
(begin (get-ch port) (loop (cons c chars)))))))
(define named-chars
'(("space" . #\space) ("newline" . #\newline) ("tab" . #\tab)
("return" . #\return) ("nul" . #\nul) ("null" . #\nul)
("delete" . #\delete) ("escape" . #\escape) ("alarm" . #\alarm)
("backspace" . #\backspace)))
;;; A char is C's, one byte: #\λ was a multi-character constant, whose
;;; value is the C compiler's to choose
(define (read-char-lit port)
(let ((first (get-ch port)))
(when (eof-object? first)
(error "Unexpected end of input in character literal"))
(when (> (char->integer first) 127)
(error "a char is one byte, and this is not: write its code point, or a string"
first))
(if (char-alphabetic? first)
(let ((rest (read-atom-string port)))
(if (string=? rest "")
first
(let ((name (string-append (string first) rest)))
(cond
((assoc name named-chars) => cdr)
(else (error "Unknown character name" name))))))
first)))
;;; String literal with escape processing, matching the common escapes
;;; the previous reader (CHICKEN `read') interpreted
(define (read-string-lit port)
(get-ch port) ; consume opening quote
(let loop ((chars (list)))
(let ((c (get-ch port)))
(cond
((eof-object? c) (error "Unterminated string literal"))
((char=? c #\") (list->string (reverse chars)))
((char=? c #\\) (let ((escaped (read-escape port)))
(loop (if escaped (cons escaped chars) chars))))
(else (loop (cons c chars)))))))
;;; C's escapes, each one character of the string, or #f for a backslash
;;; ending a line, which joins it to the next. A string is text, so \x
;;; and octal, bytes to C, reach only as far as ASCII: past it the
;;; character is written as itself or its \u.
;;;
;;; \x41 \101 A -> A \012 -> newline é -> é
(define (read-escape port)
(let ((c (get-ch port)))
(cond
((eof-object? c) (error "Unterminated string literal"))
((assv c simple-escapes) => cdr)
((char=? c #\newline) #f)
((digit-in 8 c) => (lambda (d) (ascii (more-digits port 8 2 d))))
((char=? c #\x)
(let ((d (digit-in 16 (peek port))))
(unless d (error "\\x needs a hex digit"))
(get-ch port)
(ascii (more-digits port 16 #f d))))
((char=? c #\u) (code-point port 4))
((char=? c #\U) (code-point port 8))
(else (error "unknown escape" (string #\\ c))))))
(define simple-escapes
(list (cons #\n #\newline) (cons #\t #\tab) (cons #\r #\return)
(cons #\a #\alarm) (cons #\b #\backspace)
(cons #\f (integer->char 12)) (cons #\v (integer->char 11))
(cons #\\ #\\) (cons #\" #\") (cons #\' #\') (cons #\? #\?)))
(define (digit-in radix c)
(and (char? c) (string->number (string c) radix)))
;;; N, with up to MOST more digits of RADIX read onto it; any number of
;;; them for MOST #f
(define (more-digits port radix most n)
(let loop ((n n) (left most))
(let ((d (and (or (not left) (> left 0)) (digit-in radix (peek port)))))
(if d
(begin (get-ch port) (loop (+ (* n radix) d) (and left (- left 1))))
n))))
(define (ascii n)
(if (> n 127)
(error "a byte past ASCII is not text; write the character or \\u, or a [u8 N] array for bytes")
(integer->char n)))
(define (code-point port digits)
(let loop ((n 0) (left digits))
(if (= left 0)
(if (or (<= #xD800 n #xDFFF) (> n #x10FFFF))
(error "no character has this code point")
(integer->char n))
(let ((d (digit-in 16 (peek port))))
(unless d (error "\\u takes four hex digits and \\U eight"))
(get-ch port)
(loop (+ (* n 16) d) (- left 1))))))
(define (skip-block-comment port depth)
(if (= depth 0)
#t
(let ((c (get-ch port)))
(cond
((eof-object? c) (error "Unterminated block comment"))
((and (char=? c #\|) (eqv? (peek port) #\#))
(get-ch port) (skip-block-comment port (- depth 1)))
((and (char=? c #\#) (eqv? (peek port) #\|))
(get-ch port) (skip-block-comment port (+ depth 1)))
(else (skip-block-comment port depth))))))
;;; Read every top-level form from `port'. Locations are recorded by
;;; next-token, for every form rather than only these. An error says
;;; where it was met, the way a later stage's says where its form was
;;; written: file:line: what
(define (parse-all port)
(parameterize ((current-line 1))
(handle-exceptions e
(let ((message ((condition-property-accessor 'exn 'message #f) e)))
(if message
(apply error
(string-append (current-source-file) ":"
(number->string (current-line)) ": " message)
((condition-property-accessor 'exn 'arguments (list)) e))
(abort e)))
(let loop ((acc (list)))
(skip-whitespace port)
(let ((tok (next-token port)))
(cond
((eof-object? tok) (reverse acc))
((or (eq? tok close-paren)
(eq? tok close-bracket))
(error "Unmatched closing bracket at top level"))
((eq? tok dot-token)
(error "Unexpected . at top level"))
(else
(loop (cons tok acc)))))))))
;;; Entry point: read all forms from a file, or from the current input
;;; port when the source is 'stdin
(define (read-from-file file)
;; Resolve the name before with-directory moves us, so an imported
;; module's forms carry that module's path rather than the importer's
(let ((source-file (to-absolute-pathname file)))
(with-directory file
(with-input-from-file (pathname-strip-directory file)
(lambda ()
(parameterize ((current-source-file source-file))
(parse-all (current-input-port))))))))
(define (read-raw-forms input-source)
(if (eq? input-source 'stdin)
(parameterize ((current-source-file "stdin"))
(parse-all (current-input-port)))
(read-from-file input-source)))