[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
including non-S-expr code
The new `include/reader' form in MzLib's "include.ss" library lets you
provide your own reader for the included file.
Enclosed is a small example consisting of three files:
scheme-as-xml.ss - exports a silly reader that consumes XML and
ignores everything except entity names and elements. An entity `&lit;'
is converted to a symbol or number `lit'. An element `<e>c ...</e>' is
converted to a syntax sequence `(e [c] ...)' where `[c]' is the
conversion of each element/entity `c'.
a.ss - includes "a.xml", which is supposed to define an `f' to be
exported. This is the file that uses `include/reader'.
a.xml - defines f as a function that adds 1 to its argument. Note that
if you pass a non-number to f in DrScheme, relevant XML source is
hilited.
(Why XML? It doesn't look like S-expressions and there was a reader
handy.)
Matthew
----------------------------------------
scheme-as-xml.ss
----------------------------------------
(module scheme-as-xml mzscheme
(require (lib "xml.ss" "xml")
(lib "list.ss"))
(provide read-scheme-as-xml)
(define read-scheme-as-xml
(lambda (src-name port)
(if (eof-object? (peek-char port))
eof
(let ([doc (read-xml port)])
(let loop ([e (document-element doc)])
(let ([start (source-start e)]
[stop (source-stop e)])
(if (element? e)
;; Element case: --------------------
(datum->syntax-object
#f
(cons (element-name e)
(map loop (filter (lambda (c)
(or (element? c)
(entity? c)))
(element-content e))))
;; Half of the works turns out to be converting
;; XML source locations to MzScheme locations!
(list
src-name
(and (location? start)
(location-line start))
(and (location? start)
(location-char start))
(if (location? start)
(location-offset start)
start)
(- (if (location? stop)
(location-offset stop)
stop)
(if (location? start)
(location-offset start)
start))))
;; Entity case: --------------------
(datum->syntax-object
#f
(entity-text e)
#f))))))))) ; entities have no location?
----------------------------------------
a.ss
----------------------------------------
(module a mzscheme
(require (lib "include.ss"))
(require-for-syntax "scheme-as-xml.ss")
(include/reader "a.xml" read-scheme-as-xml)
(provide f))
----------------------------------------
a.xml
----------------------------------------
<define><f>&x;</f><add1>&x;</add1></define>