1 (***********************************************************************)
5 (* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
7 (* Copyright 2002 Institut National de Recherche en Informatique et *)
8 (* en Automatique. All rights reserved. This file is distributed *)
9 (* under the terms of the GNU Library General Public License, with *)
10 (* the special exception on linking described in file ../LICENSE. *)
12 (***********************************************************************)
16 (** Formatted input functions. *)
18 (** {6 Functional input with format strings.} *)
20 (** The formatted input functions provided by module [Scanf] are functionals
21 that apply their function argument to the values they read in the input.
22 The specification of the values to read is simply given by a format string
23 (the same format strings as those used to print material using module
24 {!Printf} or module {!Format}).
26 As an example, consider the formatted input function [scanf] that reads
27 from standard input; a typical call to [scanf] is simply [scanf fmt f],
28 meaning that [f] should be applied to the arguments read according to the
29 format string [fmt]. For instance, if [f] is defined as [let f x = x + 1],
30 then [scanf "%d" f] will read a decimal integer [i] from [stdin] and return
31 [f i]; thus, if we enter [41] at the keyboard, [scanf "%d" f] evaluates to
34 This module provides general formatted input functions that read from any
35 kind of input, including strings, files, or anything that can return
37 Hence, a typical call to a formatted input function [bscan] is
38 [bscan ib fmt f], meaning that [f] should be applied to the arguments
39 read from input [ib], according to the format string [fmt].
41 The Caml scanning facility is reminiscent of the corresponding C feature.
42 However, it is also largely different, simpler, and yet more powerful: the
43 formatted input functions are higher-order functionals and the parameter
44 passing mechanism is simply the regular function application not the
45 variable assigment based mechanism which is typical of formatted input in
46 imperative languages; the format strings also feature useful additions to
47 easily define complex tokens; as expected of a functional programming
48 language feature, the formatted input functions support polymorphism, in
49 particular arbitrary interaction with polymorphic user-defined scanners.
50 Furthermore, the Caml formatted input facility is fully type-checked at
53 (** {6 Scanning buffers} *)
57 (** The type of scanning buffers. A scanning buffer is the source from which a
58 formatted input function gets characters. The scanning buffer holds the
59 current state of the scan, plus a function to get the next char from the
60 input, and a token buffer to store the string matched so far.
62 Note: a scan may often require to examine one character in advance;
63 when this ``lookahead'' character does not belong to the token read,
64 it is stored back in the scanning buffer and becomes the next
68 (** The scanning buffer reading from [stdin].
69 [stdib] is equivalent to [Scanning.from_channel stdin].
71 Note: when input is read interactively from [stdin], the newline character
72 that triggers the evaluation is incorporated in the input; thus, scanning
73 specifications must properly skip this character (simply add a ['\n']
74 as the last character of the format string). *)
76 val from_string
: string -> scanbuf
;;
77 (** [Scanning.from_string s] returns a scanning buffer which reads from the
79 Reading starts from the first character in the string.
80 The end-of-input condition is set when the end of the string is reached. *)
82 val from_file
: string -> scanbuf
;;
83 (** Bufferized file reading in text mode. The efficient and usual
84 way to scan text mode files (in effect, [from_file] returns a
85 scanning buffer that reads characters in large chunks, rather than one
86 character at a time as buffers returned by [from_channel] do).
87 [Scanning.from_file fname] returns a scanning buffer which reads
88 from the given file [fname] in text mode. *)
90 val from_file_bin
: string -> scanbuf
;;
91 (** Bufferized file reading in binary mode. *)
93 val from_function
: (unit -> char
) -> scanbuf
;;
94 (** [Scanning.from_function f] returns a scanning buffer with the given
95 function as its reading method.
97 When scanning needs one more character, the given function is called.
99 When the function has no more character to provide, it must signal an
100 end-of-input condition by raising the exception [End_of_file]. *)
102 val from_channel
: in_channel
-> scanbuf
;;
103 (** [Scanning.from_channel ic] returns a scanning buffer which reads
104 one character at a time from the input channel [ic], starting at the
105 current reading position. *)
107 val end_of_input
: scanbuf
-> bool;;
108 (** [Scanning.end_of_input ib] tests the end-of-input condition of the given
111 val beginning_of_input
: scanbuf
-> bool;;
112 (** [Scanning.beginning_of_input ib] tests the beginning of input condition of
113 the given scanning buffer. *)
115 val name_of_input
: scanbuf
-> string;;
116 (** [Scanning.file_name_of_input ib] returns the name of the character source
117 for the scanning buffer [ib]. *)
121 exception Scan_failure
of string;;
122 (** The exception raised by formatted input functions when the input cannot be
123 read according to the given format. *)
125 type ('a
, 'b
, 'c
, 'd
) scanner
=
126 ('a
, Scanning.scanbuf
, 'b
, 'c
, 'a
-> 'd
, 'd
) format6
-> 'c
;;
127 (** The type of formatted input scanners: [('a, 'b, 'c, 'd) scanner] is the
128 type of a formatted input function that reads from some scanning buffer
129 according to some format string; more precisely, if [scan] is some
130 formatted input function, then [scan ib fmt f] applies [f] to the arguments
131 specified by the format string [fmt], when [scan] has read those arguments
132 from some scanning buffer [ib].
134 For instance, the [scanf] function below has type [('a, 'b, 'c, 'd)
135 scanner], since it is a formatted input function that reads from [stdib]:
136 [scanf fmt f] applies [f] to the arguments specified by [fmt], reading
137 those arguments from [stdin] as expected.
139 If the format [fmt] has some [%r] indications, the corresponding input
140 functions must be provided before the [f] argument. For instance, if
141 [read_elem] is an input function for values of type [t], then [bscanf ib
142 "%r;" read_elem f] reads a value of type [t] followed by a [';']
145 (** {6 Formatted input functions} *)
147 val bscanf
: Scanning.scanbuf
-> ('a
, 'b
, 'c
, 'd
) scanner
;;
148 (** [bscanf ib fmt r1 ... rN f] reads arguments for the function [f] from the
149 scanning buffer [ib] according to the format string [fmt], and applies [f]
151 The result of this call to [f] is returned as the result of [bscanf].
152 For instance, if [f] is the function [fun s i -> i + 1], then
153 [Scanf.sscanf "x = 1" "%s = %i" f] returns [2].
155 Arguments [r1] to [rN] are user-defined input functions that read the
156 argument corresponding to a [%r] conversion.
158 The format is a character string which contains three types of
160 - plain characters, which are simply matched with the characters of the
162 - conversion specifications, each of which causes reading and conversion of
163 one argument for [f],
164 - scanning indications to specify boundaries of tokens.
166 Among plain characters the space character (ASCII code 32) has a
167 special meaning: it matches ``whitespace'', that is any number of tab,
168 space, line feed and carriage return characters. Hence, a space in the format
169 matches any amount of whitespace in the input.
171 Conversion specifications consist in the [%] character, followed by
172 an optional flag, an optional field width, and followed by one or
173 two conversion characters. The conversion characters and their
176 - [d]: reads an optionally signed decimal integer.
177 - [i]: reads an optionally signed integer
178 (usual input formats for hexadecimal ([0x[d]+] and [0X[d]+]),
179 octal ([0o[d]+]), and binary [0b[d]+] notations are understood).
180 - [u]: reads an unsigned decimal integer.
181 - [x] or [X]: reads an unsigned hexadecimal integer.
182 - [o]: reads an unsigned octal integer.
183 - [s]: reads a string argument that spreads as much as possible,
184 until the next white space, the next scanning indication, or the
185 end-of-input is reached. Hence, this conversion always succeeds:
186 it returns an empty string if the bounding condition holds
187 when the scan begins.
188 - [S]: reads a delimited string argument (delimiters and special
189 escaped characters follow the lexical conventions of Caml).
190 - [c]: reads a single character. To test the current input character
191 without reading it, specify a null field width, i.e. use
192 specification [%0c]. Raise [Invalid_argument], if the field width
193 specification is greater than 1.
194 - [C]: reads a single delimited character (delimiters and special
195 escaped characters follow the lexical conventions of Caml).
196 - [f], [e], [E], [g], [G]: reads an optionally signed
197 floating-point number in decimal notation, in the style [dddd.ddd
199 - [F]: reads a floating point number according to the lexical
200 conventions of Caml (hence the decimal point is mandatory if the
201 exponent part is not mentioned).
202 - [B]: reads a boolean argument ([true] or [false]).
203 - [b]: reads a boolean argument (for backward compatibility; do not use
205 - [ld], [li], [lu], [lx], [lX], [lo]: reads an [int32] argument to
206 the format specified by the second letter (decimal, hexadecimal, etc).
207 - [nd], [ni], [nu], [nx], [nX], [no]: reads a [nativeint] argument to
208 the format specified by the second letter.
209 - [Ld], [Li], [Lu], [Lx], [LX], [Lo]: reads an [int64] argument to
210 the format specified by the second letter.
211 - [\[ range \]]: reads characters that matches one of the characters
212 mentioned in the range of characters [range] (or not mentioned in
213 it, if the range starts with [^]). Reads a [string] that can be
214 empty, if the next input character does not match the range. The set of
215 characters from [c1] to [c2] (inclusively) is denoted by [c1-c2].
216 Hence, [%\[0-9\]] returns a string representing a decimal number
217 or an empty string if no decimal digit is found; similarly,
218 [%\[\\048-\\057\\065-\\070\]] returns a string of hexadecimal digits.
219 If a closing bracket appears in a range, it must occur as the
220 first character of the range (or just after the [^] in case of
221 range negation); hence [\[\]\]] matches a [\]] character and
222 [\[^\]\]] matches any character that is not [\]].
223 - [r]: user-defined reader. Takes the next [ri] formatted input function and
224 applies it to the scanning buffer [ib] to read the next argument. The
225 input function [ri] must therefore have type [Scanning.scanbuf -> 'a] and
226 the argument read has type ['a].
227 - [\{ fmt %\}]: reads a format string argument to the format
228 specified by the internal format [fmt]. The format string to be
229 read must have the same type as the internal format [fmt].
230 For instance, "%\{%i%\}" reads any format string that can read a value of
231 type [int]; hence [Scanf.sscanf "fmt:\\\"number is %u\\\"" "fmt:%\{%i%\}"]
232 succeeds and returns the format string ["number is %u"].
233 - [\( fmt %\)]: scanning format substitution.
234 Reads a format string to replace [fmt]. The format string read
235 must have the same type as [fmt].
236 - [l]: returns the number of lines read so far.
237 - [n]: returns the number of characters read so far.
238 - [N] or [L]: returns the number of tokens read so far.
239 - [!]: matches the end of input condition.
240 - [%]: matches one [%] character in the input.
242 Following the [%] character that introduces a conversion, there may be
243 the special flag [_]: the conversion that follows occurs as usual,
244 but the resulting value is discarded.
245 For instance, if [f] is the function [fun i -> i + 1], then
246 [Scanf.sscanf "x = 1" "%_s = %i" f] returns [2].
248 The field width is composed of an optional integer literal
249 indicating the maximal width of the token to read.
250 For instance, [%6d] reads an integer, having at most 6 decimal digits;
251 [%4f] reads a float with at most 4 characters; and [%8\[\\000-\\255\]]
252 returns the next 8 characters (or all the characters still available,
253 if fewer than 8 characters are available in the input).
255 Scanning indications appear just after the string conversions [%s]
256 and [%\[ range \]] to delimit the end of the token. A scanning
257 indication is introduced by a [@] character, followed by some
258 constant character [c]. It means that the string token should end
259 just before the next matching [c] (which is skipped). If no [c]
260 character is encountered, the string token spreads as much as
261 possible. For instance, ["%s@\t"] reads a string up to the next
262 tab character or to the end of input. If a scanning
263 indication [\@c] does not follow a string conversion, it is treated
264 as a plain [c] character.
266 Raise [Scanf.Scan_failure] if the input does not match the format.
268 Raise [Failure] if a conversion to a number is not possible.
270 Raise [End_of_file] if the end of input is encountered while some more
271 characters are needed to read the current conversion specification.
272 As a consequence, scanning a [%s] conversion never raises exception
273 [End_of_file]: if the end of input is reached the conversion succeeds and
274 simply returns the characters read so far, or [""] if none were read.
276 Raise [Invalid_argument] if the format string is invalid.
280 - the scanning indications introduce slight differences in the
281 syntax of [Scanf] format strings compared to those used by the
282 [Printf] module. However, scanning indications are similar to those
283 of the [Format] module; hence, when producing formatted text to be
284 scanned by [!Scanf.bscanf], it is wise to use printing functions
285 from [Format] (or, if you need to use functions from [Printf],
286 banish or carefully double check the format strings that contain
289 - in addition to relevant digits, ['_'] characters may appear
290 inside numbers (this is reminiscent to the usual Caml lexical
291 conventions). If stricter scanning is desired, use the range
292 conversion facility instead of the number conversions.
294 - the [scanf] facility is not intended for heavy duty lexical
295 analysis and parsing. If it appears not expressive enough for your
296 needs, several alternative exists: regular expressions (module
297 [Str]), stream parsers, [ocamllex]-generated lexers,
298 [ocamlyacc]-generated parsers.
301 val fscanf
: in_channel
-> ('a
, 'b
, 'c
, 'd
) scanner
;;
302 (** Same as {!Scanf.bscanf}, but reads from the given channel.
304 Warning: since all formatted input functions operate from a scanning
305 buffer, be aware that each [fscanf] invocation must allocate a new
306 fresh scanning buffer (unless you make careful use of partial
307 application). Hence, there are chances that some characters seem
308 to be skipped (in fact they are pending in the previously used
309 scanning buffer). This happens in particular when calling [fscanf] again
310 after a scan involving a format that necessitated some look ahead
311 (such as a format that ends by skipping whitespace in the input).
313 To avoid confusion, consider using [bscanf] with an explicitly
314 created scanning buffer. Use for instance [Scanning.from_file f]
315 to allocate the scanning buffer reading from file [f].
317 This method is not only clearer it is also faster, since scanning
318 buffers to files are optimized for fast buffered reading. *)
320 val sscanf
: string -> ('a
, 'b
, 'c
, 'd
) scanner
;;
321 (** Same as {!Scanf.bscanf}, but reads from the given string. *)
323 val scanf
: ('a
, 'b
, 'c
, 'd
) scanner
;;
324 (** Same as {!Scanf.bscanf}, but reads from the predefined scanning
325 buffer {!Scanf.Scanning.stdib} that is connected to [stdin]. *)
328 Scanning.scanbuf
-> (Scanning.scanbuf
-> exn
-> 'd
) ->
329 ('a
, 'b
, 'c
, 'd
) scanner
;;
330 (** Same as {!Scanf.bscanf}, but takes an additional function argument
331 [ef] that is called in case of error: if the scanning process or
332 some conversion fails, the scanning function aborts and calls the
333 error handling function [ef] with the scanning buffer and the
334 exception that aborted the scanning process. *)
337 Scanning.scanbuf
-> ('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
->
338 (('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
-> 'g
) -> 'g
;;
339 (** [bscanf_format ib fmt f] reads a format string token from the scannning
340 buffer [ib], according to the given format string [fmt], and applies [f] to
341 the resulting format string value.
342 Raise [Scan_failure] if the format string value read doesn't have the
343 same type as [fmt]. *)
346 string -> ('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
->
347 (('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
-> 'g
) -> 'g
;;
348 (** Same as {!Scanf.bscanf_format}, but reads from the given string. *)
350 val format_from_string
:
352 ('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
-> ('a
, 'b
, 'c
, 'd
, 'e
, '
f) format6
;;
353 (** [format_from_string s fmt] converts a string argument to a format string,
354 according to the given format string [fmt].
355 Raise [Scan_failure] if [s], considered as a format string, doesn't
356 have the same type as [fmt]. *)