This is a simple example of set-read-syntax! which transforms nested { ... } braces into (begin ...) clauses. Several other examples are available in various eggs, such as objc.
In the example below we are called when the reader encounters the opening { character, and we then (read) in S-expressions in a loop until we detect a } character. Of course, what we (read) may well be another opening brace, which will call us recursively.
;; 2007/10 zb
(import (chicken read-syntax))
(set-read-syntax! #\{
(lambda (port)
(let loop ((c (peek-char port)) (exps '()))
(cond ((eof-object? c)
(error "EOF encountered while parsing { ... } clause"))
((char=? c #\})
(read-char port) ; discard
`(begin ,@(reverse exps)))
((char-whitespace? c)
(read-char port) ; discard whitespace
(loop (peek-char port) exps))
(else
(let ((exp (read port)))
(loop (peek-char port)
(cons exp exps))))))))
Example usage:
#;21> ,x { (display 'hello) (newline) { (display 'inner) (newline) } (newline) }
(begin (display 'hello) (newline) (begin (display 'inner) (newline)) (newline))
#;21> { (display 'hello) (newline) { (display 'inner) (newline) } (newline) }
hello
inner
#;22>