You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.7 KiB
Racket
37 lines
1.7 KiB
Racket
9 years ago
|
#lang racket/base
|
||
|
(require (for-syntax racket/base) syntax/strip-context)
|
||
9 years ago
|
(provide define-read-and-read-syntax)
|
||
9 years ago
|
|
||
|
;; `define-read-functions` simplifies support for the standard reading API,
|
||
|
;; which asks for `read` and `read-syntax`.
|
||
|
;; in general, `read` is just the datum from the result of `read-syntax`.
|
||
|
|
||
9 years ago
|
(define-syntax (define-read-and-read-syntax calling-site-stx)
|
||
|
(syntax-case calling-site-stx ()
|
||
9 years ago
|
[(_ (PATH PORT) BODY ...)
|
||
9 years ago
|
(with-syntax ([READ (datum->syntax calling-site-stx 'read)]
|
||
|
[READ-SYNTAX (datum->syntax calling-site-stx 'read-syntax)])
|
||
9 years ago
|
#'(begin
|
||
|
(provide READ READ-SYNTAX)
|
||
9 years ago
|
(define (calling-site-function PATH PORT)
|
||
9 years ago
|
BODY ...) ; don't care whether this produces datum or syntax
|
||
|
|
||
|
(define (READ-SYNTAX path port)
|
||
|
;; because `read-syntax` must produce syntax
|
||
|
;; coerce a datum result to syntax if needed (à la `with-syntax`)
|
||
9 years ago
|
(define result-syntax (let ([output (calling-site-function path port)])
|
||
9 years ago
|
(if (syntax? output)
|
||
|
output
|
||
|
(datum->syntax #f output))))
|
||
|
;; because `read-syntax` must produce syntax without context
|
||
|
;; see http://docs.racket-lang.org/guide/hash-lang_reader.html
|
||
|
;; "a `read-syntax` function should return a syntax object with no lexical context"
|
||
|
(strip-context result-syntax))
|
||
|
|
||
|
(define (READ port)
|
||
|
; because `read` must produce a datum
|
||
9 years ago
|
(let ([output (calling-site-function #f port)])
|
||
9 years ago
|
(if (syntax? output)
|
||
|
(syntax->datum output)
|
||
|
output)))))]))
|