Debian Codegraph @

doc/guile-reader.texi

raw
1 \input texinfo @c -*-texinfo-*-
2
3 @c %**start of header
4 @setfilename guile-reader.info
5 @settitle A Reader Framework for Guile
6 @footnotestyle end
7 @setchapternewpage odd
8 @c %**end of header
9
10 @set EDITION 1
11 @include version.texi
12
13 @copying
14 This file documents Guile-Reader.
15
16 Copyright @copyright{} 2005, 2006, 2007, 2008, 2009, 2012, 2015, 2017 Ludovic Court@`es
17
18 Permission is granted to make and distribute verbatim copies of this
19 manual provided the copyright notice and this permission notice are
20 preserved on all copies.
21
22 Permission is granted to copy and distribute modified versions of this
23 manual under the conditions for verbatim copying, provided that the
24 entire resulting derived work is distributed under the terms of a
25 permission notice identical to this one.
26
27 Permission is granted to copy and distribute translations of this manual
28 into another language, under the above conditions for modified versions,
29 except that this permission notice may be stated in a translation
30 approved by the Free Software Foundation.
31 @end copying
32
33 @dircategory The Algorithmic Language Scheme
34 @direntry
35 * Guile Reader: (guile-reader). A Reader Framework for Guile.
36 @end direntry
37
38
39 @titlepage
40 @title A Reader Framework for Guile
41 @subtitle for Guile-Reader @value{VERSION}
42 @author Ludovic Court@`es
43
44 @page
45 @vskip 0pt plus 1filll
46 Edition @value{EDITION} @*
47 @c Updated for Guile Reader @value{VERSION} @*
48 @value{UPDATED} @*
49
50 @insertcopying
51 @end titlepage
52
53 @contents
54
55 @c *********************************************************************
56 @node Top, Introduction, (dir), (dir)
57 @top A Reader Framework for Guile
58
59 This document describes Guile-Reader version @value{VERSION}, for
60 GNU@tie{}Guile's 3.0 stable series, as well as the legacy 1.8, 2.0 and
61 2.2 series. It was last updated in @value{UPDATED-MONTH}.
62
63 This documentation should be mostly complete. Details about the C API
64 are omitted from this manual. They can be found in the public header
65 files.
66
67 @menu
68 * Introduction:: The goals of Guile-Reader.
69 * Overview:: How it works.
70 * Quick Start:: For the impatient.
71 * API Reference:: Using Guile-Reader.
72 * Internals:: Performance considerations.
73
74 * Concept Index:: Concepts.
75 * Function Index:: Scheme procedures and C functions.
76 @end menu
77
78
79 @c *********************************************************************
80
81 @node Introduction, Overview, Top, Top
82 @chapter Introduction
83
84 Guile currently provides limited extensibility of its reader, by means
85 of @code{read-hash-extend} (@pxref{Reader Extensions,
86 @code{read-hash-extend},, guile, Guile Reference Manual}), for
87 instance, or @code{read-enable} (@pxref{Scheme Read,
88 @code{read-enable},, guile, Guile Reference Manual}).
89 @uref{http://srfi.schemers.org/srfi-10/srfi-10.html, SRFI-10} tries to
90 propose a generic, portable, extension mechanism similar to
91 @code{read-hash-extend} but limited to @code{#,} sequences. Moreover,
92 while this may not always be desirable, all these extension facilities
93 have a global effect, changing the behavior of the sole reader
94 implementation available at run-time. This makes it impossible to
95 have, for instance, one module consider names starting with @code{:}
96 as symbols, while another considers them as keywords.
97
98 Extensions such as the read syntax for SRFI-4 numeric vectors
99 (@pxref{Uniform Numeric Vectors, SRFI-4 vectors,, guile, Guile
100 Reference Manual}) had to be added to Guile's built-in C reader.
101 Syntactic extensions that did not appeal the majority of users, like
102 Emacs-Lisp vectors, are @code{#ifdef}'d within the reader code and are
103 not available by default. Moreover, some extensions are incompatible
104 with each other, such as the DSSSL keyword syntax and SCSH block
105 comments (@pxref{Block Comments, SCSH block comments,, guile, Guile
106 Reference Manual}). In short the current reader syntax is hardly
107 extensible.
108
109 The idea of Guile-Reader is to provide a framework allowing users to
110 quickly define readers for whatever syntax (or rather: variant of the
111 Scheme syntax) they like. Programs can then provide their own readers
112 and, thanks to Guile's @code{current-reader} mechanism, have their
113 code read with this reader. When using Guile 2.0, readers produced by
114 Guile-Reader are Unicode-capable; they can read from any
115 ASCII-compatible encoding, such as UTF-8 or ISO-8859-1.
116
117 @cindex SILex
118 @cindex lexer
119 While it is much simpler than a full-blown lexer generator such as
120 @uref{http://www.gnu.org/software/flex/, Flex},
121 @uref{http://www.iro.umontreal.ca/~dube/, Danny Dub@'e's SILex} and
122 @uref{http://www.inria.fr/mimosa/fp/Bigloo, Bigloo's RGC}, its simple
123 programming interface should make it very straightforward to implement
124 readers, especially for Scheme-like syntaxes. Best of all, Guile
125 Reader comes with a library of components that can typically be used
126 to construct a reader for the Scheme syntax. And each one of this
127 components may be reused at will when creating other readers. On the
128 other hand, one should be aware that this simpler API comes at the
129 cost of a lack of consistency in some cases, as outlined later in this
130 manual (@pxref{Limitations}).
131
132 @cindex read table
133 Common Lisp has a similar mechanism to extend its reader which is
134 called the @dfn{read
135 table}. @uref{http://www.iro.umontreal.ca/~gambit/, Gambit Scheme},
136 for instance, also provides an implementation of read tables.
137 However, it appears to have limitations similar to Guile's
138 @code{read-enable} and @code{read-hash-extend} in terms of
139 possibilities for syntax extension. On the other hand, it allows the
140 reader and writer to be kept consistent, which Guile-Reader does not
141 address.
142
143
144 @c chapter ----------------------------------------------------------
145 @node Overview, Quick Start, Introduction, Top
146 @chapter Overview
147
148 @cindex reader library
149 Guile-Reader allows for the construction of readers capable of
150 understanding various syntactic variants. The simplest way to use it
151 is through its @dfn{reader library} that allows one to pick and choose
152 various commonly used syntactic extensions to the standard Scheme
153 syntax (@pxref{Reader Library}). However, Guile-Reader also provides
154 a finer-grain programming interface allowing the construction of
155 virtually any reader, with its own syntactic specificities. The
156 following sections focus primarily on this capability.
157
158 @cindex reader
159 @cindex token reader
160 Before going into the details of the reader framework API, let us have
161 a quick overview of what this is. Basically, Guile-Reader introduces
162 two objects: @dfn{readers} and @dfn{token readers}. Readers can be
163 thought of, simply, as procedures like Scheme's @code{read}
164 (@pxref{Input, R5RS,, r5rs, Revised^5 Report on the Algorithmic
165 Language Scheme}), i.e., procedures that take one (optional) argument,
166 namely the port to read from. We will see later that readers as
167 defined by Guile-Reader can actually receive two more arguments
168 (@pxref{Defining a New Reader}). A reader, like @code{read}, reads a
169 sequence of characters (the @dfn{external representation} of some
170 object) and returns a Scheme object.
171
172 Token readers (TRs, for short) are the building block of a reader. A
173 token reader is basically an association between a character or set of
174 characters and a procedure to read and interpret a sequence of
175 characters starting with one of the former. For instance, in a
176 standard Scheme reader, the character @code{(} may be associated to a
177 procedure that reads an S-expression. Likewise, lower-case and
178 upper-case letters associated with the appropriate procedure form a
179 token reader for symbols.
180
181 In Guile-Reader, TRs may be written either in Scheme or in C, and they
182 can even be a reader produced by Guile-Reader itself. Unless it is a
183 reader, the procedure (or C function) used to create a TR will receive
184 four arguments:
185
186 @itemize
187 @item the character that was read and which triggered its call; in
188 the S-exp example, this would be @code{(};
189 @item the port to read from;
190 @item the reader which performed this invocation;
191 @item the top-level reader which yielded this invocation.
192 @end itemize
193
194 The next section shows how to get started with Guile-Reader, using a
195 high-level API. Details about of the programming interface are given in
196 the API reference (@pxref{API Reference}).
197
198
199 @c chapter ----------------------------------------------------------
200 @node Quick Start, API Reference, Overview, Top
201 @chapter Quick Start
202
203 The simplest way to get started and to produce customized readers is
204 through the high-level API provided by the @code{(system reader
205 library)} module. As the name suggests, this module provides a library
206 of readily usable readers. The @code{make-alternate-guile-reader}
207 procedure gives access to these readers. It can be passed a list of
208 symbols describing reader options, such as whether you want support for
209 DSSSL keywords, @uref{http://srfi.schemers.org/srfi-62/srfi-62.html,
210 SRFI-62 comments}, @uref{http://srfi.schemers.org/srfi-30/srfi-30.html,
211 SRFI-30 block comments}, etc.
212
213 The following example binds to @var{my-reader} a Scheme reader that
214 supports DSSSL-style keywords and SRFI-62 comments, and that is case
215 insensitive:
216
217 @findex make-alternate-guile-reader
218
219 @lisp
220 (use-modules (system reader library))
221
222 (define my-reader
223 (make-alternate-guile-reader '(dsssl-keywords
224 srfi62-sexp-comments
225 case-insensitive)))
226 @end lisp
227
228 This reader can then be used like the regular @code{read} procedure:
229
230 @lisp
231 (procedure? my-reader)
232 => #t
233
234 (with-input-from-string "some-symbol" my-reader)
235 => some-symbol
236
237 (my-reader (open-input-string "MiXeD-CaSe"))
238 => mixed-case
239
240 (my-reader (open-input-string "(an sexp with a #;srfi-62 comment)"))
241 => (an sexp with a comment)
242
243 (my-reader (open-input-string "#!some-DSSSL-keyword"))
244 => #:some-dsssl-keyword
245 @end lisp
246
247 Most of the time, you will want to use it as the current reader, at
248 least in the module where you created it. Fortunately, Guile
249 provides a mechanism for this, the @code{current-reader} fluid
250 (@pxref{Loading, @code{current-reader},, guile, Guile Reference
251 Manual}). Changing the value of this fluid from a file that is being
252 loaded will affect the reader use to load it. In general, you will want
253 to modify @code{current-reader} not only at run time, but also at
254 compile time and when the code is evaluated, which can be achieved
255 using @code{eval-when} (@pxref{Eval When, @code{eval-when},, guile, GNU
256 Guile Reference Manual}). For instance:
257
258 @vindex current-reader
259
260 @lisp
261 ;;; This is the beginning of my Scheme file. At this point, Guile's
262 ;;; default reader is used (or, alternatively, the one that was
263 ;;; passed as a second parameter to `load'). So, for instance, DSSSL
264 ;;; keywords are _not_ recognized.
265
266 ;; Let's create our own customized reader...
267 (use-modules (system reader library))
268
269 ;; 'eval-when' here is needed to make 'my-reader' accessible at
270 ;; compile time, and to have the 'current-reader' change take
271 ;; effect at compile time.
272 (eval-when (compile load eval)
273 (define my-reader
274 (make-alternate-guile-reader '(dsssl-keywords
275 srfi62-sexp-comments
276 case-insensitive)))
277
278 ;; Let's make it the current reader.
279 (fluid-set! current-reader my-reader))
280
281 ;; From now on, MY-READER is used to read the rest of this file. Thus
282 ;; we can happily use the syntactic extensions it implements: DSSSL
283 ;; keywords, SRFI-62 comments and case-insensitivity.
284
285 (if (not (keyword? #!dsssl-keyword))
286 (error "Something went wrong, this should not happen!"))
287 @end lisp
288
289 The nice thing is that @code{current-reader} is reset to its initial
290 value when the dynamic extent of @code{load} is left. In other words,
291 the loader of the file above is @emph{not} affected by the
292 @code{fluid-set!} statement. Reader changes are @emph{hygienic} and
293 modules can use their own without risking to harm each other.
294
295 The full list of options supported by @code{make-alternate-guile-reader}
296 is shown in @ref{Reader Library}. However, this option set is quite
297 limited and you may find yourself wanting a syntactic extension not
298 available here. In that case, you will want to build a new reader,
299 possibly reusing existing reader components known as @dfn{token
300 readers}, as described in @ref{Defining a New Reader}.
301
302
303 @c chapter ----------------------------------------------------------
304 @node API Reference, Internals, Quick Start, Top
305 @chapter API Reference
306
307 All the Scheme procedures described below are exported by the
308 @code{(system reader)} module. In order to be able to use them, you
309 will need to import this module first:
310
311 @example
312 (use-modules (system reader))
313 @end example
314
315 A C variant is also available for most of them by including the
316 declarations available in the @code{<guile-reader/reader.h>} header
317 file.
318
319 @menu
320 * Token Readers:: The basic components of a reader.
321 * Readers:: How to build readers.
322 @end menu
323
324 @node Token Readers, Readers, API Reference, API Reference
325 @section Token Readers
326
327 Basically, token readers are the association of a character or set of
328 characters and a function that is able to interpret character
329 sequences that start by one of these characters. We will see below
330 how to define new token readers first, and then how to re-use existing
331 ones.
332
333 @menu
334 * Defining a New Token Reader::
335 * TR Calling Convention::
336 * Invoking a Reader from a TR::
337 * Token Reader Library::
338 * Limitations::
339 @end menu
340
341 @node Defining a New Token Reader, TR Calling Convention, Token Readers, Token Readers
342 @subsection Defining a New Token Reader
343
344 @cindex token reader
345 @cindex character specification
346 @findex make-token-reader
347
348 A new token reader object can be created by calling the
349 @code{make-token-reader} procedure with a @dfn{character
350 specification} and a procedure. A character specification defines the
351 set of characters which should trigger an invocation of the
352 corresponding procedure. The character specification may be either:
353
354 @itemize
355 @item a single character;
356 @item a pair of characters, which is interpreted as a character range;
357 @item a list of characters, which is interpreted as a set of
358 characters.
359 @end itemize
360
361 The procedure passed to @code{make-token-reader} may actually be
362 either a C function or Scheme procedure that takes four arguments
363 (@pxref{TR Calling Convention}), any ``object'' returned by
364 @code{token-reader-procedure}, or a reader. This last option turns
365 out to be quite helpful. For example, this is very convenient
366 when implementing the various Scheme read syntaxes prefixed by the
367 @code{#} character: one can create a reader for @code{#}, and then
368 turn it into a token reader that is part of the top-level reader.
369
370 The reference for @code{make-token-reader} is given below:
371
372 @c Include part of API documentation snarffed from `reader.c'.
373 @include make-token-reader-doc.texi
374
375 The next section explains the token reader calling convention, i.e.,
376 how the @var{proc} argument to @code{make-token-reader} is invoked.
377
378
379 @node TR Calling Convention, Invoking a Reader from a TR, Defining a New Token Reader, Token Readers
380 @subsection Token Reader Calling Convention
381
382 @cindex calling convention
383 A token reader's procedure is passed four arguments:
384
385 @itemize
386 @item the character that was read and which triggered its call; in
387 the S-exp example, this would be @code{(};
388 @item the port to read from;
389 @item the reader which performed this invocation, i.e., either an
390 @code{scm_reader_t} object (if the token reader is written in C) or a
391 four-argument Scheme procedure (if the token reader is written in
392 Scheme);
393 @cindex top-level reader
394 @item the top-level reader which yielded this invocation and which may
395 be different from the previous argument in the case a token reader was
396 made from a reader; the use of these two arguments will be detailed in
397 the next section, @ref{Invoking a Reader from a TR}.
398 @end itemize
399
400 It must return a Scheme object resulting from the interpretation of
401 the characters read. It may as well raise an error if the input
402 sequence is corrupt. Finally, it may return @code{*unspecified*}, in
403 which case the calling reader will not return and instead continue
404 reading. This is particularly useful to define comment token readers:
405 a TR that has just read a comment will obviously not have any sensible
406 Scheme object to return, and a reader is not expected to return
407 anything but a ``real'' Scheme object. A token reader for Scheme's
408 @code{;} line comments may be defined as follows:
409
410 @smallexample
411 (make-token-reader #\; read-a-line-and-return-unspecified)
412 @end smallexample
413
414 This behavior may, however, be overridden by passing
415 @code{make-token-reader} a third argument (called @var{escape?}):
416
417 @smallexample
418 (make-token-reader #\; read-a-line-and-return-unspecified #t)
419 @end smallexample
420
421 @cindex SCSH block comments
422 A reader that includes this TR will return @code{*unspecified*} once a
423 line comment has been read. This is particularly useful, for
424 instance, when implementing @code{#!} block comments (@pxref{Block
425 Comments, SCSH block comments,, guile, Guile Reference Manual}, for
426 more information) as a TR attached to @code{#\!} within the @code{#\#}
427 sub-reader (@pxref{Defining a New Token Reader}).
428
429 Finally, the procedure passed to @code{make-token-reader} may be
430 @code{#f}, in which case the resulting TR will just have the effect of
431 ignoring the characters it is associated to. For instance,
432 handling white spaces may be done by defining a TR like this:
433
434 @smallexample
435 (make-token-reader '(#\space #\newline #\tab) #f)
436 @end smallexample
437
438
439 @node Invoking a Reader from a TR, Token Reader Library, TR Calling Convention, Token Readers
440 @subsection Invoking a Reader from a Token Reader
441
442 As seen in section @xref{Defining a New Token Reader}, token readers
443 are systematically passed to readers when invoked. The reason why
444 this may be useful may not be obvious at first sight.
445
446 Consider an S-exp token reader. The TR itself doesn't have sufficient
447 knowledge to read the objects that comprise an S-exp. So it needs to
448 be able to call the reader that is being used to actually read those
449 objects.
450
451 The need for the @var{top-level-reader} argument passed to token
452 readers may be illustrated looking at the implementation of the vector
453 read syntax (@pxref{Vector Syntax,,, guile, Guile Reference Manual}).
454 One may implement the vector reader as a token reader of the @code{#}
455 sub-reader (@pxref{Defining a New Token Reader}). The vector token
456 reader may be implemented like this:
457
458 @example
459 (lambda (chr port reader top-level-reader)
460 ;; At this point, `#' as already been read and CHR is `(',
461 ;; so we can directly call the regular S-expression reader
462 ;; and convert its result into a vector.
463 (let ((sexp-read (token-reader-procedure
464 (standard-token-reader 'sexp))))
465 (apply vector
466 (sexp-read chr port reader))))
467 @end example
468
469 When this procedure is invoked, @var{reader} points to the @code{#}
470 sub-reader.
471 @c FIXME: Currently the token_reader_proc_apply supports only
472 @c 3 arguments, see the code for details. The explanation below is
473 @c for the day when it supports the fourth argument.
474 @c
475 @c Clearly, in order to read the symbols that comprise the
476 @c list, @var{sexp-read} should @emph{not} invoke @var{reader} because
477 @c @var{reader} only knows about @code{#}-prefixed object syntaxes. For
478 @c this reason, in order to be consistent in re-usable, the S-exp reader
479 @c must call @var{top-level-reader} which points to the top-level reader,
480 @c i.e., the reader which yielded the invocation of the @code{#}
481 @c sub-reader.
482
483 @node Token Reader Library, Limitations, Invoking a Reader from a TR, Token Readers
484 @subsection Token Reader Library
485
486 @cindex token reader library
487 Guile-Reader comes with a number of re-usable token readers.
488 Together, they might be assembled to form a complete Scheme reader
489 equivalent to that of Guile (@pxref{Reader Library}). Or they can be
490 used individually in any reader.
491
492 The @code{standard-token-reader} procedure takes a symbol that names a
493 standard TR from the library and returns it (or @code{#f} if not
494 found). Currently, the available TRs are:
495
496 @c Include the documentation that was generated using `extract-doc.scm'.
497 @include token-reader-doc.texi
498
499 As can be inferred from the above two lists, reading character
500 sequences starting with the @code{#} characters can easily be done by
501 defining a sub-reader for that character. That reader can then be
502 passed to @code{make-token-reader} as the procedure attached to
503 @code{#}:
504
505 @example
506 (define sharp-reader
507 (make-reader (map standard-token-reader
508 '(boolean character
509 number+radix keyword
510 srfi-4
511 block-comment))))
512
513 (define top-level-reader
514 (make-reader (list (make-token-reader #\# sharp-reader)
515 ...
516 )))
517 @end example
518
519 The procedures available to manipulate token readers are listed below:
520
521 @c Include part of API documentation snarffed from `reader.c'.
522 @include token-reader-api-doc.texi
523
524 @node Limitations, , Token Reader Library, Token Readers
525 @subsection Limitations
526
527 This section describes the main limitations and common pitfalls
528 encountered when using Guile-Reader.
529
530 @menu
531 * Token Delimiters:: Dealing with token delimiters.
532 * Overlapping Token Readers:: Token readers that syntactically overlap.
533 @end menu
534
535 @node Token Delimiters, Overlapping Token Readers, Limitations, Limitations
536 @subsubsection Token Delimiters
537
538 @cindex token delimiters
539 As can be seen from the previous section, there exist, for instance,
540 an surprisingly high number of symbol token readers. The reason for
541 this is that different syntax variants define different @dfn{token
542 delimiters}. Token delimiters are characters that help the reader
543 determine where tokens that require implicit termination do terminate.
544 Quoting R5RS (@pxref{Lexical structure, R5RS' lexical structure,,
545 r5rs, Revised^5 Report on the Algorithmic Language Scheme}):
546
547 @quotation
548 Tokens which require implicit termination (identifiers, numbers,
549 characters, and dot) may be terminated by any <delimiter>, but not
550 necessarily by anything else.
551 @end quotation
552
553 @cindex R5RS
554 @cindex R6RS
555 R5RS defines token delimiters as one of the following: a whitespace, a
556 parentheses, a quotation mark (@code{"}) or a semi-colon (@code{;})
557 character. On the other hand, R6RS, which is to support the ability
558 to use square brackets instead of parentheses for S-expressions, also
559 considers square brackets as token delimiters. Likewise, if we were
560 to support curly braces to enclose S-expressions, then curly braces
561 would need to be considered as token delimiters too.
562
563 For this reason, the token reader library comes with several symbol
564 token readers: the @code{guile-symbol-} family does not consider
565 square brackets as delimiters while the @code{r6rs-symbol-} family
566 does, the @code{brace-free-} TR family considers curly braces as
567 delimiters but not square brackets, etc. Similarly, several variants
568 of number TRs are available. This is due to the fact that number TRs
569 may return symbols in corner cases like symbol names starting with a
570 number.
571
572 However, although keywords must also comply with the token delimiters
573 rules, there is only one keyword TR (called @code{keyword}). The
574 reason for this is that this TR relies on the top-level reader's
575 symbol reader to read the symbol that makes up the keyword being read.
576
577 @cindex pitfall
578 In the current design of Guile-Reader, this token delimiter issue
579 creates a number of pitfalls when one is willing to change the current
580 delimiters. In particular, one has to be very careful about using TRs
581 that consistently assume the same token delimiters.
582
583 A ``real'' lexer generator such as Danny Dub@'e's SILex avoids such
584 issues because it allows the definition of tokens using regular
585 expressions. However, its usage may be less trivial than that of
586 Guile-Reader.
587
588 @node Overlapping Token Readers, , Token Delimiters, Limitations
589 @subsubsection Overlapping Token Readers
590
591 As can be seen from the descriptions of the standard token readers
592 (@pxref{Token Reader Library}), token readers sometimes ``overlap'',
593 i.e., the set of input strings they match overlap. For instance, the
594 @code{boolean} token reader should match @code{#t}, @code{#T},
595 @code{#f} or @code{#F}. However, the @code{srfi-4} token reader also
596 needs to match floating-point numeric vectors such as @code{#f32(1.0
597 2.0 3.0)}. Similarly, strings like @code{1} are, logically, handled
598 by the @code{guile-number} (or similar) token reader; however, since a
599 string like @code{1+} should be recognized as a @emph{symbol}, rather
600 than a number, it must then be passed to one of the symbol token
601 readers.
602
603 In those two cases, the input sets of those two token readers
604 @emph{overlap}. In order for the resulting reader to work as
605 expected, the two overlapping token readers need to somehow
606 @emph{cooperate}. In the first example, this is achieved by having
607 the @code{srfi-4} TR read in strings starting with @code{#f} or
608 @code{#F} and passing them to the @code{boolean-srfi-4} TR if need be.
609 In the second case, this is done by having number TRs (e.g.,
610 @code{guile-number}) explicitly check for non-digit characters and
611 return a symbol instead of a number when a non-digit is encountered.
612
613 It should be obvious from these two examples that this limitation
614 impedes full separation of the various TRs. Fortunately, there are
615 not so many cases where such overlapping occurs when implementing
616 readers for R5RS-like syntaxes. The implementation of
617 @code{make-alternate-guile-reader} (@pxref{Reader Library}) shows how
618 such problems have been worked around.
619
620 @cindex lexer
621 Lexer generators such as @uref{http://www.gnu.org/software/flex/,
622 Flex}, @uref{http://www.iro.umontreal.ca/~dube/, SILex} and Bigloo's
623 RGC (@pxref{Regular Parsing, Bigloo's RGC,, bigloo, Bigloo@comma{} A
624 ``Practical Scheme Compiler''---User Manual}) obviously do not have
625 this problem: all possible ``token'' types are defined using regular
626 expressions and the string-handling code (e.g., code that converts a
627 string into a Scheme number) is only invoked once a full matching
628 string has been found.
629
630
631 @node Readers, , Token Readers, API Reference
632 @section Readers
633
634 Guile-Reader is about defining readers. Continuing to read this
635 manual was definitely a good idea since we have finally reached the
636 point where we will start talking about how to define new readers.
637
638 @menu
639 * Defining a New Reader::
640 * Reader Library::
641 * Compatibility and Confinement::
642 @end menu
643
644 @node Defining a New Reader, Reader Library, Readers, Readers
645 @subsection Defining a New Reader
646
647 @cindex reader
648 Roughly, a reader is no more than a loop which reads characters from a
649 given port, and dispatches further interpretation to more specific
650 procedures. Written in Scheme, it could resemble something like:
651
652 @lisp
653 (define (my-reader port)
654 (let loop ((result *unspecified*))
655 (let ((the-char (getc port)))
656 (case the-char
657 ((#\() (my-sexp-token-reader the-char port my-reader)))
658 ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
659 (my-number-token-reader the-char port my-reader))
660 (else
661 (error "unexpected character" the-char))))))
662 @end lisp
663
664 @findex make-reader
665 Using Guile-Reader, this is done simply by providing a list of token
666 readers to the @code{make-reader} procedure, as in the following
667 example:
668
669 @lisp
670 (define my-reader
671 (make-reader (list (make-token-reader #\( my-sexp-token-reader)
672 (make-token-reader '(#\0 . #\9)
673 my-number-token-reader))))
674 @end lisp
675
676 However, the procedure returned by @code{make-reader} is different
677 from the hand-written one above in that in takes two additional
678 optional arguments which makes it look like this:
679
680 @lisp
681 (define (my-reader port faults-caller-handled? top-level-reader)
682 (let loop ((the-char (getc port)))
683 (case the-char
684 ...
685 (else
686 (if (not faults-caller-handled?)
687 (error "unexpected character" the-char)
688 (ungetc the-char) ;; and return *unspecified*
689 )))))
690 @end lisp
691
692 Therefore, by default, @code{my-reader} will raise an error as soon as
693 it reads a character that it does not know how to handle. However, if
694 the caller passes @code{#t} as its @code{faults-caller-handled?}
695 argument, then @code{my-reader} is expected to ``unget'' the faulty
696 character and return @code{*unspecified*}, thus allowing the caller to
697 handle the situation.
698
699 This is useful, for instance, in the S-exp token reader example: the
700 S-exp token reader needs to call its calling reader in order to read
701 the components between the opening and closing brackets; however, the
702 calling reader may be unable to handle the @code{#\)} character so the
703 S-exp token reader has to handle it by itself and needs to tell it to
704 the reader.
705
706 @c Include part of API documentation snarffed from `reader.c'.
707 @include make-reader-doc.texi
708
709 Currently, the flags that may be passed to @code{make-reader} are the
710 following:
711
712 @itemize
713
714 @item @code{reader/record-positions} will yield a reader that records
715 the position of the expression read, which is mostly useful for
716 debugging purposes; this information may then be accessed via source
717 properties (@pxref{Procedure Properties, source properties,, guile,
718 Guile Reference Manual}).
719
720 @item @code{reader/lower-case} will have the yielded reader convert to
721 lower-case all the letters that it reads; note that this is not
722 sufficient to implement symbol case-insensitivity as shown in @ref{Reader
723 options,,, guile, Guile Reference Manual}. For this, the token
724 reader(s) that read symbols must also convert all subsequent
725 characters to lower-case.
726
727 @item @code{reader/upper-case} will have the yielded reader convert to
728 upper-case all the letters that it reads; again, that is not
729 sufficient to implement case-insensitivity.
730
731 @item @code{reader/debug} causes the generated reader to produce
732 debugging output.
733
734 @end itemize
735
736 @node Reader Library, Compatibility and Confinement, Defining a New Reader, Readers
737 @subsection Reader Library
738
739 @cindex reader library
740 The @code{(system reader)} module exports the @code{default-reader}
741 procedure which returns a reader equivalent to Guile's built-in
742 default reader made of re-usable token readers written in C
743 (@pxref{Token Reader Library}).
744
745 @c Include part of API documentation snarffed from `reader-lib.c'.
746 @include default-reader-doc.texi
747
748 Additionally, the @code{(system reader library)} module exports a
749 number of procedures that ease the re-use of readers.
750
751 @c Include part of the API documentation snarffed from `reader-lib.c'.
752 @include make-guile-reader-doc.texi
753
754 @c Include part of the API documentation obtained from `library.scm'.
755 @include reader-lib-doc.texi
756
757
758 @node Compatibility and Confinement, , Reader Library, Readers
759 @subsection Compatibility and Confinement
760
761 @findex read-options
762 @findex read-enable
763 @findex read-disable
764 @findex read-set!
765 @findex read-hash-extend
766 Guile's core read subsystem provides an interface to customize its
767 reader, namely via the @code{read-options} (@pxref{Scheme Read,,,
768 guile, Guile Reference Manual}) and @code{read-hash-extend}
769 (@pxref{Reader Extensions, @code{read-hash-extend},, guile, Guile
770 Reference Manual}) procedures.
771
772 The main problem with this approach is that changing the reader's
773 options using these procedures has a global effect since there is only
774 one instance of @code{read}. Changing the behavior of a single
775 function at the scale of the whole is not very ``schemey'' and can be
776 quite harmful. Suppose a module relies on case-insensitivity while
777 another relies on case-sensitivity. If one tries to use both modules
778 at the same time, chances are that at least one of them will not work
779 as expected. Risks of conflicts are even higher when
780 @code{read-hash-extend} is used: imagine a module that uses
781 DSSSL-style keywords, while another needs SCSH-style block comments.
782
783 @cindex confinement
784 @cindex reader confinement
785 @findex read-options-interface
786 In @code{(system reader confinement)}, guile-reader offers an
787 implementation of @code{read-option-interface} and
788 @code{read-hash-extend} that allows to @emph{confine} such settings on
789 a per-module basis. In order to enable reader confinement, one just
790 has to do this:
791
792 @smalllisp
793 (use-modules (system reader confinement))
794 @end smalllisp
795
796 Note that this must be done before the suspicious modules are loaded,
797 that is, typically when your program starts. This will redefine
798 @code{read-options-interface} and @code{read-hash-extend} so that any
799 future modification performed via Guile's built-in reader option
800 interface will be confined to the calling module.
801
802 @findex current-reader
803 Starting from Guile 1.8.0, @code{current-reader} is a core binding
804 bound to a fluid whose value should be either @code{#f} or a reader
805 (i.e., a @code{read}-like procedure). The value of this fluid
806 dictates the reader that is to be used by @code{primitive-load} and
807 its value can be changed dynamically (@pxref{Loading,
808 @code{current-reader},, guile, Guile Reference Manual}).
809
810 The confined variants of @code{read-options-interface} and
811 @code{read-hash-extend} rely on this feature to make reader
812 customizations local to the file being loaded. This way, invocations
813 of these functions from within a file being loaded by
814 @code{primitive-load} take effect immediately.
815
816 @c @cindex forward-compatibility
817 @c When using a version of Guile that does not support the
818 @c @code{current-reader} feature, the @code{(system reader compat)}
819 @c module defines a new @code{current-reader} core binding and redefines
820 @c @code{primitive-load} in order to provide compatibility with newer
821 @c versions of Guile.
822
823
824 @c chapter ----------------------------------------------------------
825 @node Internals, Concept Index, API Reference, Top
826 @chapter Internals
827
828 In order to not have to trade too much performance for flexibility,
829 Guile-Reader dynamically compiles code for the readers defined using
830 GNU @emph{lightning} (@pxref{Overview, Introduction to GNU
831 @emph{lightning},, lightning, Using and Porting GNU
832 @emph{lightning}}). As of version 1.2c, GNU @emph{lightning} can
833 generate code for the PowerPC, SPARC, and IA32 architectures. For
834 other platforms, Guile-Reader provides an alternative (slower) C
835 implementation that does not depend on it. Using the
836 @emph{lightning}-generated readers typically provides a 5% performance
837 improvement over the static C implementation. However, note that
838 @emph{lightning}@tie{}2.x is not supported yet.
839
840 Re-using token readers written in C, as explained in @xref{Token
841 Reader Library}, does not imply any additional cost: the underlying C
842 function will be called directly by the reader, without having to go
843 through any marshalling/unmarshalling stage.
844
845 @findex make-guile-reader
846 Additionally, on the C side, token readers may be initialized
847 @emph{statically} (except, obviously, token readers made out of a
848 dynamically-compiled reader). Making good use of it can improve the
849 startup time of a program. For example, @code{make-guile-reader}
850 (@pxref{Reader Library}) is implemented in C and it uses statically
851 initialized arrays of token readers. It still needs to invoke
852 @code{scm_c_make_reader ()}, but at least, token readers themselves
853 are ``ready to use''.
854
855 Scanners as generated by Flex or similar tools should theoretically be
856 able to provide better performance because the input reading and
857 pattern matching loop is self-contained, may fit in cache, and only
858 has to perform function calls once a pattern has been fully
859 recognized.
860
861
862 @c *********************************************************************
863 @node Concept Index, Function Index, Internals, Top
864 @unnumbered Concept Index
865 @printindex cp
866
867 @node Function Index, , Concept Index, Top
868 @unnumbered Function Index
869 @printindex fn
870
871
872 @bye
873
874 @ignore
875 ;;; arch-tag: e82c9dff-b040-4398-a1e9-1e2570cfc025
876 @end ignore
877
878 @c Local Variables:
879 @c ispell-local-dictionary: "american"
880 @c End: