1@node Library modules - Utilities, C to Scheme mapping, Library modules - SRFIs, Top
2@chapter Library modules - Utilities
3@c NODE ライブラリモジュール - ユーティリティ
4
5
6@c ----------------------------------------------------------------------
7@menu
8* Binary I/O::                  binary.io
9* Packing binary data::         binary.pack
10* Running Chibi-scheme test suite::  compat.chibi-test
11* Rational-less arithmetic::    compat.norational
12* A common job descriptor for control modules::  control.job
13* Thread pools::                control.thread-pool
14* Password hashing::            crypt.bcrypt
15* Cache::                       data.cache
16* Heap::                        data.heap
17* Immutable deques::            data.ideque
18* Immutable map::               data.imap
19* Priority map::                data.priority-map
20* Queue::                       data.queue
21* Random data generators::      data.random
22* Ring buffer::                 data.ring-buffer
23* Skew binary random-access lists::  data.skew-list
24* Sparse data containers::      data.sparse
25* Trie::                        data.trie
26* Database independent access layer::  dbi
27* Generic DBM interface::       dbm
28* File-system dbm::             dbm.fsdbm
29* GDBM interface::              dbm.gdbm
30* NDBM interface::              dbm.ndbm
31* Original DBM interface::      dbm.odbm
32* Filtering file content::      file.filter
33* Filesystem utilities::        file.util
34* Mathematic constants::        math.const
35* Mersenne-Twister random number generator::  math.mt-random
36* Prime numbers::               math.prime
37* Windows support::             os.windows
38* PEG parser combinators::      parser.peg
39* RFC822 message parsing::      rfc.822
40* Base64 encoding/decoding::    rfc.base64
41* HTTP cookie handling::        rfc.cookie
42* FTP::                         rfc.ftp
43* HMAC keyed-hashing::          rfc.hmac
44* HTTP::                        rfc.http
45* ICMP packets::                rfc.icmp
46* IP packets::                  rfc.ip
47* JSON parsing and construction::  rfc.json
48* MD5 message digest::          rfc.md5
49* MIME message handling::       rfc.mime
50* Quoted-printable encoding/decoding::  rfc.quoted-printable
51* SHA message digest::          rfc.sha
52* Transport layer security::    rfc.tls
53* URI parsing and construction::  rfc.uri
54* UUID::                        rfc.uuid
55* Zlib compression library::    rfc.zlib
56* SLIB::                        slib
57* Functional XML parser::       sxml.ssax
58* SXML query language::         sxml.sxpath
59* Manipulating SXML structure::  sxml.tools
60* Serializing XML and HTML from SXML::  sxml.serializer
61* Text terminal control::       text.console
62* CSV tables::                  text.csv
63* Calculate difference of text streams::  text.diff
64* EDN parsing and construction::  text.edn
65* Running external editor::     text.external-editor
66* Gap buffer::                  text.gap-buffer
67* Localized messages::          text.gettext
68* Simple HTML document construction::  text.html-lite
69* Display with pager::          text.pager
70* Parsing input stream::        text.parse
71* Showing progress on text terminals::  text.progress
72* SQL parsing and construction::  text.sql
73* Simple template expander::    text.template
74* Transliterate characters::    text.tr
75* Lazy text construction::      text.tree
76* Combination library::         util.combinations
77* Message digester framework::  util.digest
78* Calculate dominator tree::    util.dominator
79* Determine isomorphism::       util.isomorph
80* The longest common subsequence::  util.lcs
81* Levenshtein edit distance::   util.levenshtein
82* Pattern matching::            util.match
83* SLIB-compatible record type::  util.record
84* Relation framework::          util.relation
85* Stream library::              util.stream
86* Topological sort::            util.toposort
87* Unification::                 util.unification
88* CGI utility::                 www.cgi
89* CGI testing::                 www.cgi.test
90* CSS parsing and construction::  www.css
91@end menu
92
93@c ----------------------------------------------------------------------
94@node Binary I/O, Packing binary data, Library modules - Utilities, Library modules - Utilities
95@section @code{binary.io} - Binary I/O
96@c NODE バイナリI/O, @code{binary.io} - バイナリI/O
97
98@deftp {Module} binary.io
99@mdindex binary.io
100@c EN
101This module provides basic procedures to perform binary I/O
102of numeric data.  Each datum can be read from or written to a port,
103and got from or put to a uniform vector (see @ref{Uniform vectors}).
104For structured binary data I/O,
105more convenient @code{pack} utility is implemented
106on top of this module (see @ref{Packing binary data}).
107You might want to use this module directly if you need
108speed or want a flexible control of endianness.
109
110See also @ref{Uniform vectors}, which provides binary block I/O.
111@c JP
112このモジュールは数値データを読み書きするバイナリ入出力用の基本手続きを提
113供します。各データはポートあるいはユニフォームベクタ
114(@ref{Uniform vectors}参照)から読み込み、あるいはそれらへ書き出すことが
115できます。
116構造をもつバイナリデータの入出力については、便利な
117@code{pack}ユーティリティがこのモジュールを使って実装されています
118(@ref{Packing binary data}を参照してください)。
119スピードあるいはエンディアンの柔軟な制御などをやりたいときにこのモジュー
120ルが使えます。
121
122バイナリのブロック入出力については@ref{Uniform vectors}を参照してくだ
123さい。
124@c COMMON
125@end deftp
126
127@c EN
128@subheading Endianness
129Most procedures of this module take an optional @var{endian} argument,
130specifying the byte order of the binary input.
131It must be either one of symbols @code{big-endian}, @code{little-endian},
132or @code{arm-little-endian}.
133If the endian argument is omitted, the current value of the builtin
134parameter @code{default-endian} is used (@pxref{Endianness}).
135(For 8-bit I/O procedures like @code{read-u8} the endian
136argument has no effect, but is accepted for consistency).
137@c JP
138@subheading エンディアン
139このモジュールのほとんどの手続はオプション引数として@var{endian}引数を
140とります。これは@code{big-endian}、@code{little-endian}、
141@code{arm-little-endian}のいずれかのシンボルでなければなりません。
142エンディアン引数が省略された場合には、組込みパラメータ@code{default-endian}
143の現在値が使われます (@ref{Endianness}参照)。
144(@code{read-u8}の ような
1458ビット入出力手続ではエンディアン引数は意味がありませんが、
146一貫性のため受け入れるようにしてあります。)
147@c COMMON
148
149@c EN
150@subheading I/O using port
151@c JP
152@subheading ポートを用いたI/O
153@c COMMON
154
155@defun read-u8 :optional port endian
156@defunx read-u16 :optional port endian
157@defunx read-u32 :optional port endian
158@defunx read-u64 :optional port endian
159@c MOD binary.io
160@c EN
161Reads 8, 16, 32 or 64 bit unsigned integer from @var{port}
162with specified endian, respectively.  If @var{port} is omitted,
163current input port is used.  If @var{port} reaches EOF before
164a complete integer is read, EOF is returned.
165@c JP
166それぞれ指定したエンディアンで@var{port}から8、16、32、64ビット符号無
167整数を読み込みます。@var{port}が省略された場合は、現在の入力ポートが使
168われます。@var{port}が整数の読み込みが完了する前にEOFに到達してしまっ
169た場合にはEOFが返ります。
170@c COMMON
171@end defun
172
173@defun read-s8 :optional port endian
174@defunx read-s16 :optional port endian
175@defunx read-s32 :optional port endian
176@defunx read-s64 :optional port endian
177@c MOD binary.io
178@c EN
179Reads 8, 16, 32 or 64 bit 2's complement signed integer from @var{port}
180with specified endian, respectively.  If @var{port} is omitted,
181current input port is used.  If @var{port} reaches EOF before
182a complete integer is read, EOF is returned.
183@c JP
184それぞれ指定したエンディアンで@var{port}から8、16、32、64ビット、2の補
185数符号付き整数を読み込みます。@var{port}が省略された場合は、現在の入力
186ポートが使われます。@var{port}が整数の読み込みが完了する前にEOFに到
187達してしまった場合にはEOFが返ります。
188@c COMMON
189@end defun
190
191@defun read-uint size :optional port endian
192@defunx read-sint size :optional port endian
193@c MOD binary.io
194@c EN
195More flexible version.  Reads @var{size}-octet unsigned
196or signed integer from @var{port} with specified endian.
197If @var{port} reaches EOF before a complete integer is read,
198EOF is returned.
199@c JP
200さらに柔軟性が高く、@var{size}オクテットの符号無しあるいは符号付き整数
201を@var{port}から指定のエンディアンで読み込みます。
202@var{port}が整数の読み込みが完了する前にEOFに到
203達してしまった場合にはEOFが返ります。
204@c COMMON
205@end defun
206
207@defun read-ber-integer :optional port
208@c MOD binary.io
209@c EN
210Reads BER compressed integer a la X.209.
211A BER compressed integer is an unsigned integer in base 128,
212most  significant digit first, where the high bit is set on all but the
213final (least significant) byte.
214@c JP
215X.209のBER圧縮形式整数を読み込みます。BER圧縮形式整数は128進符号無し整
216数です。最上位桁が最初にきます。最下位桁のバイトをのぞき、すべてのバイ
217トの最上位ビットはオンになっています。
218@c COMMON
219@end defun
220
221@defun write-u8 val :optional port endian
222@defunx write-u16 val :optional port endian
223@defunx write-u32 val :optional port endian
224@defunx write-u64 val :optional port endian
225@c MOD binary.io
226@c EN
227Writes a nonnegative integer @var{val} as 8, 16, 32 or 64 bit
228unsigned integer
229to @var{port} with specified endian, respectively.  @var{Val} must be within
230the range of integers representable by the specified bits.
231When @var{port} is omitted, current output port is used.
232@c JP
233それぞれ指定したエンディアンで@var{port}へ 8、16、32、64ビット、符号無
234し整数として表現されている非負整数@var{val}を書き出します。
235@var{val}はそれぞれ指定したビット数の範囲で表現できる値でなければなり
236ません。@var{port}が省略された場合は、現在の出力ポートが使われます。
237@c COMMON
238@end defun
239
240@defun write-s8 val :optional port endian
241@defunx write-s16 val :optional port endian
242@defunx write-s32 val :optional port endian
243@defunx write-s64 val :optional port endian
244@c MOD binary.io
245@c EN
246Writes an integer @var{val} as 8, 16, 32 or 64 bit
247as 2's complement signed integer to @var{port} with specified endian,
248respectively.  @var{Val} must be within
249the range of integers representable by the specified bits.
250When @var{port} is omitted, current output port is used.
251@c JP
252それぞれ指定したエンディアンで@var{port}へ 8、16、32、64ビット、2の補
253数符号付き整数として表現されている整数@var{val}を書き出します。
254@var{val}はそれぞれ指定したビット数の範囲で表現できる値でなければなり
255ません。@var{port}が省略された場合は、現在の出力ポートが使われます。
256@c COMMON
257@end defun
258
259@defun write-uint size val :optional port endian
260@defunx write-sint size val :optional port endian
261@c MOD binary.io
262@c EN
263More flexible version.  Writes an integer @var{val} as unsigned
264or signed integer of @var{size} bytes to @var{port} with
265specified endian.
266When @var{port} is omitted, current output port is used.
267@c JP
268さらに柔軟性が高く、@var{size}オクテットの符号無しあるいは符号付き整数
269@var{val}を@var{port}へ、指定のエンディアンで書き出します。
270@var{port}が省略された場合は、現在の出力ポートが使われます。
271@c COMMON
272@end defun
273
274@defun write-ber-integer val :optional port
275@c MOD binary.io
276@c EN
277Writes a nonnegative integer @var{val} in BER compressed integer
278to @var{port}.  See @code{read-ber-integer} above for BER format.
279@c JP
280BER圧縮形式の非負整数@var{val}を@var{port}へ書き出します。
281BER圧縮形式については前述の@code{read-ber-integer}を見てください。
282@c COMMON
283@end defun
284
285@defun read-f16 :optional port endian
286@defunx read-f32 :optional port endian
287@defunx read-f64 :optional port endian
288@c MOD binary.io
289@c EN
290Reads 16, 32, or 64-bit floating point numbers, respectively.
29132bit is IEEE754 single-precision, and 64bit is
292IEEE754 double-precision numbers.  16-bit floating
293point number consists of 1-bit sign, 5-bit exponent and
29410-bit mantissa, as used in some HDR image format.
295
296If @var{port} is omitted,
297current input port is used.  If @var{port} reaches EOF before
298a complete number is read, EOF is returned.
299@c JP
300それぞれ、16、32、64ビットの浮動小数点数を読み込みます。
30132ビットはIEEE754単精度、64ビットは倍精度の浮動小数点数です。
30216ビット浮動小数点数は、1ビットの符号、5ビットの指数、10ビットの仮数からなる、
303HDRイメージフォーマット等に使われている形式です。
304
305@var{port}が省略された場合には、
306現在の入力ポートが使われます。@var{port}が数値の読み込みが完了する前に
307EOFに到達してしまった場合にはEOFが返ります。
308@c COMMON
309@end defun
310
311@defun write-f16 val :optional port endian
312@defunx write-f32 val :optional port endian
313@defunx write-f64 val :optional port endian
314@c MOD binary.io
315@c EN
316Writes a real number @var{val} to @var{port} in 16,
31732, or 64-bit floating point number, respectively.
318If @var{port} is omitted, current output port is used.
319@c JP
320実数値@var{val}を、それぞれ16、32、64ビットの浮動小数点数として
321書き出します。
322@var{port}が省略された場合には、現在の出力ポートが使われます。
323@c COMMON
324@end defun
325
326
327@c EN
328@subheading I/O using uniform vectors
329@c JP
330@subheading ユニフォームベクタを用いたI/O
331@c COMMON
332
333@c EN
334In the following routines, the argument @var{uv} can be any
335type of uniform vector; if it is not a @code{u8vector}, it is
336treated as if @code{(uvector-alias <u8vector> @var{uv})} is
337called---that is, it reads directly from the memory image
338that holds the uvector's content.  The @var{pos} argument
339specifies the byte position from the beginning of the memory
340area (it is always byte position, regardless of the uniform
341vector's element size).
342@c JP
343以下のルーチンでは、引数 @var{uv} は任意の型のユニフォームベクタをとり
344えます。@code{u8vector} ではない場合には @code{(uvector-alias
345<u8vector> @var{uv})} が呼ばれたのと同様の扱いになります。すなわち、
346uvectorの内容を保持するメモリイメージから直接読み込まれます。@var{pos}
347引数は当該のメモリ領域の最初からのバイト位置を指定するのに使います(こ
348れはユニフォームベクタの要素のサイズにかかわらず、つねにバイト位置です)。
349@c COMMON
350
351@defun get-u8 uv pos :optional endian
352@defunx get-u16 uv pos :optional endian
353@defunx get-u32 uv pos :optional endian
354@defunx get-u64 uv pos :optional endian
355@defunx get-s8 uv pos :optional endian
356@defunx get-s16 uv pos :optional endian
357@defunx get-s32 uv pos :optional endian
358@defunx get-s64 uv pos :optional endian
359@defunx get-f16 uv pos :optional endian
360@defunx get-f32 uv pos :optional endian
361@defunx get-f64 uv pos :optional endian
362@c MOD binary.io
363@c EN
364Reads a number of a specific format from a uniform vector @var{uv},
365starting at a byte position @var{pos}.  An error is signaled
366if the specified position makes reference outside of the uniform
367vector's content.  Returns the read number.
368@c JP
369ユニフォームベクタ @var{uv} のバイト位置 @var{pos} から指定したフォー
370マットで数値を読み込み、その数値を返します。指定した位置が当該ユニフォー
371ムベクタの内容のある範囲外を参照するものであった場合、エラーを示すシグ
372ナルがあがります。
373@c COMMON
374@end defun
375
376@defun get-u16be uv pos
377@defunx get-u16le uv pos
378@defunx get-u32be uv pos
379@defunx get-u32le uv pos
380@defunx get-u64be uv pos
381@defunx get-u64le uv pos
382@defunx get-s16be uv pos
383@defunx get-s16le uv pos
384@defunx get-s32be uv pos
385@defunx get-s32le uv pos
386@defunx get-s64be uv pos
387@defunx get-s64le uv pos
388@defunx get-f16be uv pos
389@defunx get-f16le uv pos
390@defunx get-f32be uv pos
391@defunx get-f32le uv pos
392@defunx get-f64be uv pos
393@defunx get-f64le uv pos
394@c MOD binary.io
395@c EN
396These are big-endian (@code{be}) or little-endian (@code{le}) specific
397versions of @code{get-*} procedures.  In speed-sensitive code,
398you might want to use these to avoid the overhead of optional-argument
399handling.
400@c JP
401これらは、@code{get-*} 手続のエンディアン(ビッグエンディアン @code{be}
402あるいはリトルエンディアン @code{le})を指定した版です。スピードを要求
403されるコードではオプション引数処理のオーバーヘッドを避けるためこちらを
404使うのがいいでしょう。
405@c COMMON
406@end defun
407
408@defun get-uint size uv pos :optional endian
409@defunx get-sint size uv pos :optional endian
410@c MOD binary.io
411@c EN
412Read @var{size} octets from uvector @var{uv},
413starting from @var{pos}-th octet, as an unsigned or signed integer,
414respectively.
415@c JP
416ユニフォームベクタ@var{uv}の@var{pos}番目のオクテットから@var{size}オクテットを、
417それぞれ符号無し、符号つき整数として読み取ります。
418@c COMMON
419
420@example
421(get-uint 3 '#u8(1 2 3 4) 1 'big-endian)
422  @result{} 131884 ; @r{#x020304}
423
424(get-sint 3 '#u9(1 2 3 #xff) 1 'little-endian)
425  @result{} -64766 ; @r{sign extended #xff0302}
426@end example
427@end defun
428
429@defun put-u8! uv pos val :optional endian
430@defunx put-u16! uv pos val :optional endian
431@defunx put-u32! uv pos val :optional endian
432@defunx put-u64! uv pos val :optional endian
433@defunx put-s8! uv pos val :optional endian
434@defunx put-s16! uv pos val :optional endian
435@defunx put-s32! uv pos val :optional endian
436@defunx put-s64! uv pos val :optional endian
437@defunx put-f16! uv pos val :optional endian
438@defunx put-f32! uv pos val :optional endian
439@defunx put-f64! uv pos val :optional endian
440@c MOD binary.io
441@c EN
442Writes a number @var{val} into a uniform vector @var{uv} in
443a specific format, starting at a byte position @var{pos}.
444An error is signaled
445if the specified position makes reference outside of the uniform
446vector's content.
447@c JP
448数値 @var{val} をユニフォームベクタ @var{uv} のバイト位置 @var{pos} か
449ら指定されたフォーマットで書き出します。指定した位置が当該ユニフォーム
450ベクタの内容のある範囲外を参照するものであった場合、エラーを示すシグナ
451ルがあがります。
452@c COMMON
453@end defun
454
455@defun put-u16be! uv pos val
456@defunx put-u16le! uv pos val
457@defunx put-u32be! uv pos val
458@defunx put-u32le! uv pos val
459@defunx put-u64be! uv pos val
460@defunx put-u64le! uv pos val
461@defunx put-s16be! uv pos val
462@defunx put-s16le! uv pos val
463@defunx put-s32be! uv pos val
464@defunx put-s32le! uv pos val
465@defunx put-s64be! uv pos val
466@defunx put-s64le! uv pos val
467@defunx put-f16be! uv pos val
468@defunx put-f16le! uv pos val
469@defunx put-f32be! uv pos val
470@defunx put-f32le! uv pos val
471@defunx put-f64be! uv pos val
472@defunx put-f64le! uv pos val
473@c MOD binary.io
474@c EN
475These are big-endian (@code{be}) or little-endian (@code{le}) specific
476versions of @code{put-*} procedures.  In speed-sensitive code,
477you might want to use these to avoid the overhead of optional-argument
478handling.
479@c JP
480これらは、@code{put-*} 手続のエンディアン(ビッグエンディアン @code{be}
481あるいはリトルエンディアン @code{le})を指定した版です。スピードを要求
482されるコードではオプション引数処理のオーバーヘッドを避けるためこちらを
483使うのがいいでしょう。
484@c COMMON
485@end defun
486
487@defun put-uint! size uv pos val :optional endian
488@defunx put-sint! size uv pos val :optional endian
489@c MOD binary.io
490@c EN
491Write an unsigned or signed integer @var{val} into
492an uvector @var{uv} starting from @var{pos}-th octet,
493for @var{size} octets, respectively.
494@c JP
495それぞれ符号無しまたは符号つき整数@var{val}を、
496ユニフォームベクタ@var{uv}の@var{pos}番目のオクテットから@var{size}オクテット分に
497書き込みます。
498@c COMMON
499@end defun
500
501
502@c EN
503@subheading Compatibility notes
504@c JP
505@subheading 互換性への注
506@c COMMON
507
508@c EN
509@code{read-u8} etc. were called @code{read-binary-uint8} etc., and
510@code{read-f32} and @code{read-f64} were called @code{read-binary-float}
511and @code{read-binary-double}, respectively.
512These old names are still supported for the backward compatibility
513but their use is deprecated.  The reason of the changes is
514for brevity and for consistency with the uniform vectors.
515@c JP
516@code{read-u8} などは @code{read-binary-uint8} と呼ばれていたもので、
517@code{read-f32} や @code{read-f64} はそれぞれ @code{read-binary-float}、
518@code{read-binary-double} と呼ばれていたものです。
519これらの古い名前は後方互換のためいまのところサポートされていますが、使
520用については非推奨とします。この変更は名前の短縮とユニフォームベクタと
521の一貫性維持のために行われました。
522@c COMMON
523
524@c ----------------------------------------------------------------------
525@node Packing binary data, Running Chibi-scheme test suite, Binary I/O, Library modules - Utilities
526@section @code{binary.pack} - Packing binary data
527@c NODE バイナリデータのパック, @code{binary.pack} - バイナリデータのパック
528
529@deftp {Module} binary.pack
530@mdindex binary.pack
531@c EN
532This module provides an interface for packing and unpacking (writing
533and reading) binary data with templates.  The functionality was
534inspired largely by the Perl pack/unpack functions, with comparison of
535similar features from other languages, however an effort was made to
536make it more general and more efficient, to be usable for
537database-like processing.  To that end, the most notable differences
538are that any packable value is unpackable (and vice versa), and the
539default behavior is to pack and unpack using port I/O, so you can seek
540in a large file and unpack from it.  Also, templates may be stored as
541dispatch closures to pack, unpack or even skip over values without
542re-parsing the template.
543@c JP
544このモジュールは、バイナリデータをテンプレートを使って
545パック/アンパック(読み書き)するためのインタフェースを提供します。
546この機能は、その多くをPerlのpack/unpack関数から着想し、他の言語での
547同じような機能と比較しながら、しかし、データベースライクな処理に
548便利なように、より一般的でより効率が良くなるように実装しました。
549これを受けて、最も大きな相違点は、全てのパック可能な値はアンパック
550可能で(逆も同様)、パック/アンパックのデフォルトの振る舞いはポートI/Oを
551使うので、巨大なファイルを読みながらそこからアンパックすることが
552できます。また、テンプレートはディスパッチクロージャとして格納でき、
553パック、アンパック、あるいは値のスキップさえも、テンプレートを
554パーズし直すことなく行えます。
555@c COMMON
556
557@c See also binary.io - Binary I/O for utilities to read and write
558@c individual binary values.
559@end deftp
560
561@defun pack template list :key output to-string?
562@c MOD binary.pack
563@c EN
564Writes the values in @var{list} to the current output port, according
565to the format specified by the string @var{template}.  The template
566string is a series of single character codes, optionally followed by a
567numeric count (which defaults to 1).
568@c JP
569@var{list}にある値を、文字列@var{template}で指定されたフォーマットに
570したがって、現在の出力ポートに書き出します。テンプレート文字列は、
5711文字のコードの連続で、オプションで(デフォルトが1である)カウント用の数字
572が続きます。
573
574@c EN
575The format characters can generally be divided into string types,
576which interpret the count as a string byte size, and object types,
577which treat the count as a repetition indicator.  The count may be
578specified as the character @code{*}, which means to use the full
579size of the string for string types, and use all remaining values for
580object types.
581@c JP
582フォーマット文字は一般的に、カウントを文字のバイト数と解釈する
583文字列型と、カウントを繰り返し指示子と解釈するオブジェクト型に
584分けられます。カウントは文字@code{*}で指定され、文字列型では
585文字列の全体の長さを、オブジェクト型では残りの全ての値を使うことを
586意味します。
587
588@c EN
589Counts may also be specified as a template enclosed in brackets, which
590means the count is the byte size of the enclosed template.  For
591example, @code{x[L]} skips a long.
592@c JP
593カウントは大括弧に囲まれたテンプレートとしても指定でき、その場合
594カウントはその大括弧を囲んでいるテンプレートのバイト数を意味します。
595例えば、@code{x[L]}はlongをスキップします。
596
597@c EN
598The special format character @code{/} may be used to indicate a
599structure where the packed data contains a dynamic count followed by
600the value itself.  The template is written as
601@code{<count-item>/<value-item>}, where @code{<count-item>} is any
602template character to be interpreted as a numeric count, and
603@code{<value-item>} is any other template character to use this count.
604If a normal count is given after @code{<value-item>} it is ignored.
605@c JP
606特別なフォーマット文字@code{/}は、パックされたデータが、値に続く
607動的なカウント分を含むという構造を表すために使われます。
608テンプレートは、@code{<count-item>/<value-item>}のように書かれ、
609ここでは@code{<count-item>}は数値のカウントと解釈されるいかなる
610テンプレート文字、@code{<value-item>}はこのカウントを使ういかなる
611他のテンプレート文字です。
612@code{<value-item}>の後に通常のカウントが与えられても、無視されます。
613
614@c EN
615The format character @code{@@} may be used with a count to pad to an
616absolute position since the start of the template.
617@c JP
618フォーマット文字@code{@@}は、カウントとともに使われ、テンプレートの
619最初からの絶対位置までパディングします。
620
621@c EN
622Sub-templates may be grouped inside parentheses.  If angle-brackets
623are used, then they also behave as group operators but recursively
624operate on nested lists.
625@c JP
626サブテンプレートは、括弧の中にグループ化されます。<>が使われると、
627ネストされたリストに再帰的に適用されるグループ化オペレータとしても
628振舞います。
629
630@c EN
631The string types:
632@c JP
633文字列型:
634
635@c COMMON
636@table @code
637@item a
638@c EN
639An arbitrary incomplete string, null padded.
640@c JP
641任意の不完全文字列。NULLでパディングされます。
642@c COMMON
643
644@item A
645@c EN
646A text string, space padded.
647@c JP
648テキスト文字列。空白スペースでパディングされます。
649@c COMMON
650
651@item Z
652@c EN
653A null terminated (ASCIZ) string, null padded.
654@c JP
655NULL終端(ASCIZ)文字列。NULLでパディングされます。
656@c COMMON
657
658@item b
659@c EN
660A bit string (ascending bit order inside each byte).
661@c JP
662ビット文字列(それぞれのバイトにおけるビットオーダーは昇順)。
663@c COMMON
664
665@item B
666@c EN
667A bit string (descending bit order inside each byte).
668@c JP
669ビット文字列(それぞれのバイトにおけるビットオーダーは降順)。
670@c COMMON
671
672@item h
673@c EN
674A hex string (low nybble first).
675@c JP
67616進文字列(低いニブルが先)。
677@c COMMON
678
679@item H
680@c EN
681A hex string (high nybble first).
682@c JP
68316進文字列(高いニブルが先)。
684@c COMMON
685@end table
686
687@c EN
688The object types:
689@c JP
690オブジェクト型:
691@c COMMON
692
693@table @code
694@item c
695@c EN
696A signed 8bit integer.
697@c JP
698符号付き8ビット整数。
699@c COMMON
700
701@item C
702@c EN
703An unsigned 8bit integer.
704@c JP
705符号なし8ビット整数。
706@c COMMON
707
708@item s
709@c EN
710A signed short (16 bit) value.
711@c JP
712符号付き16ビット整数。
713@c COMMON
714
715@item S
716@c EN
717An unsigned short (16 bit) value.
718@c JP
719符号なし16ビット整数。
720@c COMMON
721
722@item i
723@c EN
724A signed integer (>= 32 bit) value.
725@c JP
726符号付き整数(>= 32ビット)。
727@c COMMON
728
729@item I
730@c EN
731An unsigned integer (>= 32 bit) value.
732@c JP
733符号なし整数(>= 32ビット)。
734@c COMMON
735
736@item l
737@c EN
738A signed long (32 bit) value.
739@c JP
740符号付きlong(32ビット)。
741@c COMMON
742
743@item L
744@c EN
745An unsigned long (32 bit) value.
746@c JP
747符号なしlong(32ビット)。
748@c COMMON
749
750@item n, n!
751@c EN
752An unsigned and signed short (16 bit) in "network" (big-endian) order.
753@c JP
754ネットワークオーダー(ビッグエンディアン)での符号なし/符号つきshort(16ビット)。
755@c COMMON
756
757@item N, N!
758@c EN
759An unsigned and signed long (32 bit) in "network" (big-endian) order.
760@c JP
761ネットワークオーダー(ビッグエンディアン)での符号なし/符号つきlong(32ビット)。
762@c COMMON
763
764@item v, v!
765@c EN
766An unsigned and signed short (16 bit) in "VAX" (little-endian) order.
767@c JP
768VAXオーダー(リトルエンディアン)での符号なし/符号つきshort(16ビット)。
769@c COMMON
770
771@item V, V!
772@c EN
773An unsigned and signed long (32 bit) in "VAX" (little-endian) order.
774@c JP
775VAXオーダー(リトルエンディアン)での符号なし/符号つきlong(32ビット)。
776@c COMMON
777
778@item q
779@c EN
780A signed quad (64 bit) value.
781@c JP
782符号付きquad(64ビット)。
783@c COMMON
784
785@item Q
786@c EN
787An unsigned quad (64 bit) value.
788@c JP
789符号なしquad(64ビット)。
790@c COMMON
791
792@item f
793@c EN
794A single-precision float in the native format.
795@c JP
796ネイティブ形式の単精度float。
797@c COMMON
798
799@item d
800@c EN
801A double-precision float in the native format.
802@c JP
803ネイティブ形式の倍精度float。
804@c COMMON
805
806@item w
807@c EN
808A BER compressed integer.  An unsigned integer in base 128, most
809significant digit first, where the high bit is set on all but the
810final (least significant) byte.  Thus any size integer can be encoded,
811but the encoding is efficient and small integers don't take up any
812more space than they would in normal char/short/int encodings.
813@c JP
814BER圧縮された整数。ベース128における符号なし整数で、最も大きな桁が
815最初で、高いビットが最後の(一番小さな)バイト以外にセットされる。
816したがって、どのような大きさの整数もエンコードできるが、
817エンコーディングは効率的で、小さな整数は通常のchar/short/int
818エンコーディングの場合よりも占有する空間が少ない。
819@c COMMON
820
821@item x
822@c EN
823A null byte.
824@c JP
825NULLバイト。
826@c COMMON
827
828@item o
829@c EN
830An sexp, handled with @code{read} and @code{write}.
831@c JP
832S式。@code{read}と@code{write}で扱われる。
833@c COMMON
834
835@end table
836
837@c EN
838If the optional keyword @var{:output} is given that port is used
839instead of the current output port.  If @var{:to-string?} is given and
840true, then pack accumulates and returns the output as a string.
841
842Note that the returned string may be an incomplete string
843if the packed string contains a byte sequence invalid as
844a character sequence.
845@c JP
846オプションのキーワード@var{:output}が与えられると、
847現在の出力ポートの代わりにそのポートが使われます。
848@var{:to-string?}が与えられそれが真である場合は、
849パックは蓄積され、その出力は文字列として返ります。
850@c COMMON
851
852@example
853(pack "CCCC" '(65 66 67 68) :to-string? #t)
854 @result{} "ABCD"
855
856(pack "C/a*" '("hello") :to-string? #t)
857 @result{} "\x05hello"
858@end example
859@end defun
860
861@defun unpack template :key :input :from-string
862@c MOD binary.pack
863@c EN
864The complement of pack, unpack reads values from the current input
865port assuming they've been packed according to the string template and
866returns the values as a list.  unpack accepts the same format strings
867as pack.  Further, the following tautology holds:
868@c JP
869packの逆を行うもので、unpackは現在の入力ポートから、値が文字列の
870templateでパックされているものとして読み込み、その値をリストとして
871返します。unpackはpackと同じフォーマット文字列を受け付けます。
872また、いかなるリスト@var{x}とフォーマット文字列@var{fmt}においても、
873次のようなトートロジーが維持されます。
874@c COMMON
875
876@example
877(equal? x (unpack fmt :from-string (pack fmt x :to-string? #t)))
878@end example
879
880@c EN
881for any list @var{x} and format string @var{fmt}.  The only exceptions
882to this are when the template includes a @code{*} and when the
883@code{o} template is used, since Scheme numeric literals cannot be
884reliably delimited (though future versions of @code{pack} may
885circumvent this by registering a new read syntax).
886
887If the optional keyword @var{:input} is given that port is used
888instead of the current input port.  If @var{:from-string} is given,
889then pack reads input from that string.
890@c JP
891ただ一つの例外は、テンプレートが@code{*}を含み、@code{o}テンプレートが
892使われている場合です。これは、Schemeの数値リテラルは確実に区切られる
893ことができないからです(@code{pack}の将来のバージョンでは、
894新しいread構文を登録することによってこれは回避されるでしょう)。
895
896オプションのキーワード@var{:input}が与えられると、現在の入力ポートの
897代わりにそのポートが使われます。@var{:from-string}が与えられると、
898packはその文字列を入力とします。
899@c COMMON
900
901@example
902(unpack "CCCC" :from-string "ABCD")
903 @result{} '(65 66 67 68)
904
905(unpack "C/a*" :from-string "\x05hello")
906 @result{} '("hello")
907@end example
908
909@c EN
910@emph{Note:} in the current version, @code{@@} in @code{unpack}
911template has a bug and does not work as supposed.  It will
912be fixed in the future version.
913@c JP
914@emph{註:} 現在のバージョンには、@code{unpack}のテンプレートの
915@code{@@}が想定したように動かないというバグがあります。
916将来のバージョンでfixされます。
917@c COMMON
918@end defun
919
920@defun unpack-skip template :key :input
921@c MOD binary.pack
922@c EN
923unpack-skip is the same as unpack except it does not return the
924values.  In some cases, particularly with fixed-size templates, this
925can be much more efficient when you just want to skip over a value.
926@c JP
927unpack-skipは、値を返さないことを除いてunpackと同じです。
928いくつかのケースでは、特に固定サイズのテンプレートを使うときには、
929単に値を読み飛ばしたいときにより効率的です。
930@c COMMON
931@end defun
932
933@defun make-packer template
934@c MOD binary.pack
935@c EN
936The low-level interface.  This function returns a dispatch closure
937that can be used to pack, unpack and skip over the same cached
938template.  The dispatch closure accepts symbol methods as follows:
939@c JP
940低レベルなインタフェースです。この関数は、pack、unpackやキャッシュ
941された同じテンプレートを読み飛ばす時に使われるディスパッチクロージャを
942返します。ディスパッチクロージャは、以下のようにシンボルメソッドを
943受け付けます。
944@c COMMON
945
946@table @code
947@item 'pack list
948@c EN
949pack the items in list to the current output port.
950@c JP
951listにあるアイテムを、現在の出力ポートへpackします。
952@c COMMON
953
954@item 'unpack
955@c EN
956unpack items from the current input port.
957@c JP
958現在の入力ポートからアイテムをunpackします。
959@c COMMON
960
961@item 'skip
962@c EN
963skip items from the current input port.
964@c JP
965現在の入力ポートからのアイテムをスキップします。
966@c COMMON
967
968@item 'packer
969@c EN
970return the cached 'pack closure
971@c JP
972キャッシュされた'packクロージャを返します。
973@c COMMON
974
975@item 'unpacker
976@c EN
977return the cached 'unpack closure.
978@c JP
979キャッシュされた'unpackクロージャを返します。
980@c COMMON
981
982@item 'skipper
983@c EN
984return the cached 'skip closure.
985@c JP
986キャッシュされた'skipクロージャを返します。
987@c COMMON
988
989@item 'length
990@c EN
991return the known fixed length of the template.
992@c JP
993テンプレートの知られている固定された長さを返します。
994@c COMMON
995
996@item 'variable-length?
997@c EN
998return #t if the template has variable length elements.
999@c JP
1000テンプレートが可変長の要素を持っている場合に#tを返します。
1001@c COMMON
1002@end table
1003@end defun
1004
1005@c ----------------------------------------------------------------------
1006
1007@node Running Chibi-scheme test suite, Rational-less arithmetic, Packing binary data, Library modules - Utilities
1008@section @code{compat.chibi-test} - Running Chibi-scheme test suite
1009@c NODE Chibi schemeテストの実行, @code{compat.chibi-test} - Chibi schemeテストの実行
1010
1011@deftp {Module} compat.chibi-test
1012@mdindex compat.chibi-test
1013@c EN
1014Quite a few srfis come with test suites that's to be run with
1015Chibi Scheme test framework.  This module enables Gauche to run
1016the test code as is.
1017@c JP
1018多くのsrfiには、Chibi Schemeのテストフレームワークで実行できるテストコードが
1019付いてきます。このモジュールはGaucheでそのテストコードを実行できるようにします。
1020@c COMMON
1021@end deftp
1022
1023@defmac chibi-test code @dots{}
1024@c EN
1025Run @var{code} @dots{}, while translating Chibi test framework
1026to Gauche's.
1027@c JP
1028ChibiのテストフレームワークをGaucheのそれに置き換えながら、
1029@code{code} @dots{}を実行します。
1030@c COMMON
1031
1032@c EN
1033A typical usage is to write a wrapper that includes the original
1034test code (suppose it's called @file{test-suite.scm}):
1035@c JP
1036典型的な使い方は、元のテストコード(@file{test-suite.scm}とします)を
1037includeするラッパーを書くことです。
1038@c COMMON
1039
1040@example
1041(use gauche.test)
1042(test-start "running test-suite.scm")
1043(chibi-test
1044  (include "test-suite.scm"))
1045(test-end)
1046@end example
1047
1048@c EN
1049Chibi's test directives are translated to Gauche's test directives
1050(@pxref{Unit testing}, for Gauche's test framework).
1051@c JP
1052Chibiのテストディレクティブは、Gaucheのテストフレームワークのテストディレクティブへと
1053変換されます(@ref{Unit testing}参照)。
1054@c COMMON
1055
1056@c EN
1057The main thing is that Chibi allows expressions and definitions to
1058be intermingled within a body, while Gauche only allows all definitions
1059before expressions within a body.
1060We expand such body into nested @code{let} by @code{chibi-test} macro.
1061Chibi test macros (e.g. @code{test-assert}) are defined as local macros
1062in @code{chibi-test} expansion, which expand into @code{gauche.test}
1063macros.
1064@c JP
1065Chibiはボディ中に式と定義が交互に現れることを許していますが、Gaucheでは
1066ボディ中で全ての定義が式に先立たねばなりません。そこで、@code{chibi-test}マクロは
1067@code{code} @dots{}をネストした@code{let}に変換します。
1068また、Chibiテストマクロ(@code{test-assert}等)は変換後のコードではローカルマクロとして
1069定義され、そのローカルマクロは@code{gauche.test}マクロへと展開されます。
1070@c COMMON
1071
1072@c EN
1073Note that we ignore @code{use} forms inside @code{chibi-test}; we might
1074want to use different modules that work better in Gauche.  Necessary
1075modules need to be @code{use}'d before you call @code{chibi-test}.
1076@c JP
1077なお、@code{chibi-test}中の@code{use}フォームは無視されます。
1078これは、Gaucheで実行するのに別のモジュールを使った方が良い場合があるからです。
1079必要なモジュールは@code{chibi-test}を呼ぶ前に@code{use}しておいてください。
1080@c COMMON
1081
1082@c EN
1083You may want to check out @file{test/srfi.scm} in Gauche source tree
1084for the use case.
1085@c JP
1086Gaucheのソースツリーの@file{test/srfi.scm}に実際の使用例を見ることができます。
1087@c COMMON
1088@end defmac
1089
1090
1091@c ----------------------------------------------------------------------
1092
1093@node Rational-less arithmetic, A common job descriptor for control modules, Running Chibi-scheme test suite, Library modules - Utilities
1094@section @code{compat.norational} - Rational-less arithmetic
1095@c NODE 有理数のない算術演算, @code{compat.norational} - 有理数のない算術演算
1096
1097@deftp {Module} compat.norational
1098@mdindex compat.norational
1099
1100@c EN
1101Until release 0.8.7, Gauche didn't have exact rational numbers.
1102It was able to read the rational number literals such as
1103@code{2/3}, but they are immediately coerced to inexact real
1104numbers (except when it represents a whole integer).
1105And if you divided an exact integer by another exact integer,
1106the result could be coerced to an inexact real if the result
1107wasn't a whole integer.
1108@c JP
1109リリース 0.8.7 までは、Gauche は正確な有理数をサポートしていませんでし
1110た。@code{2/3}のような有理数リテラルを読み込むことはできていましたが、
1111約分して整数になる場合をのぞいては、その場で不正確な実数に変換されてい
1112ました。正確な整数を正確な整数で割った場合も約分して整数になる場合をの
1113ぞき、結果は不正確な実数になりました。
1114@c COMMON
1115
1116@c EN
1117As of 0.8.8, this is not the case anymore.  Exact division
1118always yields exact result, except when the divisor is zero.
1119@c JP
1120リリース 0.8.8 ではもうこのようなことはありません。正確な数同士の割り
1121算の結果は常に正確な数になります。ゼロで割ったときはもちろん例外です。
1122@c COMMON
1123@example
1124(/ 2 3)  @result{} 2/3
1125(/ 5)    @result{} 1/5
1126(/ 4 2)  @result{} 2
1127@end example
1128
1129@c EN
1130This is more precise, but has one drawback: exact rational
1131arithmetic is much slower than the integer and inexact real
1132arithmetic.  If you inadvertently produce
1133a rational number in the early stage of calculation, and
1134continue to apply exact arithmetic, performance would be
1135degraded miserably.
1136@c JP
1137計算は正確な値でできますが、ひとつ欠点もあります。正確有理数演算は整
1138数演算や不正確実数同士の演算にくらべてはるかに遅いのです。意図せず、計
1139算の初期段階で有理数を生成してしまうとその後の計算にはすべて正確な演算
1140が適用されてしまい性能は悲惨なことになります。
1141@c COMMON
1142
1143@c EN
1144The proper way to solve this is to insert @code{exact->inexact}
1145to appropriate places.  However, to ease the transition, you can
1146just import this module and the division @code{/} behaves
1147in the way it used to.
1148@c JP
1149この問題を解決する適切は方法は適切な場所に@code{exact->inexact}を挿入
1150することです。しかし、この変換を簡単におこなうには、このモジュールをイ
1151ンポートし、割り算に@code{/}を使うだけですみます。
1152@c COMMON
1153
1154@example
1155(use compat.norational)
1156
1157(/ 2 3)  @result{} 0.6666666666666666
1158(/ 5)    @result{} 0.2
1159(/ 4 2)  @result{} 2
1160@end example
1161
1162@c EN
1163The effect is not global, but only to the modules you explicitly
1164import @code{compat.norational}.
1165@c JP
1166効果はグローバルには起こらず、明示的に@code{compat.norational}をインポー
1167トしたモジュールでのみ有効です。
1168@c COMMON
1169
1170@c EN
1171This module only redefines @code{/}.  So if your code has
1172exact rational literals, they are treated as exact rationals
1173rather than coerced to inexact reals.  You should prefix
1174rational literals with @code{#i} to force Gauche to coerce
1175them to inexact reals:
1176@c JP
1177このモジュールは@code{/}を再定義しているだけです。したがって、コードに
1178正確な有理数のリテラルが含まれていても、それは不正確な実数に変換される
1179ことはなく、正確な有理数としてあつかわれます。Gaucheに不正確な実数とし
1180て有理数リテラルを扱わせるには、@code{#i}という接頭辞を追加しなければ
1181なりません。
1182@c COMMON
1183@example
1184gosh> 1/3
11851/3
1186gosh> #i1/3
11870.3333333333333333
1188@end example
1189@end deftp
1190
1191@c ----------------------------------------------------------------------
1192@node A common job descriptor for control modules, Thread pools, Rational-less arithmetic, Library modules - Utilities
1193@section @code{control.job} - A common job descriptor for control modules
1194@c NODE 制御モジュールのための汎用ジョブ記述子, @code{control.job} - 制御モジュールのための汎用ジョブ記述子
1195
1196@deftp {Module} control.job
1197@mdindex control.job
1198@c EN
1199This module provides a @code{job} record type, a lightweight
1200structure to be used in the control flow subsystems
1201(@code{control.*} modules).
1202Currently the only user is @code{control.thread-pool}, but
1203some other modules are planned to use @code{job} records.
1204@c JP
1205このモジュールは、制御フローサブシステム(@code{control.*}モジュール)
1206の中で使う軽量な構造である @code{job} レコード型を提供します。
1207現在のところ、これを使っているのは@code{control.thread-pool}だけですが、
1208他にもいくつかのモジュールが@code{job}レコードを使う予定です。
1209@c COMMON
1210
1211@c EN
1212A @code{job} record may be returned to an application
1213by other @code{control.*} modules so that the application
1214can keep track of the job.  It's not meant for
1215general use, however.   An application isn't supposed to
1216create a new job, or to modify its content; it can just query
1217the job's properties.
1218@c JP
1219@code{control.*}モジュールは、アプリケーションがジョブを追跡できるように
1220@code{job}レコードを返すことができます。ただし、
1221これは、アプリケーションが普通に使用するための
1222ものではありません。アプリケーションが新しいジョブを
1223作成したり、その内容を変更したりすることは想定されていません;
1224できるのは、そのジョブの属性について問い合わせることだけです。
1225@c COMMON
1226
1227@c EN
1228In this section we only describe procedures an application
1229needs to know.  The interface for control subsystems is still
1230fluid and may be changed as more subsystems are developed.
1231@c JP
1232この節では、アプリケーションが知るべき手続きだけを説明します。
1233制御サブシステムのためのインタフェースは未だ流動的であり、
1234さらなるサブシステムの開発が進むにつれて、変更されるかもしれません。
1235@c COMMON
1236
1237@c EN
1238Different control flow subsystems may use job structure differently.
1239This section only describes the common properties.  Check the
1240individual control flow module to know how to handle returned job
1241objects.
1242@c JP
1243異なる制御フローサブシステムは、ジョブ構造の使い方が異なる
1244かもしれません。この節では、共通する属性のみを説明します。
1245返されたジョブオブジェクトの扱い方については、個々の制御フロー
1246モジュールを調べて下さい。
1247@c COMMON
1248@end deftp
1249
1250@deftp {Record type} job
1251@c MOD control.job
1252@c EN
1253A record type denotes the job.  Applications should treat it
1254as an opaque structure.
1255@c JP
1256ジョブを表すレコード型です。アプリケーションはこれを、不透明(opaque)な
1257構造として扱うべきです。
1258@c COMMON
1259@end deftp
1260
1261@defun job? obj
1262@c MOD control.job
1263@c EN
1264Returns @code{#t} iff @var{obj} is a job record, @code{#f} otherwise.
1265@c JP
1266@var{obj}がジョブレコードだったら@code{#t}を、そうでなければ@code{#f}を返します。
1267@c COMMON
1268@end defun
1269
1270@defun job-status job
1271@c MOD control.job
1272@c EN
1273Returns the status of the job.  It may be either one of the followings.
1274@c JP
1275ジョブの状態を返します。ジョブの状態は以下のいずれかになります。
1276@c COMMON
1277@table @code
1278@item #f
1279@c EN
1280Newborn or orphaned job.  Usually an application won't see a job
1281in this status.
1282@c JP
1283作成したてか、孤児のジョブです。通常、アプリケーションがジョブの
1284この状態に遭遇することはありません。
1285@c COMMON
1286@item acknowledged
1287@c EN
1288A job is recognized by a control flow library, but haven't yet
1289been run.
1290@c JP
1291ジョブは制御フローライブラリによって認識されていますが、まだ
1292実行されてはいません。
1293@c COMMON
1294@item running
1295@c EN
1296A job is being processed.
1297@c JP
1298ジョブは実行中です。
1299@c COMMON
1300@item done
1301@c EN
1302A job is finished.  An application can retrieve its result
1303by @code{job-result}.
1304@c JP
1305ジョブは完了しています。アプリケーションはその処理の結果を、
1306@code{job-result}を使って受け取ることができます。
1307@c COMMON
1308@item error
1309@c EN
1310A job is terminated by an error.  An application can retrieve the
1311error causing condition by @code{job-result}.
1312@c JP
1313ジョブはエラーで終了しています。アプリケーションはエラーの原因となった
1314コンディションを、@code{job-result}を使って受け取ることができます。
1315@c COMMON
1316@item killed
1317@c EN
1318A job is killed by external force.  An application can retrieve the
1319reason of kill (which is specific to a particular control flow
1320subsystem) by @code{job-result}.
1321@c JP
1322ジョブは外部から殺されています。アプリケーションは殺された理由を、
1323@code{job-result}を使って受け取ることができます。
1324どのような理由でジョブが殺されるかは制御フローサブシステムによります。
1325@c COMMON
1326@end table
1327@end defun
1328
1329@defun job-result job
1330@c MOD control.job
1331@c EN
1332If the job is in @code{done} status, it returns the result of the job.
1333If the job is in @code{error} status, it returns the condition object
1334that describes the error.
1335If the job is in @code{killed} status, it returns an object describing
1336the reason of kill.  The details of the object depends on a particular
1337control flow library.
1338Calling @code{job-result} on a job in any other status may return
1339anything; you can't rely on the result.
1340@c JP
1341与えられたジョブが@code{done}状態だったら、そのジョブの処理結果を返します。
1342与えられたジョブが@code{error}状態だったら、そのエラーを説明する
1343コンディションオブジェクトを返します。そのジョブが@code{killed}状態だったら、
1344殺された理由を説明するオブジェクトを返します。このオブジェクトの詳細は、
1345実際の制御フローライブラリに依存することになります。これら以外の状態の
1346ジョブに対して@code{job-result}を読んだ場合、何が返るかはわかりません;
1347その結果を当てにすることはできません。
1348@c COMMON
1349@end defun
1350
1351@defun job-wait job :optional timeout timeout-val
1352@c MOD control.job
1353@c EN
1354Suspends the calling thread until the job becomes either
1355@code{done}, @code{error} or @code{killed} status.  If the job
1356is already in one of those status, it returns immediately.
1357Returns job's status.
1358@c JP
1359与えられたジョブが@code{done}、@code{error}もしくは@code{killed}
1360状態になるまで、呼び出したスレッドの実行をサスペンドします。
1361ジョブがすでにこれらの状態であった時は、ただちに制御を戻します。
1362ジョブの状態が返ります。
1363@c COMMON
1364
1365@c EN
1366If @var{timeout} is given and not @code{#f}, it must be
1367a valid timeout spec (a @code{<time>} object that represents
1368an absolute time point, or a real number that represents a
1369relative time in seconds.)  The meaning of @var{timeout} is
1370the same as in @code{mutex-unlock!} (@pxref{Synchronization primitives}).
1371Once the timeout reaches, @code{job-wait} returns no matter
1372how the job's status is, and returns the value specified
1373to @var{timeout-val}, which defaults to @code{#f}.
1374@c JP
1375@var{timeout}が与えられ、それが@code{#f}ではない場合は、
1376タイムアウトのスペックとして有効なもの(時間の絶対値を表す
1377@code{<time>}か、現時点からの相対的な秒数を表す実数)で
1378なければなりません。@var{timeout}の意味は、@code{mutex-unlock!}
1379(@pxref{Synchronization primitives})のそれと同じです。
1380タイムアウトすると、そのジョブの状態が何であれ、
1381@code{job-wait}は引数@var{timeout-val}として指定された
1382値を返します。デフォルト値は@code{#f}です。
1383@c COMMON
1384
1385@c EN
1386Depending on the control flow subsystem, jobs created by it
1387may not be waitable; check out each subsystem's documentation for the details.
1388@c JP
1389そのジョブを作成する制御フローサブシステムによっては、
1390待ち受けできないかもしれません。それぞれのサブシステムの
1391ドキュメントを調べて詳細を確認してください。
1392@c COMMON
1393@end defun
1394
1395@defun job-acknowledge-time job
1396@defunx job-start-time job
1397@defunx job-finish-time job
1398@c MOD control.job
1399@c EN
1400If the control flow subsystem keeps track of timestamps,
1401these procedure returns the time (in @code{<time>} objects)
1402when the job is acknowledged, started and finished (either normally,
1403or abnormally by an error or by being killed).  If the job hasn't
1404reached to certain status, @code{#f} is returned instead.
1405@c JP
1406制御フローサブシステムがジョブのタイムスタンプを記録する場合、
1407これらの手続きは、そのジョブがサブシステムによって認識された時刻、
1408開始された時刻、(正常に、あるいはエラーや殺されるなど異常に)
1409終了した時刻を(@code{<time>}オブジェクトとして)返します。
1410ジョブがそうした状態に達していない場合は@code{#f}を返します。
1411@c COMMON
1412
1413@c EN
1414If the subsystem does not track timestamps, these procedures
1415always returns @code{#f}.
1416@c JP
1417そのサブシステムがタイムスタンプを記録しない場合、これらの
1418手続きは常に@code{#f}を返します。
1419@c COMMON
1420@end defun
1421
1422@c ----------------------------------------------------------------------
1423@node Thread pools, Password hashing, A common job descriptor for control modules, Library modules - Utilities
1424@section @code{control.thread-pool} - Thread pools
1425@c NODE スレッドプール, @code{control.thread-pool} - スレッドプール
1426
1427@deftp {Module} control.thread-pool
1428@mdindex control.thread-pool
1429@c EN
1430Provides thread pools.  Only available when Gauche is compiled
1431with pthreads support.
1432@c JP
1433スレッドプールを提供します。Gaucheがpthreadサポート付きでコンパイルされている
1434場合にのみ利用可能です。
1435@c COMMON
1436@end deftp
1437
1438@deftp {Class} <thread-pool>
1439@clindex thread-pool
1440@c MOD control.thread-pool
1441@c EN
1442A class for thread pool objects.   It maintains a set of worker threads, and
1443let them work on the jobs you ask to do asynchronously.
1444
1445Currently the size of pool (number of threads) is fixed
1446and you have to specify it when creating a pool.
1447In future we might add a feature to grow or shrink the pool.
1448
1449You can also set maximum backlog of the job queue.  You cannot
1450put a job when the queue already reaches the max length (see
1451@code{add-job!} below).
1452@c JP
1453スレッドプールオブジェクトのクラスです。ワーカースレッドのセットを保持し、
1454投入されたジョブを非同期に実行します。
1455
1456現在の実装では、プールのサイズ (スレッド数) は固定で、プール作成時に
1457指定しなければなりません。いずれスレッド数を動的に増減させる機能を
1458追加する予定です。
1459
1460また、ジョブのキューの最大長を指定することもできます。ジョブのキューが
1461一杯になると、空きができるまでは新たなジョブを投入することができなくなります
1462(下記の@code{add-job!}参照)。
1463@c COMMON
1464@end deftp
1465
1466
1467@deftp {Condition type} <thread-pool-shut-down>
1468@c MOD control.thread-pool
1469@c EN
1470A condition indicating that a thread pool is already shut down
1471by @code{terminate-all!} and no longer accepting new jobs.
1472Inherits @code{<error>}.  The following slot is provided.
1473@c JP
1474スレッドプールが@code{terminate-all!}によって停止され、
1475新規のジョブを受け付けていないことを示すコンディションです。
1476@code{<error>}を継承します。次のスロットが提供されます。
1477@c COMMON
1478
1479@defivar <thread-pool-shut-down> pool
1480@c EN
1481The thread pool object that caused the condition.
1482@c JP
1483例外の原因となったスレッドプールオブジェクト
1484@c COMMON
1485@end defivar
1486@end deftp
1487
1488@defun make-thread-pool size :key (max-backlog 0)
1489@c MOD control.thread-pool
1490@c EN
1491Creates a new thread pool of size @var{size} (the number of
1492worker threads).  Optionally you can give a nonnegative integer
1493to the maximum backlog; 0 means unlimited.
1494@c JP
1495大きさ(ワーカースレッド数)@var{size}のスレッドプールを作成して返します。
1496省略可能引数@var{max-backlog}によってジョブのバックログの最大値を
1497指定することもできます。0を与えた場合(デフォルト)は無制限です。
1498@c COMMON
1499@end defun
1500
1501@defun thread-pool-results pool
1502@c MOD control.thread-pool
1503@c EN
1504When you put a job to a thread pool, you can specify
1505whether you need to check its result or not.  If you say you need
1506a result, the terminated job is queued to a @emph{result queue},
1507an @code{<mt-queue>} object, in the pool.
1508This procedure returns the pool's result queue.
1509@xref{Queue}, for the details of @code{<mt-queue>}.
1510@c JP
1511ジョブをスレッドプールに投入する際に、ジョブの結果を知る必要があるかどうかを
1512指定することができます。結果を要求した場合は、終了したジョブレコードが
1513プール中の結果キュー(@code{<mt-queue>}オブジェクト)にエンキューされます。
1514この手続きは、プールの結果キューを返します。
1515@code{<mt-queue>}の詳細については@ref{Queue}を参照してください。
1516@c COMMON
1517@end defun
1518
1519@defun thread-pool-shut-down? pool
1520@c MOD control.thread-pool
1521@c EN
1522Returns @code{#t} if the thread pool is shut down and no longer
1523accepting new jobs, or @code{#f} otherwise.
1524@c JP
1525スレッドプールが停止され、新規のジョブを受け付けていない場合に@code{#t}を、
1526そうでなければ@code{#f}を返します。
1527@c COMMON
1528@end defun
1529
1530@defun add-job! pool thunk :optional (need-result #f) (timeout #f)
1531@c MOD control.thread-pool
1532@c EN
1533Add a @var{thunk} to be executed in the thread pool @var{pool}.
1534Returns a @code{job} record (@pxref{A common job descriptor for control modules}).
1535@c JP
1536@var{thunk}がスレッドプール@var{pool}のスレッドにより実行されるように設定します。
1537@code{job}レコードを返します。
1538(@ref{A common job descriptor for control modules}参照)。
1539@c COMMON
1540
1541@c EN
1542The returned job record is not waitable; if you need to track
1543its result, you have to give a true value to @var{need-result}
1544argument.  Then when the job is terminated (either normally or
1545abnormally) the job is queued to the @code{result-queue} of
1546the pool, and you can check the queue.   If you don't pass
1547a true value to @var{need-result}, the job won't be queued
1548to @code{result-queue} even it is terminated.
1549@c JP
1550返される@code{job}レコードはwaitableにはなっていません。結果を知る必要が
1551ある場合は、省略可能引数@var{need-result}に真の値を渡してください。
1552そうするとジョブが終了した時点 (正常終了でも異常終了でも) で、
1553@code{job}レコードがスレッドプールの@code{result-queue}に
1554入るので、そのキューから結果を受け取ることができます。
1555@var{need-result}を省略したり偽値を渡した場合は、ジョブが終了しても
1556@code{job}レコードは@code{result-queue}に入れられません。
1557@c COMMON
1558
1559@c EN
1560The returned job is timestamped.  You can examine acknowledged
1561time, start time and finish time of the job (if the job hasn't
1562been started and/or finished, the corresponding timestamp fields
1563are @code{#f}.)  It's sometimes
1564handy to find out how long the job was waiting in the
1565queue and how long it took to run.
1566@c JP
1567返される@code{job}レコードにはタイムスタンプが付加され、
1568受付時間、実行開始時間、実行終了時間が記録されます。
1569(ジョブがまだ実行されていなかったり、終了されていない場合は、対応する
1570タイムスタンプは@code{#f}になっています)。
1571ジョブがどのくらいキューの中で待たされ、どのくらい実行にかかったかを
1572知るのに便利でしょう。
1573@c COMMON
1574
1575@c EN
1576If the pool has positive @code{max-backlog} value, and it
1577already has that many jobs to be waiting, then @code{add-job!}
1578blocks until some jobs are start being executed.
1579You can give a real number in seconds, or a @code{<time>} object
1580as an absolute point of time, to the @var{timeout} argument
1581to set the time limit of blocking.  If timeout is reached,
1582@code{add-job!} returns @code{#f} without creating any job.
1583Omitting @var{timeout}
1584or giving @code{#f} to it sets no timeout.
1585@c JP
1586スレッドプールが非負の@code{max-backlog}値を持ち、
1587既にその数だけジョブが待ち行列に入っている場合は、
1588@code{add-job!}は待ち行列に空きができるまでブロックします。
1589@var{timeout}引数に、実数値の秒数、あるいは絶対時刻を指定する@code{<time>}
1590オブジェクトを渡すことでタイムアウトを指定できます。タイムアウトに
1591達した場合は、@code{add-job!}はジョブを作らずに@code{#f}を返します。
1592@var{timeout}引数を省略するか、@code{#f}を渡した場合はタイムアウトが設定されません。
1593@c COMMON
1594
1595@c EN
1596(Note: This behavior is different from 0.9.1, in which @code{add-job!}
1597didn't take the timeout argument and always behaved as if zero
1598timeout value was given.  To achieve the same behavior, you have
1599to give 0 to the @var{timeout} argument explicitly.)
1600@c JP
1601(註: この動作は0.9.1から変更されました。0.9.1では、@code{add-job!}は
1602タイムアウト引数を取らず、常にタイムアウトに0秒が指定されたかのように
1603振る舞っていました。現在のバージョンで同じ動作をさせるには、@var{timeout}引数
1604に0を明示的に渡します。)
1605@c COMMON
1606
1607@c EN
1608If the thread pool is shut down, this procedure
1609raises @code{<thread-pool-shut-down>} condition.
1610@c JP
1611スレッドプールが停止していた場合、この手続きは
1612@code{<thread-pool-shut-down>}コンディションを投げます。
1613@c COMMON
1614@end defun
1615
1616@defun wait-all pool :optional (timeout #f) (check-interval #e5e8)
1617@c MOD control.thread-pool
1618@c EN
1619Wait for the job queue to be empty and
1620all worker threads to finish.  It is done by polling the
1621pool's status in every @var{check-interval} nanoseconds.
1622Returns @code{#t} if all jobs are finished.
1623
1624You can give a real number in seconds, or a @code{<time>} object
1625as an absolute point of time, in @var{timeout} optional argument.
1626When timeout is reached, @code{wait-all} returns @code{#f}.
1627@c JP
1628ジョブ待ち行列が空になり、すべての実行中のジョブも終了するまで待ちます。
1629終了待ちは@var{check-interval}にナノ秒で指定される間隔でスレッドプールを
1630ポールすることで行われます。すべてのジョブが終了したら@code{#t}を返します。
1631
1632秒数を表す実数か、絶対時刻を表す@code{<time>}オブジェクトを@var{timeout}
1633引数に渡すことで、タイムアウトを指定できます。タイムアウトに達した場合は、
1634@code{wait-all}は@code{#f}を返します。
1635@c COMMON
1636@end defun
1637
1638@defun terminate-all! pool :key (force-timeout #f) (cancel-queued-jobs #f)
1639@c MOD control.thread-pool
1640@c EN
1641Wait for all the queued jobs to be finished, then ask all threads
1642to terminate.  After calling this procedure, the pool no longer
1643accepts new jobs.  Calling @code{add-job!} on this module would
1644raise a @code{<thread-pool-shut-down>} condition.
1645This is intended to be called when shutting down the application.
1646
1647By default, this procedure first waits for all queued jobs
1648to be handled, then tries to terminate threads gracefully.
1649
1650Giving a true value to the @var{cancel-queued-jobs} argument
1651immediately cancels queued but not started jobs; the status
1652of such jobs is set @code{killed}.
1653It does not cancels already started jobs, though.
1654
1655If you want to cancel already started jobs,
1656you can give a timeout value (either @code{<time>} object to
1657specify absolute point of time, or a real number indicating
1658relative time in seconds) to the @var{force-timeout} argument.
1659Once timeout is reached, it forcefully terminates the threads
1660and the jobs handled at that time are also killed.
1661
1662Forcing termination of threads is an extreme measure; the terminated
1663thread may not have a chance to clean up properly.  So it is usually
1664better to give some time for the thread to finish the executing jobs.
1665@c JP
1666投入されたジョブがすべて終了するのを待ち、すべてのスレッドを終了させます。
1667ひとたびこの手続きを呼ぶと、スレッドプール@var{pool}は新規のジョブを受けつけ
1668ません。この状態のスレッドプールに対して@code{add-job!}を呼ぶと
1669@code{<thread-pool-shut-down>}コンディションが投げられます。
1670この手続きはアプリケーションのシャットダウン時などに呼ばれることを意図しています。
1671
1672デフォルトでは、この手続きはまずキューに既に投入されたジョブが全て処理されるのを
1673待ち、それからスレッドを穏やかに終了させます。
1674
1675真の値を@var{cancel-queued-jobs}引数に与えると、キューに入っているが
1676まだ開始されていないジョブは直ちにキャンセルされます。それらのジョブの
1677ステータスには@code{killed}がセットされます。
1678ただし、既に開始されたジョブについてはキャンセルされません。
1679
1680既に開始されたジョブも中断したい場合は、
1681タイムアウト値(秒数を表す実数か、絶対時刻を表す@code{<time>}オブジェクト)を
1682@var{force-timeout}引数に渡します。
1683タイムアウトに達した時点で残っているスレッドは強制終了され、実行中のジョブも
1684キャンセルされます。
1685
1686スレッドの強制終了は極端な処置です。終了されるスレッドは、適切なクリーンアップを
1687行う機会も与えられないかもしれません。したがって通常は、
1688スレッドが処理中のジョブを終わらせるための適切な時間的猶予を与えるのが良いでしょう。
1689@c COMMON
1690@end defun
1691
1692@c ----------------------------------------------------------------------
1693@node Password hashing, Cache, Thread pools, Library modules - Utilities
1694@section @code{crypt.bcrypt} - Password hashing
1695@c NODE パスワードハッシュ, @code{crypt.bcrypt} - パスワードハッシュ
1696
1697@deftp {Module} crypt.bcrypt
1698@mdindex crypt.bcrypt
1699@c EN
1700This module implements a password hashing algorithm using blowfish,
1701and compatible to OpenBSD's bcrypt algorithm (version 2a, 2b).
1702@c JP
1703このモジュールは、blowfishを使ったパスワードハッシュアルゴリズムを実装します。
1704OpenBSDのbcryptアルゴリズム(version 2a, 2b)と互換です。
1705@c COMMON
1706
1707@c EN
1708Don't use version ``2a'' for new code. It's vulnerable.
1709Use version ``2b''.
1710@c JP
1711version 2a は脆弱性が発見されているので、新規のコードでは使用しないで
1712ください。代わりに version 2b を使用して下さい。
1713@c COMMON
1714
1715@c EN
1716The typical usage of this module is simple enough.
1717To get a new password hash value (e.g. for a new user), pass the
1718password string to @code{bcrypt-hashpw} as the only argument:
1719@c JP
1720典型的な使い方は非常にシンプルです。新しいパスワードハッシュ値を
1721得たい場合 (例えば新しいユーザのために、など) は、パスワード文字列を
1722唯一の引数として@code{bcrypt-hashpw}を呼び出してください。
1723@c COMMON
1724
1725@example
1726(bcrypt-hashpw @var{password})
1727  @result{} @r{hashed-string}
1728@end example
1729
1730@c EN
1731The routine automatically adds a salt value.  The returned hash
1732string can be stored in the user database.  To check if the given
1733password matches the stored one, pass the
1734hashed string as the second argument of @code{bcrypt-hashpw} to
1735check the password.
1736@c JP
1737このルーチンは自動的にソルト値を付加します。戻り値の文字列はそのままユーザ
1738データベースに格納できます。与えられたパスワードがハッシュ値に一致するか
1739どうかを調べるには、ハッシュ値そのものを第二引数として@code{bcrypt-hashpw}に
1740渡します。
1741@c COMMON
1742
1743@example
1744(bcrypt-hashpw @var{password} @var{hashed-string})
1745  @result{} @r{hashed-string}
1746@end example
1747
1748@c EN
1749If the given password is correct, the returned value should
1750exactly matches @var{hash-string}.
1751@c JP
1752パスワードが正しければ、戻り値は@var{hashed-string}と完全に一致するはずです。
1753@c COMMON
1754@end deftp
1755
1756@defun bcrypt-hashpw password :optional setting
1757@c MOD crypt.bcrypt
1758@c EN
1759Calculates a hash value of @var{password}, using the salt value
1760and parameters included in @var{setting}.  If @var{setting} is
1761omitted, a suitable default settings and random salt value is
1762chosen automatically.
1763
1764The returned hash value contains the salt value and parameters,
1765and can be used as @var{setting}.  So, to check the password
1766against existing hash value, just pass the hash value to
1767@var{setting}; if the password is correct, the returned hash value
1768should match the one you passed in.
1769
1770The bcrypt algorithm supports up to 72 octets for the password.
1771
1772To tweak parameters when you calculate a new hash value,
1773use @code{bcrypt-gensalt} below to get the initial @var{setting}
1774value.
1775@c JP
1776@var{password}のハッシュ値を計算します。@var{setting}は
1777ソルト値とパラメータを指定する文字列です。@var{setting}が
1778省略された場合は、適切なデフォルトのパラメータとランダムなソルト値が
1779自動的に選択されます。
1780
1781戻り値のハッシュ値文字列にはソルト値とパラメータが含まれているので、
1782それを再び@var{setting}に渡すことができます。したがって、パスワードを
1783既存のハッシュ値に一致するかチェックしたい場合は、ハッシュ値を@var{setting}に渡し、
1784戻ってきた文字列が渡したハッシュ値と一致するかを見れば良いことになります。
1785
1786bcryptアルゴリズムは最大72オクテットまでのパスワードを使えます。
1787
1788新しいハッシュ値を計算する際にパラメータを指定したい場合は、次に説明する
1789@code{bcrypt-gensalt}を使うと@var{setting}に使える文字列を得ることができます。
1790@c COMMON
1791@end defun
1792
1793@defun bcrypt-gensalt :key prefix count entropy-source
1794@c MOD crypt.bcrypt
1795@c EN
1796Returns a string that contains given parameters and suitable to
1797pass to the @var{setting} argument of @code{bcrypt-hashpw}.
1798
1799The @var{prefix} argument specifies the version/scheme of
1800password hashing.  Currently @code{$2a$} and @code{$2b$} are supported,
1801which means the blowfish algorithm compatible to bcrypt.
1802But @code{$2a$} is vulnerable. Use @code{$2b$} for new code.
1803If you omit @var{prefix}, use @code{$2b$} for default value.
1804
1805The @var{count} argument specifies the amount of iterations;
1806the larger the value is, the more time is required to calculate
1807the hash value.  Note that for the password hashing, taking more
1808time is actually a good thing, for it works against the dictionary attack.
1809For normal password checking you need to run the hash routine only
1810once per login, so it doesn't matter if the calculation takes a fraction
1811of second.
1812The bcrypt algorithm iterates @code{(expt 2 @var{count})} times.
1813
1814The @var{entropy-source} argument is a @code{u8vector} to feed
1815a random bytes.  For bcrypt algorithm it must be at least 16 octet long.
1816@c JP
1817与えられたパラメータを折り込んだ、
1818@code{bcrypt-hashpw}の@var{setting}引数に使える文字列を返します。
1819
1820@var{prefix}引数はハッシュ関数およびそのバージョンを指定する文字列です。
1821現在のところ、@code{bcrypt}互換である@code{$2a$}と@code{$2b$}がサポート
1822されています。
1823ただし、@code{$2a$}には脆弱性が発見されていますので、
1824新規のコードには@code{$2b$}を使用して下さい。
1825@var{perfix}引数を省略した場合は@code{$2b$}が用いられます。
1826
1827@var{count}引数はハッシュの繰り返し回数に関係します。大きな値を指定すれば、
1828ハッシュ値の計算により長い時間がかかります。パスワードハッシュにおいては、
1829時間をかけた方が良いことに注意してください。一回のハッシュの時間が長くなれば
1830辞書攻撃への防御になります。一方で、通常のパスワードチェックでは
1831ログインの度にたかだか一回しはハッシュ関数を呼ばないので、それがたとえコンマ数秒
1832かかったとしてもたいした負荷ではありません。
1833bcryptアルゴリズムでは、@code{(expt 2 @var{count})}回ハッシュが繰り返されます。
1834
1835@var{entropy-source}引数はランダムなバイト列を格納した@code{u8vector}です。
1836bcryptアルゴリズムでは少なくとも16バイトの長さが必要です。
1837@c COMMON
1838@end defun
1839
1840@c ----------------------------------------------------------------------
1841@node Cache, Heap, Password hashing, Library modules - Utilities
1842@section @code{data.cache} - Cache
1843@c NODE キャッシュ, @code{data.cache} - キャッシュ
1844
1845@deftp {Module} data.cache
1846@mdindex data.cache
1847@c EN
1848A cache works similarly as a dictionary, associating keys to values,
1849but its entries may disappear according to the policy of the cache
1850algorithm.  This module defines
1851a common protocol for cache datatypes, and also provides several
1852typical cache implementations.
1853@c JP
1854キャッシュは、キーと値を結びつけるという点では辞書と似たように動作しますが、
1855キャッシュアルゴリズムの方針によってエントリが消去されることがあります。
1856このモジュールは、キャッシュについて共通のプロトコルを定義し、
1857またいくつかの典型的なキャッシュの実装を提供します。
1858@c COMMON
1859@end deftp
1860
1861@c EN
1862@subheading Examples
1863@c JP
1864@subheading 例
1865@c COMMON
1866
1867@c EN
1868Let's start from simple examples to get the idea.
1869@c JP
1870まず簡単な例によって、どんな具合かを示しましょう。
1871@c COMMON
1872
1873@c EN
1874Suppose you want to read given files and you want to
1875cache the frequently read ones.  The following code defines
1876a cached version of @code{file->string}:
1877@c JP
1878指定されたファイルを読み込むルーチンに、
1879頻繁に読むファイルをキャッシュする機能をつけたいとします。
1880次のコードは@code{file->string}にキャッシュ機能を持たせたものです。
1881@c COMMON
1882
1883@example
1884(use data.cache)
1885(use file.util)
1886
1887(define file->string/cached
1888  (let1 file-cache (make-lru-cache 10 :comparator string-comparator)
1889    (^[path] (cache-through! file-cache path file->string))))
1890@end example
1891
1892@c EN
1893The procedure closes a variable @code{file-cache},
1894which is an LRU (least recently used) cache that associates
1895string pathnames to the file contents.
1896The actual logic is in @code{cache-through!}, which first consults the
1897cache if it has an entry for the @code{path}.  If the cache has
1898the entry, its value (the file content) is returned.  If not,
1899it calls @code{file->string} with the @var{path} to fetch the file content,
1900register it to the cache, and return it.  The capacity of cache is
1901set to 10 (the first argument of @code{make-lru-cache}), so when the
190211th file is read, the least recently used file will be purged from the
1903cache.
1904@c JP
1905この手続きは@code{file-cache}変数をクロージャの中に綴じ込んでいます。
1906その値は文字列のパス名とファイルの中身を結びつけるLRU(least recently used)キャッシュです。
1907キャッシュの動作は@code{cache-through!}で実現されています。
1908この手続きは、
1909まず@var{path}をキーとして持つエントリが@code{file-cache}にあるかどうか調べます。
1910そのキーを持つエントリがキャッシュ中にあればその値(ファイルの中身)が返されます。
1911キャッシュ中に無ければ、@code{file->string}が@var{path}を引数として呼ばれ、
1912それが返したファイルの中身がキャッシュに登録され、返されます。
1913キャッシュの容量は@code{make-lru-cache}の第1引数で指定され、ここでは10になっています。
1914つまり、11個目のファイルが読まれた時に、一番長く使われていない
1915(least recently used)ファイルがキャッシュから消去されます。
1916@c COMMON
1917
1918@c EN
1919The effect of cache isn't very visible in the above example.  You
1920can insert some print stubs to see the cache is actually in action,
1921as the following example.
1922Try read various files using @code{file->string/cached}.
1923@c JP
1924上の例そのままではキャッシュの効果が見え辛いです。
1925次の例の通り、printスタブをいれて、いろいろなファイルを
1926@code{file->string/cached}で読んでみて下さい。
1927いつキャッシュが実際にファイルの中身を取りにゆくかわかるでしょう。
1928@c COMMON
1929
1930@example
1931(define file->string/cached
1932  (let1 file-cache (make-lru-cache 10 :comparator string-comparator)
1933    (^[path]
1934      (print #"file->string/cached called on ~path")
1935      (cache-through! file-cache path
1936                      (^[path]
1937                        (print #"cache miss.  fetching ~path")
1938                        (file->string path))))))
1939@end example
1940
1941@c EN
1942Caveat: A cache itself isn't MT-safe.  If you are using it in
1943multithreaded programs, you have to wrap it with an atom
1944(@pxref{Synchronization primitives}):
1945@c JP
1946注意: キャッシュ自身はスレッドセーフではありません。
1947マルチスレッドプログラムでキャッシュを使う場合は、キャッシュをatomでラップしてください。
1948@c COMMON
1949
1950@example
1951(use data.cache)
1952(use file.util)
1953(use gauche.threads)
1954
1955(define file->string/cached
1956  (let1 file-cache (atom (make-lru-cache 10 :comparator string-comparator))
1957    (^[path]
1958      (atomic file-cache (cut cache-through! <> path file->string)))))
1959@end example
1960
1961@c EN
1962@subheading Common properties of caches
1963@c JP
1964@subheading キャッシュに共通の性質
1965@c COMMON
1966
1967@c EN
1968A cache of any kind has a comparator and a storage.
1969The comparator is used to compare keys; in the example above,
1970we use @code{string-comparator} to compare string pathnames
1971(@pxref{Basic comparators}, for more about comparators).
1972@c JP
1973どんなキャッシュにも、比較器とストレージがあります。
1974比較器はキーを比較するのに使われます。上の例ではパス名を比較するために
1975@code{string-comparator}を渡しています
1976比較器について詳しくは@ref{Basic comparators}を参照してください。
1977@c COMMON
1978
1979@c EN
1980The storage is a dictionary that maps keys to internal
1981structures of the cache.  By default, a hashtable is
1982created automatically using the given comparator (or,
1983if a comparator is omitted, using @code{default-comparator}).
1984The comparator must have hash function.
1985@c JP
1986ストレージは、キーとキャッシュ内部の構造とをマッピングする辞書です。
1987デフォルトでは与えられた比較器を使うハッシュテーブルが使われるので、
1988比較器はハッシュ関数を持っていなければなりません。
1989比較器が省略された場合は@code{default-comparator}が使われます。
1990@c COMMON
1991
1992@c EN
1993Alternatively, you can give a pre-filled dictionary
1994(copied from another instance of the same kind of cache)
1995to start cache with some data already in it.  Note that
1996what the cache keeps in the dictionary totally depends on the
1997cache algorithm, so you can't just pass a random dictionary;
1998it has to be created by the same kind of cache.
1999If you pass in the storage, the comparator is taken from it.
2000@c JP
2001あるいは、
2002(同じ種類のキャッシュからコピーされた)辞書をストレージとして渡すことで、
2003既にエントリがある状態のキャッシュを作ることもできます。
2004キャッシュが辞書に登録している構造はキャッシュアルゴリズムごとに異なるので、
2005何でも辞書を渡せるわけではないことに注意してください。
2006同じ種類のキャッシュによって作られた辞書しか渡せません。
2007ストレージとなる辞書を渡した場合、比較器はその辞書から取られます。
2008@c COMMON
2009
2010@c EN
2011Thus, the cache constructors uniformly take keyword arguments
2012@var{comparator} and @var{storage}; you can specify either one,
2013or omit both to use the defaults.
2014@c JP
2015従ってキャッシュのコンストラクタは共通して@var{comparator}と@var{storage}の
2016キーワード引数を取ります。デフォルトの動作で良ければ、
2017どちらかひとつ、あるいは両方とも省略することができます。
2018@c COMMON
2019
2020@c EN
2021@subheading Predefined caches
2022@c JP
2023@subheading 定義済みのキャッシュ
2024@c COMMON
2025
2026@c EN
2027For the @var{storage} and @var{comparator} keyword arguments, see above.
2028@c JP
2029@var{storage}と@var{comparator}キーワード引数については上の節を参照してください。
2030@c COMMON
2031
2032@defun make-fifo-cache capacity :key storage comparator
2033@c MOD data.cache
2034@c EN
2035Creates and returns a FIFO (first-in, first-out) cache that can
2036hold up to @var{capacity} entries.
2037If the number of entries exceeds @var{capacity}, the oldest entry
2038is removed.
2039@c JP
2040@var{capacity}個までのエントリを保持できる、FIFO(先入れ先出し)キャッシュを作って返します。
2041エントリ数が@var{capacity}を越えそうになった場合、一番古いものから削除されます。
2042@c COMMON
2043@end defun
2044
2045@defun make-lru-cache capacity :key storage comparator
2046@c MOD data.cache
2047@c EN
2048Creates and returns an LRU (least recently used) cache that can
2049hold up to @var{capacity} entries.
2050If the number of entries exceeds @var{capacity}, the least recently used
2051entry is removed.
2052@c JP
2053@var{capacity}個までのエントリを保持できる、
2054LRU(least recently used)キャッシュを作って返します。
2055エントリ数が@var{capacity}を越えそうになった場合、一番長く使われなかったものから削除されます。
2056@c COMMON
2057@end defun
2058
2059@defun make-ttl-cache timeout :key storage comparator timestamper
2060@c MOD data.cache
2061@c EN
2062Creates and returns a TTL (time to live) cache with the timeout value
2063@var{timeout}.
2064Each entry is timestamped when it's inserted, and it is removed
2065when the current time passes @var{timeout} unit from the timestamp.
2066The actual entry removal is done when the cache is accessed.
2067@c JP
2068タイムアウト値@var{timeout}を持つTTL(生存時間)キャッシュを作って返します。
2069各エントリには、挿入された時間が記録されます。@var{timeout}を経過したエントリは削除されます。
2070実際の削除は、キャッシュがアクセスされた時に行われます。
2071@c COMMON
2072
2073@c EN
2074By default, the Unix system time (seconds from Epoch) is used
2075as a timestamp, and @var{timeout} is in seconds.  It may not be
2076fine-grained enough if you add multiple entries in shorter intervals
2077than seconds.   You can customize
2078it by giving a thunk to @var{timestamper}; the thunk is called to
2079obtain a timestamp, which can be any monotonically increasing real number
2080(it doesn't need to be associated with physical time).
2081If you give @var{timestamper}, the unit of @var{timeout} value should
2082be the same as whatever @var{timestamper} returns.
2083@c JP
2084デフォルトではUnixシステム時間(Epochからの秒数)がタイムスタンプに使われます。
20851秒より短い間隔でたくさんのエントリが追加される場合にはこれでは分解能が足りないかもしれません。
2086@var{timestamper}にサンクを与えることで、タイムスタンプをカスタマイズすることができます。
2087キャッシュは時刻が必要になる度に@var{timestamper}を引数無しで呼び出します。
2088@var{timestamper}は単調非減少な実数を返さねばなりません(物理的な時間と結びついている必要は
2089ありません)。
2090@var{timestamper}を与えた場合、@var{timeout}引数の単位は
2091@var{timestamper}が返す値の単位と同じでなければなりません。
2092@c COMMON
2093@end defun
2094
2095@defun make-ttlr-cache timeout :key storage comparator timestamper
2096@c MOD data.cache
2097@c EN
2098A variation of TTL cache, but the entry's timestamp is updated
2099(refreshed) whenever the entry is read.  Hence we call it TTL with refresh
2100(TTLR).  But you can also think it as a variation of LRU cache with
2101timeout.
2102@c JP
2103TTLキャッシュのバリエーションで、エントリは書き込まれた時だけでなく、
2104読み出された時にもタイムスタンプが更新されます。
2105手続きの名前TTLRは、リフレッシュ付きTTL(TTL with refresh)という意味です。
2106ただ、これをタイムアウト付きLRUキャッシュと見ることもできます。
2107@c COMMON
2108
2109@c EN
2110The unit of timeout, and the role of @var{timestamper} argument, are
2111the same as @code{make-ttl-cache}.
2112@c JP
2113タイムアウトの単位および@var{timestamper}引数の役割については、
2114@code{make-ttl-cache}と同じです。
2115@c COMMON
2116@end defun
2117
2118@c EN
2119@subheading Common operations of caches
2120@c JP
2121@subheading キャッシュに共通の操作
2122@c COMMON
2123
2124@c EN
2125The following APIs are for the users of a cache.
2126@c JP
2127以下のAPIはキャッシュのユーザに向けたものです。
2128@c COMMON
2129
2130@defun cache-lookup! cache key :optional default
2131@c MOD data.cache
2132@c EN
2133Look for an entry with @var{key} in @var{cache}, and returns its
2134value if it exists.  If there's no entry, the procedure returns @var{default}
2135if it is provided, or throws an error otherwise.
2136
2137Some types of cache algorithms update @var{cache} by this operation, hence
2138the bang is in the name.
2139@c JP
2140@var{cache}から@var{key}に結びつけられたエントリを探し、見つかれば返します。
2141エントリが無い場合は、@var{default}が与えられていればそれを返し、
2142与えられていなければエラーを投げます。
2143
2144キャッシュアルゴリズムによってはこの操作で@var{cache}がアップデートされる場合があるため、
2145名前にエクスクラメーションマークがついています。
2146@c COMMON
2147@end defun
2148
2149@defun cache-through! cache key value-fn
2150@c MOD data.cache
2151@c EN
2152Look for an entry with @var{key} in @var{cache}, and returns its
2153value if it exists.  If there's no entry, a procedure @var{value-fn}
2154is called with @var{key} as the argument, and its return value
2155is inserted into @var{cache} and also returned.
2156@c JP
2157@var{cache}から@var{key}に結びつけられたエントリを探し、見つかれば返します。
2158見つからなかった場合、@var{value-fn}が@var{key}を引数として呼び出され、
2159その結果が@var{cache}に新たなエントリとして追加され、また@code{cache-through!}の
2160戻り値として返されます。
2161@c COMMON
2162@end defun
2163
2164@deffn {Generic function} cache-write! cache key value
2165@c MOD data.cache
2166@c EN
2167This inserts association of @var{key} and @var{value} into @var{cache}.
2168If there's already an entry with @var{key}, it is overwritten.
2169Otherwise a new entry is created.
2170
2171The same effect can be achieved by calling @code{cache-evict!} then
2172@code{cache-through!}, but cache algorithms may provide efficient
2173way through this method.
2174@c JP
2175@var{cache}に、@var{key}と@var{value}の関係を追加します。既に@var{key}に
2176結びつけられたエントリがあった場合は上書きされ、そうでなければ新たなエントリが作られます。
2177
2178同じ効果は、@code{cache-evict!}を呼んでから@code{cache-through!}を呼ぶことでも
2179達成できますが、アルゴリズムによっては@code{cache-write!}に対して効率のよい
2180実装を提供しているかもしれません。
2181@c COMMON
2182@end deffn
2183
2184@deffn {Generic function} cache-evict! cache key
2185@c MOD data.cache
2186@c EN
2187Removes an entry with @var{key} from @var{cache}, if it exists.
2188@c JP
2189@var{cache}から@var{key}に結びついたエントリを(もしあれば)削除します。
2190@c COMMON
2191@end deffn
2192
2193@deffn {Generic function} cache-clear! cache
2194@c MOD data.cache
2195@c EN
2196Removes all entries from @var{cache}.
2197@c JP
2198@var{cache}内のエントリを全て取り除きます。
2199@c COMMON
2200@end deffn
2201
2202@c EN
2203@subheading Implementing a cache algorithm
2204@c JP
2205@subheading キャッシュアルゴリズムの実装
2206@c COMMON
2207
2208@c EN
2209Each cache algorithm must define a class inheriting @code{<cache>},
2210and implement the following two essential methods.
2211The higher-level API calls them.
2212@c JP
2213新たなキャッシュアルゴリズムを提供するには、@code{<cache>}を継承したクラスを定義し、
2214次の二つの必須メソッドを実装します。高レベルAPIはこれらの必須メソッドを呼び出します。
2215@c COMMON
2216
2217@deffn {Generic function} cache-check! cache key
2218@c MOD data.cache
2219@c EN
2220Looks for an entry with @var{key} in @var{cache}.
2221If it exists, returns a pair of @var{key} and the associated value.
2222Otherwise, returns @code{#f}.  It may update the cache,
2223for example, the timestamp of the entry for being read.
2224@c JP
2225@var{cache}から@var{key}に結びついたエントリを探します。
2226見つかれば、@var{key}とその値とのペアを、見つからなければ@code{#f}を返します。
2227この時、必要ならばキャッシュを更新して構いません。
2228例えば読み出されたエントリのタイムスタンプを更新するなどです。
2229@c COMMON
2230@end deffn
2231
2232@deffn {Generic function} cache-register! cache key value
2233@c MOD data.cache
2234@c EN
2235Add an entry with @var{key} and associated @var{value} into @var{cache}.
2236This is called after @var{key} is confirmed not being in @var{cache}.
2237@c JP
2238@var{cache}に、@var{key}と対応する@var{value}を追加します。
2239このメソッドは、@var{cache}に@var{key}に対応するエントリが無いことが確認された後で
2240呼び出されます。
2241@c COMMON
2242@end deffn
2243
2244@c EN
2245Additionally, the implementation should consider the following points.
2246@c JP
2247アルゴリズムの実装は、また以下の点を考慮しなければなりません。
2248@c COMMON
2249
2250@itemize @bullet
2251@item
2252The initialize method must call @code{next-method} first, which sets up
2253the @code{comparator} and @code{storage} slots.  You should check
2254if @code{storage} has pre-filled entries, and if so, set up other
2255internal structures appropriately.
2256@item
2257The default methods of @code{cache-evict!} and @code{cache-clear!} only
2258takes care of the storage of the cache.  You should implement them
2259if your auxiliary structure needs to be taken care of.
2260@item
2261The default method of @code{cache-write!} is just @code{cache-evict!}
2262followed by @code{cache-register!}.  You may provide alternative method
2263if you can do it more efficiently, which is often the case.
2264@end itemize
2265
2266There are several procedures that help implementing cache subclasses:
2267
2268@defun cache-comparator cache
2269@defunx cache-storage cache
2270@c MOD data.cache
2271Returns the comparator and the storage of the cache, respectively.
2272@end defun
2273
2274Typical caches may be constructed with a storage (dictionary) and
2275a queue, where the storage maps keys to @code{(<n> . <value>)},
2276and queues holds @code{(<key> . <n>)}, @code{<n>} being a number
2277(timestamp, counter, etc.)  Here are some common operations work
2278on this queue-and-dictionary scheme:
2279
2280@defun cache-populate-queue! queue storage
2281@c MOD data.cache
2282You can call this in the @code{initialize} method to set up the
2283queue.  This procedure walks storage to construct @code{(<key> . <n>)}
2284pairs, sorts it in increasing order of @code{<n>}, and pushes them
2285into the queue.
2286@end defun
2287
2288@defun cache-compact-queue! queue storage
2289@c MOD data.cache
2290The queue may contain multiple pairs with the same key.  Sometimes the
2291queue gets to have too many duplicated entries (e.g. the same entry
2292is read repeatedly).  This scans the queue and removes duplicated entries
2293but the up-to-date one.  After this operation, the length of the queue
2294and the number of entries in the storage should match.
2295@end defun
2296
2297@defun cache-renumber-entries! queue storage
2298@c MOD data.cache
2299This procedure renumbers @code{<n>}s in the queue and the storage
2300starting from 0, without changing their order, and returns the
2301maximum @code{<n>}.  The duplicated entries in the queue is removed
2302as in @code{cache-compact-queue!}.
2303
2304When you're using monotonically increasing counter for @code{<n>} and
2305you don't want @code{<n>} to get too big (i.e. bignums), you can
2306call this procedure occasionally to keep @code{<n>}'s in reasonable
2307range.
2308@end defun
2309
2310
2311@c ----------------------------------------------------------------------
2312@node Heap, Immutable deques, Cache, Library modules - Utilities
2313@section @code{data.heap} - Heap
2314@c NODE ヒープ, @code{data.heap} - ヒープ
2315
2316@deftp {Module} data.heap
2317@mdindex data.heap
2318@c EN
2319A heap is a data container that allows efficient retrieval of
2320the minimum or maximum entry.  Unlike a @code{<tree-map>}
2321(@pxref{Treemaps}), which always keeps all entries in order,
2322a heap only cares the minimum or the maximum of the current set;
2323the other entries are only partially ordered, and reordered
2324when the minimu/maximum entry is removed.  Hence it is more
2325efficient than a treemap if all you need is minimum/maximum value.
2326Besides binary heaps can store entries in packed, memory-efficient way.
2327@c JP
2328ヒープは最小値また最大値を効率よく取り出せるデータコンテナです。
2329@code{<tree-map>}は全てのエントリの順序を常に保っていますが (@ref{Treemaps}参照)、
2330ヒープは最小値/最大値以外については部分的にしか順序を保持していません。
2331最小値/最大値が取り除かれる時点で内部を再構成して、次の最小値/最大値を見つけます。
2332したがって、最小値/最大値のみが必要な場合、treemapより効率が良いです。
2333さらに、バイナリヒープでは値をメモリ効率の良い詰められた形で保持できます。
2334@c COMMON
2335@end deftp
2336
2337@deftp {Class} <binary-heap>
2338@clindex binary-heap
2339@c MOD data.heap
2340@c EN
2341An implementation of a binary heap.  Internally it uses min-max heap,
2342so that you can find both minimum and maximum value in O(1).
2343Pushing a new value and popping the minimum/maximum value are both O(log n).
2344
2345It also stores its values in a flat vector, a lot more compact
2346than a general tree structure that needs a few pointers per node.
2347By default it uses a sparse vector for the backing storage, allowing
2348virtually unlimited capacity (@pxref{Sparse vectors}).
2349But you can use an ordinal vector
2350or a uniform vector as a backing storage instead.
2351@c JP
2352バイナリヒープの実装です。内部的にmin-maxヒープを使っており、
2353最大値と最小値のどちらにもO(1)でアクセスできます。新たな値をpushしたり、
2354最大最小値をpopするのはO(log n)です。
2355
2356バイナリヒープはまた、値をフラットなベクタに格納します。一般的なツリー構造が
2357ノードあたりいくつかのポインタを必要とするのに比べずっとコンパクトです。
2358デフォルトでは疎なベクタ (@ref{Sparse vectors}) がバッキングストレージとして使われ、
2359事実上上限なしでデータを格納できますが、通常のベクタやユニフォームベクタを
2360バッキングストレージとして指定することもできます。
2361@c COMMON
2362
2363@c EN
2364A binary heap isn't MT-safe structure; you must put it in atom
2365or use mutexes if multiple threads can access to it
2366(@pxref{Synchronization primitives}).
2367@c JP
2368バイナリヒープはスレッドセーフではありません。複数のスレッドでアクセスする
2369可能性がある場合は、atomに入れるか、mutexを適切に使ってください(@ref{Synchronization primitives}参照)。
2370@c COMMON
2371@end deftp
2372
2373@defun make-binary-heap :key comparator storage key
2374@c MOD data.heap
2375@c EN
2376Creates and returns a new binary heap.
2377
2378The @var{comparator} keyword argument specifies how to compare the
2379entries.  It must have comparison procedure or ordering predicate.
2380The default is @code{default-comparator}.
2381@xref{Basic comparators}, for the details of comparators.
2382
2383The @var{storage} keyword argument gives alternative
2384backing storage.  It must be either a vector, a uniform vector,
2385or an instance of a sparse vector (@pxref{Sparse vectors}).
2386The default is an instance of @code{<sparse-vector>}.
2387If you pass a vector or a uniform vector, it determines
2388the maximum number of elements the heap can hold.
2389The heap won't be extend the storage once it gets full.
2390
2391The @var{key} keyword argument must be a procedure; it is applied
2392on each entry before comparison.  Using key procedure allows you to
2393store auxiliary data other than the actual value to be compared.
2394The following example shows the entries are compared by their @code{car}'s:
2395@c JP
2396新しいバイナリヒープを作って返します。
2397
2398@var{comparator}キーワード引数は、エントリの比較方法を指定する比較器です。
2399比較手続きを持っていなければなりません。省略時は@code{default-comparator}が
2400使われます。比較器について詳しくは@ref{Basic comparators}を参照してください。
2401
2402@var{storage}キーワード引数には、データの格納に使うデータ構造を渡します。引数は
2403ベクタ、ユニフォームベクタ、あるいは疎ベクタ(@ref{Sparse vectors}参照)の
2404インスタンスでなければなりません。省略時は@code{<sparse-vector>}の
2405インスタンスが使われます。
2406
2407ベクタまたはユニフォームベクタを渡した場合、そのベクタの大きさが
2408ヒープが格納できる要素の最大数を決めます。
2409それが一杯になった時に自動的に拡張されることはありません。
2410
2411@var{key}キーワード引数は手続きでなければならず、要素の比較の前に各要素に適用されます。
2412この手続きを使って、実際に比較される値に付随するデータを格納しておくことができます。
2413次の例では、データの@code{car}を使って比較しています。
2414@c COMMON
2415
2416@example
2417(define *heap* (make-binary-heap :key car))
2418(binary-heap-push! *heap* (cons 1 'a))
2419(binary-heap-push! *heap* (cons 3 'b))
2420(binary-heap-push! *heap* (cons 1 'c))
2421
2422(binary-heap-find-min *heap*) @result{} (1 . c)
2423(binary-heap-find-max *heap*) @result{} (3 . b)
2424@end example
2425@end defun
2426
2427@defun build-binary-heap storage :key comparator key num-entries
2428@c MOD data.heap
2429@c EN
2430Create a heap from the data in @var{storage}, and returns it.
2431(Sometimes this operation is called @emph{heapify}.)
2432This allows you to create a heap without allocating a new storage.
2433The @var{comparator} and @var{key} arguments are the same as
2434@code{make-binary-heap}.
2435
2436@var{Storage} must be either a vector, a uniform vector,
2437or an instance of a sparse vector.  The storage is modified
2438to satisfy the heap property, and will be used as the backing
2439storage of the created heap.  Since the storage will be owned
2440by the heap, you shouldn't modify the storage later.
2441
2442The storage supposed to have keys from index 0 below
2443@var{num-entries}.
2444If @var{num-entries} is omitted or @code{#f}, entire vector or
2445uniform vector, or up to @code{sparse-vector-num-entries} on
2446the sparse vector, is heapified.
2447@c JP
2448@var{storage}に入っているデータを使ってヒープを作り返します。
2449(この操作はしばしばヒープ化(@emph{heapify})と呼ばれます。)
2450データ格納場所を新たにアロケートせずにヒープを作ることが可能です。
2451@var{comparator}および@var{key}引数は@code{make-binary-heap}と同じです。
2452
2453@var{storage}はベクタ、ユニフォームベクタ、疎ベクタのインスタンスでなければ
2454なりません。このデータはヒープの属性を満たすために変更され、さらには
2455作られたヒープのデータ格納場所となります。ヒープの一部になるので、
2456@var{storage}を後から変更してはなりません。
2457
2458@var{storage}の要素のうち、先頭から@var{num-entries}までの要素が
2459有効であるとしてヒープ化されます。@var{num-entries}が省略されるか
2460@code{#f}であれば、ベクタおよびユニフォームベクタはその全てが、
2461疎ベクタは@code{sparse-vector-num-entries}までの要素がヒープ化されます。
2462@c COMMON
2463@end defun
2464
2465@defun binary-heap-copy heap
2466@c MOD data.heap
2467@c EN
2468Copy the heap.  The backing storage is also copied.
2469@c JP
2470ヒープをコピーして返します。データ格納場所も全てコピーされます。
2471@c COMMON
2472@end defun
2473
2474@defun binary-heap-clear! heap
2475@c MOD data.heap
2476@c EN
2477Empty the heap.
2478@c JP
2479ヒープを空にします。
2480@c COMMON
2481@end defun
2482
2483@defun binary-heap-num-entries heap
2484@c MOD data.heap
2485@c EN
2486Returns the current number of entries in the heap.
2487@c JP
2488ヒープ中の要素数を返します。
2489@c COMMON
2490@end defun
2491
2492@defun binary-heap-empty? heap
2493@c MOD data.heap
2494@c EN
2495Returns @code{#t} if the heap is empty, @code{#f} otherwise.
2496@c JP
2497ヒープが空なら@code{#t}を、そうでなければ@code{#f}を返します。
2498@c COMMON
2499@end defun
2500
2501@defun binary-heap-push! heap item
2502@c MOD data.heap
2503@c EN
2504Insert @var{item} into the @var{heap}.  This is O(log n) operation.
2505If the heap is already full, an error is raised.
2506@c JP
2507@var{item}を@var{heap}に挿入します。O(log n)の操作です。
2508ヒープが既に一杯であった場合はエラーが通知されます。
2509@c COMMON
2510@end defun
2511
2512@defun binary-heap-find-min heap :optional fallback
2513@defunx binary-heap-find-max heap :optional fallback
2514@c MOD data.heap
2515@c EN
2516Returns the minimum and maximum entry of the heap, respectively.
2517The heap will be unmodified.  This is O(1) operation.
2518
2519If the heap is empty, @var{fallback} is returned when it is provided,
2520or an error is signaled.
2521@c JP
2522それぞれヒープ中の最小および最大の要素を返します。O(1)の操作です。
2523ヒープ自体は変更されません。
2524
2525ヒープが空の場合、@var{fallback}が与えられればそれが返され、
2526そうでなければエラーが通知されます。
2527@c COMMON
2528@end defun
2529
2530@defun binary-heap-pop-min! heap
2531@defunx binary-heap-pop-max! heap
2532@c MOD data.heap
2533@c EN
2534Removes the minimum and maximum entry of the heap and returns it,
2535respectively.  O(log n) operation.
2536If the heap is empty, an error is signaled.
2537@c JP
2538それぞれヒープから最小および最大の要素を取り除き、取り除いた要素を返します。
2539O(log n)の操作です。
2540ヒープが空ならエラーが通知されます。
2541@c COMMON
2542@end defun
2543
2544@c EN
2545The following procedures are not heap operations, but provided
2546for the convenience.
2547@c JP
2548以下の手続きは一般的なデータ構造としてのヒープの操作には含まれませんが、
2549便利なので用意してあります。
2550@c COMMON
2551
2552@defun binary-heap-swap-min! heap item
2553@defunx binary-heap-swap-max! heap item
2554@c MOD data.heap
2555@c EN
2556These are operationally equivalent to the followings, respectively:
2557@c JP
2558これらはそれぞれ以下のコードと操作的には等価です。
2559@c COMMON
2560
2561@example
2562(begin0 (binary-heap-pop-min! heap)
2563  (binary-heap-push! heap item))
2564
2565(begin0 (binary-heap-pop-max! heap)
2566  (binary-heap-push! heap item))
2567@end example
2568
2569@c EN
2570However, those procedures are slightly efficient,
2571using heap property maintaining procedure only once per function call.
2572@c JP
2573ただしこれらの手続きは、
2574ヒープ特性を維持するための手続きを呼び出し毎に1回しか行わないので、
2575やや効率的です。
2576@c COMMON
2577@end defun
2578
2579
2580
2581@defun binary-heap-find heap pred
2582@c MOD data.heap
2583@c EN
2584Returns an item in the heap that satisfies @var{pred}.
2585If there are more than one item that satisfy @var{pred},
2586any one of them can be returned.  If no item satisfy @var{pred},
2587@code{#f} is returned.  This is O(n) operation.
2588@c JP
2589ヒープの中で、述語@var{pred}を満たす要素を返します。@var{pred}を満たす要素が
2590複数ある場合にどれが返るかは不定です。@var{pred}を満たす要素が無ければ
2591@code{#f}が返ります。O(n)の操作です。
2592@c COMMON
2593@end defun
2594
2595@defun binary-heap-remove! heap pred
2596@c MOD data.heap
2597@c EN
2598Remove all items in the heap that satisfy @var{pred}.  This is O(n) operation.
2599@c JP
2600@var{pred}を満たす要素を全てヒープから取り除きます。O(n)の操作です。
2601@c COMMON
2602@end defun
2603
2604@defun binary-heap-delete! heap item
2605@c MOD data.heap
2606@c EN
2607Delete all items in the heap that are equal to @var{item},
2608in terms of the heap's comparator and key procedure.  This is O(n) operation.
2609
2610Note that the key procedure is applied to @var{item} as well
2611before comparison.
2612@c JP
2613@var{item}に等しい要素を全てヒープから取り除きます。「等しい」の判定には
2614ヒープの比較器およびキー手続きが使われます。O(n)の操作です。
2615
2616キー手続きは、比較の前に@var{item}にも適用されます。
2617@c COMMON
2618@end defun
2619
2620@c ----------------------------------------------------------------------
2621@node Immutable deques, Immutable map, Heap, Library modules - Utilities
2622@section @code{data.ideque} - Immutable deques
2623@c NODE 変更不可な両端キュー, @code{data.ideque} - 変更不可な両端キュー
2624
2625@deftp {Module} data.ideque
2626@mdindex data.ideque
2627This module provides a functional double-ended queue (deque,
2628pronounced as ``deck'').
2629
2630Almost all procedures in this module are now a part of R7RS large.
2631@xref{R7RS immutable deques}, for description of the following
2632procedures:
2633
2634@example
2635ideque               ideque-unfold        ideque-unfold-right
2636ideque-tabulate      ideque?              ideque-empty?
2637ideque-add-front     ideque-add-back
2638ideque-remove-front  ideque-remove-back
2639ideque-front         ideque-back
2640ideque-reverse       ideque=              ideque-ref
2641ideque-take          ideque-drop
2642ideque-take-right    ideque-drop-right
2643ideque-split-at      ideque-append        ideque-zip
2644ideque-map           ideque-for-each      ideque-for-each-right
2645ideque-fold          ideque-fold-right    ideque-append-map
2646ideque-filter        ideque-remove
2647ideque-find          ideque-find-right
2648ideque-take-while    ideque-take-while-right
2649ideque-drop-while    ideque-drop-while-right
2650ideque-span          ideque-break
2651ideque-any           ideque-every
2652ideque->list         list->ideque
2653ideque->generator    generator->ideque
2654@end example
2655@end deftp
2656
2657@defun make-ideque n :optional init
2658@c MOD data.ideque
2659Creates an ideque of length @var{n} with all the elements being
2660@var{init}.  If @var{init} is omitted, @code{#f} is used.
2661
2662This is provided just for the symmetry with other container data
2663structures; it's not in srfi-134, and the portable code can use
2664@code{ideque-tabulate}.
2665@end defun
2666
2667
2668@c ----------------------------------------------------------------------
2669@node Immutable map, Priority map, Immutable deques, Library modules - Utilities
2670@section @code{data.imap} - Immutable map
2671@c NODE 変更不可なマップ, @code{data.imap} - 変更不可なマップ
2672
2673@deftp {Module} data.imap
2674@mdindex data.imap
2675@c EN
2676This module provides a immutable data structure with O(log n)
2677access and update operations (here, update means to return a
2678new structure with requested changes).
2679The current implementation is
2680based on the functional red-black tree.
2681@c JP
2682このモジュールは、O(log n)でアクセスと更新が可能な、変更不可のデータ構造を
2683提供します(ここでの「更新」とは、要求された変更を取り込んだ新たな構造を
2684作って返すことです)。
2685現在の実装は関数的な赤黒木に基づいています。
2686@c COMMON
2687@end deftp
2688
2689@c EN
2690Although lists and alists are useful for stack-like immutable
2691operations, where you can add and remove items to the head of
2692existing data without modifying them, they require O(n) access time
2693and sometimes you need better one.  The @code{<imap>} object
2694provides O(log n) access, in exchange of O(log n) insertion and
2695deletion.
2696@c JP
2697リストや連想リストは、スタック風の変更不可なデータ構造として使えます。
2698つまり既存のデータ構造自体に変更を加えることなく、その先頭に要素を追加したり、
2699先頭から要素を取り除いたりできるということです。一方で、リストや連想リストは
2700任意の要素にアクセスするにはO(n)の時間を必要としますが、もっと速いアクセスが必要な
2701場合もあります。@code{<imap>}オブジェクトはO(log n)のアクセスを可能にします。
2702そのかわり、要素の追加や削除にもO(log n)を必要とします。
2703@c COMMON
2704
2705@deftp {Class} <imap-meta>
2706@c MOD data.imap
2707@c EN
2708Metaclass of @code{<imap>}.
2709@c JP
2710@code{<imap>}のメタクラスです。
2711@c COMMON
2712@end deftp
2713
2714@deftp {Class} <imap>
2715@c MOD data.imap
2716@c EN
2717Immutable map class.  An instance of @code{<imap-meta>}.
2718
2719Inherits @code{<ordered-dictionary>}, conforms dictionary protocol
2720except mutating operators (@pxref{Dictionary framework}).
2721As a sequence, you can access key-value
2722pairs in increasing order of keys.
2723@c JP
2724変更不可なマップのクラスです。@code{<imap-meta>}をメタクラスとします。
2725
2726@code{<ordered-dictionary>}を継承し、変更操作を除くディクショナリプロトコル
2727を実装します(@ref{Dictionary framework}参照)。
2728シーケンスとしてアクセスした場合は、キーと値のペアをキーの昇順に取り出すことができます。
2729@c COMMON
2730@end deftp
2731
2732@defun make-imap
2733@defunx make-imap comparator
2734@defunx make-imap key=? key<?
2735@c MOD data.imap
2736@c EN
2737Creates a new empty immutable map.  Without arguments,
2738@code{default-comparator} is used to compare keys.  To give a
2739specific comparator, use the second form; the @var{comparator}
2740argument should have comparison procedure.
2741For the details of comparators, @pxref{Basic comparators}.
2742The third form creates a key comparator from a equality
2743predicate @var{key=?} and less-than predicate @code{key<?},
2744both must accept two keys.  This interface is consistent with
2745@code{tree-map} (@pxref{Treemaps}).
2746@c JP
2747空の変更不可なマップを新たに作って返します。
2748引数無しの場合は、キーの比較には@code{default-comparator}が使われます。
2749キーの比較方法を指定したい場合は、比較手続きを持つ比較器@var{comparator}を
2750引数に渡してください。比較器については@ref{Basic comparators}を参照。
27513番目の呼び出し形式は、キーの等価性を調べる述語@var{key=?}と
2752大小比較の述語@var{key<?}から比較器を作ります。どちらの述語も
2753ふたつの引数をとらなければなりません。このインタフェースは
2754@code{tree-map}との一貫性のためにサポートされています (@ref{Treemaps}参照)。
2755@c COMMON
2756@end defun
2757
2758@defun alist->imap alist
2759@defunx alist->imap alist comparator
2760@defunx alist->imap alist key=? key<?
2761@c MOD data.imap
2762Creates a new empty immutable map, populates it with
2763key-value association list @var{alist}, and returns it.
2764This may be a bit more efficient than creating an empty map with
2765@code{make-imap} and populates it with @code{imap-put}
2766one by one.
2767
2768The @var{comparator} argument specifies how to compare the keys.
2769It must have comparison procedure.  If omitted, @code{default-comparator}
2770is used.  @xref{Basic comparators}, for the details.
2771
2772The third form creates a key comparator from a equality
2773predicate @var{key=?} and less-than predicate @code{key<=?},
2774both must accept two keys.
2775
2776@example
2777(define m (alist->imap '((a . 1) (b . 2))))
2778
2779(imap-get m 'a) @result{} 1
2780(imap-get m 'b) @result{} 2
2781@end example
2782@end defun
2783
2784@defun tree-map->imap tree-map
2785@c MOD data.imap
2786Returns a new immutable map with the same content (and the same comparator)
2787as @var{tree-map}.
2788@end defun
2789
2790@defun imap? obj
2791@c MOD data.imap
2792Returns @code{#t} if @var{obj} is an immutable map,
2793@code{#f} otherwise.
2794@end defun
2795
2796@defun imap-empty? immap
2797@c MOD data.imap
2798Returns @code{#t} if an immutable map @var{immap} is empty,
2799@code{#f} otherwise.
2800@end defun
2801
2802@defun imap-exists? immap key
2803@c MOD data.imap
2804Returns @code{#t} if @var{key} exists in an immutable map @var{immap}.
2805@end defun
2806
2807@defun imap-get immap key :optional default
2808@c MOD data.imap
2809Returns the value associated with @var{key} in an immutable map @var{immap}.
2810If @var{immap} doesn't have @var{key}, @var{default} is returned
2811when provided, otherwise an error is signalled.
2812@end defun
2813
2814@defun imap-put immap key val
2815@c MOD data.imap
2816Returns a new immutable map where association of @var{key} to @var{val}
2817is added to (or replaced in) an immutable map @var{immap}.
2818This operation is O(log n).
2819
2820@example
2821(define m1 (alist->imap '((a . 1) (b . 2))))
2822
2823(define m2 (imap-put m1 'a 3))
2824
2825(imap-get m2 'a)  @result{} 3
2826(imap-get m1 'a)  @result{} 1  ; not affected
2827@end example
2828@end defun
2829
2830@defun imap-delete immap key
2831@c MOD data.imap
2832Returns a new immutable map where @var{key} is removed from
2833@var{immap}.   If @var{immap} doesn't have @var{key}, returned
2834map has the same content as @var{immap}.
2835
2836@example
2837(define m1 (alist->imap '((a . 1) (b . 2))))
2838
2839(define m2 (imap-delete m1 'a))
2840
2841(imap-get m2 'a #f)  @result{} #f
2842(imap-get m1 'a)     @result{} 1  ; not affected
2843@end example
2844@end defun
2845
2846@defun imap-min immap
2847@defunx imap-max immap
2848@c MOD data.imap
2849Returns a pair of key and value with the minimum or maximum
2850key in @var{immap}, respectively.  If @var{immap} is empty,
2851@code{#f} is returned.
2852@end defun
2853
2854@c ----------------------------------------------------------------------
2855@node Priority map, Queue, Immutable map, Library modules - Utilities
2856@section @code{data.priority-map} - Priority map
2857@c NODE プライオリティマップ, @code{data.priority-map} - プライオリティマップ
2858
2859@deftp {Module} data.priority-map
2860@mdindex data.priority-map
2861Priority map is a dictionary that can map keys to values, while
2862the entires are sorted by their @emph{values}.
2863(If the entires are sorted by keys, it's a treemap--@pxref{Treemaps}).
2864
2865It is useful when you wanted a sorted sequence, with quick access by
2866keys that are associated to each value.
2867
2868Note: If what you need is just a priority queue, you can use
2869@code{data.heap} (@pxref{Heap}).
2870@end deftp
2871
2872@deftp {Class} <priority-map>
2873@cindex priority-map
2874@c MOD data.priority-map
2875Priority map class.  It has no public slots.
2876Instances of priority maps must be created by
2877@code{make-priority-map} procedure instead of @code{make} method on
2878the class.
2879
2880Inherits @code{<ordered-dictionary>}, and implements dictionary protocol.
2881Operations concerning
2882associations of keys and values are done through dictionary generic
2883functions (@pxref{Generic functions for dictionaries}).
2884
2885When iterated, it iterates increasing order of values.
2886@end deftp
2887
2888@defun make-priority-map :key key-comparator value-comparator
2889@c MOD data.priority-map
2890Creates and returns an empty priority map.
2891It can take @var{key-comparator}, which must have a hash procedure
2892and is used to hash keys, and
2893@var{value-comparator}, which must have ordering predicate
2894and is used to order values.
2895When omitted, @code{default-comparator} is assumed.
2896@end defun
2897
2898@defun priority-map-min pmap
2899@defunx priority-map-max pmap
2900@c MOD data.priority-map
2901Return a pair of a key and a value, where the value is smallest or
2902largest in the priority map @var{pmap}, respectively.
2903
2904If @var{pmap} is empty, @code{#f} is returned.
2905
2906If @var{pmap} has more than one value that are equal to each other
2907(w.r.t. @var{value-comparator} given to the constructor),
2908either one of them is picked.
2909@end defun
2910
2911@defun priority-map-pop-min! pmap
2912@defunx priority-map-pop-max! pmap
2913@c MOD data.priority-map
2914Remove one entry with the smallest or largest value, respectively,
2915and returns a pair of the key and the value of removed entry.
2916
2917If @var{pmap} is empty, @var{#f} is returned.
2918
2919If @var{pmap} has more than one value that are equal to each other
2920(w.r.t. @var{value-comparator} given to the constructor),
2921either one of them is picked.
2922@end defun
2923
2924@c ----------------------------------------------------------------------
2925@node Queue, Random data generators, Priority map, Library modules - Utilities
2926@section @code{data.queue} - Queue
2927@c NODE キュー, @code{data.queue} - キュー
2928
2929@deftp {Module} data.queue
2930@mdindex data.queue
2931@c EN
2932Provides a queue (FIFO).  You can create a simple queue,
2933which is lightweight but not thread-safe, or an MTqueue,
2934a thread-safe queue.  Basic queue operations work on
2935both type of queues.  When an mtqueue is passed to the
2936procedures listed in this section, each operation is
2937done in atomic way, unless otherwise noted.
2938
2939There are also a set of procedures for mtqueues that
2940can be used for thread synchronization; for example,
2941you can let the consumer thread block if an
2942mtqueue is empty, and/or the producer thread block if the number
2943of items in the mtqueue reaches a specified limit.
2944Using these procedures allows the program to use an mtqueue
2945as a @emph{channel}.
2946
2947The simple queue API is a superset of SLIB's queue implementation,
2948which supports not only @code{enqueue!} (add item to the end of the sequence)
2949and @code{dequeue!} (take item from the front of the sequence), but also
2950@code{queue-push!} (add item to the front of the sequence), so that
2951it can be used as a stack as well.
2952
2953If you also want to take item from the end of the sequence in O(1),
2954you need a deque (double-ended queue).
2955@xref{Ring buffer}, which works as an efficient (both speed and space)
2956dequeue on top of vectors.  Or you can use immutable deques
2957provided by @code{data.ideque} (@pxref{Immutable deques}).
2958
2959See also @code{scheme.list-queue} (@ref{R7RS list queues}), which defines a
2960portable API for list-based queue.
2961@c JP
2962キュー(FIFO)機能を提供します。
2963極めて軽量ですがスレッドセーフでないシンプルなキューと、
2964スレッドセーフなmtqueueがあります。基本的なキュー操作手続きは
2965どちらのキューに対しても使うことができます。本節で説明されている
2966手続きをmtqueueに適用した場合、特に断りが無い限り、操作は
2967アトミックに行われます。
2968
2969また、スレッド間同期に使えるmtqueue用の手続きも用意されています。
2970例えばキューが空の時に読み出しスレッドをブロックさせたり
2971キューの長さが指定値に達した場合に書き込みスレッドをブロックさせることができ、
2972いわゆる「チャネル」としてキューを使うことができます。
2973
2974シンプルキューのAPIはSLIBのキュー実装の上位互換になっています。
2975要素を並びの末尾に追加する@code{enqueue!}と、要素を並びの先頭から取り除く
2976@code{dequeue!}だけでなく、要素を並びの先頭に追加する@code{queue-push!}も
2977提供されているので、スタックとしても使えます。
2978
2979要素を並びの末尾からO(1)で取り除くAPIも欲しい場合は、
2980deque (double-ended queue)が必要です。@code{data.ring-buffer}モジュール
2981は、ベクタの上に実装された(空間的にも時間的にも)効率の良いdequeを提供しています
2982(@ref{Ring buffer}参照)。また、変更不可な両端キュー@code{data.ideque}
2983もあります(@ref{Immutable deques}参照)。
2984
2985また、@code{scheme.list-queue}はポータブルなリストベースのキューのAPIを提供しています
2986(@ref{R7RS list queues})。
2987@c COMMON
2988@end deftp
2989
2990@deftp {Class} <queue>
2991@clindex queue
2992@c MOD data.queue
2993@c EN
2994A class of simple queue.
2995@c JP
2996シンプルなキューのクラスです。
2997@c COMMON
2998
2999@defivar {<queue>} length
3000@c EN
3001A read-only slot that returns the number of items in the queue.
3002@c JP
3003キュー中の要素の数を返す、読み取り専用のスロットです。
3004@c COMMON
3005@end defivar
3006@end deftp
3007
3008@deftp {Class} <mtqueue>
3009@c MOD data.queue
3010@clindex mtqueue
3011@c EN
3012A class of mtqueue.  Inherits @code{<queue>}.
3013@c JP
3014mtqueueのクラスです。@code{<queue>}を継承しています。
3015@c COMMON
3016
3017@defivar {<mtqueue>} max-length
3018@c EN
3019The upper bound of the number of items in the queue.
3020@c JP
3021キュー中の要素数の上限を示します。
3022@c COMMON
3023
3024@c EN
3025If this slot is zero, the queue cannot hold any items, but
3026works as a synchronization device.
3027A writer will block until a reader appears to take the item;
3028a reader will block until a writer appears to give the item.
3029@c JP
3030このスロットが0の場合、キューは要素を中に持つことはできませんが、同期デバイスとして動作します。
3031書き込みスレッドは、その要素を受け取る読み出しスレッドが現れるまでブロックし、
3032読み出しスレッドは、要素を渡してくれる書き込みスレッドが現れるまでブロックします。
3033@c COMMON
3034@end defivar
3035@end deftp
3036
3037@defun make-queue
3038@c MOD data.queue
3039@c EN
3040Creates and returns an empty simple queue.
3041@c JP
3042空のシンプルなキューを作って返します。
3043@c COMMON
3044@end defun
3045
3046@defun make-mtqueue :key max-length
3047@c MOD data.queue
3048@c EN
3049Creates and returns an empty mtqueue.  When an integer is given
3050to the keyword argument @var{max-length}, it is used to
3051initialize the @code{max-length} slot.
3052@c JP
3053空のmtqueueを作って返します。整数が@var{max-length}に与えられた場合は、
3054それが@code{max-length}スロットの値となります。
3055@c COMMON
3056@end defun
3057
3058@defun queue? obj
3059@c MOD data.queue
3060@c EN
3061Returns @code{#t} if @var{obj} is a queue (either a simple queue
3062or an mtqueue).
3063@c JP
3064@var{obj}がキューであれば(シンプルなキューでもmtqueueでも)@code{#t}を返します。
3065@c COMMON
3066@end defun
3067
3068@defun mtqueue? obj
3069@c MOD data.queue
3070@c EN
3071Returns @code{#t} if @var{obj} is an mtqueue.
3072@c JP
3073@var{obj}がmtqueueであれば@code{#t}を返します。
3074@c COMMON
3075@end defun
3076
3077@defun queue-empty? queue
3078@c MOD data.queue
3079@c EN
3080Returns @code{#t} if @var{obj} is an empty queue.
3081@c JP
3082@var{obj}が空のキューであれば@code{#t}を返します。
3083@c COMMON
3084@end defun
3085
3086@defun queue-length queue
3087@c MOD data.queue
3088@c EN
3089Returns the number of the items in the queue.
3090@c JP
3091キューの中にある要素の数を返します。
3092@c COMMON
3093@end defun
3094
3095@defun mtqueue-max-length mtqueue
3096@c MOD data.queue
3097@c EN
3098Returns the maximum number of items the mtqueue can hold.
3099If the queue doesn't have a limit, @code{#f} is returned.
3100@c JP
3101キューが保持できる要素の最大数を返します。限度がない場合は@code{#f}が返ります。
3102@c COMMON
3103@end defun
3104
3105@defun mtqueue-room mtqueue
3106@c MOD data.queue
3107@c EN
3108Returns the number of elements the mtqueue can accept at this moment
3109before it hits its maximum length.   For example, if the queue
3110already has the maximum number of elements, 0 is returned.
3111If the queue doesn't have the limit, @code{+inf.0} is returned.
3112@c JP
3113保持できる最大容量に達するまであといくつ要素を受け入れることができるかを
3114示す整数を返します。例えば、既にキューがいっぱいであれば0が返ります。
3115キューに最大容量が設定されていなければ@code{+inf.0}が返ります。
3116@c COMMON
3117
3118@c EN
3119Note that even if this returns a non-zero finite value, subsequent
3120@code{enqueue!} may throw an error because of the queue being full.
3121It's because another thread may put an item to the queue
3122between this procedure call and @code{enqueue!}.  To avoid
3123this situation, use @code{enqueue/wait!} to insert item
3124to mtqueue with finite max-length.
3125@c JP
3126この手続きが0以外有限値を返した場合でも、続く@code{enqueue!}の呼び出し時点で
3127キューがいっぱいになっている可能性があることに注意してください。
3128この手続きの呼び出しと@code{enqueue!}の
3129呼び出しの間に、他のスレッドがキューに要素を入れるかもしれないからです。
3130有限長のmtqueueに確実に要素を挿入したい場合は@code{enqueue/wait!}を使ってください。
3131@c COMMON
3132@end defun
3133
3134@defun mtqueue-num-waiting-readers mtqueue
3135@c MOD data.queue
3136@c EN
3137Returns the number of threads waiting on the mtqueue to read
3138at this moment.
3139The return value is always a nonnegative exact integer.
3140
3141Note that the value might change between this procedure's returning
3142the value and your checking it, if some other thread inserts
3143an element into the queue.  To use the value reliably, you need
3144another mutex to restrict putting items in the queue.
3145@c JP
3146@var{mtqueue}からの読み出しで待っているスレッドの数を返します。
3147返り値は常に非負の正確な整数です。
3148
3149この手続きが値を返してからその値を使うまでの間に、別のスレッドが
3150キューに要素を挿入したら、待っているスレッドの数は変わってしまうことに
3151注意してください。この手続きの返り値を安全に使うには、
3152キューに値を挿入する部分を別に排他制御する必要があります。
3153@c COMMON
3154
3155@example
3156(define q (make-mtqueue))
3157
3158(thread-start! (make-thread (^[] (dequeue/wait! q))))
3159
3160(mtqueue-num-waiting-readers q) @result{} 1
3161
3162(enqueue! q 'a)
3163
3164(mtqueue-num-waiting-readers q) @result{} 0
3165@end example
3166@end defun
3167
3168@defun copy-queue queue
3169@c MOD data.queue
3170@c EN
3171Returns a copy of the queue.
3172@c JP
3173キューqueueのコピーを返します。
3174@c COMMON
3175@end defun
3176
3177@defun enqueue! queue obj :optional more-objs @dots{}
3178@c MOD data.queue
3179@c EN
3180Add @var{obj} to the end of @var{queue}.  You may give more than
3181one object, and each of them are enqueued in order.
3182@c JP
3183@var{obj}をキュー@var{queue}の末尾に追加します。
3184一つ以上の@var{obj}を与えることができ、その場合はそれらが順にenqueueされます。
3185@c COMMON
3186
3187@c EN
3188If @var{queue} is an mtqueue, all the objects are enqueued
3189atomically; no other objects from other threads can be inserted
3190between the objects given to a single @code{enqueue!} call.
3191Besides, if the value of its @code{max-length} slot
3192has a positive finite value, and adding @var{obj}s makes the number of
3193elements in @var{queue} exceeds @code{max-length},
3194an error is signaled and @var{queue} won't be modified.
3195(If @code{max-length} is zero, this procedure always fail.
3196Use @code{enqueue/wait!} below.)
3197@c JP
3198@var{queue}がmtqueueの場合、渡されたオブジェクト全ての追加は
3199アトミックに行われます。すなわち、途中に別スレッドが要素を挿入する
3200ことはありません。さらに、@code{max-length}スロットが正の有限値を
3201持っており、この@code{enqueue!}の実行によってキューの要素数が
3202@code{max-length}を越えることになる場合は、@var{queue}は
3203変更されずエラーとなります。
3204(@code{max-length}がゼロの場合、この手続きは常にエラーとなります。
3205下に説明する@code{enqueue/wait!}を使ってください。)
3206@c COMMON
3207@end defun
3208
3209@defun queue-push! queue obj :optional more-objs @dots{}
3210@c MOD data.queue
3211@c EN
3212Add @var{obj} in front of @var{queue}.  You may give more than
3213one object, and each of them are pushed in order.
3214
3215Like @code{enqueue!}, when @var{queue} is an mtqueue,
3216all objects are added atomically, and the value of
3217@code{max-length} slot is checked.  See @code{enqueue!} above
3218for the details.
3219@c JP
3220@var{obj}をキュー@var{queue}の先頭に追加します。
3221一つ以上の@var{obj}を与えることができ、その場合はそれらが順にpushされます。
3222
3223@code{enqueue!}と同様に、@var{queue}がmtqueueの場合は
3224全てのオブジェクトはアトミックに追加され、また@code{max-length}の値も
3225チェックされます。詳しくは上の@code{enqueue!}の説明を参照してください。
3226@c COMMON
3227@end defun
3228
3229@defun enqueue-unique! queue eq-proc obj :optional more-objs @dots{}
3230@defunx queue-push-unique! queue eq-proc obj :optional more-objs @dots{}
3231@c MOD data.queue
3232@c EN
3233Like @code{enqueue!} and @code{queue-push!}, respectively, except that these
3234don't modify @var{queue} if it already contains @var{obj}
3235(elements are compared by two-argument procedure @var{eq-proc}).
3236
3237When @var{queue} is an mtqueue, all objects are added atomically,
3238and the value of
3239@code{max-length} slot is checked.  See @code{enqueue!} above
3240for the details.
3241@c JP
3242@var{obj}が既に@var{queue}の中に含まれている場合には@var{queue}を
3243変更しないことを以外には、@code{enqueue!}および@code{queue-push!}と同じ
3244動作をします。@var{obj}が含まれているかどうかの検査は
32452引数の関数@var{eq-proc}で行います。
3246
3247@var{queue}がmtqueueの場合は
3248全てのオブジェクトはアトミックに追加され、また@code{max-length}の値も
3249チェックされます。詳しくは上の@code{enqueue!}の説明を参照してください。
3250@c COMMON
3251@end defun
3252
3253@defun dequeue! queue :optional fallback
3254@defunx queue-pop! queue :optional fallback
3255@c MOD data.queue
3256@c EN
3257Take one object from the front of the queue @var{queue} and returns it.
3258Both function works the same, but @code{queue-pop!} may be used to
3259emphasize it works with @code{queue-push!}.
3260
3261If @var{queue} is empty, @var{fallback} is returned if given,
3262otherwise an error is signaled.
3263
3264If @var{queue} is an mtqueue and its @code{max-length} is zero,
3265the queue is always empty.  Use @code{dequeue/wait!} to use
3266such a queue as an synchronization device.
3267@c JP
3268キュー@var{queue}の先頭からひとつ要素を取って返します。
3269二つの手続きは全く同じ動作をします。@code{queue-pop!}は@code{queue-push!}と
3270ペアで使われていることを強調したいときに使うと良いでしょう。
3271
3272キューが空の場合は、@var{fallback}が与えられていればそれが返され、
3273そうでなければエラーが報告されます。
3274
3275キューがmtqueueでその@code{max-length}がゼロの場合、
3276キューは常に空であるとみなされます。ゼロ長のキューを同期デバイスとして
3277使う場合は@code{dequeue/wait!}を使ってください。
3278@c COMMON
3279@end defun
3280
3281@defun dequeue-all! queue
3282@c MOD data.queue
3283@c EN
3284Returns the whole content of the queue by a list, with emptying
3285@var{queue}.   If @var{queue} is already empty, returns an empty list.
3286See also @code{queue->list} below.
3287@c JP
3288キューの全ての内容をリストにして返します。キューそのものは空になります。
3289キューが既に空の場合は空リストが返されます。
3290下の@code{queue->list}も参照してください。
3291@c COMMON
3292@end defun
3293
3294@defun queue-front queue :optional fallback
3295@defunx queue-rear queue :optional fallback
3296@c MOD data.queue
3297@c EN
3298Peek the head or the tail of the queue and returns the object, respectively.
3299The queue itself is not modified.
3300If @var{queue} is empty, @var{fallback} is returned if it is given,
3301otherwise an error is signaled.
3302@c JP
3303キュー@var{queue}の先頭もしくは末尾の要素を返します。キューそのものは変更されません。
3304キューが空の場合、@var{fallback}が与えられていればその値を返し、
3305そうでなければエラーを報告します。
3306@c COMMON
3307@end defun
3308
3309@defun list->queue list :optional class :rest initargs
3310@c MOD data.queue
3311@c EN
3312Returns a new queue whose content is the elements in @var{list},
3313in the given order.
3314
3315By default the created queue is a simple queue, but you
3316can create mtqueue or instances of other subclasses of @code{<queue>}
3317by giving the class to the optional @var{class} arguments.
3318The optional @var{initargs} arguments are passed to the constructor
3319of @var{class}.
3320@c JP
3321与えられたリスト@var{list}の各要素をその順で持つようなキューを作成して返します。
3322
3323デフォルトではシンプルキューが作られますが、@var{class}に@code{<class>}の
3324サブクラスを渡すことで他のキュークラスのインスタンスを作ることができます。
3325@var{initargs}は@var{class}のコンストラクタに渡されます。
3326@c COMMON
3327@end defun
3328
3329@defun queue->list queue
3330@c MOD data.queue
3331@c EN
3332Returns a list whose content is the items in the queue in order.
3333Unlike @code{dequeue-all!}, the content of @var{queue} remains intact.
3334
3335In Gauche, @code{queue->list} copies the content of the queue to a
3336freshly allocated list, while @code{dequeue-all!} doesn't copy but
3337directly returns the queue's internal list.   There are some Scheme
3338systems that has @code{queue->list} but doesn't guarantee the content
3339is copied, so if you're planning to share the code among these
3340implementations, it's better not to rely on the fact that
3341@code{queue->list} copies the content.
3342@c JP
3343キュー@var{queue}の内容をリストにして返します。
3344@code{dequeue-all!}と異なり、キューそのものの内容は変化しません。
3345
3346Gaucheでは@code{queue->list}は新しいリストをアロケートしてキューの
3347内容をコピーします (@code{dequeue-all!}はコピーをせずにキューの内部の
3348リストをそのまま返します)。組込みで@code{queue->list}を持っているScheme
3349実装がいくつかありますが、その中には@code{queue->list}がキューの
3350内容をコピーすることを保証していないものがあるので、それらの処理系と
3351共有するコードでは@code{queue->list}がリストをコピーすることを
3352あてにしない方が良いでしょう。
3353@c COMMON
3354@end defun
3355
3356@defun queue-internal-list queue
3357@c MOD data.queue
3358@c EN
3359Like @code{queue->list}, returns a list whose content is the items
3360in the queue in order, but the returned list @emph{may} share the
3361internal storage of @var{queue}.  The returned list can be modified
3362by subsequent operations of @var{queue}, and any modification on the
3363list can make @var{queue} inconsistent.
3364
3365Because of this danger, we don't allow @code{<mtqueue>} to be
3366passed to this procedure; it would signal an error if you do so.
3367
3368If you just want to extract the accumulated result in @var{queue} without
3369copying, consider @code{dequeue-all!}, which is safe because it atomically
3370resets the queue.  Use this procedure only when you absolutely need
3371to access the contents of the queue without taking them out.
3372@c JP
3373@code{queue->list}と同じように、@var{queue}の内容をリストとして返しますが、
3374そのリストは@var{queue}の内部構造と共有されているかもしれません。
3375つまり、返されたリストは続く@var{queue}への操作によって変更される可能性があり、
3376また返されたリストを変更すると@var{queue}の一貫性は失われるでしょう。
3377
3378この危険性のため、@code{<mtqueue>}をこの手続きに渡すことは禁じられています。
3379もしそうしたらエラーとなります。
3380
3381@var{queue}に蓄積されたデータをコピーせずに取り出したいというだけなら、
3382@code{dequeue-all!}を使ってください。それは取り出すのとキューを空にする
3383操作をアトミックに行うので安全です。この手続きは、キューの中身を取り出すこと無く
3384内部にアクセスしたいという場合にだけ使って下さい。
3385@c COMMON
3386@end defun
3387
3388@defun find-in-queue pred queue
3389@c MOD data.queue
3390@c EN
3391Returns the first item in @var{queue} that satisfies a
3392predicate @var{pred}.  The order of arguments follows
3393@code{find} (@pxref{Other list procedures}).
3394@c JP
3395キュー内の要素のうち述語@var{pred}を満たす最初の要素を返します。
3396引数の順序は@code{find}に揃えました (@ref{Other list procedures}参照)。
3397@c COMMON
3398@end defun
3399
3400@defun any-in-queue pred queue
3401@c MOD data.queue
3402@c EN
3403Like @code{any} in SRFI-1, apply @var{pred} on each item
3404in @var{queue} until it evaluates true, and returns that
3405true value (doesn't necessarily be @code{#t}).  If no
3406items in the queue satisfies @var{pred}, @code{#f} is returned.
3407@c JP
3408SRFI-1の@code{any}のように、@var{queue}中の各要素に
3409順に@var{pred}を適用し、それが真の値 (@code{#t}である必要はありません) に
3410評価されたらその値を返します。@var{pred}を満たす要素が無ければ@code{#f}が
3411返ります。
3412@c COMMON
3413@end defun
3414
3415@defun every-in-queue pred queue
3416@c MOD data.queue
3417@c EN
3418Like @code{every} in SRFI-1, apply @var{pred} on each item
3419in @var{queue}.  If @var{pred} returns @code{#f}, stops
3420iteration and returns @code{#f} immediately.
3421Otherwise, returns the result of the application of
3422@var{pred} on the last item of the queue.  If the queue
3423is empty, @code{#t} is returned.
3424@c JP
3425SRFI-1の@code{every}のように、@var{queue}中の各要素に
3426順に@var{pred}を適用し、それが@code{#f}を返したらすぐ@code{#f}を返します。
3427@var{pred}に対し@code{#f}を返す要素が無ければ、最後の要素に@var{pred}を
3428適用した結果が返ります。キューが空なら@code{#f}が返ります。
3429@c COMMON
3430@end defun
3431
3432@defun remove-from-queue! pred queue
3433@c MOD data.queue
3434@c EN
3435Removes all items in the queue that satisfies @var{pred}.
3436Returns @code{#t} if any item is removed.  Otherwise returns @code{#f}.
3437The order of arguments follows
3438@code{remove} in @code{scheme.list}
3439(@pxref{R7RS lists}).
3440@c JP
3441キューから、述語@var{pred}を満たす要素を全て取り除きます。
3442要素が削除された場合は@code{#t}が、そうでなければ@code{#f}が返されます。
3443引数の順序は@code{scheme.list}
3444の@code{remove}に揃えました (@ref{R7RS lists}参照)。
3445@c COMMON
3446@end defun
3447
3448@c EN
3449Note on portability:
3450Scheme48 has @code{delete-from-queue!}, which takes object to remove
3451rather than predicate, and also takes arguments in reversed order
3452(i.e. queue comes first).   Avoid conflicting with that I intentionally
3453left out @code{delete-from-queue!}; it's easy to write one in either
3454Scheme48 compatible way or consistent to SRFI-1 argument order.
3455@c JP
3456移植性に関する註:Scheme48には、述語ではなく削除するオブジェクトそのものを取る
3457@code{delete-from-queue!}がありますが、引数の順序が逆(キューが先)になっています。
3458まぎらわしい衝突を避けるため、敢えて@code{delete-from-queue!}は
3459提供しませんでした。@code{remove-from-queue!}を使えば、Scheme48互換の方法でも、
3460あるいはSRFI-1と一貫性のある方法でも@code{delete-from-queue!}を簡単に書けるでしょう。
3461@c COMMON
3462
3463@defun enqueue/wait! mtqueue obj :optional timeout timeout-val
3464@defunx queue-push/wait! mtqueue obj :optional timeout timeout-val
3465@defunx dequeue/wait! mtqueue :optional timeout timeout-val
3466@defunx queue-pop/wait! mtqueue :optional timeout timeout-val
3467@c MOD data.queue
3468@c EN
3469These synchronizing variants work on an mtqueue and
3470make the caller thread block when the mtqueue has reached
3471its maximum length (for @code{enqueue/wait!} and @code{queue-push/wait!}),
3472or the mtqueue is empty (for @code{dequeue/wait!} and
3473@code{queue-pop/wait!}).   The blocked caller thread is unblocked
3474either when the blocking condition is resolved, or the timeout
3475condition is met.
3476
3477The optional @var{timeout} argument specifies the timeout condition.
3478If it is @code{#f}, those procedures wait indefinitely.
3479If it is a real number, they wait at least the given number of
3480seconds.  If it is a @code{<time>} object (@pxref{Time}),
3481they wait until the absolute point of time the argument specifies.
3482
3483In case the call is blocked then timed out, the value of
3484@var{timeout-val} is returned, which defaults to @code{#f}.
3485
3486When @code{enqueue/wait!} and @code{queue-push/wait!} succeeds
3487without hitting timeout, they return @code{#t}.
3488@c JP
3489これらの手続きは@var{mtqueue}に対して使うことができ、
3490スレッド間同期を実現できます。
3491@code{enqueue/wait!}と@code{queue-push/wait!}は、
3492キューの要素数が@var{max-length}を越える場合に、キューに空きができるまで、
3493@code{dequeue/wait!}と@code{queue-pop/wait!}は、
3494キューが空の場合に、キューに要素が追加されるまで、
3495呼び出しスレッドをブロックします。
3496
3497@var{timeout}引数で、ブロックされたスレッドのタイムアウトを指定することができます。
3498@code{#f}は指定しなかった場合と同じで、キューの状態が変化するまで
3499無期限に待ちます。実数が渡された場合はそれが秒数と解釈され、最低限
3500その時間経過するまでは待ちます。渡されたのが@code{<time>}オブジェクト
3501(@ref{Time}参照)である場合は、そのオブジェクトが指定する絶対時刻を
3502経過するまで待ちます。
3503
3504タイムアウトによりブロックが解かれた場合は、@var{timeout-val}で
3505指定した値が返されます。@var{timeout-val}の省略時値は@code{#f}です。
3506
3507@code{enqueue/wait!}と@code{queue-push/wait!}は、
3508タイムアウトせずに操作が成功した場合は@code{#t}を返します。
3509@c COMMON
3510@end defun
3511
3512
3513
3514@c ----------------------------------------------------------------------
3515@node Random data generators, Ring buffer, Queue, Library modules - Utilities
3516@section @code{data.random} - Random data generators
3517@c NODE ランダムデータの生成, @code{data.random} - ランダムデータの生成
3518
3519@deftp {Module} data.random
3520@mdindex data.random
3521@c EN
3522This module defines a set of generators and generator makers
3523that yield random data of specific type and distribution.
3524@c JP
3525このモジュールは、特定のデータ型や、特定の値の分布を持つランダムなデータを
3526生成するジェネレータ、およびそういったジェネレータを作り出すジェネレータ構築器を
3527提供します。
3528@c COMMON
3529@end deftp
3530
3531@c EN
3532A naming convention: Procedures that takes parameters and returns
3533a generator is suffixed by @code{$} (e.g. @code{integer$}).
3534Procedures that are generators themselves are not (e.g. @code{fixnums}).
3535Procedures that are combinators, that is, the ones that take
3536one or more generators and returns a generator, generally ends
3537with a preposition (e.g. @code{list-of}).
3538@c JP
3539名前付けの規則:パラメータを受け取り、それにそったジェネレータを返す
3540手続きにはサフィックス@code{$}がついています (例: @code{integer$})。
3541それ自体がジェネレータである手続きにはサフィックスがつきません (例: @code{fixnums})。
3542コンビネータ、つまり複数のジェネレータを取ってジェネレータを返す手続きの名前は、
3543通常前置詞で終わります (例: @code{list-of})。
3544@c COMMON
3545
3546@c EN
3547@subheading Global state
3548@c JP
3549@subheading グローバルな状態
3550@c COMMON
3551
3552@c EN
3553All the generators in this module shares a global random state.
3554The random seed is initialized by a fixed value when the module
3555is loaded.
3556You can get and set the random seed by
3557the following procedure.
3558@c JP
3559このモジュールのジェネレータはすべて一つのグローバルな乱数状態を共有します。
3560モジュールがロードされた時点で、固定のシードによりこの状態は初期化されます。
3561次の手続きでグローバルな乱数状態のシードを読み出したり、新たな値に
3562設定することができます。
3563@c COMMON
3564
3565@defun random-data-seed
3566@defunx {(setter random-data-seed)} seed-value
3567@c MOD data.random
3568@c EN
3569Calling @code{random-data-seed} (without arguments)
3570returns the random seed value used to initialize the current random state.
3571
3572It can be used with generic setter, to reinitialize the random state
3573with @var{seed-value}.
3574
3575Random seed value must be an exact integer.  Its lower 32bits are used.
3576@c JP
3577引数無しで@code{random-data-seed}を呼ぶと、現在の乱数状態を初期化した
3578シード値が返されます。
3579
3580ジェネリックなセッターと一緒に使えば、乱数状態を@var{seed-value}をシードとして
3581再初期化することができます。
3582
3583ランダムシード値は正確な整数でなければなりません。その下位32ビットが使われます。
3584@c COMMON
3585
3586@example
3587; @r{reinitialize the random state with a new random seed.}
3588(set! (random-data-seed) 1)
3589
3590(random-data-seed) @result{} 1
3591@end example
3592
3593@c EN
3594Note: This procedure doesn't have parameter interface (alter the global
3595value by giving the new value as an argument), since it doesn't work
3596like a parameter (@pxref{Parameters}).
3597You can get the random seed value, but you can't
3598get the current random state itself---if you restore the
3599random seed value again, the internal state is reset, instead
3600of restoring the state at the time you called @code{random-data-seed}.
3601@c JP
3602註: この手続きはパラメータインタフェース (引数として値を与えるとそれを新たな
3603値に設定し、以前の値を返す) にはなっていません。本質的に、パラメータとは
3604相容れないからです (@ref{Parameters}参照)。
3605得られるのは現在の乱数状態の出発点となるシード値であって、
3606現在の乱数状態そのものではありません。一旦別のシード値に切り替えて、
3607その後元のシード値に戻した場合、乱数状態は切り替えた時点に戻るのではなく、
3608あらためて初期化されます。
3609@c COMMON
3610
3611@c EN
3612If you want to use different random state temporarily, and ensure to
3613restore original state afterwards, use @code{with-random-data-seed} below.
3614@c JP
3615乱数状態を一時的に切り替えて、その後で切り替えた時点の状態を確実に回復したい場合は、
3616次に示す@code{with-random-data-seed}を使ってください。
3617@c COMMON
3618@end defun
3619
3620@defun with-random-data-seed seed thunk
3621@c MOD data.random
3622@c EN
3623Saves the current global random state, initializes the random state with
3624@var{seed}, then executes @var{thunk}.  If @var{thunk} returns or
3625the control exits out of @var{thunk}, the state at the time
3626@code{with-random-data-seed} was called is restored.
3627@c JP
3628現在のグローバルな乱数状態を保存し、乱数状態を@var{seed}で初期化して
3629@var{thunk}を実行します。@var{thunk}から帰ってくるか、
3630制御が@var{thunk}を抜け出した場合、乱数状態は@code{with-random-data-seed}が
3631呼び出された時点の状態に戻されます。
3632@c COMMON
3633@end defun
3634
3635@c EN
3636Since the default random seed value is fixed, you can get deterministic
3637output when you call the random data generators below without altering
3638the random seed explicitly.
3639@c JP
3640デフォルトのランダムシードが固定なのは、何もしなければ再現可能な振る舞いが得られる
3641からです。
3642@c COMMON
3643
3644@c EN
3645@subheading Generators of primitive data types
3646@c JP
3647@subheading プリミティブデータ型のジェネレータ
3648@c COMMON
3649
3650@c EN
3651Those generators generate uniformly distributed data.
3652@c JP
3653以下のジェネレータは特に断りが無い限り、一様分布するデータを生成します。
3654@c COMMON
3655
3656@c EN
3657In the following examples, we use @code{generator->list} to show
3658some concrete data from the generators.  It is provided
3659in @code{gauche.generator} module.  @xref{Generators}, for more
3660utilities work on generators.
3661@c JP
3662例の中では、生成された値を具体的に示すために
3663@code{gauche.generator}モジュールの@code{generator->list}を
3664使っています。ジェネレータを扱うユーティリティについては
3665@ref{Generators}を参照してください。
3666@c COMMON
3667
3668@defun integers$ size :optional (start 0)
3669@defunx integers-between$ lower-bound upper-bound
3670@c MOD data.random
3671@c EN
3672Create exact integer generators.  The first one, @code{integers$}, creates
3673a generator that generates integers from start (inclusive) below
3674start+size (exclusive) uniformly.  The second one, @code{integers-between$},
3675creates a generator that generates integers between
3676@var{lower-bound} and @var{upper-bound} (both inclusive) uniformly.
3677@c JP
3678正確な整数のジェネレータを作成します。
3679@code{integer$}が返すジェネレータは、
3680@var{start} 以上 @var{start} + @var{size} 未満の整数を一様に発生させます。
3681@code{integers-between$}はが返すジェネレータは、@var{lower-bound}以上、
3682@var{upper-bound}以下の整数を一様に発生させます。
3683@c COMMON
3684
3685@example
3686@c EN
3687;; A dice roller
3688@c JP
3689;; サイコロ
3690@c COMMON
3691(define dice (integers$ 6 1))
3692
3693@c EN
3694;; Roll the dice 10 times
3695@c JP
3696;; サイコロを10回振ってみる
3697@c COMMON
3698(generator->list dice 10)
3699 @result{} (6 6 2 4 2 5 5 1 2 2)
3700@end example
3701@end defun
3702
3703@defun fixnums
3704@defunx int8s
3705@defunx uint8s
3706@defunx int16s
3707@defunx uint16s
3708@defunx int32s
3709@defunx uint32s
3710@defunx int64s
3711@defunx uint64s
3712@c MOD data.random
3713@c EN
3714Uniform integer generators.  Generate integers in fixnum range, and
37158/16/32/64bit signed and unsigned integers, respectively.
3716@c JP
3717固定範囲の一様整数ジェネレータです。
3718それぞれ、fixnumおよび8/16/32/64ビットの符号つき/符号無し整数を生成します。
3719@c COMMON
3720
3721@example
3722(generator->list int8s 10)
3723 @result{} (20 -101 50 -99 -111 -28 -19 -61 39 110)
3724@end example
3725@end defun
3726
3727@defun booleans
3728@c MOD data.random
3729@c EN
3730Generates boolean values (@code{#f} and @code{#t}) in equal probability.
3731@c JP
3732真偽値(@code{#f}と@code{#t})を等確率で生成します。
3733@c COMMON
3734
3735@example
3736(generator->list booleans 10)
3737 @result{} (#f #f #t #f #f #t #f #f #f #f)
3738@end example
3739@end defun
3740
3741@defun chars$ :optional char-set
3742@c MOD data.random
3743@c EN
3744Creates a generator that generates characters in @var{char-set} uniformly.
3745The default @var{char-set} is @code{#[A-Za-z0-9]}.
3746@c JP
3747@var{char-set}にある文字を一様分布で生成するジェネレータを作ります。
3748@var{char-set}が省略された場合は@code{#[A-Za-z0-9]}が使われます。
3749@c COMMON
3750
3751@example
3752(define alphanumeric-chars (chars$))
3753
3754(generator->list alphanumeric-chars 10)
3755 @result{} (#\f #\m #\3 #\S #\z #\m #\x #\S #\l #\y)
3756@end example
3757@end defun
3758
3759@defun reals$ :optional size start
3760@defunx reals-between$ lower-bound upper-bound
3761@c MOD data.random
3762@c EN
3763Create a generator that generates real numbers uniformly with given range.
3764The first procedure, @code{reals$}, returns reals between start
3765and start+size, inclusively.  The default of size is 1.0 and start is 0.0.
3766The second procedure, @code{reals-between$}, returns reals between
3767lower-bound and upper-bound, inclusively.
3768@c JP
3769与えられた範囲の実数値を一様に生成するジェネレータを返します。
3770@code{reals$}の返すジェネレータは、
3771@var{start} 以上 @var{start} + @var{size} 以下の実数値を生成します。
3772@var{size}のデフォルト値は@code{1.0}、@var{start}のデフォルト値は@code{0.0}です。
3773@code{reals-between$}の返すジェネレータは、
3774@var{lower-bound}以上@var{upper-bound}以下の実数値を生成します。
3775@c COMMON
3776
3777@example
3778(define uniform-100 (reals$ 100))
3779
3780(generator->list uniform-100 10)
3781 @result{} (81.67965004942268 81.84927577572596 53.02443813660833)
3782@end example
3783
3784@c EN
3785Note that a generator from @code{reals$} can generate the upper-bound
3786value start+size, as opposed to @code{integers$}.  If you need to exclude
3787the bound value, just discard the bound value; @code{gfilter} may come
3788handy.
3789@c JP
3790@code{reals$}の返すジェネレータは、@code{integer$}と違って
3791上限の値を生成し得ることに注意してください。限界値を除外したい場合は、
3792@code{gfilter}等を使ってその値を棄却します。
3793@c COMMON
3794
3795@example
3796(define generate-from-0-below-1
3797  (gfilter (^r (not (= r 1.0))) (reals$ 1.0 0.0)))
3798@end example
3799@end defun
3800
3801@defun samples$ collection
3802@c MOD data.random
3803@c EN
3804Creates a generator that returns randomly chosen item in @var{collection}
3805at a time.
3806
3807Do not confuse this with @code{samples-from} below, which is to combine
3808multiple generators for sampling.
3809@c JP
3810コレクション@var{collection}から毎回ランダムにひとつ要素を選んで返すジェネレータを
3811作成します。
3812
3813下で説明する@code{samples-from}と混同しないようにしてください。@code{samples-from}
3814は複数のジェネレータを組み合わせてサンプリングするものです。
3815@c COMMON
3816
3817@example
3818(define coin-toss (samples$ '(head tail)))
3819
3820(generator->list coin-toss 5)
3821 @result{} (head tail tail head tail)
3822@end example
3823@end defun
3824
3825@defun regular-string$ regexp
3826@c MOD data.random
3827@c EN
3828Creates an infinite
3829generator that generates random strings each of which matches the given
3830@var{regexp}.  The @var{regexp} shouldn't include conditional patterns
3831and lookahead/behind assertions.
3832
3833Note: It is hard to define how the distribution of the generated strings
3834should look like.  For now, we build an NFA from regexp and put the
3835same probability when there are multiple choices, but that may not be
3836really useful for typical use cases (e.g. generate test data).
3837Please assume the current implementation strategy a provisional one.
3838@c JP
3839与えられた@var{regexp}にマッチするランダムな文字列を生成し続けるジェネレータを
3840作って返します。@var{regexp}には条件付きパターン、lookahead/lookbehindアサーションを
3841含めないでください。
3842
3843註: 生成される文字列の分布をどうすべきかというのは難しい問題です。
3844現在の実装は単純に、内部で正規表現からNFAを生成し、複数の選択肢がある場合は
3845等しい重みでランダムに選択していますが、それが目的(例えばテストデータの生成)に
3846ふさわしいかどうかはまだわかりません。
3847現在の実装は暫定的なものと考えてください。
3848@c COMMON
3849@end defun
3850
3851@c EN
3852@subheading Nonuniform distributions
3853@c JP
3854@subheading 非一様分布
3855@c COMMON
3856
3857@defun reals-normal$ :optional mean deviation
3858@c MOD data.random
3859@c EN
3860Creates a generator that yields real numbers from normal distribution
3861with @var{mean} and @var{deviation}.  The default of @var{mean} is 0.0
3862and @var{deviation} is 1.0.
3863@c JP
3864期待値@var{mean}、標準偏差@var{deviation}の正規分布に従って実数値を生成する
3865ジェネレータを作ります。省略時は@var{mean}が0.0、@var{deviation}が
38661.0になります。
3867@c COMMON
3868@end defun
3869
3870@defun reals-exponential$ mean
3871@c MOD data.random
3872@c EN
3873Creates a generator that yields real numbers from exponential distribution
3874with @var{mean}.
3875@c JP
3876期待値@var{mean}の指数分布に従って実数値を生成するジェネレータを作ります。
3877@c COMMON
3878@end defun
3879
3880@defun integers-geometric$ p
3881@c MOD data.random
3882@c EN
3883Creates a generator that yields integers from geometric distribution
3884with success probability @var{p} (0 <= p <= 1).  The mean is @code{1/p} and
3885variance is @code{(1-p)/p^2}.
3886@c JP
3887成功確率@var{p} (0 ≦ p ≦ 1) である幾何分布に従って
3888非負整数値を生成するジェネレータを作ります。
3889期待値は@code{1/p}、分散は@code{(1-p)/p^2}になります。
3890@c COMMON
3891@end defun
3892
3893@defun integers-poisson$ L
3894@c MOD data.random
3895@c EN
3896Creates a generator that yields integers from poisson distribution with
3897mean @var{L}, variance @var{L}.
3898@c JP
3899期待値@var{L}のポアソン分布に従う非負整数値を生成するジェネレータを作ります。
3900分散も@var{L}になります。
3901@c COMMON
3902@end defun
3903
3904@c EN
3905@subheading Aggregate data generators
3906@c JP
3907@subheading 複合データ型のジェネレータ
3908@c COMMON
3909
3910@defun samples-from generators
3911@c MOD data.random
3912@c EN
3913Takes a finite sequence of generators
3914(sequence in the sense of @code{gauche.sequence}),
3915and returns a generator.  Every time the resulting generator is called,
3916it picks one of the input generators in equal probability, then
3917calls it to get a value.
3918@c JP
3919ジェネレータの有限シーケンス (ここでは@code{gauche.sequence}がシーケンスとして
3920扱うもの) を取り、新たなジェネレータを返します。
3921返されたジェネレータは、値を必要とする度に、
3922入力となるジェネレータのどれかを等確率で選んで、その入力ジェネレータから値を取ります。
3923@c COMMON
3924
3925@example
3926(define g (samples-from (list uint8s (chars$ #[a-z]))))
3927
3928(generator->list g 10)
3929 @result{} (207 107 #\m #\f 199 #\o #\b 57 #\j #\e)
3930@end example
3931
3932@c EN
3933NB: To create a generator that samples from a fixed collection of items,
3934use @code{samples$} described above.
3935@c JP
3936註: 固定した要素の集まりからサンプルするジェネレータを作るには、
3937上の方で説明した@code{samples$}を使ってください。
3938@c COMMON
3939@end defun
3940
3941@defun weighted-samples-from weight&gens
3942@c MOD data.random
3943@c EN
3944The argument is a list of pairs of a nonnegative real number and a generator.
3945The real number determines the weight, or the relative probability
3946that the generator is chosen.  The sum of weight doesn't need to
3947be 1.0.
3948@c JP
3949引数は、非負の実数値とジェネレータのペアのリストです。
3950実数値が「重み」、すなわちペアとなっているジェネレータが選ばれる相対確率を決定します。
3951重みの総和が1.0である必要はありません。
3952@c COMMON
3953
3954@c EN
3955The following example chooses the uint8 generator four times frequently
3956than the character generator.
3957@c JP
3958次の例では、@code{uint8}ジェネレータは文字ジェネレータより4倍頻繁に使われます。
3959@c COMMON
3960
3961@example
3962(define g (weighted-samples-from
3963           `((4.0 . ,uint8s)
3964             (1.0 . ,(chars$)))))
3965
3966(generator->list g 10)
3967 @result{} (195 97 #\j #\W #\5 72 49 143 19 164)
3968@end example
3969@end defun
3970
3971@defun pairs-of car-gen cdr-gen
3972@c MOD data.random
3973@c EN
3974Returns a generator that yields pairs,
3975whose car is generated from @var{car-gen}
3976and whose cdr is generated from @var{cdr-gen}.
3977@c JP
3978ペアを生成するジェネレータを作ります。
3979各ペアのcarはジェネレータ@var{car-gen}、
3980cdrはジェネレータ@var{cdr-gen}によって生成されます。
3981@c COMMON
3982
3983@example
3984(define g (pairs-of int8s booleans))
3985
3986(generator->list g 10)
3987 @result{} ((113 . #t) (101 . #f) (12 . #t) (68 . #f) (-55 . #f))
3988@end example
3989@end defun
3990
3991@defun tuples-of gen @dots{}
3992@c MOD data.random
3993@c EN
3994Returns a generator that yields lists,
3995whose i-th element is generated from the i-th argument.
3996@c JP
3997リストを生成するジェネレータを作ります。
3998各リストのi番目の要素はi番目の引数のジェネレータによって生成されます。
3999@c COMMON
4000
4001@example
4002(define g (tuples-of int8s booleans (char$)))
4003
4004(generator->list g 3)
4005 @result{} ((-43 #f #\8) (53 #f #\1) (-114 #f #\i))
4006@end example
4007@end defun
4008
4009@defun permutations-of seq
4010@c MOD data.random
4011@c EN
4012Returns a generator that yields a random permutations of @var{seq}.
4013
4014The type of @var{seq} should be a sequence with a builder
4015(@pxref{Sequence framework}).  The type of generated objects
4016will be the same as @var{seq}.
4017@c JP
4018シーケンス@var{seq}の要素をランダムに並べ替えたシーケンスを生成する
4019ジェネレータを作ります。
4020
4021@var{seq}の型は、ビルダーを持つシーケンスである必要があります
4022(@ref{Sequence framework}参照)。生成されるオブジェクトは
4023@var{seq}と同じ型になります。
4024@c COMMON
4025
4026@example
4027(generator->list (permutations-of '(1 2 3)) 3)
4028 @result{} ((1 2 3) (2 3 1) (3 2 1))
4029
4030(generator->list (permutations-of "abc") 3)
4031 @result{} ("cba" "cba" "cab")
4032@end example
4033@end defun
4034
4035@defun combinations-of size seq
4036@c MOD data.random
4037@c EN
4038Returns a generator that yields a sequence of @var{size} elements
4039randomly picked from @var{seq}.
4040
4041The type of @var{seq} should be a sequence with a builder
4042(@pxref{Sequence framework}).  The type of generated objects
4043will be the same as @var{seq}.
4044@c JP
4045シーケンス@var{seq}からランダムに@var{size}個の要素を取り出して
4046並べたシーケンスを生成するジェネレータを作ります。
4047
4048@var{seq}の型は、ビルダーを持つシーケンスである必要があります
4049(@ref{Sequence framework}参照)。生成されるオブジェクトは
4050@var{seq}と同じ型になります。
4051@c COMMON
4052
4053@example
4054(generator->list (combinations-of 2 '(a b c)) 5)
4055 @result{} ((a c) (a b) (a c) (b a) (a c))
4056
4057(generator->list (combinations-of 2 '#(a b c)) 5)
4058 @result{} (#(a c) #(b c) #(c b) #(b a) #(b c))
4059@end example
4060@end defun
4061
4062@c EN
4063The following procedures takes optional @var{sizer} argument, which can
4064be either a nonnegative integer or a generator of nonnegative integers.
4065The value of the sizer determines the length of the result data.
4066@c JP
4067以下の手続きは、省略可能な@var{sizer}引数を取ります。
4068@var{sizer}引数は非負整数か、非負整数を生成するジェネレータで、
4069その値(もしくは生成された値)が、最終的に生成されるデータの長さを決定します。
4070@c COMMON
4071
4072@c EN
4073Unlike most of Gauche procedures, @var{sizer} argument comes before
4074the last argument when it is not omitted.
4075We couldn't resist the temptation to
4076write something like @code{(lists-of 3 booleans)}.
4077@c JP
4078Gaucheの他のほとんどの手続きと違って、@var{sizer}引数は省略されない時は
4079最後の引数よりも前に来ます。これは統一性を損ないますが、
4080@code{(lists-of 3 booleans)} のように書ける、という誘惑に勝てませんでした。
4081@c COMMON
4082
4083@c EN
4084If @var{sizer} is omitted, the default value is taken from
4085the parameter @code{default-sizer}.  The default of @code{default-sizer}
4086is @code{(integers-poisson$ 4)}.
4087@c JP
4088@var{sizer}引数が省略された場合、パラメータ@code{default-sizer}の値が
4089使われます。@code{default-sizer}のデフォルトは
4090@code{(integers-poisson$ 4)}で作られるジェネレータです。
4091@c COMMON
4092
4093@defun lists-of item-gen
4094@defunx lists-of sizer item-gen
4095@defunx vectors-of item-gen
4096@defunx vectors-of sizer item-gen
4097@defunx strings-of
4098@defunx strings-of item-gen
4099@defunx strings-of sizer item-gen
4100@c MOD data.random
4101@c EN
4102Creates a generator that generates lists, vectors or strings of values from @var{item-gen}, respectively.  The size of each datum is determined by
4103@var{sizer}.
4104@c JP
4105それぞれ、リスト、ベクタ、文字列を生成するジェネレータを作ります。
4106作られるデータの各要素はジェネレータ@var{item-gen}から取られます。
4107各データの長さは@var{sizer}により決定されます。
4108@c COMMON
4109
4110@c EN
4111You can also omit @var{item-gen} for @code{strings-of}.  In that case,
4112a generator created by @code{(chars$)} is used.
4113@c JP
4114@code{strings-of}の場合は@var{item-gen}も省略することができます。
4115その場合は、@code{(chars$)}で作られるジェネレータが使われます。
4116@c COMMON
4117
4118@example
4119(generator->list (lists-of 3 uint8s) 4)
4120 @result{} ((254 46 0) (77 158 46) (1 134 156) (74 5 110))
4121
4122@c EN
4123;; using the default sizer
4124@c JP
4125;; デフォルトのsizerを使う
4126@c COMMON
4127(generator->list (lists-of uint8s) 4)
4128 @result{} ((93 249) (131 97) (98 206 144 247 241) (126 156 31))
4129
4130@c EN
4131;; using a generator for the sizer
4132@c JP
4133;; sizerにジェネレータを使う
4134@c COMMON
4135(generator->list (strings-of (integers$ 8) (chars$)) 5)
4136 @result{} ("dTJYVhu" "F" "PXkC" "w" "")
4137@end example
4138@end defun
4139
4140@defun sequences-of class item-gen
4141@defunx sequences-of class sizer item-gen
4142@c MOD data.random
4143@c EN
4144Creates a generator that yields sequences of class @var{class},
4145whose items are generated by @var{item-gen}.  The size of each
4146sequence is determined by @var{sizer}, or the value of @code{default-sizer}
4147if omitted; the sizer can be a nonnegative integer, or a generator
4148that yields nonnegative integers.
4149
4150The class @var{class} must be a subclass of @code{<sequence>} and
4151implement the builder interface.
4152@c JP
4153クラス@var{class}のインスタンスであるシーケンスを生成するジェネレータを作ります。
4154シーケンスの要素は@var{item-gen}により生成されます。
4155各シーケンスの長さは@var{sizer}引数 (省略時は@code{default-sizer}の値)
4156によって決められます。@var{sizer}は非負整数か、非負整数を生成するジェネレータです。
4157
4158@var{class}は@code{<sequence>}のサブクラスであり、
4159ビルダーインタフェースを実装していなければなりません。
4160@c COMMON
4161
4162@example
4163(generator->list (sequences-of <u8vector> 4 uint8s) 3)
4164 @result{} (#u8(95 203 243 46) #u8(187 199 153 152) #u8(39 114 39 25))
4165@end example
4166@end defun
4167
4168
4169@deffn {Parameter} default-sizer
4170@c MOD data.random
4171@c EN
4172The sizer used by @code{lists-of}, @code{vectors-of} and @code{strings-of}
4173when @var{sizer} argument is omitted.
4174
4175The value must be either an nonnegative integer, or a generator
4176of nonnegative integers.
4177@c JP
4178@code{lists-of}、@code{vectors-of}、@code{strings-of}で
4179@var{sizer}引数が省略された場合に使われるsizerです。
4180
4181値は、非負整数か、非負整数を生成するジェネレータでなければなりません。
4182@c COMMON
4183@end deffn
4184
4185@c ----------------------------------------------------------------------
4186@node Ring buffer, Skew binary random-access lists, Random data generators, Library modules - Utilities
4187@section @code{data.ring-buffer} - Ring buffer
4188@c NODE リングバッファ, @code{data.ring-buffer} - リングバッファ
4189
4190@deftp {Module} data.ring-buffer
4191@mdindex data.ring-buffer
4192@c EN
4193A ring buffer is an array with two fill pointers; in a typical usage,
4194a producer adds new data to one end while a consumer removes data
4195from the other end; if fill pointer reaches at the end of the array,
4196it wraps around to the beginning, hence the name.
4197@c JP
4198リングバッファは、両端を指す二つのポインタを持つ配列と考えられます。良くある使い方は、
4199生産者が配列の一方の端にデータを追加してゆき、消費者がもう一方の端から
4200データを取り出してゆくというものです。もし端を示すポインタが配列の
4201終端に達したら、それはもう一方の端につながっているように振る舞います。
4202「リング」バッファと呼ばれるのはそのためです。
4203@c COMMON
4204
4205@c EN
4206The ring buffer of this module allows adding and removing elements
4207from both ends, hence functionally it is a double-ended queue,
4208or deque.  It also allows O(1) indexed access to the contents,
4209and customized handling for the case when the buffer gets full.
4210@c JP
4211このモジュールの提供するリングバッファは、どちらの端にもデータを追加し、
4212どちらの端からもデータを取り出すことができます。したがって機能的には
4213両端キュー(double-ended queue, deque)の一種とも考えられます。
4214また、O(1)で要素にアクセス可能で、
4215さらにバッファが一杯になった時の振る舞いをカスタマイズできます。
4216@c COMMON
4217
4218@c EN
4219You can use an ordinary vector or a uniform vector as the backing
4220storage of a ring buffer.
4221@c JP
4222リングバッファがデータを格納するバッキングストレージとして、
4223通常のベクタかユニフォームベクタを使えます。
4224@c COMMON
4225@end deftp
4226
4227@defun make-ring-buffer :optional initial-storage :key overflow-handler
4228@c MOD data.ring-buffer
4229@c EN
4230Creates a ring buffer.  By default, a fresh vector is allocated
4231for the backing storage.  You can pass a vector or a uvector to
4232@var{initial-storage} to be used instead.  The passed storage must
4233be mutable, and will
4234be modified by the ring buffer; the caller shouldn't modify it,
4235nor make assumption about its content.
4236@c JP
4237リングバッファを作成します。デフォルトでは、データ格納のための領域として
4238新たなベクタがアロケートされます。かわりに、呼び出し側でベクタかユニフォームベクタ
4239を用意して@var{initial-storage}に渡すこともできます。その場合、
4240渡すベクタやユニフォームベクタは変更可能でなければなりません。以降、
4241リングバッファがそのベクタを変更するので、呼び出し側でベクタを変更
4242したりベクタの内容が保存されることを期待してはいけません。
4243@c COMMON
4244
4245@c EN
4246The @var{overflow-handler} keyword argument specifies what to do when
4247a new element is about to be added to the full buffer.
4248It must be a procedure, or a symbol @code{error}
4249or @code{overwrite}.
4250@c JP
4251@var{overflow-handler}キーワード引数は、バッファがフルの状態で
4252新たな要素が追加されようとした時の振る舞いを指定します。
4253引数は手続きか、シンボル@code{error}か@code{overwrite}のいずれかでなければなりません。
4254@c COMMON
4255
4256@c EN
4257If it is a procedure, it will be called with a ring buffer and
4258a backing storage (vector or uvector) when it is filled.  The procedure
4259must either (1) allocate and return a larger vector/uvector of the same
4260type of the passed backing storage, (2) return a symbol @code{error},
4261or (3) return a symbol @code{overwrite}.  If it returns a vector/uvector,
4262it will be used as the new backing storage.  The returned vector doesn't need
4263to be initialized; the ring buffer routine takes care of copying the
4264necessary data.
4265If it returns @code{error},
4266an error (``buffer is full'') is thrown.  If it returns @code{overwrite},
4267the new element overwrites the existing element (as if one element
4268from the other end is popped and discarded.)
4269@c JP
4270引数が手続きの場合、リングバッファと(一杯になった)バッキングストレージ
4271が引数として渡されます。この手続きは以下の3つのアクションのうちひとつを
4272実行しなければなりません。(1)渡されたバッキングストレージ(ベクタか
4273ユニフォームベクタ)と同じ型で、より大きなベクタまたはユニフォームベクタをアロケートして
4274返す。(2)シンボル@code{error}を返す。(3)シンボル@code{overwrite}を返す。
4275手続きがベクタもしくはユニフォームベクタを返した場合は、それが
4276新たなバッキングストレージとして使われます。
4277返すベクタの内容を設定する必要はありません。リングバッファが適切に内容のコピーや
4278必要な初期化を行います。手続きが@code{error}を返した場合は、
4279``buffer is full''のエラーが投げられます。
4280手続きが@code{overwrite}を返した場合は、
4281新たな要素で古い要素を上書きします(つまり、
4282あたかも別の端から1要素がポップされて捨てられ、その後で新たな要素が
4283追加されたかのように振る舞います)。
4284@c COMMON
4285
4286@c EN
4287Passing a symbol @code{error} or @code{overwrite} to @var{overflow-handler}
4288is a shorthand of passing a procedure that unconditionally returns
4289@code{error} or @code{overwrite}, respectively.
4290@c JP
4291@var{overflow-handler}引数にシンボル@code{error}か@code{overwrite}
4292を渡した場合は、あたかもそれらのシンボルを無条件に返すoverflow handlerが
4293指定されたかのように振る舞います。
4294@c COMMON
4295
4296@c EN
4297The default behavior on overflow is to double the size of backing
4298storage.  You can use @code{make-overflow-doubler} below to create
4299the customized overflow handler easily.
4300@c JP
4301@var{overflow-handler}が指定されない場合のデフォルトの動作は、
4302元のバッキングストレージの倍の容量をアロケートして返すことです。
4303下の@code{make-overflow-doubler}を使うと、カスタマイズした
4304オーバフローハンドラを簡単に作ることができます。
4305@c COMMON
4306@end defun
4307
4308@defun make-overflow-doubler :key max-increase max-capacity
4309@c MOD data.ring-buffer
4310@c EN
4311Returns a procedure suitable to be passed to the @var{overflow-handler}
4312keyword argument of @code{make-ring-buffer}.
4313
4314The returned procedure takes a ring buffer and its backing storage,
4315and behaves as follows.
4316@c JP
4317@code{make-ring-buffer}の@var{overflow-handler}キーワード引数に
4318渡せる手続きを作って返します。
4319
4320返される手続きは、リングバッファとバッキングストレージを引数に取り、
4321以下のとおり振る舞います。
4322@c COMMON
4323
4324@itemize
4325@item
4326@c EN
4327If the size of current backing storage is equal to or greater than
4328@var{max-capacity}, returns @code{error}.
4329@c JP
4330現在のバッキングストレージの大きさが@var{max-capacity}以上であれば、
4331@code{error}を返す。
4332@c COMMON
4333@item
4334@c EN
4335Otherwise, if the size of current backing storage is equal to or
4336greater than @var{max-increase}, allocates a vector/uvector of
4337the same type of the current backing storage, with the size
4338@code{(+ max-increase size-of-current-storage)}.
4339@c JP
4340そうではなく、現在のバッキングストレージの大きさが@var{max-increase}以上で
4341あれば、@code{(+ max-increase 現在の大きさ)}の大きさを持つ
4342ベクタもしくはユニフォームベクタをアロケートして返す。
4343@c COMMON
4344@item
4345@c EN
4346Otherwise, allocates a vector/uvector of
4347the same type of the current backing storage with the size
4348@code{(* 2 size-of-current-storage)}.
4349@c JP
4350そうでない場合は、@code{(* 2 現在の大きさ)} の大きさを持つ
4351ベクタもしくはユニフォームベクタをアロケートして返す。
4352@c COMMON
4353@end itemize
4354
4355@c EN
4356The default value of @var{max-increase} and @var{max-capacity} is
4357@code{+inf.0}.
4358@c JP
4359@var{max-increase}と@var{max-capacity}のデフォルト値はどちらも
4360@code{+inf.0}です。
4361@c COMMON
4362@end defun
4363
4364@defun ring-buffer-empty? rb
4365@c MOD data.ring-buffer
4366@c EN
4367Returns @code{#t} if the ring buffer @var{rb} is empty,
4368@code{#f} if not.
4369@c JP
4370リングバッファ@var{rb}が空なら@code{#t}を、そうでなければ@code{#f}を返します。
4371@c COMMON
4372@end defun
4373
4374@defun ring-buffer-full? rb
4375@c MOD data.ring-buffer
4376@c EN
4377Returns @code{#t} if the ring buffer @var{rb} is full,
4378@code{#f} if not.
4379@c JP
4380リングバッファ@var{rb}がフルなら@code{#t}を、そうでなければ@code{#f}を返します。
4381@c COMMON
4382@end defun
4383
4384@defun ring-buffer-num-entries rb
4385@c MOD data.ring-buffer
4386@c EN
4387Returns the number of current elements in the ring buffer @var{rb}.
4388@c JP
4389リングバッファ@var{rb}が格納している要素数を返します。
4390@c COMMON
4391@end defun
4392
4393@defun ring-buffer-capacity rb
4394@c MOD data.ring-buffer
4395@c EN
4396Returns the size of the current backing storage of the ring buffer @var{rb}.
4397@c JP
4398リングバッファの現在のバッキングストレージの容量(格納可能な要素数)を返します。
4399@c COMMON
4400@end defun
4401
4402@defun ring-buffer-front rb
4403@defunx ring-buffer-back rb
4404@c MOD data.ring-buffer
4405@c EN
4406Returns the element in the front or back of the ring buffer @var{rb},
4407respectively.
4408If the buffer is empty, an error is signaled.
4409@c JP
4410リングバッファ@var{rb}の先頭あるいは末尾の要素をそれぞれ返します。
4411バッファが空の場合はエラーが投げられます。
4412@c COMMON
4413@end defun
4414
4415@defun ring-buffer-add-front! rb elt
4416@defunx ring-buffer-add-back! rb elt
4417@c MOD data.ring-buffer
4418@c EN
4419Add an element to the front or back of the ring buffer @var{rb},
4420respectively.  If @var{rb} is full, the behavior is determined by
4421the buffer's overflow handler, as described in @code{make-ring-buffer}.
4422@c JP
4423リングバッファ@var{rb}の先頭もしくは末尾にそれぞれ要素を追加します。
4424@var{rb}がフルの場合の振る舞いは、バッファのオーバーフローハンドラによって
4425決定されます。詳しくは@code{make-ring-buffer}のエントリを参照してください。
4426@c COMMON
4427@end defun
4428
4429@defun ring-buffer-remove-front! rb
4430@defunx ring-buffer-remove-back! rb
4431@c MOD data.ring-buffer
4432@c EN
4433Remove an element from the front or back of the ring buffer @var{rb},
4434and returns the removed element, respectively.
4435If the buffer is empty, an error is signaled.
4436@c JP
4437リングバッファ@var{rb}の先頭もしくは末尾から要素をひとつ取り、取った要素を
4438返します。
4439バッファが空の場合はエラーが投げられます。
4440@c COMMON
4441@end defun
4442
4443@defun ring-buffer-ref rb index :optional fallback
4444@c MOD data.ring-buffer
4445@c EN
4446Returns @var{index}-th element in the ring buffer @var{rb}.
4447The elements are counted from the front; thus, if a new element
4448is added to the front, the indexes of existing elements will shift.
4449
4450If the index out of bounds of the existing content,
4451@var{fallback} will be returned; if @var{fallback} is not
4452provided, an error is signaled.
4453@c JP
4454リングバッファ@var{rb}の@var{index}番目の要素を返します。
4455要素は先頭から数えられます。したがって、新たな要素が先頭に付け加えられた場合、
4456既存の要素のインデックスはひとつづつずれます。
4457
4458@var{index}が@var{rb}の持つ要素の範囲外の場合、@var{fallback}が与えられていれば
4459それを返し、そうでなければエラーが投げられます。
4460@c COMMON
4461@end defun
4462
4463@defun ring-buffer-set! rb index value
4464@c MOD data.ring-buffer
4465@c EN
4466Sets @var{index}-th element of the ring buffer @var{rb} to @var{value}.
4467The elements are counted from the front; thus, if a new element
4468is added to the front, the indexes of existing elements will shift.
4469
4470An error is signaled if the index is out of bounds.
4471@c JP
4472リングバッファ@var{rb}の@var{index}番目の要素に@var{value}をセットします。
4473要素は先頭から数えられます。したがって、新たな要素が先頭に付け加えられた場合、
4474既存の要素のインデックスはひとつづつずれます。
4475
4476@var{index}が@var{rb}の持つ要素の範囲外の場合はエラーが投げられます。
4477@c COMMON
4478@end defun
4479
4480
4481@c ----------------------------------------------------------------------
4482@node Skew binary random-access lists, Sparse data containers, Ring buffer, Library modules - Utilities
4483@section @code{data.skew-list} - Skew binary random-access lists
4484@c NODE Skew binary random-access lists, @code{data.sparse} - Skew binary random-access lists
4485
4486@deftp {Module} data.skew-list
4487@mdindex data.skew-list
4488This module implements skew binary random-access list (we call it skew-list
4489for short).  It's an immutable
4490data structure that has properties of both list and vector; constant
4491time to take the first element (car) and append an element in front
4492of existing one (cons), O(log n) to take the rest of
4493the elements (cdr), and O(log n) for indexed access, wher n is
4494the number of elements.
4495
4496A skew-list is always 'proper'; that is, it is either an empty
4497skew-list (@code{skew-list-null}), or an object appended in front
4498of a skew-list.
4499@end deftp
4500
4501@deftp {Class} <skew-list>
4502@clindex skew-list
4503@c MOD data.skew-list
4504The class for skew-lists.
4505
4506It inherits @code{<sequence>} and follws the sequence protocol.
4507@end deftp
4508
4509@defun skew-list? obj
4510@c MOD data.skew-list
4511Returns @code{#t} iff @var{obj} is a skew-list.
4512@end defun
4513
4514@defun skew-list-empty? sl
4515@c MOD data.skew-list
4516The argument must be a skew list.  Returns @code{#t} iff @var{sl}
4517is an empty skew list.
4518@end defun
4519
4520@defvar skew-list-null
4521@c MOD data.skew-list
4522An empty skew list.
4523@end defvar
4524
4525@defun skew-list-cons obj sl
4526@c MOD data.skew-list
4527Returns a new skew-list which has @var{obj} prepended to
4528a skew-list @var{sl}.
4529@end defun
4530
4531@defun skew-list-car sl
4532@c MOD data.skew-list
4533Returns the first element of a skew-list @var{sl}.  An error is
4534raised when @var{sl} is empty.
4535@end defun
4536
4537@defun skew-list-cdr sl
4538@c MOD data.skew-list
4539Returns a new skew-list that containts elements in @var{sl} but
4540the firest one.  An error is
4541raised when @var{sl} is empty.
4542@end defun
4543
4544@defun skew-list-ref sl k :optional fallback
4545@c MOD data.skew-list
4546Returns the @var{k}-th element of a skew-list @var{sl}.  If @var{k}
4547points past the range of @var{sl}, @var{fallback} is returned if it
4548is given, or an error is signaled.
4549
4550Sicne a skew-list is also a sequence, you can use generic @code{ref} as well
4551(@pxref{Sequence framework}.
4552@end defun
4553
4554@defun skew-list-set sl k obj
4555@c MOD data.skew-list
4556Returns a new skew-list which is the same as @var{sl} except the @var{k}-th
4557element is replaced with @var{obj}.  The argument @var{sl} remains intact.
4558
4559It is an error if @var{k} points beyond the last element of @var{sl}.
4560@end defun
4561
4562@defun skew-list-length sl
4563@c MOD data.skew-list
4564Returns an integer length of a skew-list @var{sl}.
4565
4566Sicne a skew-list is also a sequence, you can use generic @code{size-of} as well
4567(@pxref{Sequence framework}.
4568@end defun
4569
4570@defun skew-list-length<=? sl n
4571@c MOD data.skew-list
4572Returns @code{#t} iff the length of a skew-list @var{sl} is less than
4573or equal to @var{n}.  It is more efficient than calculating
4574the total length and compares with @var{n}.
4575@end defun
4576
4577@defun list->skew-list lis
4578@c MOD data.skew-list
4579Returns a new skew-list which contains elements in @var{lis}, with the
4580same order.  It is an error if @var{lis} is not a proper list.
4581
4582Sicne a skew-list is also a sequence, you can use generic @code{coerce-to}
4583as well (@pxref{Sequence framework}.
4584@end defun
4585
4586@defun list*->skew-list lis
4587@c MOD data.skew-list
4588The argument @var{lis} may be an improper list (but can't be circular).
4589Returns two values: a new skew-list which contains elements
4590in @var{lis} except the last cdr of it, and the last cdr of @var{lis}.
4591@end defun
4592
4593@defun skew-list->list sl
4594@c MOD data.skew-list
4595Returns a new list that contains all the elements in a skew-list @var{sl},
4596with the same order.
4597
4598Sicne a skew-list is also a sequence, you can use generic @code{coerce-to}
4599as well (@pxref{Sequence framework}.
4600@end defun
4601
4602@defun skew-list->generator sl
4603@c MOD data.skew-list
4604Returns a new generator that traverses a skew-list @var{sl}.
4605@end defun
4606
4607@defun skew-list->lseq sl
4608@c MOD data.skew-list
4609Converts a skew-list @var{sl} to a lazy sequence.
4610@end defun
4611
4612@defun skew-list-take sl k
4613@defunx skew-list-drop sl k
4614@c MOD data.skew-list
4615Returns a new skew-list of the first @var{k} elements and the elements
4616except the first @var{k} elements, respectively.
4617@end defun
4618
4619@defun skew-list-split-at sl k
4620@c MOD data.skew-list
4621Returns two values, the result of @code{(skew-list-take sl k)}
4622and @code{(skew-list-drop sl k)}, but more efficiently.
4623@end defun
4624
4625@defun skew-list-append sl sl2 @dots{}
4626@c MOD data.skew-list
4627Returns a skew-list which is a concatenation of all the given skew-lists.
4628@end defun
4629
4630@defun skew-list-fold sl kons knil
4631@c MOD data.skew-list
4632Like @var{fold} on a list.
4633
4634Sicne a skew-list is also a sequence, you can use generic @code{fold}
4635as well (@pxref{Sequence framework}.
4636@end defun
4637
4638@defun skew-list-map sl proc
4639@c MOD data.skew-list
4640Returns a skew list, each element of which is the result of
4641applying @var{proc} on the element of @var{sl}.
4642
4643NB: If you want ot map over multiple skew-lists, you can use generic
4644@code{map} (@pxref{Sequence framework}).  The @code{skew-list-map} employs
4645optimization that's specific to one-argument case.
4646@end defun
4647
4648
4649@c ----------------------------------------------------------------------
4650@node Sparse data containers, Trie, Skew binary random-access lists, Library modules - Utilities
4651@section @code{data.sparse} - Sparse data containers
4652@c NODE 疎なデータコンテナ, @code{data.sparse} - 疎なデータコンテナ
4653
4654@deftp {Module} data.sparse
4655@mdindex data.sparse
4656@c EN
4657This module provides a @emph{sparse vector} and @emph{sparse matrix},
4658a space efficient data container indexed by nonnegative integer(s), and
4659a @emph{sparse table}, a hash table using a sparse vector
4660as a backing storage.
4661@c JP
4662このモジュールは、非負整数でインデックスされる空間効率の良いデータ構造である
4663@emph{疎ベクタ} (@emph{sparse vector})と
4664@emph{疎行列} (@emph{sparse matrix})、
4665および
4666疎ベクタを格納領域に用いるハッシュテーブルである@emph{疎テーブル} (@emph{sparse table})
4667を提供します。
4668@c COMMON
4669@end deftp
4670
4671@c EN
4672A sparse vector associates a nonnegative integer index
4673to a value.  It has @emph{vector} in its name since it is indexed
4674by an integer, but it isn't like a flat array on contiguous memory;
4675it's more like an associative array.  (Internally, the current
4676implementation uses compact trie structure.)
4677It is guaranteed that you can store a value with index at least
4678up to @code{2^32-1}; the actual maximum bits of indexes can
4679be queried by @code{sparse-vector-max-index-bits}.
4680(We have a plan to remove the maximum bits limitation in future).
4681@c JP
4682疎ベクタは非負整数のインデックスと値を関連付けます。
4683整数でインデックスされるので名前に@emph{ベクタ}がついていますが、
4684連続するメモリに置かれる配列ではなく、むしろ連想配列のようなものです。
4685(内部的には、現在の実装はコンパクトなトライを使っています)。
4686少なくとも@code{2^32-1}までのインデックスが使えることは保証されています。
4687実装が許す最大のインデックスのビット長は
4688@code{sparse-vector-max-index-bits}で得ることができます。
4689(将来的にはこの制限を無くす計画です)。
4690@c COMMON
4691
4692@c EN
4693Unlike ordinary vectors, you don't need to specify the size
4694of a sparse vector when you create one.  You can just set
4695a value to any index in the supported range.
4696@c JP
4697通常のベクタと違い、疎ベクタは作る時に大きさを指定する必要がありません。
4698サポートされている範囲内ならどんなインデックスにでも単に値を格納できます。
4699@c COMMON
4700
4701@example
4702(define v (make-sparse-vector))
4703
4704(sparse-vector-set! v 0 'a)
4705(sparse-vector-ref v 0) @result{} a
4706
4707(sparse-vector-set! v 100000000 'b)
4708(sparse-vector-ref v 100000000) @result{} b
4709
4710;; set! also work
4711(set! (sparse-vector-ref v 100) 'c)
4712(sparse-vector-ref v 100) @result{} c
4713@end example
4714
4715@c EN
4716If you try to access an element that hasn't been set,
4717an error is signaled by default.  You can set
4718a default value for each vector, or give a
4719fallback value to @code{sparse-vector-ref}, to suppress the error.
4720@c JP
4721値がセットされていない要素にアクセスすると、デフォルトではエラーが通知されます。
4722ベクタごとに既定値を設定したり、
4723@code{sparse-vector-ref}の省略可能引数にフォールバック値を
4724渡すことでエラーを回避できます。
4725@c COMMON
4726
4727@example
4728(sparse-vector-ref v 1)        @result{} @r{error}
4729(sparse-vector-ref v 1 'noval) @result{} noval
4730
4731(let1 w (make-sparse-vector #f :default 'x)
4732  (sparse-vector-ref w 1))     @result{} x
4733@end example
4734
4735@c EN
4736A sparse matrix is like a sparse vector, except it can be indexed
4737by a pair of integers.
4738@c JP
4739疎行列は、二つの整数でインデックスされるという点以外は疎なベクタと同じです。
4740@c COMMON
4741
4742@c EN
4743A sparse table works just like a hash table, but it uses
4744a sparse vector to store the values using hashed number of the keys.
4745@c JP
4746疎テーブルはハッシュテーブルと同じように動作しますが、キーのハッシュ値を
4747インデックスとして値を疎ベクタに格納しています。
4748@c COMMON
4749
4750@c EN
4751The main reason of these sparse data containers are for
4752memory efficiency.   If you want to store values in a vector
4753but knows you'll use only some entries sparsely, obviously it
4754is waste to allocate a large vector and to leave many entries unused.
4755But it is worse than that; Gauche's GC doesn't like a large
4756contiguous region of memory.  Using lots of large vectors adds
4757GC overhead quickly.  It becomes especially visible when you
4758store large number of entries (like >100,000) into hash tables,
4759since Gauche's builtin hash tables use a flat vector as a backing
4760storage.   You'll see the heap size grows quickly and
4761GC runs more frequently and longer.
4762On the other hand, sparse table works pretty stable with
4763large number of entries.
4764@c JP
4765これらの疎なデータコンテナの主な目的は、メモリ効率です。
4766ベクタに値を入れておきたいけれどごく一部のインデックスしか使わないことが
4767分かっている、と言った場合に、巨大なベクタをアロケートしてその大部分を
4768使わないでおくのは明らかに無駄でしょう。ただそれだけではありません。
4769Gaucheのガベージコレクタは、一続きの巨大なメモリ領域を確保するのとあまり
4770相性が良くありません。大きなベクタを大量に使うとGCのオーバヘッドが急速に増えます。
4771Gaucheの組み込みハッシュテーブルは
4772データストアに通常のベクタを使っているのですが、
4773大量のデータを詰め込むとその効果が目に見えてきます。ヒープサイズが急に増え、
4774GCはより頻繁に走り、しかも一回一回に要する時間は長くなるでしょう。
4775一方で、疎テーブルは大量のデータに対してもかなり安定に動作します。
4776@c COMMON
4777
4778@c EN
4779Sparse data containers does have overhead on access speed.
4780They are a bit slower than the ordinary hash tables,
4781and much slower than ordinary vectors.  We should note, however,
4782as the number of entries grow, access time on ordinary hash
4783tables grows quicker than sparse tables and eventually two become
4784comparable.
4785@c JP
4786疎なデータコンテナは、単純なデータコンテナに比べるとアクセスにオーバヘッドはあります。
4787通常のハッシュテーブルより若干遅いですし、通常のベクタと比べるとかなり遅いです。
4788けれども、テーブル内のデータ数が大きくなる領域では、通常のハッシュテーブルの
4789アクセス時間の方が急速に悪化するため、いずれ二つのアクセス時間は
4790そこそこ同じになります。
4791@c COMMON
4792
4793@c EN
4794It depends on your application which you should use, and
4795if you're not sure, you need to benchmark.
4796As a rule of thumb, if you use more than several hashtables
4797each of which contains more than a few tens of thousands of
4798entries, sparse tables may work better.
4799If you see GC Warnings telling ``repeated allocation of large
4800blocks'', you should definitely consider sparse tables.
4801@c JP
4802どちらを使うべきかはアプリケーションに依存します。良く分からないのであれば、
4803ベンチマークを取りましょう。簡単な基準としては、数万以上のエントリを持つ
4804ハッシュテーブルを数個以上作るなら、疎テーブルの方が良くなるかもしれません。
4805実行中に``repeated allocation of large blocks''というGCからの
4806警告を目にしたなら、疎テーブルへの切り替えを考えてみましょう。
4807@c COMMON
4808
4809@menu
4810* Sparse vectors::
4811* Sparse matrixes::
4812* Sparse tables::
4813@end menu
4814
4815@node Sparse vectors, Sparse matrixes, Sparse data containers, Sparse data containers
4816@subsection Sparse vectors
4817@c NODE 疎なベクタ
4818
4819@deftp {Class} <sparse-vector-base>
4820@clindex sparse-vector-base
4821@c MOD data.sparse
4822@c EN
4823An abstract base class of sparse vectors.
4824Inherits @code{<dictionary>} and @code{<collection>}.
4825Note that sparse vectors are @emph{not} @code{<sequence>}; even
4826they can be indexable by integers, they don't have
4827means of @emph{ordered} access.
4828
4829Sparse vector may be a general vector
4830that can contain any Scheme objects (like @code{<vector>}),
4831or a specialized vector that can contain only certain
4832types of numbers (like @code{<s8vector>} etc.).
4833
4834All of these sparse vectors can be accessed by the same API.
4835
4836Sparse vectors also implements the Collection API
4837(@pxref{Collection framework}) and the Dictionary API
4838(@pxref{Dictionary framework}).
4839@c JP
4840疎なベクタの抽象ベースクラスです。@code{<dictionary>}と@code{<collection>}を
4841継承しています。@code{<sequence>}は継承していないことに注意してください。
4842疎なベクタは整数でインデクス可能ですが、インデクスの順番に要素にアクセスする手段を
4843持っていません。
4844
4845疎なベクタは、@code{<vector>}と同様、任意のSchemeオブジェクトを格納可能である
4846ものもあれば、@code{<s8vector>}等と同様に特定の範囲の数値のみ格納可能なものもあります。
4847全ての疎なベクタは同一セットのAPIで利用可能です。
4848
4849疎なベクタはまた、コレクションAPIとディクショナリAPIを実装しています。これらについては
4850@ref{Collection framework}および@ref{Dictionary framework}を
4851参照してください。
4852@c COMMON
4853@end deftp
4854
4855@deftp {Class} <sparse-vector>
4856@deftpx {Class} <sparse-@@vector>
4857@clindex sparse-vector
4858@clindex sparse-s8vector
4859@clindex sparse-u8vector
4860@clindex sparse-s16vector
4861@clindex sparse-u16vector
4862@clindex sparse-s32vector
4863@clindex sparse-u32vector
4864@clindex sparse-s64vector
4865@clindex sparse-u64vector
4866@clindex sparse-f16vector
4867@clindex sparse-f32vector
4868@clindex sparse-f64vector
4869@c MOD data.sparse
4870@c EN
4871The actual sparse vector classes.  Inherits @code{<sparse-vector-base>}.
4872An instance of @code{<sparse-vector>} can contain any Scheme objects.
4873
4874@code{@@} is either one of @code{s8}, @code{u8},
4875@code{s16}, @code{u16}, @code{s32}, @code{u32},
4876@code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
4877The range of values an instance of those classes can hold
4878is the same as the corresponding @code{<@@vector>} class
4879in @code{gauche.uvector} (@pxref{Uniform vectors}).  That is,
4880@code{<sparse-u8vector>} can have exact integer values
4881between 0 and 255.
4882@c JP
4883疎なベクタの具体クラスです。それぞれ@code{<sparse-vector-base>}を継承します。
4884
4885@code{<sparse-vector>}のインスタンスは任意のSchemeオブジェクトを格納できます。
4886
4887@code{@@}は @code{s8}, @code{u8},
4888@code{s16}, @code{u16}, @code{s32}, @code{u32},
4889@code{s64}, @code{u64}, @code{f16}, @code{f32}, @code{f64}のいずれかで、
4890それぞれの疎なベクタの格納可能な値は、@code{gauche.uvector}の
4891対応する@code{<@@vector>}に準じます(@ref{Uniform vectors}参照)。
4892つまり、@code{<sparse-u8vector>}の要素には0以上255以下の正確な整数を
4893格納できます。
4894@c COMMON
4895@end deftp
4896
4897@defun make-sparse-vector :optional type :key default
4898@c MOD data.sparse
4899@c EN
4900Creates an empty sparse vector.  The @var{type} argument can be
4901@code{#f} (default), one of subclasses of @code{<sparse-vector-base>},
4902or a symbol of either one of @code{s8}, @code{u8},
4903@code{s16}, @code{u16}, @code{s32}, @code{u32},
4904@code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
4905
4906If @var{type} is omitted or @code{#f}, a @code{<sparse-vector>} is
4907created.  If it is a class, an instance of the class is created
4908(It is an error to pass a class that is not a subclass of
4909@code{<sparse-vector-base>}.)
4910If it is a symbol, an instance of corresponding @code{<sparse-@@vector>}
4911is created.
4912@c JP
4913空の疎なベクタを作成して返します。@var{type}引数は@code{#f}(デフォルト)か、
4914@code{<sparse-vector-base>}のサブクラスのどれか、
4915あるいはシンボル@code{s8}, @code{u8},
4916@code{s16}, @code{u16}, @code{s32}, @code{u32},
4917@code{s64}, @code{u64}, @code{f16}, @code{f32}, @code{f64}のいずれかを
4918指定できます。
4919
4920@var{type}が省略されるか@code{#f}の場合は@code{<sparse-vector>}のインスタンスが
4921作られます。@var{type}がクラスであればそのインスタンスが、またシンボルであれば、
4922対応する@code{<sparse-@@vector>}のインスタンスが作られます。
4923@c COMMON
4924
4925@c EN
4926You can specify the default value of the vector by @var{default}
4927keyword argument.   If given, the vector behaves as if it is filled
4928with the default value (but the vector iterator only picks
4929the values explicitly set).
4930
4931Note that you have to give the optional argument as well
4932to specify the keyword argument.
4933@c JP
4934キーワード引数@var{default}によって、作成するベクタの要素既定値を指定できます。
4935この引数が与えられると、ベクタは全てあらかじめその値で埋められているかのように
4936振る舞います (ただしイテレータは陽にセットされた値のみ取り出します)。
4937
4938キーワード引数を与える場合、それに先立って省略可能引数も与える必要が
4939あることに注意してください。
4940@c COMMON
4941
4942@example
4943(define v (make-sparse-vector 'u8 :default 128))
4944
4945(sparse-vector-ref v 0) @result{} 128
4946@end example
4947@end defun
4948
4949@defun sparse-vector-max-index-bits
4950@c MOD data.sparse
4951@c EN
4952Returns maximum number of bits of allowed integer.  If this
4953returns 32, the index up to @code{(expt 2 32)} is supported.
4954It is guaranteed that this is at least 32.
4955@c JP
4956実装が利用できる、疎なベクタのインデックスの最大のビット数を返します。
4957例えばこれが32を返したなら、インデックスとして@code{(expt 2 32)}まで
4958使えるということです。この値は最低でも32であることが保証されています。
4959@c COMMON
4960@end defun
4961
4962@c EN
4963In the following entries, the argument @var{sv} denotes
4964an instance of sparse vector; an error is signaled if other
4965object is passed.
4966@c JP
4967以下のエントリにおいて、引数@var{sv}は疎なベクタのインスタンスです。
4968他のオブジェクトが渡された場合はエラーが報告されます。
4969@c COMMON
4970
4971@defun sparse-vector-copy sv
4972@c MOD data.sparse
4973@c EN
4974Returns a copy of a sparse vector @var{sv}.
4975@c JP
4976疎なベクタ@var{sv}のコピーを返します。
4977@c COMMON
4978@end defun
4979
4980@defun sparse-vector-ref sv k :optional fallback
4981@c MOD data.sparse
4982@c EN
4983Returns @var{k}-th element of a sparse vector @var{sv}, where
4984@var{k} must an exact integer.
4985
4986If the sparse vector doesn't have a value for @var{k}, it
4987behaves as follows:
4988
4989@itemize @bullet
4990@item
4991If @var{fallback} is given, it is returned.
4992@item
4993Otherwise, if the vector has the default value, it is returned.
4994@item
4995Otherwise, an error is signaled.
4996@end itemize
4997@c JP
4998疎なベクタ@var{sv}のインデックス@var{k}にある要素を返します。
4999@var{k}は正確な整数でなければなりません。
5000
5001@var{k}に対応する要素がない場合は、次のように振る舞います。
5002
5003@itemize @bullet
5004@item
5005@var{fallback}引数が与えられていればそれを返します。
5006@item
5007そうでなく、ベクタが既定値を持っていれば、それを返します。
5008@item
5009そうでなければ、エラーが報告されます。
5010@end itemize
5011@c COMMON
5012@end defun
5013
5014@defun sparse-vector-set! sv k value
5015@c MOD data.sparse
5016@c EN
5017Sets @var{value} for @var{k}-th element of a sparse vector @var{sv}.
5018@var{K} must be a nonnegative exact integer, and below the maximum
5019allowed index.
5020
5021If @var{sv} is a numeric sparse vector, @var{value} must also be
5022within the allowed range, or an error is signaled.
5023@c JP
5024疎なベクタ@var{sv}の@var{k}番めの要素に@var{value}を設定します。
5025@var{k}は非負の正確な整数で、許される最大のインデックス以下でなければなりません。
5026@c COMMON
5027@end defun
5028
5029@defun sparse-vector-num-entries sv
5030@c MOD data.sparse
5031@c EN
5032Returns the number of entries in @var{sv}.
5033@c JP
5034@var{sv}の持つ要素数を返します。
5035@c COMMON
5036@end defun
5037
5038@defun sparse-vector-exists? sv k
5039@c MOD data.sparse
5040@c EN
5041Returns @code{#t} if @var{sv} has an entry for index @var{k},
5042@code{#f} otherwise.
5043@c JP
5044@var{sv}の@var{k}番目のエントリが値を持っていれば@code{#t}を、
5045そうでなければ@code{#f}を返します。
5046@code{#t}
5047@c COMMON
5048@end defun
5049
5050@defun sparse-vector-delete! sv k
5051@c MOD data.sparse
5052@c EN
5053Deletes the @var{k}-th entry of @var{sv}.  If @var{sv} had the entry ,
5054returns @code{#t}.  If @var{sv} didn't have the entry, returns @code{#f}.
5055@c JP
5056@var{sv}の@var{k}番目のエントリが値を持っていれば、それを消去して
5057@code{#t}を返します。
5058そうでなければ何もせずに@code{#f}を返します。
5059@c COMMON
5060@end defun
5061
5062@defun sparse-vector-clear! sv
5063@c MOD data.sparse
5064@c EN
5065Empties a sparse vector.
5066@c JP
5067疎なベクタを空にします。
5068@c COMMON
5069@end defun
5070
5071@defun sparse-vector-inc! sv k delta :optional (fallback 0)
5072@c MOD data.sparse
5073@c EN
5074@c EN
5075This is a shortcut of the following.  It is especially efficient
5076for numeric sparse vectors.
5077
5078@example
5079(sparse-vector-set! sv k (+ (sparse-vector-ref sv k fallback) delta))
5080@end example
5081
5082If the result of addition exceeds the allowed value range of @var{sv},
5083an error is signaled.  In future we'll allow an option to clamp
5084the result value within the range.
5085@c JP
5086これは次のコードと同じ動作をしますが、数値を格納する疎ベクタでは特に
5087効率よく動作します。
5088
5089@example
5090(sparse-vector-set! sv k (+ (sparse-vector-ref sv k fallback) delta))
5091@end example
5092
5093もし加算の結果が@var{sv}に許される数値の範囲を越えた場合は、
5094エラーが投げられます。将来はそういった場合に値をクランプするオプションも
5095用意する予定です。
5096@c COMMON
5097@end defun
5098
5099@defun sparse-vector-update! sv k proc :optional fallback
5100@defunx sparse-vector-push! sv k val
5101@defunx sparse-vector-pop! sv k :optional fallback
5102@c MOD data.sparse
5103@c EN
5104Convenience routines to fetch-and-update an entry of
5105a sparse vector.  Works just like @code{hash-table-update!},
5106@code{hash-table-push!} and @code{hash-table-pop!};
5107(@pxref{Hashtables}).
5108@c JP
5109疎なベクタのエントリの値を取り出してアップデートするパターンを
5110簡単に書くためのルーチンです。それぞれ、@code{hash-table-update!}、
5111@code{hash-table-push!}、@code{hash-table-pop!}と
5112同じように動作します。(@ref{Hashtables}参照)。
5113@c COMMON
5114@end defun
5115
5116@c EN
5117The following procedures traverses a sparse vector.
5118Note that elements are not visited in the order of index;
5119it's just like hash table traversers.
5120@c JP
5121以下の手続きは疎なベクタの要素を横断します。
5122要素は必ずしもインデックスの順に訪問されるわけではないことに注意してください。
5123その点ではハッシュテーブルの横断と似ています。
5124@c COMMON
5125
5126@c EN
5127At this moment, if you want to walk a sparse vector with
5128increasing/decreasing index order, you have to get a list
5129of keys by @code{sparse-vector-keys}, sort it, then use
5130it to retrieve values.
5131We may add an option in future to @code{make-sparse-vector} so that
5132those walk operation will be more convenient.
5133@c JP
5134今のところ、疎なベクタをインデックスの昇順/降順に処理したい場合は、
5135@code{sparse-vector-keys}で全てのキーを得て、
5136それをソートしたもので順に値を取り出してゆくしかありません。
5137将来は、@code{make-sparse-vector}にオプションをつけて
5138インデックスの順番による横断を簡単にするかもしれません。
5139@c COMMON
5140
5141@defun sparse-vector-fold sv proc seed
5142@c MOD data.sparse
5143@c EN
5144For each entry in @var{sv}, calls @var{proc} as
5145@code{(proc @var{k_n} @var{v_n} @var{seed_n})}, where
5146@var{k_n} is an index and @var{v_n} is a value for it,
5147and @var{seed_n} is the returned value of the previous
5148call to @var{proc} if @var{n} @code{>=} 1, and @var{seed} if @var{n} = 0.
5149Returns the value of the last call of @var{proc}.
5150@c JP
5151@var{sv}の各エントリに対し、手続き@var{proc}を
5152@code{(proc @var{k_n} @var{v_n} @var{seed_n})}のように呼び出してゆきます。
5153ここで@var{seed_n}は@var{n} @code{>=} 1の時は直前の@var{proc}の戻り値、
5154@var{n} = 0の時は引数@var{seed}です。
5155最後の@var{proc}の戻り値を返します。
5156@c COMMON
5157@end defun
5158
5159@defun sparse-vector-for-each sv proc
5160@defunx sparse-vector-map sv proc
5161@c MOD data.sparse
5162Calls @code{proc} with index and value, e.g. @code{(proc k value)},
5163for each element of @var{sv}.
5164
5165The results of @var{proc} are discarded by @code{sparse-vector-for-each},
5166and gathered to a list and returned by @code{sparse-vector-map}.
5167@end defun
5168
5169@defun sparse-vector-keys sv
5170@defunx sparse-vector-values sv
5171@c MOD data.sparse
5172@c EN
5173Returns a list of all keys and all values in @var{sv}, respectively.
5174@c JP
5175それぞれ、@var{sv}中の全てのキー、または全ての値をリストにして返します。
5176@c COMMON
5177@end defun
5178
5179@node Sparse matrixes, Sparse tables, Sparse vectors, Sparse data containers
5180@subsection Sparse matrixes
5181@c NODE 疎行列
5182
5183@c EN
5184A sparse matrix is like a sparse vector, except it can be indexed
5185by two nonnegative integers.
5186@c JP
5187疎行列は要素が2つの非負整数でインデックスされること以外は疎なベクタと同じです。
5188@c COMMON
5189
5190@c EN
5191Note: This implementation of sparse matrixes aims at a reasonable
5192space efficiency for sparse matrixes without knowing its structure
5193beforehand (imagine, for example, a 2D map with some scattered landmarks).
5194If what you want is a sparse matrix implementation for efficient numeric
5195calculations, with certain particular structures,
5196probably the access speed of this module isn't suitable.
5197@c JP
5198註:この疎行列の実装は、事前に構造が分かっていない疎な行列をそれなりに空間効率良く
5199扱うことを目的としています(例えば、2Dのマップにランドマークを記録してゆく、
5200といったイメージです)。もし探しているものが、数値計算用に特定の構造を持つ疎行列の
5201実装でしたら、このモジュールは速度的に十分ではないでしょう。
5202@c COMMON
5203
5204@c EN
5205Currently, each index can have half of bits of
5206@code{sparse-vector-max-index-bits}.  We'll remove
5207this limitation in future.
5208@c JP
5209現在の実装では、それぞれのインデックスの最大ビット数が
5210@code{sparse-vector-max-index-bits}の半分までという制限があります。
5211将来はこの制限をなくす予定です。
5212@c COMMON
5213
5214
5215@deftp {Class} <sparse-matrix-base>
5216@clindex sparse-matrix-base
5217@c MOD data.sparse
5218An abstract base class of sparse matrixes.  Inherits @code{<collection>}.
5219
5220Like sparse vectors, a sparse matrix can be of type that
5221can store any Scheme objects, or that can store only
5222certain types of numbers.
5223
5224All of these sparse matrix subtypes can be accessed by the same API.
5225@end deftp
5226
5227@deftp {Class} <sparse-matrix>
5228@deftpx {Class} <sparse-@@matrix>
5229@clindex sparse-matrix
5230@clindex sparse-s8matrix
5231@clindex sparse-u8matrix
5232@clindex sparse-s16matrix
5233@clindex sparse-u16matrix
5234@clindex sparse-s32matrix
5235@clindex sparse-u32matrix
5236@clindex sparse-s64matrix
5237@clindex sparse-u64matrix
5238@clindex sparse-f16matrix
5239@clindex sparse-f32matrix
5240@clindex sparse-f64matrix
5241@c MOD data.sparse
5242The actual sparse matrix classes.  Inherits @code{<sparse-matrix-base>}.
5243An instance of @code{<sparse-matrix>} can contain any Scheme objects.
5244
5245@code{@@} is either one of @code{s8}, @code{u8},
5246@code{s16}, @code{u16}, @code{s32}, @code{u32},
5247@code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
5248The range of values an instance of those classes can hold
5249is the same as the corresponding @code{<@@vector>} class
5250in @code{gauche.uvector} (@pxref{Uniform vectors}).  That is,
5251@code{<sparse-u8matrix>} can have exact integer values
5252between 0 and 255.
5253@end deftp
5254
5255@defun make-sparse-matrix :optional type :key default
5256@c MOD data.sparse
5257Creates an empty sparse matrix.  The @var{type} argument can be
5258@code{#f} (default), one of subclasses of @code{<sparse-matrix-base>},
5259or a symbol of either one of @code{s8}, @code{u8},
5260@code{s16}, @code{u16}, @code{s32}, @code{u32},
5261@code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
5262
5263If @var{type} is omitted or @code{#f}, a @code{<sparse-matrix>} is
5264created.  If it is a class, an instance of the class is created
5265(It is an error to pass a class that is not a subclass of
5266@code{<sparse-matrix-base>}.)
5267If it is a symbol, an instance of corresponding @code{<sparse-@@matrix>}
5268is created.
5269
5270You can specify the default value of the matrix by @var{default}
5271keyword argument.   If given, the vector behaves as if it is filled
5272with the default value (but the matrix iterator only picks
5273the values explicitly set).
5274
5275Note that you have to give the optional argument as well
5276to specify the keyword argument.
5277@end defun
5278
5279@defun sparse-matrix-num-entries mat
5280@c MOD data.sparse
5281Returns the number of entries explicitly set in a sparse matrix @var{mat}.
5282@end defun
5283
5284@defun sparse-matrix-ref mat x y :optional fallback
5285@c MOD data.sparse
5286Returns an element indexed by (@var{x}, @var{y}) in a sparse matrix @var{mat}.
5287If the indexed element isn't set, @var{fallback} is returned if provided;
5288otherwise, if the matrix has the default value, it is returned; otherwise,
5289an error is raised.
5290@end defun
5291
5292@defun sparse-matrix-set! mat x y value
5293@c MOD data.sparse
5294Set @var{value} to the sparse matrix @var{mat} at the location
5295(@var{x}, @var{y}).
5296@end defun
5297
5298@defun sparse-matrix-exists? mat x y
5299@c MOD data.sparse
5300Returns @code{#t} iff the sparse matrix @var{mat} has a value at
5301(@var{x}, @var{y}).
5302@end defun
5303
5304@defun sparse-matrix-clear! mat
5305@c MOD data.sparse
5306Empties the sparse matrix @var{mat}.
5307@end defun
5308
5309@defun sparse-matrix-delete! mat x y
5310@c MOD data.sparse
5311Remove the value at (@var{x}, @var{y}) from the sparse matrix @var{mat}.
5312@end defun
5313
5314@defun sparse-matrix-copy mat
5315@c MOD data.sparse
5316Returns a fresh copy of @var{mat}.
5317@end defun
5318
5319@defun sparse-matrix-update! mat x y proc :optional fallback
5320@c MOD data.sparse
5321Call @var{proc} with the value at (@var{x}, @var{y}) of the sparse matrix,
5322and sets the result of @var{proc} as the new value of the location.
5323
5324The optional @var{fallback} argument works just like @code{sparse-matrix-ref};
5325if provided, it is passed to @var{proc} in case the
5326matrix doesn't have a value at (@var{x}, @var{y}).
5327If @var{fallback} isn't provided and the matrix doesn't have a value
5328at the location, the default value of the matrix is used if it has one.
5329Otherwise, an error is signalled.
5330@end defun
5331
5332@defun sparse-matrix-inc! mat x y delta :optional fallback
5333@c MOD data.sparse
5334@example
5335(sparse-matrix-update! mat x y (cut + <> delta) fallback)
5336@end example
5337@end defun
5338
5339@defun sparse-matrix-push! mat x y val
5340@c MOD data.sparse
5341@example
5342(sparse-matrix-update! mat x y (cut cons val <>) '())
5343@end example
5344@end defun
5345
5346@defun sparse-matrix-pop! mat x y
5347@c MOD data.sparse
5348@example
5349(rlet1 r #f
5350  (sparse-matrix-update! mat x y (^p (set! r (car p)) (cdr p))))
5351@end example
5352@end defun
5353
5354@defun sparse-matrix-fold mat proc seed
5355@c MOD data.sparse
5356Loop over values in the sparse matrix @var{mat}.  The procedure
5357@var{proc} is called with four arguments, @var{x}, @var{y}, @var{val}
5358and @var{seed}, for each index (@var{x}, @var{y}) which has the value
5359@var{val}.  The initial value of @var{seed} is the one given to
5360@code{sparse-matrix-fold}, and the result of @var{proc} is passed
5361as the next seed value.  The last result of @var{proc} is returned
5362from @code{sparse-matrix-fold}.
5363
5364The procedure @var{proc} is only called on the entries that's actually
5365has a value, and the order of which the procedure is called is undefined.
5366@end defun
5367
5368@defun sparse-matrix-map mat proc
5369@c MOD data.sparse
5370@example
5371(sparse-matrix-fold sv (^[x y v s] (cons (proc x y v) s)) '()))
5372@end example
5373@end defun
5374
5375@defun sparse-matrix-for-each mat proc
5376@c MOD data.sparse
5377@example
5378(sparse-matrix-fold sv (^[x y v _] (proc x y v)) #f))
5379@end example
5380@end defun
5381
5382@defun sparse-matrix-keys mat
5383@c MOD data.sparse
5384@example
5385(sparse-matrix-fold sv (^[x y _ s] (cons (list x y) s)) '())
5386@end example
5387@end defun
5388
5389@defun sparse-matrix-values mat
5390@c MOD data.sparse
5391@example
5392(sparse-matrix-fold sv (^[x y v s] (cons v s)) '())
5393@end example
5394@end defun
5395
5396@node Sparse tables,  , Sparse matrixes, Sparse data containers
5397@subsection Sparse tables
5398@c NODE 疎なテーブル
5399
5400@deftp {Class} <sparse-table>
5401@clindex sparse-table
5402@c MOD data.sparse
5403A class for sparse table.  Inherits @code{<dictionary>} and
5404@code{<collection>}.
5405
5406Operationally sparse tables are the same as hash tables, but
5407the former consumes less memory in trade of slight slower access.
5408(Roughly x1.5 to x2 access time when the table is small.
5409As the table gets larger the difference becomes smaller.)
5410@end deftp
5411
5412@defun make-sparse-table comparator
5413@c MOD data.sparse
5414Creates and returns an empty sparse table.
5415The @var{comparator} argument specifies how to compare and hash keys;
5416it must be either a comparator (@pxref{Basic comparators}),
5417or one of the symbols @code{eq?}, @code{eqv?}, @code{equal?} and
5418@code{string=?}, like hash tables (@pxref{Hashtables}).   If it is a symbol,
5419@code{eq-comparator}, @code{eqv-comparator}, @code{equal-comparator} or
5420@code{string-comparator} are used, respectively.
5421@end defun
5422
5423@defun sparse-table-comparator st
5424@c MOD data.sparse
5425Returns the comparator used in the sparse table @var{st}.
5426@end defun
5427
5428@defun sparse-table-copy st
5429@c MOD data.sparse
5430Returns a copy of a sparse table @var{st}.
5431@end defun
5432
5433@defun sparse-table-num-entries st
5434@c MOD data.sparse
5435Returns the number of entries in a sparse table @var{st}.
5436@end defun
5437
5438@defun sparse-table-ref st key :optional fallback
5439@c MOD data.sparse
5440Retrieves a value associated to the @var{key} in @var{st}.
5441If no entry with @var{key} exists, @var{fallback} is returned
5442when it is provided, or an error is signaled otherwise.
5443@end defun
5444
5445@defun sparse-table-set! st key value
5446@c MOD data.sparse
5447Sets @var{value} with @var{key} in @var{st}.
5448@end defun
5449
5450@defun sparse-table-exists? st key
5451@c MOD data.sparse
5452Returns @code{#t} if an entry with @var{key} exists in @var{st},
5453@code{#f} otherwise.
5454@end defun
5455
5456@defun sparse-table-delete! st key
5457@c MOD data.sparse
5458Deletes an entry with @var{key} in @var{st} if it exists.
5459Returns @code{#t} if an entry is actually deleted, or @code{#f}
5460if there hasn't been an entry with @var{key}.
5461@end defun
5462
5463@defun sparse-table-clear! st
5464@c MOD data.sparse
5465Empties @var{st}.
5466@end defun
5467
5468@defun sparse-table-update! st key proc :optional fallback
5469@defunx sparse-table-push! st key val
5470@defunx sparse-table-pop! st key :optional fallback
5471@c MOD data.sparse
5472@end defun
5473
5474@defun sparse-table-fold st proc seed
5475@defunx sparse-table-for-each st proc
5476@defunx sparse-table-map st proc
5477@c MOD data.sparse
5478@end defun
5479
5480@defun sparse-table-keys st
5481@defunx sparse-table-values st
5482@c MOD data.sparse
5483@end defun
5484
5485@c ----------------------------------------------------------------------
5486@node Trie, Database independent access layer, Sparse data containers, Library modules - Utilities
5487@section @code{data.trie} - Trie
5488@c NODE Trie, @code{data.trie} - Trie
5489
5490@deftp {Module} data.trie
5491@mdindex data.trie
5492@c EN
5493This module provides @emph{Trie}, a dictionary-like data
5494structure that maps keys to values, where a key is an arbitrary sequence.
5495Internally it stores the data as a tree where each node corresponds
5496to each element in the key sequence.
5497Key lookup is O(n) where n is the length of the key, and not affected
5498much by the number of total entries.
5499Also it is easy to find a set of values whose keys share a common prefix.
5500@c JP
5501このモジュールは@emph{Trie}を提供します。@emph{Trie}はディレクトリに似
5502たデータ構造で、キーを値に写像します。また、キーは任意のシーケンスです。
5503内部的にはデータはツリーとして保持されます。このとき各ノードがキーシー
5504ケンスの各要素に対応します。キーの検索は O(n) で、n はキーの長さです。
5505したがって、全体のエントリ数には余り影響を受けません。また、キーが共通
5506の接頭辞をもつような値の集合を簡単にみつけられます。
5507@c COMMON
5508
5509@c EN
5510The following example may give you the idea.
5511@c JP
5512以下のサンプルを見れば考え方が理解できると思います。
5513@c COMMON
5514
5515@example
5516(define t (make-trie))   ;; create a trie
5517
5518(trie-put! t "pho" 3)    ;; populate the trie
5519(trie-put! t "phone" 5)
5520(trie-put! t "phrase" 6)
5521
5522(trie-get t "phone")  @result{} 5  ;; lookup
5523
5524(trie-common-prefix t "pho")       ;; common prefix search
5525  @result{} (("phone" . 5) ("pho" . 3))
5526(trie-common-prefix-keys t "ph")
5527  @result{} ("phone" "pho" "phrase")
5528@end example
5529
5530@c EN
5531Tries are frequently used with string keys, but you are not
5532limited to do so; any sequence (@pxref{Sequence framework}) can be
5533a key.  If the types of keys differ, they are treated as different
5534keys:
5535@c JP
5536Trieでは文字列キーを使うことが多いですが、それに限定される必要はありま
5537せん。あらゆるシーケンス(@pxref{Sequence framework})をキーにすることが
5538できます。キーの型が違えば、別のキーとして扱われます。
5539@c COMMON
5540
5541@example
5542(trie-put! t '(#\p #\h #\o) 8)  ;; different key from "pho"
5543@end example
5544
5545@c EN
5546Trie inherits @code{<collection>} and implements collection framework
5547including the builder. So you can apply generic collection
5548operations on a trie (@pxref{Collection framework}).
5549When iterated, each element of a trie appears as a pair of a key
5550and a value.
5551@c JP
5552Trieは@code{<collection>}を継承しており、コレクションフレームワークを
5553ビルダも含めて実装しています。それゆえ、ジェネリックなコレクション操作
5554をTrieに適用することが可能です(@ref{Collection framework}参照)。
5555反復するとTrieの各要素がキーと値の対として現れます。
5556@c COMMON
5557@end deftp
5558
5559@deftp {Class} <trie>
5560@clindex trie
5561@c MOD data.trie
5562@c EN
5563A class for Trie.  No slots are intended for public.
5564Use the following procedures to operate on tries.
5565@c JP
5566Trieクラス。パブリックなスロットはありません。trieを操作するには以下の
5567手続きを使ってください。
5568@c COMMON
5569
5570@c EN
5571This class also implements the dictionary interface
5572(@pxref{Generic functions for dictionaries}).
5573@c JP
5574このクラスはまた、ディクショナリインタフェースを実装しています
5575(@ref{Generic functions for dictionaries}参照)。
5576@c COMMON
5577@end deftp
5578
5579@defun make-trie :optional tab-make tab-get tab-put! tab-fold tab-empty?
5580@c MOD data.trie
5581@c EN
5582Creates and returns an empty trie.  The optional arguments
5583are procedures to customize how the nodes of the internal
5584tree are managed.
5585@c JP
5586空のtrieを生成し返します。オプション引数は、
5587内部木のノードをどのようにマージするかをカスタマイズする手続きです。
5588@c COMMON
5589
5590@c EN
5591Each node can have a table to store its child nodes, indexed
5592by an element of the key sequence (e.g. if the trie uses strings
5593as keys, a node's table is indexed by characters).
5594@c JP
5595それぞれのノードは子のノードを格納するテーブルを持つことができます。
5596キーシーケンスの要素でインデックスできます。(たとえば、trieがキーとし
5597え文字列を使っているとすると、ノードのテーブルは文字でインデックスされ
5598ています。)
5599@c COMMON
5600
5601@c EN
5602@table @code
5603@item tab-make
5604A procedure with no arguments.  When called, creates and
5605returns an empty table for a node.
5606@item tab-get @var{tab} @var{elt}
5607Returns a child node indexed by @var{elt}, or returns @code{#f}
5608if the table doesn't have a child for @var{elt}.
5609@item tab-put! @var{tab} @var{elt} @var{child-node}
5610If @var{child-node} isn't @code{#f},
5611stores a @var{child-node} with index @var{elt}.
5612If @var{child-node} is @code{#f},
5613removes the entry with index @var{elt}.
5614In both cases, this procedure should return the updated table.
5615@item tab-fold @var{tab} @var{proc} @var{seed}
5616Calls @var{proc} for every index and node in @var{tab}, while
5617passing a seed value, whose initial value is @var{seed}.
5618That is, @var{proc} has a type of @code{(index, node, seed) -> seed}.
5619Should return the last result of @var{proc}.
5620@item tab-empty? @var{tab}
5621Returns @code{#t} if @var{tab} is empty, @code{#f} otherwise.
5622You can omit or pass @code{#f} to this procedure; then we use
5623@code{tab-fold} to check if @var{tab} is empty, which can be expensive.
5624@end table
5625@c JP
5626@table @code
5627@item tab-make
5628引数なしの手続き。呼ばれるとノード用の空テーブルを生成し返します。
5629@item tab-get @var{tab} @var{elt}
5630@var{elt}でインデックスされた子ノードを返すか、あるいは@var{elt}に対応
5631する子がテーブルにない場合には @code{#f}を返します。
5632@item tab-put! @var{tab} @var{elt} @var{child-node}
5633@var{child-node}が@code{#f}でなければ、@var{child-node}に@var{elt}とい
5634うインデックスをつけて保存します。@var{child-node}が@code{#f}なら
5635@var{elt}のインデックスをもつエントリを削除します。どちらの場合にも
5636この手続きは更新されたテーブルを返します。
5637@item tab-fold @var{tab} @var{proc} @var{seed}
5638@var{tab}内の各インデックスと要素ごとに@var{proc}を呼びます。シード値
5639が順に渡されていきます。シード値の初期値は@var{seed}です。すなわち、
5640@var{proc}の型は@code{(index, node, seed) -> seed} のような型というこ
5641とになります。返り値は最後の@var{proc}の適用結果です。
5642@item tab-empty? @var{tab}
5643@var{tab}が空なら@code{#t}を、そうでなければ@code{#f}を返す手続きです。
5644この手続きは省略するか@code{#f}を渡すことができます。その場合は空かどうかを
5645チェックするのに@code{tab-fold}手続きが使われますが、少々重くなるかもしれません。
5646@end table
5647@c COMMON
5648
5649@c EN
5650The default assumes @code{eqv?}-hashtables, i.e. the
5651following procedures are used.
5652@c JP
5653デフォルトでは@code{eqv?}-ハッシュ可能であることが仮定されます。すなわ
5654ち、以下の手続きが使われます。
5655@c COMMON
5656
5657@example
5658tab-make: (lambda () (make-hash-table 'eqv?))
5659
5660tab-get:  (lambda (tab k) (hash-table-get tab k #f))
5661
5662tab-put!: (lambda (tab k v)
5663            (if v
5664              (hash-table-put! tab k v)
5665              (hash-table-delete! tab k))
5666            tab)
5667
5668tab-fold: hash-table-fold
5669
5670tab-empty?: (lambda (tab) (zero? (hash-table-num-entries tab)))
5671@end example
5672
5673@c EN
5674The following example creates a trie using
5675assoc list to manage children, while comparing
5676string keys with case-insensitive way:
5677@c JP
5678以下の例では子を管理するのに連想リストを用いるtrieを作成しています。
5679文字列キーの比較は大文字小文字を無視する方法で行っています。
5680@c COMMON
5681
5682@example
5683(make-trie list
5684           (cut assoc-ref <> <> #f char-ci=?)
5685           (lambda (t k v)
5686             (if v
5687               (assoc-set! t k v char-ci=?)
5688               (alist-delete! k t char-ci=?)))
5689           (lambda (t f s) (fold f s t))
5690           null?)
5691@end example
5692
5693@c EN
5694It is important that @code{tab-put!} must return an updated
5695table---by that, you can replace the table structure on the fly.
5696For example, you may design a table which uses assoc list when
5697the number of children are small, and then switches to a vector
5698(indexed by character code) once the number of children grows over
5699a certain threshold.
5700@c JP
5701@code{tab-put!}が更新されたテーブルを返すというのは重要で、これのおか
5702げで、テーブル構造を実行中に置き換えることができます。たとえば、
5703子の数が少い場合にはテーブルに連想リストを使い、いったん子の数がある閾
5704値を越えたら、(文字コードでインデックスされた)ベクタを使うように設計す
5705ることができます。
5706@c COMMON
5707@end defun
5708
5709@defun trie params kv @dots{}
5710@c MOD data.trie
5711@c EN
5712Construct a trie with the initial contents
5713@var{kv} @dots{}, where each @var{kv} is a pair of a key and a value.
5714@var{Params} are a list of arguments
5715which will be given to @code{make-trie} to create the trie.
5716The following example creates a trie with two entries
5717and the default table procedures.
5718@c JP
5719初期の内容が@var{kv} @dots{} であるようなtrieを構成します。ここで、
5720@var{kv}はキーと値の対です。@var{params}はtrieを生成するときに
5721@code{make-trie}に渡される引数のリストです。以下の例は2つのエントリ
5722とデフォルトのテーブル手続をもつtrieを生成します。
5723@c COMMON
5724
5725@example
5726(trie '() '("foo" . a) '("bar" . b))
5727@end example
5728@end defun
5729
5730@defun trie-with-keys params key @dots{}
5731@c MOD data.trie
5732@c EN
5733A convenient version of @code{trie} when you only concern
5734the keys.  Each value is the same as its key.
5735The following example creates a trie with two entries
5736and the default table procedures.
5737@c JP
5738キーにだけ関心がある場合には便利な@code{trie}。各値はキーと同じ。以下
5739の例では2つのエントリとデフォルトのテーブル手続をもつtrieを生成します。
5740@c COMMON
5741
5742@example
5743(trie-with-keys '() "foo" "bar")
5744@end example
5745@end defun
5746
5747@defun trie? obj
5748@c MOD data.trie
5749@c EN
5750Returns @code{#t} if @var{obj} is a trie, or @code{#f} otherwise.
5751@c JP
5752@var{obj}がtrieなら@code{#t}を返し、さもなければ@code{#f}を返します。
5753@c COMMON
5754@end defun
5755
5756@defun trie-num-entries trie
5757@c MOD data.trie
5758@c EN
5759Returns the number of entries in @var{trie}.
5760@c JP
5761@var{trie}中のエントリの数を返します。
5762@c COMMON
5763@end defun
5764
5765@defun trie-exists? trie key
5766@c MOD data.trie
5767@c EN
5768Returns @code{#t} if @var{trie} contains an entry with @var{key},
5769or returns @code{#f} otherwise.
5770@c JP
5771@var{trie}が@var{key}というキーのエントリを含む場合には@code{#t}を返し、
5772さもなければ、@code{#f}を返します。
5773@c COMMON
5774
5775@example
5776(let1 t (trie '() '("foo" . ok))
5777  (list (trie-exists? t "foo")
5778        (trie-exists? t "fo")
5779        (trie-exists? t "bar")))
5780  @result{} '(#t #f #f)
5781@end example
5782@end defun
5783
5784@defun trie-partial-key? trie seq
5785@c MOD data.trie
5786@c EN
5787Returns @code{#t} if there's at least one key in @var{trie} that is
5788not equal to @var{seq} but @var{seq} matches its prefix.   Note that
5789@var{seq} may or may not a key of @var{trie}; see the example below.
5790@c JP
5791@var{trie}の中に少なくともひとつ、@var{seq}と同じではないが@var{seq}を
5792プリフィクスとするようなキーがあれば@code{#t}を返します。
5793@var{seq}と一致するキーが他にあるかないかは結果には影響を及ぼしません。
5794下の例を見てください。
5795@c COMMON
5796
5797@example
5798(define t (trie '() '("foo" . ok) '("fo" . ok)))
5799
5800(trie-partial-key? t "f")    @result{} #t
5801(trie-partial-key? t "fo")   @result{} #t
5802(trie-partial-key? t "foo")  @result{} #f
5803(trie-partial-key? t "bar")  @result{} #f
5804@end example
5805@end defun
5806
5807
5808@defun trie-get trie key :optional fallback
5809@c MOD data.trie
5810@c EN
5811Returns the value associated with @var{key} in @var{trie}, if
5812such an entry exists.  When there's no entry for @var{key},
5813if @var{fallback} is given, it is returned; otherwise,
5814an error is signaled.
5815@c JP
5816@var{trie}中の@var{key}をもつエントリがあれば、それにむすびついている
5817値を返します。そのようなエントリがない場合、@var{fallback}が与えられて
5818いればそれを返し、さもなければ、エラーシグナルがあがります。
5819@c COMMON
5820@end defun
5821
5822@defun trie-put! trie key value
5823@c MOD data.trie
5824@c EN
5825Puts @var{value} associated to @var{key} into @var{trie}.
5826@c JP
5827@var{key}に結びついた@var{value}を@var{trie}に挿入します。
5828@c COMMON
5829@end defun
5830
5831@defun trie-update! trie key proc :optional fallback
5832@c MOD data.trie
5833@c EN
5834Works like the following code, except that the
5835lookup of entry in @var{trie} is done only once.
5836@c JP
5837@var{trie}中のエントリの検索が一度きりしか起らないことをのぞけば以下の
5838コードのように動きます。
5839@c COMMON
5840
5841@example
5842(let ((val (trie-get trie key fallback)))
5843  (trie-put! trie key (proc val)))
5844@end example
5845@end defun
5846
5847@defun trie-delete! trie key
5848@c MOD data.trie
5849@c EN
5850Removes an entry associated with @var{key} from @var{trie}.
5851If there's no such entry, this procedure does nothing.
5852@c JP
5853@var{trie}から@var{key}に関連するエントリを削除します。
5854そのようなエントリがない場合にはこの手続きはなにもしません。
5855@c COMMON
5856@end defun
5857
5858@defun trie->list trie
5859@c MOD data.trie
5860@c EN
5861Makes each entry in @var{trie} to a pair @code{(@var{key} . @var{value})}
5862and returns a list of pairs of all entries.  The order of entries
5863are undefined.
5864@c JP
5865@var{trie}の各エントリを@code{(@var{key} . @var{value})}という対にして
5866すべてのエントリの対のリストを返します。エントリの順序は未定義です。
5867@c COMMON
5868@end defun
5869
5870@defun trie-keys trie
5871@defunx trie-values trie
5872@c MOD data.trie
5873@c EN
5874Returns a list of all keys and values in @var{trie}, respectively.
5875The order of keys/values are undefined.
5876@c JP
5877それぞれ、@var{trie}のすべてのキーのリスト、すべての値のリストを返しま
5878す。順序は未定義です。
5879@c COMMON
5880@end defun
5881
5882@defun trie->hash-table trie ht-type
5883@c MOD data.trie
5884@c EN
5885Creates a hash table with type @var{ht-type} (see @ref{Hashtables},
5886about hash table types), and populates it with every key and value
5887pair in @var{trie}.
5888@c JP
5889@var{ht-type}タイプのハッシュテーブル(ハッシュテーブルのタイプについて
5890は@ref{Hashtables}を参照)を作成し、@var{trie}のすべてのキーと値の対を
5891セットします。
5892@c COMMON
5893@end defun
5894
5895@defun trie-longest-match trie seq :optional fallback
5896@c MOD data.trie
5897@c EN
5898Returns a pair of the key and its value, where the key is the
5899longest prefix of @var{seq}.   If no such key is found, @var{fallback}
5900is returned if it is provided, or an error is thrown.
5901
5902Do not confuse this with @code{trie-common-prefix-*} procedures below;
5903In this procedure, the key is the prefix of the given argument.
5904In @code{trie-common-prefix-*} procedures, the given argument is
5905the prefix of the keys.
5906@c JP
5907@var{seq}のプレフィクスになっているキーのうちもっとも長いものを見つけて、
5908そのキーと値のペアを返します。そういったキーが見つからなかった場合は、
5909@var{fallback}が与えられればそれを返し、なければエラーが通知されます。
5910
5911この手続きと以下の@code{trie-common-prefix-*}手続きを混同しないようにしてください。
5912この手続きでは、キーが引数のプレフィクスです。
5913@code{trie-common-prefix-*}手続きでは、引数がキーのプレフィクスです。
5914@c COMMON
5915
5916@example
5917(let1 t (make-trie)
5918  (trie-put! t "a"  'a)
5919  (trie-put! t "ab" 'ab)
5920
5921  (trie-longest-match t "abc")  @result{} ("ab" . ab)
5922  (trie-longest-match t "acd")  @result{} ("a"  . a)
5923  (trie-longest-match t "ab")   @result{} ("ab" . ab)
5924  (trie-longest-match t "zy")   @result{} error
5925  )
5926@end example
5927@end defun
5928
5929
5930@defun trie-common-prefix trie prefix
5931@defunx trie-common-prefix-keys trie prefix
5932@defunx trie-common-prefix-values trie prefix
5933@c MOD data.trie
5934@c EN
5935Gathers all entries whose keys begin with @var{prefix};
5936@code{trie-common-prefix} returns those entries in a list of
5937pairs @code{(key . value)}; @code{trie-common-prefix-keys} returns
5938a list of keys; and @code{trie-common-prefix-values} returns a list
5939of values.   The order of entries in a returned list is undefined.
5940If @var{trie} contains no entry whose key has @var{prefix}, an
5941empty list is returned.
5942@c JP
5943@var{prefix}ではじまるキーをもつエントリをすべて集め、
5944@code{trie-common-prefix}はその各エントリを@code{(key . value)}の対にし
5945たリストを返します。@code{trie-common-prefix-keys}は、キーのリストを
5946@code{trie-common-prefix-values}は値のリストを返します。返されるリスト
5947のエントリの順序は未定義です。
5948@var{trie}に指定した@var{prefix}をもつキーのエントリがなければ、
5949空リストが返されます。
5950@c COMMON
5951
5952@c EN
5953Note that prefix matching doesn't consider the type of sequence;
5954if @var{trie} has entries for @code{"foo"} and @code{(#\f #\o #\o)},
5955@code{(trie-common-prefix trie "foo")} will return both entries.
5956@c JP
5957接頭辞照合ではシーケンスの型を考慮しないことに注意してください。
5958@var{trie}のなかに@code{"foo"}と@code{(#\f #\o #\o)}に対応するエントリ
5959があれば、@code{(trie-common-prefix trie "foo")}はその両方を返します。
5960@c COMMON
5961@end defun
5962
5963@defun trie-common-prefix-fold trie prefix proc seed
5964@c MOD data.trie
5965@c EN
5966For each entry whose key begins with @var{prefix},
5967calls @var{proc} with three arguments, the entry's key,
5968its value, and the current seed value.  @var{Seed} is
5969used for the first seed value, and the value @var{proc}
5970returns is used for the seed value of the next call of @var{proc}.
5971The last returned value from @var{proc} is returned from
5972@code{trie-common-prefix-fold}.
5973The order of entries on which @var{proc} is called is undefined.
5974If @var{trie} contains no entry whose key has @var{prefix},
5975@var{proc} is never called and @var{seed} is returned.
5976@c JP
5977@var{prefix}ではじまるキーをもつ各エントリに対して、@var{proc}を3つの
5978引数、エントリのキー、値、現在のシード値で呼びます。@var{seed}は最初の
5979シード値として使われ、@var{proc}が返す値は次の@var{proc}の呼び出しのシー
5980ド値として使われます。@var{proc}が返した最後の値が
5981@code{trie-common-prefix-fold}から返ります。
5982@var{proc}が適用される順序は未定義です。@var{trie}が@var{prefix}を持つ
5983キーのエントリを含まない場合には@var{proc}が呼ばれることはなく、
5984@var{seed}が返ります。
5985@c COMMON
5986@end defun
5987
5988@defun trie-common-prefix-map trie prefix proc
5989@defunx trie-common-prefix-for-each trie prefix proc
5990@c MOD data.trie
5991@c EN
5992These are to @var{trie-common-prefix-fold} as @code{map} and @code{for-each}
5993are to @code{fold}; @code{trie-common-prefix-map} calls
5994@var{proc} with key and value for matching entries and
5995gathers its result to a list; @code{trie-common-prefix-for-each}
5996also applies @var{proc}, but discards its results.
5997@c JP
5998@code{map}や@code{for-each}を@code{fold}を合せたのと同じように、
5999@var{trie-common-prefix-fold}に合せたものです。
6000@code{trie-common-prefix-map}は@var{proc}をマッチするエントリのキーと
6001値に適用し結果をリストにあつめます。
6002@code{trie-common-prefix-for-each}も同じく@var{proc}を適用しますが
6003結果は捨てます。
6004@c COMMON
6005@end defun
6006
6007@defun trie-fold trie proc seed
6008@defunx trie-map trie proc
6009@defunx trie-for-each trie proc
6010@c MOD data.trie
6011@c EN
6012These procedures are like their common-prefix versions, but
6013traverse entire @var{trie} instead.
6014@c JP
6015これらの手続きはcommon-prefix版とおなじような働きをしますが、
6016@var{trie}全体をトラバースします。
6017@c COMMON
6018@end defun
6019
6020
6021
6022
6023@c ----------------------------------------------------------------------
6024
6025@node Database independent access layer, Generic DBM interface, Trie, Library modules - Utilities
6026@section @code{dbi} - Database independent access layer
6027@c NODE データベース非依存アクセス層, @code{dbi} - データベース非依存アクセス層
6028
6029@deftp {Module} dbi
6030@mdindex dbi
6031@c EN
6032This module provides the unified interface to access various
6033relational database systems (RDBMS).  The operations specific
6034to individual database systems are packaged
6035in database driver (DBD) modules, which is usually loaded
6036implicitly by DBI layer.
6037@c JP
6038このモジュールはさまざまなリレーショナルデータベースシステム(RDBMS)に
6039アクセスするための統一されたインタフェースを提供します。個々のデータベー
6040スシステムに特有の操作についてはデータベースドライバ(DBD)モジュールに
6041パッケージされています。DBDのモジュールは通常暗黙裏にDBIの層からロード
6042されます。
6043@c COMMON
6044
6045@c EN
6046The module is strongly influenced by Perl's DBI/DBD architecture.
6047If you have used Perl DBI, it would be easy to use this module.
6048@c JP
6049このモジュールは Perl の DBI/DBD アーキテクチャに強く影響を受けていま
6050す。Perl DBIを使った経験があるなら、このモジュールを使うのはたやすいで
6051しょう。
6052@c COMMON
6053@end deftp
6054
6055@c EN
6056It's better to look at the example.  This is a simple outline
6057of accessing a database by @code{dbi} module:
6058@c JP
6059まず例を見るほうがよいでしょう。以下は@code{dbi}モジュールを使ったデー
6060タベースアクセス例の概要です。
6061@c COMMON
6062
6063@example
6064(use dbi)
6065(use gauche.collection) ; to make 'map' work on the query result
6066
6067(guard (e ((<dbi-error> e)
6068           ;; handle error
6069           ))
6070  (let* ((conn   (dbi-connect "dbi:mysql:test;host=dbhost"))
6071         (query  (dbi-prepare conn
6072                   "SELECT id, name FROM users WHERE department = ?"))
6073         (result (dbi-execute query "R&D"))
6074         (getter (relation-accessor result)))
6075    (map (lambda (row)
6076           (list (getter row "id")
6077                 (getter row "name")))
6078         result)))
6079@end example
6080
6081@c EN
6082There's nothing specific to the underlying database system
6083except the argument @code{"dbi:mysql:test;host=dbhost"}
6084passed to @code{dbi-connect}, from which @code{dbi} module
6085figures out that it is an access to @code{mysql} database,
6086loads @code{dbd.mysql} module, and let it handle the mysql-specific
6087stuff.  If you want to use whatever database system, you can just
6088pass @code{"dbi:@var{whatever}:@var{parameter}"} to @code{dbi-connect}
6089instead, and everything stays the same as far as you have
6090@code{dbd.whatever} installed in your system.
6091@c JP
6092@code{dbi-connect}にわたす、@code{"dbi:mysql:test;host=dbhost"}引数以
6093外は使用するデータベースシステムに依存する部分はありません。この引数に
6094より、@code{dbi}モジュールはこのアクセスが@code{mysql}データベースに対
6095するものであると判断します。そして、mysql-特有の手続を扱うようにします。
6096別のデータベースシステムwhateverを使いたいのであれば、単に
6097@code{"dbi:@var{whatever}:@var{parameter}"}を@code{dbi-connect}に渡せ
6098ばよく、@code{dbd.whatever}がシステムにインストールされていれば同じよ
6099うにできます。
6100@c COMMON
6101
6102@c EN
6103A query to the database can be created by @code{dbi-prepare}.
6104You can issue the query by @code{dbi-execute}.  This two-phase
6105approach allows you to create a prepared query, which is a kind of
6106parameterized SQL statement.  In the above example the query
6107takes one parameter, denoted as @code{'?'} in the SQL.
6108The actual value is given in @code{dbi-execute}.  When you
6109issue similar queries a lot, creating a prepared query and
6110execute it with different parameters may give you performance gain.
6111Also the parameter is automatically quoted.
6112@c JP
6113データベースに対するクエリは@code{dbi-prepare}を使って作成します。
6114クエリの発行は@code{dbi-execute}で行います。このような2つのフェーズを
6115使うことで、パラメータ化されたSQL文の一種であるプリペアドクエリを
6116作ることができます。上の例ではクエリはSQL文の中で@code{'?'}で表現され
6117ている部分に、ひとつの引数をわりあてます。実引数の値は
6118@code{dbi-execute}で設定されます。類似のクエリを大量に発行するような場
6119合にはプリペアドクエリをひとつ生成し、それにさまざまなパラメータを渡し
6120て実行するとパフォーマンスがかせげます。このパラメータは自動的にクォー
6121トされます。
6122@c COMMON
6123
6124@c EN
6125When the query is a @code{SELECT} statement,
6126its result is returned as a collection that implements
6127the relation protocol.  See @ref{Collection framework}
6128and @ref{Relation framework} for the details.
6129@c JP
6130クエリが@code{SELECT}文の場合、その結果は関係プロトコルを実装するコレ
6131クションとして返されます。詳細は@ref{Collection framework}および
6132@ref{Relation framework}を見てください。
6133@c COMMON
6134
6135@c EN
6136The outermost @code{guard} is to catch errors.  The @code{dbi} related
6137errors are supposed to inherit @code{<dbi-error>} condition.
6138There are a few specific errors defined in @code{dbi} module.
6139A specific @code{dbd} layer may define more specific errors.
6140@c JP
6141いちばん外側にある@code{guard}はエラーを捕捉するためのものです。
6142@code{dbi}に関連したエラーは@code{<dbi-error>}コンディションを継承して
6143いるものと見なされます。いくつかの特有のエラーは@code{dbi}モジュールで
6144定義されています。特定の@code{dbd}層はさらに固有のエラーを定義していま
6145す。
6146@c COMMON
6147
6148@c EN
6149In the next section we describe user-level API, that is,
6150the procedures you need to concern when you're using @code{dbi}.
6151The following section is for the driver API, which you need to use
6152to write a specific @code{dbd} driver to make it work with @code{dbi}
6153framework.
6154@c JP
6155次節ではユーザレベルのAPIについて説明します。すなわち、@code{dbi}を使
6156う際に必要となる手続に関する説明です。そのあとのセクションではドライバ
6157APIを説明をします。すなわち特定の@code{dbd}ドライバを@code{dbi}フレー
6158ムワークで使えるようにするために使うAPIの説明です。
6159@c COMMON
6160
6161@menu
6162* DBI user API::
6163* Writing drivers for DBI::
6164@end menu
6165
6166@node DBI user API, Writing drivers for DBI, Database independent access layer, Database independent access layer
6167@subsection DBI user API
6168@c NODE DBIのユーザAPI
6169
6170@c EN
6171@subsubheading DBI Conditions
6172@c JP
6173@subsubheading DBIのコンディション
6174@c COMMON
6175
6176@c EN
6177There are several predefined conditions @code{dbi} API may throw.
6178See @ref{Exceptions} for the details of conditions.
6179@c JP
6180@code{dbi} API が投げる可能性のあるコンディションがいくつか定義されて
6181います。コンディションの詳細については@ref{Exceptions}を見てください。
6182@c COMMON
6183
6184@deftp {Condition Type} <dbi-error>
6185@c MOD dbi
6186@c EN
6187The base class of @code{dbi}-related conditions.  Inherits @code{<error>}.
6188@c JP
6189@code{dbi}-関連のコンディションのベースクラス。@code{<error>}を継承し
6190ています。
6191@c COMMON
6192@end deftp
6193
6194@deftp {Condition Type} <dbi-nonexistent-driver-error>
6195@c MOD dbi
6196@c EN
6197This condition is thrown by @code{dbi-connect} when it cannot
6198find the specified driver.  Inherits @code{<dbi-error>}.
6199@c JP
6200@code{dbi-connect}は指定されたドライバが見つからない場合にこのコンディ
6201ションを投げます。@code{<dbi-error>}を継承しています。
6202@c COMMON
6203
6204@defivar <dbi-nonexistent-driver-error> driver-name
6205@c EN
6206Holds the requested driver name as a string.
6207@c JP
6208要求されたドライバの名前を文字列として保持している。
6209@c COMMON
6210@end defivar
6211@end deftp
6212
6213@deftp {Condition Type} <dbi-unsupported-error>
6214@c MOD dbi
6215@c EN
6216This condition is thrown when the called method isn't supported
6217by the underlying driver.  Inherits @code{<dbi-error>}.
6218@c JP
6219呼び出されたメソッドが基盤となるドライバでサポートされていない場合、こ
6220のコンディションが投げられます。@code{<dbi-error>}を継承しています。
6221@c COMMON
6222@end deftp
6223
6224@deftp {Condition Type} <dbi-parameter-error>
6225@c MOD dbi
6226@c EN
6227This condition is thrown when the number of parameters given to
6228the prepared query doesn't match the ones in the prepared statement.
6229@c JP
6230プリペアドクエリへ渡されたパラメータの数がプリペアドステートメントの中
6231のものと一致しないとき、このコンディションが投げられます。
6232@c COMMON
6233@end deftp
6234
6235@c EN
6236Besides these errors, if a driver relies on @code{dbi} to
6237parse the prepared SQL statement, @code{<sql-parse-error>} may
6238be thrown if an invalid SQL statement is passed to @code{dbi-prepare}.
6239(@pxref{SQL parsing and construction}).
6240@c JP
6241上の3つのエラー以外に、@code{dbi}がプリペアドSQL文を構文解析するのにド
6242ライバを利用す場合、不正なSQL文が@code{dbi-prepare}に渡されると、
6243@code{<sql-parse-error>}が投げられます
6244(@ref{SQL parsing and construction}参照)。
6245@c COMMON
6246
6247@c EN
6248@subsubheading Connecting to the database
6249@c JP
6250@subsubheading データベースへの接続
6251@c COMMON
6252
6253@defun dbi-connect dsn :key username password
6254@c MOD dbi
6255@c EN
6256Connect to a database using a data source specified by @var{dsn}
6257(data source name).  @var{Dsn} is a string with the following syntax:
6258@c JP
6259@var{dsn}(データソース名)で指定されたデータソースを使ってデータベース
6260に接続します。@var{dsn}は以下の構文をもつ文字列です。
6261@c COMMON
6262@example
6263dbi:@var{driver}:@var{options}
6264@end example
6265
6266@c EN
6267@var{Driver} part names a specific driver.  You need to have the
6268corresponding driver module, @code{dbd.@var{driver}}, installed in
6269your system.  For example, if @var{dsn} begins with @code{"dbi:mysql:"},
6270@code{dbi-connect} tries to load @code{dbd.mysql}.
6271@c JP
6272@var{driver}は特定のドライバ名です。対応するドライバモジュールがなけれ
6273ばなりません。すなわち、@code{dbd.@var{driver}}がシステムにインストー
6274ルされていなければなりません。たとえば、@var{dsn}が@code{"dbi:mysql:"}
6275ではじまるとすると、@code{dbi-connect}は@code{dbd.mysql}をロードしよう
6276とします。
6277@c COMMON
6278
6279@c EN
6280Interpretation of the @var{options} part is up to the driver.
6281Usually it is in the form of @code{key1=value1;key2=value2;...},
6282but some driver may interpret it differently.  For example,
6283@code{mysql} driver allows you to specify a database name
6284at the beginning of @var{options}.   You have to check out
6285the document of each driver for the exact specification of
6286@var{options}.
6287@c JP
6288@var{options}部分の解釈はドライバに依存します。通常この部分のフォーマッ
6289トは@code{key1=value1;key2=value2;...}のようになっていますが、ドライバ
6290によっては別の解釈になります。たとえば、@code{mysql}ドライバでは、
6291@var{options}の最初の部分でデータベース名を指定することができます。
6292@var{options}の正確な仕様については各ドライバのドキュメントをチェック
6293してください。
6294@c COMMON
6295
6296@c EN
6297The keyword arguments gives extra information required for
6298connection.  The @var{username} and @var{password} are commonly
6299supported arguments.  The driver may recognize more keyword arguments.
6300@c JP
6301接続のために必要な追加情報はキーワード引数であたえます。
6302@var{username}および@var{password}は共通でサポートされている引数です。
6303ドライバは他にもキーワード引数を認識します。
6304@c COMMON
6305
6306@c EN
6307If a connection to the database is successfully established,
6308a connection object (an instance of a subclass of @code{<dbi-connection>})
6309is returned.  Otherwise, an error is signaled.
6310@c JP
6311データベースへの接続が成功したら、コネクションオブジェクト
6312(@code{<dbi-connection>}のサブクラスのインスタンス)が返ります。さもな
6313ければ、エラーがあがります。
6314@c COMMON
6315@end defun
6316
6317@deftp {Class} <dbi-connection>
6318@clindex dbi-connection
6319@c MOD dbi
6320@c EN
6321The base class of a connection to a database system.
6322Each driver defines a subclass of this to keep information about
6323database-specific connections.
6324@c JP
6325データベースシステムへの接続のベースクラス。各ドライバはこのクラスのサ
6326ブクラスを定義し、これにデータベース特有のコネクションに関する情報を持
6327たせます。
6328@c COMMON
6329@end deftp
6330
6331@deffn {Method} dbi-open? (c <dbi-connection>)
6332@c MOD dbi
6333@c EN
6334Queries whether a connection to the database is still open (active).
6335@c JP
6336データベースへの接続がオープン状態(アクティブ状態)にあるかどうかを確か
6337めます。
6338@c COMMON
6339@end deffn
6340
6341@deffn {Method} dbi-close (c <dbi-connection>)
6342@c MOD dbi
6343@c EN
6344Closes a connection to the database.  This causes releasing resources
6345related to this connection.   Once closed, @var{c} cannot
6346be used for any dbi operations (except passing to @code{dbi-open?}).
6347Calling @code{dbi-close} on an already closed connection has no effect.
6348@c JP
6349データベースへの接続を閉じます。これによりこの接続に関連付けられたリソー
6350スが解放されます。いったん閉じた@var{c}に対してはどのようなdbi操作もで
6351きません。(@code{dbi-open?}だけは例外)。すでに閉じられたコネクションに
6352対して@code{dbi-close}を呼んでもなにも起りません。
6353@c COMMON
6354
6355@c EN
6356Although a driver usually closes a connection when @code{<dbi-connection>}
6357object is garbage-collected, it is not a good idea to rely on that,
6358since the timing of GC is unpredictable.  The user program must make
6359sure that it calls @code{dbi-close} at a proper moment.
6360@c JP
6361ドライバは通常@code{<dbi-connection>}がガベージコレクションされたとき
6362にコネクションを閉じますが、このことを期待したコードを書くのはいただけ
6363ません。GCのタイミングというのは予測不可能だからです。ユーザプログラム
6364は適切なタイミングで@code{dbi-close}を呼ぶようにすべきです。
6365@c COMMON
6366@end deffn
6367
6368@defun dbi-list-drivers
6369@c MOD dbi
6370@c EN
6371Returns a list of module names of known drivers.
6372@c JP
6373解っているドライバのモジュール名のリストを返します。
6374@c COMMON
6375@end defun
6376
6377@deftp {Class} <dbi-driver>
6378@clindex dbi-driver
6379@c MOD dbi
6380@c EN
6381The base class of a driver.  You usually don't need to see this
6382as far as you're using the high-level @code{dbi} API.
6383@c JP
6384ドライバのベースクラス。高レベルの@code{dbi} APIを使うかぎり、これが必
6385要になることはありません。
6386@c COMMON
6387@end deftp
6388
6389@defun dbi-make-driver driver-name
6390@c MOD dbi
6391@c EN
6392This is a low-level function called from @code{dbi-connect} method,
6393and usually a user doesn't need to call it.
6394@c JP
6395@code{dbi-connect}から呼ばれる低レベル関数、通常この関数を呼ぶ必要はあ
6396りません。
6397@c COMMON
6398
6399@c EN
6400Loads a driver module specified by @var{driver-name}, and
6401instantiate the driver class and returns it.
6402@c JP
6403@var{driver-name}で指定されたドライバモジュールをロードし、当該のドラ
6404イバクラスのインスタンスを生成してそれを返します。
6405@c COMMON
6406@end defun
6407
6408@c EN
6409@subsubheading Preparing and issuing queries
6410@c JP
6411@subsubheading クエリの準備と発行
6412@c COMMON
6413
6414@deffn {Method} dbi-prepare conn sql :key pass-through @dots{}
6415@c MOD dbi
6416@c EN
6417From a string representation of SQL statement @var{sql},
6418creates and returns a query object (an instance of @code{<dbi-query>}
6419or its subclass) for the database connection @code{conn}
6420@c JP
6421SQL文の文字列表現@var{sql}からデータベースコネクション@code{conn}用の
6422クエリオブジェクト(@code{<dbi-query>}のインスタンスもしくはそのサブク
6423ラスのインスタンス)を生成してそれを返します。
6424@c COMMON
6425
6426@c EN
6427@var{Sql} may contain parameter slots, denoted by @code{?}.
6428@c JP
6429@var{sql}は@code{?}であらわされているパラメータスロットを持ちます。
6430@c COMMON
6431@example
6432(dbi-prepare conn "insert into tab (col1, col2) values (?, ?)")
6433
6434(dbi-prepare conn "select * from tab where col1 = ?")
6435@end example
6436
6437@c EN
6438They will be filled when you actually issue the query by
6439@code{dbi-execute}.
6440There are some advantages of using parameter
6441slots: (1) The necessary quoting is done automatically.
6442You don't need to concern about security holes caused by
6443improper quoting, for example.
6444(2) Some drivers support a feature to send the template SQL
6445statement to the server at the preparation stage, and send
6446only the parameter values at the execution stage.  It would be
6447more efficient if you issue similar queries lots of time.
6448@c JP
6449これらのスロットは@code{dbi-execute}を使って実際にクエリを発行したとき
6450に埋められます。パラメータスロットを使うのは以下の利点があるからです。
6451(1) クォートが自動的にほどこされます。不適切なクォートによるセキュリティ
6452ホールを気にする必要はありません。
6453(2) いくつかのドライバでは準備の段階でサーバへテンプレートSQL文を送る
6454機能がサポートされていて、実行段階ではパラメータを送るだけで済みます。
6455これは似たようなクエリを大量に一度に発行するときには効率のよいやりかた
6456です。
6457@c COMMON
6458
6459@c EN
6460If the backend doesn't support prepared statements (SQL templates
6461having @code{?} parameters), the driver may use @code{text.sql}
6462module to parse @var{sql}.  It may raise @code{<sql-parse-error>}
6463condition if the given SQL is not well formed.
6464@c JP
6465バックエンドでプリペアド文がサポートされていない場合(でSQLテンプレー
6466トが@code{?}パラメータを持つ場合)、ドライバは@var{sql}を解析するのに
6467@code{text.sql}モジュールを使います。与えられたSQL文が正しい構文でなけ
6468れば、@code{<sql-parse-error>}コンディションが発生します。
6469@c COMMON
6470
6471@c EN
6472You may pass a true value to the keyword argument @var{pass-through}
6473to suppress interpretation of SQL and pass @var{sql} as-is to the
6474back end database system.  It is useful if the back-end supports
6475extension of SQL which @code{text.sql} doesn't understand.
6476@c JP
6477キーワード引数@var{pass-through}に真の値を渡して、SQLの解釈を抑制し、
6478@var{sql}をそのままバックエンドのデータベースシステムに渡すことができ
6479ます。@code{text.sql}で理解できないようなSQLの拡張をバックエンドがサポー
6480トしている場合に役立ちます。
6481@c COMMON
6482
6483@c EN
6484If the driver lets prepared statement handled in back-end,
6485without using @code{text.sql}, the @code{pass-through} argument
6486may be ignored.
6487The driver may also take other keyword arguments.  Check out
6488the documentation of individual drivers.
6489@c JP
6490ドライバがプリペアド文を@code{text.sql}抜きでバックエンドに処理させた
6491場合、@code{pass-through}引数は無視されます。ドライバは他のキーワード
6492引数を取ることもあります。詳細はそれぞれのドライバのドキュメントを参照
6493してください。
6494@c COMMON
6495
6496@c EN
6497@emph{Note:} Case folding of SQL statement
6498is implementation dependent.  Some DBMS may treat table
6499names and column names in case insensitive way, while
6500others do in case sensitive way.  To write a portable
6501SQL statement, make them quoted identifiers, that is,
6502always surround names by double quotes.
6503@c JP
6504@emph{注意}:SQL文のケース畳み込みは実装依存です。DBMSのなかにはテーブ
6505ル名やカラム名は大文字小文字の区別をしないものもあり、一方で区別するも
6506のもあります。ポータブルなSQL文を書きたいのなら、識別子をクォートしま
6507しょう。すなわち常に名前をダブルクォートで囲むようにします。
6508@c COMMON
6509@end deffn
6510
6511@deftp {Class} <dbi-query>
6512@clindex dbi-query
6513@c MOD dbi
6514@c EN
6515Holds information about prepared query, created by @code{dbi-prepare}.
6516The following slots are defined.
6517@c JP
6518@code{dbi-prepare}によって作成されたプリペアドクエリに関する情報を保持
6519します。以下のスロットが定義されています。
6520@c COMMON
6521
6522@defivar <dbi-query> connection
6523@c EN
6524Contains the @code{<dbi-connection>} object.
6525@c JP
6526@code{<dbi-connection>}オブジェクトを含みます。
6527@c COMMON
6528@end defivar
6529
6530@defivar <dbi-query> prepared
6531@c EN
6532If the driver prepares query by itself, this slot may contain
6533a prepared statement.  It is up to each driver how to use
6534this slot, so the client shouldn't rely on its value.
6535@c JP
6536ドライバがクエリを準備する場合、このスロットがプリペアド文を保持します。
6537このスロットをどのように使うかはおのおののドライバによります。したがっ
6538て、クライアントはこの値に依存してはいけません。
6539@c COMMON
6540@end defivar
6541
6542@end deftp
6543
6544@deffn {Method} dbi-open? (q <dbi-query>)
6545@c MOD dbi
6546@c EN
6547Returns @code{#t} iff the query can still be passed to
6548@code{dbi-execute}.
6549@c JP
6550クエリが@code{dbi-execute}に渡せる状態になっているときにのみ、
6551@code{#t}を返します。
6552@c COMMON
6553@end deffn
6554
6555@deffn {Method} dbi-close (q <dbi-query>)
6556@c MOD dbi
6557@c EN
6558Destroy the query and free resources associated to the query.
6559After this operation, @code{dbi-open?} returns @code{#f} for @var{q},
6560and the query can't be used in any other way.  Although the resource
6561may be freed when @var{q} is garbage-collected, it is strongly recommended
6562that the application closes queries explicitly.
6563@c JP
6564クエリを破棄し、当該クエリに関連づけられたリソースを解放します。この操
6565作を実行後は、@code{dbi-open?}は@var{q}に対して@code{#f}を返します。
6566そして、当該クエリは他の用途にはつかえません。@var{q}がガベージコレク
6567ションにより回収された場合、リソースは解放されますが、アプリケーション
6568が明示的にクエリを閉じるようにすることを強く勧めます。
6569@c COMMON
6570@end deffn
6571
6572@deffn {Method} dbi-execute (q <dbi-query>) parameter @dots{}
6573@c MOD dbi
6574@c EN
6575Executes a query created by @code{dbi-prepare}.  You should pass
6576the same number of @var{parameter}s as the query expects.
6577@c JP
6578@code{dbi-prepare}によって作成さればクエリを実行します。当該クエリが期
6579待するのと同じ数のパラメータを渡す必要があります。
6580@c COMMON
6581
6582@c EN
6583If the issued query is @code{select} statement, @code{dbi-execute}
6584returns an object represents a @emph{relation}.
6585A relation encapsulates the values in
6586rows and columns, as well as meta information like column names.
6587See "Retrieving query results" below for how to access the result.
6588@c JP
6589発行されたクエリが@code{select}文の場合@code{dbi-execute}は
6590@emph{リレーション}を表わすオブジェクトを返します。リレーションは
6591行とカラムの値をカプセル化したもので、カラム名のようなメタ情報も同様で
6592す。結果へアクセスの方法については後述の「クエリの結果を見る」を見てく
6593ださい。
6594@c COMMON
6595
6596@c EN
6597If the query is other types, such as @code{create}, @code{insert}
6598or @code{delete}, the return value of the query closure is unspecified.
6599@c JP
6600クエリがSELECT以外の@code{create}、@code{insert}、@code{delete}などの
6601場合、クエリクロージャー返り値は不定です。
6602@c COMMON
6603@end deffn
6604
6605@deffn {Method} dbi-do conn sql :optional options parameter-value @dots{}
6606@c MOD dbi
6607@c EN
6608This is a convenience procedure when you create a query
6609and immediately execute it.   It is equivalent to the following
6610expression, although the driver may overload this method to avoid
6611creating intermediate query object to avoid the overhead.
6612@c JP
6613この手続はクエリを作成し、すぐに実行したいときに便利です。これは次の式
6614と同じですが、この場合はドライバはオーバーヘッドを避けるため、中間のク
6615エリを作らないようにこのメソッドをオーバーロードします。
6616@c COMMON
6617@example
6618(dbi-execute (apply dbi-prepare conn sql options)
6619             parameter-value @dots{})
6620@end example
6621@end deffn
6622
6623@deffn {Method}  dbi-escape-sql conn str
6624@c MOD dbi
6625@c EN
6626Returns a string where special characters in @var{str} are escaped.
6627@c JP
6628@var{str}中の特殊文字をエスケープした文字列を返します。
6629@c COMMON
6630
6631@c EN
6632The official SQL standard only specify a single quote (@code{'}) as
6633such character.  However, it doesn't specify non-printable characters,
6634and the database system may use other escaping characters.  So
6635it is necessary to use this method rather than doing escaping
6636by your own.
6637@c JP
6638SQLの公式標準ではこのような文字としてはシングルクォート(@code{'})につ
6639いてだけ規定しています。しかし、印字可能文字ではない文字については規定
6640がありません。また、データベースシステムによっては他のエスケープ文字を
6641使うものもあります。それゆえ、自分でエスケープしようとせずに、このメソッ
6642ドを使う必要があります。
6643@c COMMON
6644
6645@c EN
6646@example
6647;; assumes c is a valid DBI connection
6648(dbi-escape-sql c "don't know")
6649  @result{} "don''t know"
6650@end example
6651@c JP
6652@example
6653;; c を利用可能なDBIコネクションとする
6654(dbi-escape-sql c "don't know")
6655  @result{} "don''t know"
6656@end example
6657@c COMMON
6658@end deffn
6659
6660@c EN
6661@subsubheading Retrieving query results
6662@c JP
6663@subsubheading クエリの結果を見る
6664@c COMMON
6665
6666@c EN
6667If the query is a @code{select} statement, it returns an object
6668of both @code{<collection>} and @code{<relation>}.
6669It is a collection of rows (that is, it implements @code{<collection>} API),
6670so you can use @code{map}, @code{for-each} or other generic functions
6671to access rows.  You can also use the relation API to retrieve column
6672names and accessors from it.  See @ref{Relation framework}, for the relation
6673API, and @ref{Collection framework}, for the collection API.
6674@c JP
6675クエリが@code{select}文である場合、@code{<collection>}と
6676@code{<relation>}の両方のオブジェクトが返ります。行のコレクション
6677(すなわち、@code{<collection>} APIの実装)ですから、行にアクセスするに
6678は@code{map}、@code{for-each}、その他のジェネリック関数が使えます。
6679また、カラム名やアクセサを取り出すにはリレーションAPIが使えます。
6680リレーションAPIについては@ref{Relation framework}をコレクションAPIにつ
6681いては@ref{Collection framework}を見てください。
6682@c COMMON
6683
6684@c EN
6685The actual class of the object returned from a query depends on
6686the driver, but you may use the following method on it.
6687@c JP
6688クエリから戻ったオブジェクトの実際のクラスはドライバによりますが、
6689以下のメソッドを使うことができます。
6690@c COMMON
6691
6692@deffn {Method} dbi-open? result
6693@c MOD dbi
6694@c EN
6695Check whether the result of a query is still active.
6696The result may become inactive when it is explicitly closed
6697by @code{dbi-close} and/or the connection to the database is
6698closed.
6699@c JP
6700クエリの結果がまだアクティブであるかどうかをチェックします。
6701結果は@code{dbi-close}によって明示的に閉じられるかデータベースへのコネ
6702クションが閉じられると非アクティブになります。
6703@c COMMON
6704@end deffn
6705
6706@deffn {Method} dbi-close result
6707@c MOD dbi
6708@c EN
6709Close the result of the query.  This may cause releasing resources
6710related to the result.   You can no longer use @var{result} once it is
6711closed, except passing it to @code{dbi-open?}.
6712@c JP
6713クエリの結果を閉じます。結果に関連付けられていたリソースが解放されます。
6714@var{result}は、いったん閉じると使えなくなります。ただし、
6715@code{dbi-open?}にだけは渡せます。
6716@c COMMON
6717
6718@c EN
6719Although a driver usually releases resources when the result is
6720garbage-collected, the application shouldn't rely on that and
6721is recommended call @code{dbi-close} explicitly when it is done
6722with the result.
6723@c JP
6724ドライバは通常、結果がガベージコレクタによって回収される時にリソースを
6725解放しますが、アプリケーションはこれに依存してはいけません。結果を使い
6726おわったら明示的に@code{dbi-close}を呼ぶことをおすすめします。
6727@c COMMON
6728@end deffn
6729
6730@node Writing drivers for DBI,  , DBI user API, Database independent access layer
6731@subsection Writing drivers for DBI
6732@c NODE DBI用のドライバを書く
6733
6734@c EN
6735Writing a driver for a specific database system means implementing
6736a module @code{dbd.@var{foo}}, where @var{foo} is the name of the driver.
6737@c JP
6738特定のデータベースシステムのドライバを書くということは、
6739@code{dbd.@var{foo}}モジュールを実装することです。ここで@var{foo}はド
6740ライバの名前になります。
6741@c COMMON
6742
6743@c EN
6744The module have to implement several classes and methods, as explained below.
6745@c JP
6746このモジュールは以下に説明するいくつかのクラスとメソッドを実装しなけれ
6747ばなりません。
6748@c COMMON
6749
6750@c EN
6751@subsubheading DBI classes to implement
6752@c JP
6753@subsubheading 実装するDBIクラス
6754@c COMMON
6755
6756@c EN
6757You have to define the following classes.
6758@c JP
6759以下のクラスを定義しなければなりません。
6760@c COMMON
6761
6762@c EN
6763@itemize @bullet
6764@item
6765Subclass @code{<dbi-driver>}.
6766The class name @emph{must} be @code{<@var{foo}-driver>}, where
6767@var{foo} is the name of the driver.
6768Usually this class produces a singleton instance,
6769and is only used to dispatch @code{dbi-make-connection}
6770method below.
6771@item
6772Subclass @code{<dbi-connection>}.  An instance of this class is created
6773by @code{dbi-make-connection}.  It needs to keep the information about
6774the actual connections.
6775@item
6776Subclass @code{<relation>} and @code{<collection>} to represent
6777query results suitable for the driver.  (In most cases, the order of
6778the result of SELECT statement is significant, since it may be
6779sorted by ORDER BY clause.  Thus it is more appropriate to
6780inherit @code{<sequence>}, rather than @code{<collection>}).
6781@item
6782Optionally, subclass @code{<dbi-query>} to keep driver-specific
6783information of prepared queries.
6784@end itemize
6785@c JP
6786@itemize @bullet
6787@item
6788@code{<dbi-driver>}のサブクラス。このクラスの名前は@emph{必ず}
6789@code{<@var{foo}-driver>}でなければなりません。ここで、@var{foo}は
6790ドライバの名前です。通常このクラスはシングルトンインスタンスを生成し、
6791後述の@code{dbi-make-connection}メソッドをディスパッチするためにのみ利
6792用されます。
6793@item
6794@code{<dbi-connection>}のサブクラス。このクラスのインスタンスは
6795@code{dbi-make-connection}によって生成されます。そのためには、実際のコ
6796ネクションに関する情報を保持する必要があります。
6797@item
6798ドライバにあったクエリ結果を表現するための@code{<relation>}および
6799@code{<collection>}のサブクラス。(ほとんどの場合、SELECT文の結果は順序
6800が重要です。それは、ORDER BY 節によってソートされる可能性があるからで
6801す。したがって、@code{<sequence>}を継承するほうが、@code{<collection>}
6802を継承するよりも適切です。)
6803@item
6804オプションとして、プリペアドクエリのドライバ特有の情報を保持するため
6805@code{<dbi-query>}のサブクラスを実装します。
6806@end itemize
6807@c COMMON
6808
6809@c EN
6810@subsubheading DBI methods to implement
6811@c JP
6812@subsubheading 実装するDBIメソッド
6813@c COMMON
6814
6815@c EN
6816The driver need to implement the following methods.
6817@c JP
6818ドライバは以下のメソッドを実装しなければなりません。
6819@c COMMON
6820
6821@deffn {Method} dbi-make-connection (d <foo-driver>) (options <string>) (options-alist <list>) :key username password @dots{}
6822@c MOD dbi
6823@c EN
6824This method is called from @code{dbi-connect}, and responsible to
6825connect to the database and to create a connection object.
6826It must return a connection object, or raise an @code{<dbi-error>} if
6827it cannot establish a connection.
6828@c JP
6829このメソッドは@code{dbi-connect}から呼ばれ、データベースへの接続を担い、
6830コネクションオブジェクトを作成します。コネクションオブジェクトを返さな
6831ければなりません。コネクションが確立できない場合には、
6832@code{<dbi-error>}をあげなければなりません。
6833@c COMMON
6834
6835@c EN
6836@var{Options} is the option part of the data source name (DSN) given to
6837@code{dbi-connect}.  @var{options-alist} is an assoc list of
6838the result of parsing @var{options}.  Both are provided so that
6839the driver may interpret @var{options} string in nontrivial way.
6840@c JP
6841@var{options}は@code{dbi-connect}に与えられるデータソースネーム(DSN)の
6842オプションパートです。@var{options-alist}は@var{options}を解析した結果
6843の連想リストです。両方ともに用意して、ドライバが自明ではない方法で
6844@var{options}文字列を解釈できるようにします。
6845@c COMMON
6846
6847@c EN
6848For example, given @code{"dbi:foo:myaddressbook;host=dbhost;port=8998"}
6849as DSN, foo's @code{dbi-make-connection} will receive
6850@code{"myaddressbook;host=dbhost;port=8998"} as @var{options},
6851and @code{(("myaddressbook" . #t) ("host" . "dbhost") ("port" . "8998"))}
6852as @var{options-alist}.
6853@c JP
6854たとえば、DSNとして
6855@code{"dbi:foo:myaddressbook;host=dbhost;port=8998"}が与えられたとする
6856と、fooの@code{dbi-make-connection}は@var{options}として
6857@code{"myaddressbook;host=dbhost;port=8998"}を受け取り、
6858@var{options-alist}として
6859@code{(("myaddressbook" . #t) ("host" . "dbhost") ("port" . "8998"))}
6860を受け取ります。
6861@c COMMON
6862
6863@c EN
6864After @var{options-alist}, whatever keyword arguments given to
6865@code{dbi-connect} are passed.  DBI protocol currently
6866specifies only @var{username} and @var{password}.
6867The driver may define other keyword arguments.
6868It is recommended to name the driver-specific keyword arguments
6869prefixed by the driver name, e.g. for @code{dbd.foo}, it may take
6870a @code{:foo-whatever} keyword argument.
6871@c JP
6872@var{options-alist}の後ろならどのようなキーワード引数でも
6873@code{dbi-connect}に渡せます。DBIプロトコルは現在のところは
6874@var{username}および@var{password}のみを指定します。
6875ドライバはその他のキーワード引数を定義できます。
6876ドライバ特有のキーワード引数にはドライバ名を接頭辞として付けることをお
6877勧めします。たとえば、@code{dbd.foo}なら、@code{:foo-whatever}のように
6878です。
6879@c COMMON
6880
6881@c EN
6882It is up to the driver writer to define what options are available and
6883the syntax of the options.  The basic idea is that the DSN
6884identifies the source of the data; it's role is like URL in WWW.
6885So, it may include the hostname and port number of the database,
6886and/or the name of the database, etc.  However, it shouldn't include
6887information related to authentication, such as username and password.
6888That's why those are passed via keyword arguments.
6889@c JP
6890どのようなオプションを使えるようにするか、あるいはオプションの構文をど
6891うするかはドライバを書く人しだいです。基本的な考え方は、DSN はデータの
6892ソースを識別するためのものであり、その役割りはWWWにおけるURLのようなも
6893のだということです。それゆえ、データベースのホスト名、ポート番号、それ
6894にデータベース名などが含まれることになるでしょう。しかし、ユーザ名やパ
6895スワードのような認証に関する情報を含めてはいけません。というわけで、そ
6896の手の情報はキーワード引数で渡すのです。
6897@c COMMON
6898@end deffn
6899
6900@deffn {Method} dbi-prepare (c <foo-connection>) (sql <string>) :key pass-through @dots{}
6901@c MOD dbi
6902@c EN
6903This method should create and return a prepared query object,
6904which is an instance of @code{<dbi-query>} or its subclass.
6905The query specified by @var{sql} is issued to the database system
6906when the prepared query object is passed to @code{dbi-execute}.
6907@c JP
6908このメソッドは@code{<dbi-query>}あるいはそのサブクラスのインスタンスで
6909あるプリペアドクエリオブジェクトを生成し、それを返すものでなくてはなり
6910ません。@var{sql}によるクエリがデータベースに発行されるのは、プリペア
6911ドクエリオブジェクトが@code{dbi-execute}に渡されたときです。
6912@c COMMON
6913
6914@c EN
6915The method must set @var{c} to the @code{connection} slot of
6916the returned query object.
6917@c JP
6918このメソッドは返されるクエリオブジェクトの@code{connection}スロットに
6919@var{c}を設定しなけばなりません。
6920@c COMMON
6921
6922@c EN
6923@var{Sql} is an SQL statement.  It may contain placeholders represented
6924by @code{'?'}.  The query closure should take the same number of arguments
6925as of the placeholders.   It is up to the driver whether it parses
6926@var{sql} internally and construct a complete SQL statement when
6927the query closure is called, or it passes @var{sql} to the back-end
6928server to prepare the statement and let the query closure just send
6929parameters.
6930@c JP
6931@var{sql}はSQL文です。これには@code{'?'}で表現されたプレイスホルダが含
6932まれることがあります。クエリクロージャはこのプレイスホルダと同じ数の引
6933数をとらなければなりません。内部的に@var{sql}をどのようにパーズするか、
6934クエリクロージャが呼ばれたとき完全なSQL文を構築するか、@var{sql}をバッ
6935クエンドのサーバに送って文を準備し、クエリクロージャはパラメータだけを
6936送るようにするかなどはドライバに依存します。
6937@c COMMON
6938
6939@c EN
6940If the driver parses SQL statement internally, it should recognize
6941a keyword argument @code{pass-through}.  If a true value is given,
6942the driver must treat @code{sql} opaque and pass it as is when
6943the query closure is called.
6944@c JP
6945ドライバがSQL文を内部的にわたす場合、キーワード引数@code{pass-through}
6946を認識しなければいけません。もし、真の値が与えられたら、ドライバは
6947@code{sql}を不透明なものとして扱い、これをそのままクエリクロージャが呼
6948ばれた際に渡さなければなりません。
6949@c COMMON
6950
6951@c EN
6952The driver may define other keyword arguments.
6953It is recommended to name the driver-specific keyword arguments
6954prefixed by the driver name, e.g. for @code{dbd.foo}, it may take
6955a @code{:foo-whatever} keyword argument.
6956@c JP
6957ドライバがその他のキーワード引数を定義することもできます。
6958その場合、ドライバ特有のキーワード引数にはドライバ名を接頭辞として付け
6959ることをお勧めします。たとえば、@code{dbd.foo}なら、
6960@code{:foo-whatever}のようにです。
6961@c COMMON
6962@end deffn
6963
6964@deffn {Method} dbi-execute-using-connection (c <foo-connection>) (q <dbi-query>) (params <list>)
6965@c MOD dbi
6966@c EN
6967This method is called from @code{dbi-execute}.
6968It must issue the query kept in @var{q}.  If the query is parameterized,
6969the actual parameters given to @var{dbi-execute} are passed to
6970@var{params} argument.
6971@c JP
6972このメソッドは@code{dbi-execute}から呼ばれます。@var{q}が保持するクエ
6973リを発行しなければなりません。クエリがパラメータ化されている場合、
6974@var{dbi-execute}に与えられた実際のパラメータは@var{params}引数に渡さ
6975れます。
6976@c COMMON
6977
6978@c EN
6979If @var{q} is a @code{select}-type query, this method must return
6980an appropriate relation object.
6981@c JP
6982@var{q}が@code{select}-型のクエリの場合は、このメソッドは適切なリレー
6983ションオブジェクトを返さなければなりません。
6984@c COMMON
6985@end deffn
6986
6987@deffn {Method} dbi-escape-sql (c <foo-connection>) str
6988@c MOD dbi
6989@c EN
6990If the default escape method isn't enough, the driver may
6991overload this method to implement a specific escaping.
6992For example, MySQL treats backslash characters specially
6993as well as single quotes, so it has its @code{dbi-escape-sql}
6994method.
6995@c JP
6996デフォルトのエスケープメソッドでは十分でないとき、ドライバは特別のエス
6997ケープを行うためにこのメソッドをオーバーロードすることができます。たと
6998えば、MySQLではバックスラッシュ文字はシングルクォートと同様に特別あつ
6999かいしますので、@code{dbi-escape-sql}メソッドを持っています。
7000@c COMMON
7001@end deffn
7002
7003@deffn {Method} dbi-open? (c <foo-connection>)
7004@deffnx {Method} dbi-open? (q <foo-query>)
7005@deffnx {Method} dbi-open? (r <foo-result>)
7006@deffnx {Method} dbi-close (c <foo-connection>)
7007@deffnx {Method} dbi-close (q <foo-query>)
7008@deffnx {Method} dbi-close (r <foo-result>)
7009@c MOD dbi
7010@c EN
7011Queries open/close status of a connection and a result, and
7012closes a connection and a result.  The close methods should cause
7013releasing resources used by connection/result.  The driver
7014has to allow @code{dbi-close} to be called on a connection or a
7015result which has already been closed.
7016@c JP
7017これらのメソッドでコネクションおよび結果の状態を調べ、コネクションおよ
7018び結果を閉じます。closeメソッドはコネクションや結果が利用しているリソー
7019スを解放しなければなりません。ドライバは@code{dbi-close}がすでに閉じら
7020れたコネクションや結果に対しても適用できるようにしておかなければなりま
7021せん。
7022@c COMMON
7023@end deffn
7024
7025@deffn {Method} dbi-do (c <foo-connection>) (sql <string>) :optional options parameter-value @dots{}
7026@c MOD dbi
7027@c EN
7028The default method uses @code{dbi-prepare} and @code{dbi-execute}
7029to implement the function.  It just works,
7030but the driver may overload this method in order to skip
7031creating intermediate query object for efficiency.
7032@c JP
7033この機能を実装するのにデフォルトメソッドは@code{dbi-prepare}および
7034@code{dbi-execute}を使っています。これだけでも動きますが、
7035ドライバは効率のために中間のクエリオブジェクトの生成をスキップするため
7036にこのメソッドをオーバーロードできます。
7037@c COMMON
7038@end deffn
7039
7040@c EN
7041@subsubheading DBI utility functions
7042@c JP
7043@subsubheading DBIのユーティリティ関数
7044@c COMMON
7045
7046@c EN
7047The following functions are low-level utilities which you may
7048use to implement the above methods.
7049@c JP
7050以下の関数は上述のメソッドを実装するための低レベルのユーティリティです。
7051@c COMMON
7052
7053@defun dbi-parse-dsn data-source-name
7054@c MOD dbi
7055@c EN
7056Parse the data source name (DSN) string given to @code{dbi-connect},
7057and returns tree values: (1) The driver name in a string. (2)
7058'options' part of DSN as a string.  (3) parsed options in an assoc
7059list.  This may raise @code{<dbi-error>} if the given string doesn't
7060conform DSN syntax.
7061@c JP
7062@code{dbi-connect}に与えられたデータソースネーム(DSN)文字列を解析し、
7063以下の3つの値を返す。(1) ドライバ名(文字列) (2) DSNのオプション部分(文
7064字列) (3) 解析済オプション(連想リスト)。与えられた文字列がDSN構文に準
7065拠していない場合には@code{<dbi-error>}があがります。
7066@c COMMON
7067
7068@c EN
7069You don't need to use this to write a typical driver, for the
7070parsing is done before @code{dbi-make-connection} is called.
7071This method may be useful if you're writing a kind of meta-driver,
7072such as a proxy.
7073@c JP
7074典型的なドライバを書く場合には必要ありません。構文解析は
7075@code{dbi-make-connection}を呼ぶ前にすんでいるからです。このメソッドは
7076プロキシのようなメタドライバという類のものを書くときに便利です。
7077@c COMMON
7078@end defun
7079
7080@defun dbi-prepare-sql connection sql
7081@c MOD dbi
7082@c EN
7083Parses an SQL statement @var{sql} which may contain placeholders,
7084and returns a closure, which generates a complete SQL statement when
7085called with actual values for the parameters.  If the back-end
7086doesn't support prepared statements, you may use this function
7087to prepare queries in the driver.
7088@c JP
7089プレイスホルダを含むSQL文 @var{sql} をパーズし、実際の値をパラメータと
7090して渡されたときに完全なSQLを生成するクロージャを作成します。
7091バックエンドがプリペアド文をサポートしていない場合は、ドライバ中でクエ
7092リを準備するのにこの関数を使うことになります。
7093@c COMMON
7094
7095@c EN
7096@var{Connection} is a DBI connection to the database.  It is required
7097to escape values within SQL properly (see @code{dbi-escape-sql} above).
7098@c JP
7099@var{connection}はデータベースへのDBIコネクションです。SQL中の値は適切
7100にエスケープされている必要があります(上述の@code{dbi-escape-sql}をみて
7101ください)。
7102@c COMMON
7103
7104@c EN
7105@example
7106;; assume c contains a valid dbi connection
7107((dbi-prepare-sql c "select * from table where id=?") "foo'bar")
7108 => "select * from table where id='foo''bar'"
7109@end example
7110@c JP
7111@example
7112;; c は正しいdbiコネクションを持っているとする
7113((dbi-prepare-sql c "select * from table where id=?") "foo'bar")
7114 => "select * from table where id='foo''bar'"
7115@end example
7116@c COMMON
7117@end defun
7118
7119@c ----------------------------------------------------------------------
7120
7121@node Generic DBM interface, File-system dbm, Database independent access layer, Library modules - Utilities
7122@section @code{dbm} - Generic DBM interface
7123@c NODE 汎用DBMインタフェース, @code{dbm} - 汎用DBMインタフェース
7124
7125@deftp {Module} dbm
7126@mdindex dbm
7127@c EN
7128DBM-like libraries provides an easy way to store values to a file,
7129indexed by keys.  You can think it as a persistent associative memory.
7130@c JP
7131DBM系のライブラリはキーでインデックスされた値をファイルに格納する簡単な方法を
7132提供します。一種の永続的な連想記憶と言えるでしょう。
7133@c COMMON
7134
7135@c EN
7136This modules defines @code{<dbm>} abstract class, which has
7137a common interface to use various DBM-type database packages.
7138As far as you operate on the already opened database,
7139importing @code{dbm} module is enough.
7140@c JP
7141このモジュールが定義する抽象クラス@code{<dbm>}は、DBM系ライブラリへの
7142統一されたインタフェースを提供します。@code{dbm}モジュールだけをインポートすれば、
7143既にオープンされたデータベースを操作することができます。
7144@c COMMON
7145
7146@c EN
7147To create or open a database, you need a concrete implementation
7148of the database.  With the default build-time configuration,
7149the following implementations are included in Gauche.
7150Bindings to various other dbm-like libraries are
7151available as extension packages.
7152Each module defines its own low-level accessing functions
7153as well as the common interface.
7154Note that your system may not have one or more of those DBM libraries;
7155Gauche defines only what the system provides.
7156@c JP
7157データベースをオープンしたり作成したりするには、dbmインタフェースを実装した
7158モジュールが必要になります。デフォルトのビルド時コンフィグレーションでは、
7159以下の実装がGaucheに含まれます。他の様々なdbmライブラリへのバインディングが
7160拡張パッケージとして提供されています。
7161それぞれのモジュールは、dbmインタフェース共通の手続きの他に、
7162直接実装を操作できる低レベルの手続きも提供します。
7163システムによっては以下のインタフェースの全てが実装されているわけではないことに
7164注意してください。Gaucheではシステムが提供する実装のみを定義します。
7165@c COMMON
7166
7167@table @code
7168@item dbm.fsdbm
7169@c EN
7170file-system dbm (@pxref{File-system dbm}).
7171@c JP
7172ファイルシステムdbm (@ref{File-system dbm}参照).
7173@c COMMON
7174
7175@item dbm.gdbm
7176@c EN
7177GDBM library (@pxref{GDBM interface}).
7178@c JP
7179GDBMライブラリ (@ref{GDBM interface}参照).
7180@c COMMON
7181
7182@item dbm.ndbm
7183@c EN
7184NDBM library (@pxref{NDBM interface}).
7185@c JP
7186NDBMライブラリ (@ref{NDBM interface}参照).
7187@c COMMON
7188
7189@item dbm.odbm
7190@c EN
7191DBM library  (@pxref{Original DBM interface}).
7192@c JP
7193DBMライブラリ  (@ref{Original DBM interface}参照).
7194@c COMMON
7195@end table
7196@end deftp
7197
7198@c EN
7199The following code shows a typical usage of the database.
7200@c JP
7201以下にdbmデータベースの使用例を示します。
7202@c COMMON
7203
7204@example
7205(use dbm)         ; @r{dbm abstract interface}
7206(use dbm.gdbm)    ; @r{dbm concrete interface}
7207
7208; @r{open the database}
7209(define *db* (dbm-open <gdbm> :path "mydb" :rw-mode :write))
7210
7211; @r{put the value to the database}
7212(dbm-put! *db* "key1" "value1")
7213
7214; @r{get the value from the database}
7215(define val (dbm-get *db* "key1"))
7216
7217; @r{iterate over the database}
7218(dbm-for-each *db* (lambda (key val) (foo key val)))
7219
7220; @r{close the database}
7221(dbm-close *db*)
7222@end example
7223
7224@c EN
7225The @code{<dbm>} abstract class implements collection
7226and dictionary framework.  (See @ref{Collection framework}
7227and @ref{Dictionary framework}, respectively).
7228@c JP
7229@var{<dbm>}抽象クラスは、コレクションフレームワークと
7230ディクショナリフレームワークを実装しています。
7231(それぞれ@ref{Collection framework}と@ref{Dictionary framework}参照。)
7232@c COMMON
7233
7234@menu
7235* Opening and closing a dbm database::
7236* Accessing a dbm database::
7237* Iterating on a database::
7238* Managing dbm database instance::
7239* Dumping and restoring dbm database::
7240* Writing a dbm implementation::
7241@end menu
7242
7243@node Opening and closing a dbm database, Accessing a dbm database, Generic DBM interface, Generic DBM interface
7244@subsection Opening and closing a dbm database
7245@c NODE DBMデータベースのオープンとクローズ
7246
7247@deftp {Class} <dbm>
7248@clindex dbm
7249@c MOD dbm
7250@c EN
7251An abstract class for dbm-style database.    Inherits
7252@code{<dictionary>} (@pxref{Dictionary framework}).
7253Defines the common
7254database operations.   This class has the following instance slots.
7255They must be set before the database is actually opened by
7256@code{dbm-open}.
7257
7258The concrete class may add more slots for finer control on the database,
7259such as locking.
7260@c JP
7261DBM系のデータベースのための抽象クラスです。
7262@code{<dictionary>}クラスを継承します (@ref{Dictionary framework}参照)。
7263データベースへの共通のオペレーションを
7264定義します。以下のインスタンススロットを持ちます。これらのスロットの値は
7265@code{dbm-open}によってデータベースがオープンされる前にセットされて
7266いなければなりません。
7267
7268具体クラスは、データベースの操作をより細かく行うための追加のスロット(例えばロックを
7269行うかどうか)を持つかもしれません。
7270@c COMMON
7271
7272@defivar <dbm> path
7273@c EN
7274Pathname of the dbm database.  Some dbm implementation may append
7275suffixes to this.
7276@c JP
7277データベースファイルのパス名。dbmの実装によっては、このパスにサフィックスが追加されます。
7278@c COMMON
7279@end defivar
7280
7281@defivar <dbm> rw-mode
7282@c EN
7283Specifies read/write mode.  Can be either one of the following keywords:
7284@table @code
7285@item :read
7286The database will be opened in read-only mode.  The database file must
7287exist when @code{dbm-open} is called.
7288@item :write
7289The database will be opened in Read-write mode.
7290If the database file does not exist, @code{dbm-open} creates one.
7291@item :create
7292The database will be created and opened in Read-write mode.
7293If the database file exists, @code{dbm-open} truncates it.
7294@end table
7295@c JP
7296読み書きのモードを指定します。以下の値のいずれかを取ります。
7297@table @code
7298@item :read
7299データベースは@code{dbm-open}によって読みだし専用モードでオープンされます。
7300オープンされる時点でデータベースは存在していなければなりません。
7301@item :write
7302データベースは@code{dbm-open}によって読み書き可能なモードでオープンされます。
7303データベースが存在しなければ、@code{dbm-open}は新しいデータベースを作成します。
7304@item :create
7305@code{dbm-open}によって新しいデータベースが作成され、読み書き可能なモードでオープンされます。
7306既にデータベースが存在していた場合、その内容はクリアされます。
7307@end table
7308@c COMMON
7309@end defivar
7310
7311@defivar <dbm> file-mode
7312@c EN
7313Specifies the file permissions (as @code{sys-chmod}) to create the
7314database.  The default value is @code{#o664}.
7315@c JP
7316データベースが作成されるときのファイルパーミッションを指定します。
7317デフォルトは@code{#o664}です。
7318@c COMMON
7319@end defivar
7320
7321@defivar <dbm> key-convert
7322@defivarx <dbm> value-convert
7323@c EN
7324By default, you can use only strings for both key and values.  With this
7325option, however, you can specify how to convert other Scheme values to/from
7326string to be stored in the database.   The possible values are the
7327followings:
7328@table @asis
7329@item @code{#f}
7330The default value.  Keys (values) are not converted.  They must be
7331a string.
7332@item @code{#t}
7333Keys (values) are converted to its string representation, using
7334@code{write}, to store in the database, and converted
7335back to Scheme values, using @code{read}, to retrieve from the database.
7336The data must have an external representation that can be read back.
7337(But it is not checked when the data is written; you'll get an error
7338when you read the data).  The key comparison is done in the string
7339level, so the external representation of the same key must match.
7340@item a list of two procedures
7341Both procedure must take a single argument.  The first procedure must
7342receive a Scheme object and returns a string.  It is used to convert
7343the keys (values) to store in the database.  The second procedure
7344must receive a string and returns a Scheme object.  It is used to
7345convert the stored data in the database to a Scheme object.
7346The key comparison is done in the string
7347level, so the external representation of the same key must match.
7348@end table
7349@c JP
7350デフォルトでは、dbmデータベースはキーにも値にも文字列しか使うことはできません。
7351これらのスロットによって、それ以外のSchemeオブジェクトを取り扱う方法を指定することが
7352できます。以下の値のいずれかが可能です。
7353@table @asis
7354@item @code{#f}
7355デフォルトの値です。キーあるいは値は変換されません。それらは文字列でなければなりません。
7356@item @code{#t}
7357キーあるいは値は@code{write}を使って文字列に変換されデータベースに格納されます。
7358そして@code{read}を使って文字列からSchemeオブジェクトへと変換されます。
7359後で@code{read}で読みこめるようなキーあるいは値のみを扱うことができます。
7360(但し、dbmライブラリは書き込み時にそれが後で読み込めるかどうかのチェックは行いません)。
7361キーの比較は文字列に変換された後で行われるので、同じ値となるキーは同じ文字列表現を
7362持つ必要があります。
7363@item 二つの手続きのリスト
7364どちらの手続きも一つの引数を取ります。最初の手続きはSchemeオブジェクトを受け取り、
7365文字列を返します。キーあるいは値をデータベースに格納する時に呼ばれます。
7366二つ目の手続きは文字列を受け取りSchemeオブジェクトを返します。データベースから
7367キーあるいは値を取り出す時に呼ばれます。
7368キーの比較は文字列に変換された後で行われるので、同じ値となるキーは同じ文字列に
7369変換される必要があります。
7370@end table
7371@c COMMON
7372@end defivar
7373@end deftp
7374
7375@deftp {Metaclass} <dbm-meta>
7376@clindex dbm-meta
7377@c MOD dbm
7378@c EN
7379A metaclass of @code{<dbm>} and its subclasses.
7380@c JP
7381@var{<dbm>}クラス及びそのサブクラスのメタクラスです。
7382@c COMMON
7383@end deftp
7384
7385@deffn {Method} dbm-open (dbm <dbm>)
7386@c MOD dbm
7387@c EN
7388Opens a dbm database.  @var{dbm} must be an instance of
7389one of the concrete classes that derived from the @code{<dbm>} class,
7390and its slots must be set appropriately.   On success, it returns
7391the @var{dbm} itself.  On failure, it signals an error.
7392@c JP
7393DBMデータベースをオープンします。@var{dbm}は、@code{<dbm>}クラスを継承した
7394具体クラスのインスタンスでなければなりません。また、そのスロットには適切な値が
7395セットされている必要があります。オープンに成功したら@var{dbm}自身が返されます。
7396失敗した場合はエラーが報告されます。
7397@c COMMON
7398@end deffn
7399
7400@deffn {Method} dbm-open (dbm-class <dbm-meta>) options @dots{}
7401@c MOD dbm
7402@c EN
7403A convenient method that creates dbm instance and opens it.
7404It is defined as follows.
7405@c JP
7406DBMインスタンスを作成してオープンするための便利なメソッドです。
7407次のように定義されます。
7408@c COMMON
7409@example
7410(define-method dbm-open ((class <class>) . initargs)
7411  (dbm-open (apply make class initargs)))
7412@end example
7413@end deffn
7414
7415@c EN
7416Database file is closed when it is garbage collected.
7417However, to ensure the modification is properly synchronized,
7418you should close the database explicitly.
7419@c JP
7420データベースファイルはガベージコレクトされる際にクローズされますが、
7421変更を正しくデータベースに反映するには、明示的にクローズした方が良いでしょう。
7422@c COMMON
7423
7424@deffn {Method} dbm-close (dbm @code{<dbm>})
7425@c MOD dbm
7426@c EN
7427Closes a database @var{dbm}.  Once the database is closed, any
7428operation to access the database content raises an error.
7429@c JP
7430データベース@var{dbm}をクローズします。データベースがクローズされると、
7431それ以降のアクセスオペレーションはエラーとなります。
7432@c COMMON
7433@end deffn
7434
7435@deffn {Method} dbm-closed? (dbm @code{<dbm>})
7436@c MOD dbm
7437@c EN
7438Returns true if a database @var{dbm} is already closed, false otherwise.
7439@c JP
7440データベース@var{dbm}が既にクローズされていたら@code{#t}を返します。
7441@c COMMON
7442@end deffn
7443
7444@defun dbm-type->class dbmtype
7445@c MOD dbm
7446Sometimes you don't know which type of dbm implementation you
7447need to use in your application beforehand, but rather you need to
7448determine the type according to the information given at run-time.
7449This procedure fulfills the need.
7450
7451The @var{dbmtype} argument is a symbol that names the type
7452of dbm implementation; for example, @code{gdbm} for @code{dbm.gdbm},
7453and @code{fsdbm} for @code{dbm.fsdbm}.   We assume that the
7454dbm implementation of type @code{@var{foo}} is provided as
7455a module @code{dbm.@var{foo}}, and its class is named
7456as @code{<@var{foo}>}.
7457
7458This procedure first checks if the required module has been
7459loaded, and if not, it tries to load it.   If the module
7460loads successfully, it returns the class object of the
7461named dbm implementation.   If it can't load the module,
7462or can't find the dbm class, this procedure returns #f.
7463
7464@example
7465(use dbm)
7466
7467(dbm-type->class 'gdbm)
7468  @result{} @code{#<class <gdbm>>}
7469
7470(dbm-type->class 'nosuchdbm)
7471  @result{} @code{#f}
7472@end example
7473@end defun
7474
7475@node Accessing a dbm database, Iterating on a database, Opening and closing a dbm database, Generic DBM interface
7476@subsection Accessing a dbm database
7477@c NODE DBMデータベースのアクセス
7478
7479@c EN
7480Once a database is opened, you can use the following methods
7481to access individual key/value pairs.
7482@c JP
7483データベースがオープンされたら、以下のアクセスメソッドが使えます。
7484@c COMMON
7485
7486@deffn {Method} dbm-put! (dbm @code{<dbm>}) key value
7487@c MOD dbm
7488@c EN
7489Put a @var{value} with @var{key}.
7490@c JP
7491値@var{value}をキー@var{key}と関連付けて保存します。
7492@c COMMON
7493@end deffn
7494
7495@deffn {Method} dbm-get (dbm @code{<dbm>}) key :optional default
7496@c MOD dbm
7497@c EN
7498Get a value associated with @var{key}.  If no value exists for @var{key}
7499and @var{default} is specified, it is returned.  If no value exists for
7500@var{key} and @var{default} is not specified, an error is signaled.
7501@c JP
7502キー@var{key}に関連付けられた値を返します。もし値が存在しなければ、@var{default}が
7503与えられていればそれを返し、そうでなければエラーを報告します。
7504@c COMMON
7505@end deffn
7506
7507@deffn {Method} dbm-exists? (dbm @code{<dbm>}) key
7508@c MOD dbm
7509@c EN
7510Return true if a value exists for @var{key}, false otherwise.
7511@c JP
7512キー@var{key}に関連付けられた値が存在すれば@code{#t}を返します。
7513@c COMMON
7514@end deffn
7515
7516@deffn {Method} dbm-delete! (dbm @code{<dbm>}) key
7517@c MOD dbm
7518@c EN
7519Delete a value associated with @var{key}.
7520@c JP
7521キー@var{key}に関連付けられた値を消去します。値が存在しない場合は何もしません。
7522@c COMMON
7523@end deffn
7524
7525@node Iterating on a database, Managing dbm database instance, Accessing a dbm database, Generic DBM interface
7526@subsection Iterating on a dbm database
7527@c NODE DBMデータベース上の繰り返し処理
7528
7529@c EN
7530To walk over the entire database, following methods are provided.
7531@c JP
7532全データベースを渡り歩く処理のために、以下のメソッドが用意されています。
7533@c COMMON
7534
7535@deffn {Method} dbm-fold (dbm @code{<dbm>}) procedure knil
7536@c MOD dbm
7537@c EN
7538The basic iterator.
7539For each key/value pair, @var{procedure} is called as
7540@code{(@var{procedure} @var{key} @var{value} @var{r})},
7541where @var{r} is @var{knil} for the fist call of @var{procedure},
7542and the return value of the previous call for subsequent calls.
7543Returns the result of the last call of @var{procedure}.
7544If no data is in the database, @var{knil} is returned.
7545
7546The following method returns the sum of all the integer values.
7547@c JP
7548基本的な繰り返し処理です。データベース内の各キー/値のペアに関して、手続き
7549@var{procedure}が @code{(@var{procedure} @var{key} @var{value} @var{r})},
7550のように呼ばれます。ここで@var{r}は、最初の@var{procedure}の呼び出しの時には@var{knil}
7551が、以降の呼び出しの時にはその直前の@var{procedure}が返した値が渡されます。
7552最後の@var{procedure}の戻り値が@code{dbm-fold}の戻り値となります。
7553データベース中にデータがひとつもなければ@var{knil}がそのまま返されます。
7554
7555次の例は、データベース中の整数の値を全て加算します。
7556@c COMMON
7557@example
7558(dbm-fold dbm (lambda (k v r) (if (integer? v) (+ v r) r)) 0)
7559@end example
7560@end deffn
7561
7562@deffn {Method} dbm-for-each (dbm @code{<dbm>}) procedure
7563@c MOD dbm
7564@c EN
7565For each key/value pair in the database @var{dbm}, @var{procedure}
7566is called.  Two arguments are passed to @var{procedure}---a key and
7567a value.   The result of @var{procedure} is discarded.
7568@c JP
7569データベース内の各キー/値のペアに関して、手続き@var{procedure}を呼び出します。
7570@var{procedure}にはキーと値が渡されます。@var{procedure}の戻り値は捨てられます。
7571@c COMMON
7572@end deffn
7573
7574@deffn {Method} dbm-map (dbm @code{<dbm>}) procedure
7575@c MOD dbm
7576@c EN
7577For each key/value pair in the database @var{dbm}, @var{procedure}
7578is called.  Two arguments are passed to @var{procedure}---a key and
7579a value.   The result of @var{procedure} is accumulated to a list
7580which is returned as a result of @code{dbm-map}.
7581@c JP
7582データベース内の各キー/値のペアに関して、手続き@var{procedure}を呼び出します。
7583@var{procedure}にはキーと値が渡されます。@var{procedure}の戻り値はリストに
7584集められて@code{dbm-map}の戻り値となります。
7585@c COMMON
7586@end deffn
7587
7588@node Managing dbm database instance, Dumping and restoring dbm database, Iterating on a database, Generic DBM interface
7589@subsection Managing dbm database instance
7590@c NODE DBMデータベースインスタンスの管理
7591
7592@c EN
7593Each dbm implementation has its own way to store the
7594database.  Legacy dbm uses two files, whose names are
7595generated by adding @file{.dir} and @file{.pag} to the
7596value of @var{path} slot.  @code{Fsdbm} creates a directory
7597under @var{path}.  If dbm database is backed up by
7598some database server, @var{path} may be used only as
7599a key to the database in the server.
7600@c JP
7601各DBM実装は、データベースを格納するのに独自の方法を使います。
7602レガシーなDBMは、@var{path}スロットの値にそれぞれ@file{.dir}と
7603@file{.pag}を付けた名前の2つのファイルを使います。
7604@code{fsdbm}は@var{path}の下にディレクトリを作ります。
7605DBMデータベースが他のデータベースサーバによってバック
7606アップされる場合は、@var{path}はそのサーバで単なるキーと
7607して使われるでしょう。
7608
7609@c EN
7610The following methods hide such variations and provides
7611a convenient way to manage a database itself.   You have to
7612pass a class that implements a concrete dbm database to their
7613first argument.
7614@c JP
7615以下のメソッドは、そのようなバリエーションを隠し、
7616データベースそれ自体を管理する簡易な方法を提供します。
7617最初の引数に、具体的なDBMデータベースを実装している
7618クラスを渡す必要があります。
7619@c COMMON
7620
7621@deffn {Generic Function} dbm-db-exists? class name
7622@c MOD dbm
7623@c EN
7624Returns @code{#t} if a database of class @var{class}
7625specified by @var{name} exists.
7626@c JP
7627@var{name}で指定された@var{class}クラスのデータベースが
7628存在する場合は@code{#t}を返します。
7629@c COMMON
7630
7631@example
7632;; Returns #t if testdb.dir and testdb.pag exist
7633(dbm-db-exists? <odbm> "testdb")
7634@end example
7635@end deffn
7636
7637@deffn {Generic Function} dbm-db-remove class name
7638@c MOD dbm
7639@c EN
7640Removes an entire database of class @var{class} specified by
7641@var{name}.
7642@c JP
7643@var{name}で指定される@var{class}クラスのデータベース
7644全体を削除します。
7645@c COMMON
7646@end deffn
7647
7648@deffn {Generic Function} dbm-db-copy class from to
7649@c MOD dbm
7650@c EN
7651Copy a database of class @var{class} specified by
7652@var{from} to @var{to}.  The integrity of @var{from}
7653is guaranteed if the @var{class}'s dbm implementation supports
7654locking (i.e. you won't get a corrupted database even if
7655some other process is trying to write to @var{from}
7656during copy).   If the destination database @var{to} exists,
7657its content is destroyed.  If this function is interrupted,
7658whether @var{to} is left in incomplete state or not depends
7659on the dbm implementation.   The implementation usually tries
7660its best to provide transactional behavior, that is,
7661to recover original @var{to} when the copy fails.  However,
7662for the robust operations the caller have to check the state
7663of @var{to} if @code{dbm-db-copy} fails.
7664@c JP
7665@var{from}で指定された@var{class}クラスのデータベースを
7666@var{to}へコピーします。
7667@var{class}のdbm実装がロックをサポートしている限り、@var{from}の一貫性は
7668保たれます (つまり、コピー中に他のプロセスが@var{from}を
7669変更しようとした場合であっても、@var{to}が壊れたデータベースになることは
7670ありません)。  もしコピー先の@var{to}が既に存在するデータベースで
7671あった場合、@var{to}の元の内容は失われます。
7672コピーが中断された場合に@var{to}が不完全な状態のままになるかどうかは
7673dbm実装に依存します。dbm実装の多くはトランザクショナルな振る舞い、
7674すなわち、コピーが失敗した場合に元の@var{to}を復元することを試みます。
7675しかし確実な操作のためには、コピーが失敗した場合には呼び出し側で@var{to}の
7676状態を確認することが必要です。
7677@c COMMON
7678
7679@example
7680(dbm-db-copy <gdbm> "testdb.dbm" "backup.dbm")
7681@end example
7682@end deffn
7683
7684@deffn {Generic Function} dbm-db-move class from to
7685@c MOD dbm
7686@c EN
7687Moves or renames a database of class @var{class} specified by
7688@var{from} to @var{to}.  Like @code{dbm-db-copy}, the database
7689integrity is guaranteed as far as @var{class}'s dbm implementation
7690supports locking.  If the destination database @var{to} exists,
7691its content is destroyed.
7692@c JP
7693@var{from}で指定された@var{class}クラスのデータベースを
7694@var{to}へ移動、あるいはリネームします。@code{dbm-db-copy}と同じく、
7695@var{class}のdbm実装がロックをサポートしていれば
7696データベースの一貫性は保証されます。移動先の@var{to}が既に
7697存在していた場合、その元の内容は失われます。
7698@c COMMON
7699@end deffn
7700
7701@node Dumping and restoring dbm database, Writing a dbm implementation, Managing dbm database instance, Generic DBM interface
7702@subsection Dumping and restoring dbm database
7703@c NODE DBMデータベースのダンプとリストア
7704
7705Most dbm implementations use some kind of binary format, and
7706some of them are architecture dependent.
7707That makes it difficult to pass around dbm databases
7708between different machines.
7709A safe way is to write out the content of a dbm database
7710into some portable format on the source machine,
7711and rebuild another dbm database from it on the destination
7712machine.
7713
7714The operation is so common that Gauche provides convenience
7715scripts that does the job.  They are installed into the
7716standard Gauche library directory, so it can be invoked
7717by @code{gosh <scriptname>}.
7718
7719To write out the content of a dbm database named by @var{dbm-name},
7720you can use @code{dbm/dump} script:
7721
7722@example
7723$ gosh dbm/dump [-o @var{outfile}][-t @var{type}] @var{dbm-name}
7724@end example
7725
7726The @var{outfile} argument names the output file.  If omitted,
7727the output is written out to stdout.  The @var{type} argument
7728specifies the implementation type of the dbm database; e.g.
7729@code{gdbm} or @code{fsdbm}.  The program calls
7730@code{dbm-type->class} (@pxref{Opening and closing a dbm database})
7731on the @var{type} argument to load the necessary dbm implementation.
7732
7733The dumped format is simply a series of S-expressions,
7734each of which is a dotted pair of string key and string value.
7735Character encodings are assumed to be the same as
7736@code{gosh}'s native character encoding.
7737
7738The dumped output may contain S-expressions other than dotted pair
7739of strings to include meta information.  For now, programs
7740that deals with dumped output should just ignore S-expressions
7741other than dotted pairs.
7742
7743To read back the dumped dbm format, you can use @code{dbm/restore}
7744script:
7745
7746@example
7747$ gosh dbm/restore [-i @var{infile}][-t @var{type}] @var{dbm-name}
7748@end example
7749
7750The @var{infile} argument names the dumped file to be read.
7751If omitted, it reads from stdin.  The @var{type} argument
7752specifies the dbm type, as in @code{dbm/dump} script.
7753The @var{dbm-name} argument names the dbm database; if the
7754database already exists, its content is cleared, so be careful.
7755
7756
7757@node Writing a dbm implementation,  , Dumping and restoring dbm database, Generic DBM interface
7758@subsection Writing a dbm implementation
7759@c NODE DBM実装を書く
7760
7761When you write an extension module that behaves like
7762a persistent hashtable, it is a good idea to adapt it
7763to the dbm interface, so that the application can use
7764the module in a generic way.
7765
7766The minimum procedures to conform the dbm interface
7767are as follow:
7768
7769@itemize @bullet
7770@item
7771Define a metaclass @code{<@var{foo}-meta>}.   It doesn't
7772need to inherit anything except @code{<class>}.
7773@item
7774Define a dbm class @code{<@var{foo}>} that inherits @code{<dbm>}
7775and whose metaclass is @code{<@var{foo}-meta>}.
7776@item
7777Define methods for @code{dbm-open}, @code{dbm-close},
7778@code{dbm-put!}, @code{dbm-get}, @code{dbm-exists},
7779@code{dbm-delete!}, @code{dbm-fold}, @code{dbm-closed?},
7780specialized for @code{<@var{foo}>}.
7781(The case of @code{dbm-open} for @code{<@var{foo}-meta>} is
7782handled automatically, so you don't need to define it unless
7783you want something special).
7784Also note that the specialized @code{dbm-open} must call
7785@code{next-method} in it to set up dbm base class internals.
7786@item
7787Define methods for @code{dbm-db-exists?} and
7788@code{dbm-db-remove} on @code{<@var{foo}-meta>}.
7789@end itemize
7790
7791Besides above, you may define the following methods.
7792
7793@itemize @bullet
7794@item
7795Methods for @code{dbm-for-each} and @code{dbm-map}.
7796If you don't define them, a generic implementation
7797by @code{dbm-fold} is used.  There may be an implementation
7798specific way which is more efficient.
7799@item
7800Methods for @code{dbm-db-copy} and @code{dbm-db-move}.
7801If you don't define them, a fallback method
7802opens the specified databases and copies elements one by
7803one, and removes the original if the method is  @code{dbm-db-move}.
7804Note that the fallback method is not only inefficient,
7805but also it may not copy any implementation-specific
7806meta information.  It is highly recommended for the
7807dbm implementation to provide these methods as well.
7808@end itemize
7809
7810It is generally recommended to name the implementation module
7811as @code{dbm.@var{foo}}, and the class of the implementation
7812as @code{<@var{foo}>}.  With this convention it is easier to
7813write an application that dynamically loads and uses
7814dbm implementation specified at runtime.
7815
7816@c ----------------------------------------------------------------------
7817@node File-system dbm, GDBM interface, Generic DBM interface, Library modules - Utilities
7818@section @code{dbm.fsdbm} - File-system dbm
7819@c NODE ファイルシステムdbm, @code{dbm.fsdbm} - ファイルシステムdbm
7820
7821@deftp {Module} dbm.fsdbm
7822@mdindex dbm.fsdbm
7823Implements fsdbm.  Extends @code{dbm}.
7824@end deftp
7825
7826@deftp {Class} <fsdbm>
7827@clindex fsdbm
7828@c MOD dbm.fsdbm
7829@c EN
7830@code{Fsdbm} is a dbm implementation that directly uses
7831the filesystem.  Basically, it uses file names for keys,
7832and file content for values.   Unlike other dbm implementations,
7833this doesn't depend on external libraries---it is pure Scheme
7834implementation---so it is always available, while other dbm
7835implementations may not.
7836@c JP
7837@code{fsdbm}は、直接ファイルシステムを扱うDBM実装です。
7838基本的には、ファイル名をキー、ファイルの内容を値として使います。
7839他のDBM実装とは違い、これは他の特別なライブラリに依存しません
7840(純粋にSchemeのみにより実装されています)。
7841したがって、他のDBM実装が使えないときでも、いつでも使うことが
7842できます。
7843
7844@c EN
7845Obviously, it is not suitable for the database that has
7846lots of entries, or has entries deleted and added very frequently.
7847The advantage is when the number of entries
7848are relatively small, and the values are relatively large while
7849keys are small.
7850@c JP
7851明らかに、たくさんのエントリを持っていたり、エントリの追加や
7852削除が頻繁に起こるようなデータベースには向いていません。
7853エントリの数が相対的に小さく、キーが小さいのに値が大きいような
7854場合に向いています。
7855
7856@c EN
7857The database name given to @code{<fsdbm>} instance
7858is used as a directory name that stores the data.
7859@c JP
7860@code{<fsdbm>}のインスタンスに与えられるデータベース名は、
7861データを格納するディレクトリの名前として使われます。
7862
7863@c EN
7864The data files are stored in subdirectories under @var{path} of
7865@code{fsdbm} instance, hashed by the key.  Non-alphanumeric characters
7866in the key is encoded like @code{_3a} for '@code{:}', for example.
7867If a key is too long to be a file name, it is chopped to chunks,
7868and each chunk but the last one is used as a directory name.
7869Note that a long key name may still cause a problem, for example,
7870some of old 'tar' command can't deal with pathnames (not each
7871pathname components, but the entire pathname) longer than 256
7872characters.
7873@c JP
7874データのファイルは、@code{fsdbm}インスタンスの@var{path}の
7875サブディレクトリに格納され、キーによりハッシュされます。
7876キーに英数字でない文字がある場合はエンコードされます。
7877例えば、'@code{:}'は、@code{_3a}にエンコードされます。
7878キーがファイル名としては長すぎる場合は、いくつかに
7879分割され、その最後の文字列片以外はディレクトリ名として
7880使われます。長いキー名は問題を引き起こすかも知れないことに
7881注意して下さい。例えば、いくつかの古い'tar'コマンドは、256文字
7882を越える長いパス名を扱えません(それぞれのパスコンポーネント
7883ではなく、パス名全体でです)。
7884@c COMMON
7885@end deftp
7886
7887@c EN
7888Fsdbm implements all of the dbm protocol
7889(see @ref{Generic DBM interface}).
7890It doesn't have any fsdbm-specific procedures.
7891@c JP
7892fsdbmは、全てのDBMプロトコルを実装しています
7893(@ref{Generic DBM interface}参照)。
7894fsdbm特有の手続きというものはありません。
7895@c COMMON
7896
7897@c ----------------------------------------------------------------------
7898@node GDBM interface, NDBM interface, File-system dbm, Library modules - Utilities
7899@section @code{dbm.gdbm} - GDBM interface
7900@c NODE GDBMインタフェース, @code{dbm.gdbm} - GDBMインタフェース
7901
7902@deftp {Module} dbm.gdbm
7903@mdindex dbm.gdbm
7904Provides interface to the gdbm library.  Extends @code{dbm}.
7905@end deftp
7906
7907@deftp {Class} <gdbm>
7908@clindex gdbm
7909@c MOD dbm.gdbm
7910@c EN
7911Inherits @code{<dbm>}.  Provides an implementation for GDBM library.
7912This module is only installed when your system already has GDBM
7913(1.8.0 is preferred, but works with older 1.7.x with some limitations).
7914@c JP
7915@code{<dbm>} を継承します。GDBM ライブラリのための実装を提供します。
7916このモジュールは、すでにあなたのシステムにすでに GDBM がある場合にのみ
7917インストールされます(バージョン 1.8.0 が推奨されますが、いくつかの制限が
7918あるだけで古い 1.7.x でも動作します)。
7919@c COMMON
7920
7921@defivar <gdbm> sync
7922@end defivar
7923@defivar <gdbm> nolock
7924@end defivar
7925@defivar <gdbm> bsize
7926@end defivar
7927@end deftp
7928
7929@c EN
7930Besides the unified DBM interface (@pxref{Generic DBM interface}),
7931this module provides the following low-level functions that provides
7932direct access to the gdbm API.  See gdbm manual for details of these
7933APIs.
7934@c JP
7935統合された DBM インターフェース (@pxref{Generic DBM interface}) の
7936他に、このモジュールでは GDBM API への直接のアクセスを提供する以下の
7937低レベルな手続きを提供しています。これらの API の詳細については GDBM の
7938マニュアルを見て下さい。
7939@c COMMON
7940
7941@defun gdbm-open path :optional size rwmode fmode error-callback
7942@c MOD dbm.gdbm
7943@end defun
7944
7945@defvar GDBM_READER
7946@c MOD dbm.gdbm
7947@end defvar
7948
7949@defvar GDBM_WRITER
7950@c MOD dbm.gdbm
7951@end defvar
7952
7953@defvar GDBM_WRCREAT
7954@c MOD dbm.gdbm
7955@end defvar
7956
7957@defvar GDBM_NEWDB
7958@c MOD dbm.gdbm
7959@end defvar
7960
7961@defvar GDBM_FAST
7962@c MOD dbm.gdbm
7963@end defvar
7964
7965@defvar GDBM_SYNC
7966@c MOD dbm.gdbm
7967@end defvar
7968
7969@defvar GDBM_NOLOCK
7970@c MOD dbm.gdbm
7971@end defvar
7972
7973@defun gdbm-close gdbm-object
7974@c MOD dbm.gdbm
7975@end defun
7976
7977@defun gdbm-closed? gdbm-object
7978@c MOD dbm.gdbm
7979@end defun
7980
7981@defun gdbm-store key value :optional flag
7982@c MOD dbm.gdbm
7983@end defun
7984
7985@defvar GDBM_INSERT
7986@c MOD dbm.gdbm
7987@end defvar
7988
7989@defvar GDBM_REPLACE
7990@c MOD dbm.gdbm
7991@end defvar
7992
7993
7994@defun gdbm-fetch gdbm-object key
7995@c MOD dbm.gdbm
7996@end defun
7997
7998
7999@defun gdbm-delete gdbm-object key
8000@c MOD dbm.gdbm
8001@end defun
8002
8003
8004@defun gdbm-firstkey gdbm-object
8005@c MOD dbm.gdbm
8006@end defun
8007
8008
8009@defun gdbm-nextkey gdbm-object key
8010@c MOD dbm.gdbm
8011@end defun
8012
8013
8014@defun gdbm-reorganize gdbm-object
8015@c MOD dbm.gdbm
8016@end defun
8017
8018
8019@defun gdbm-sync gdbm-object
8020@c MOD dbm.gdbm
8021@end defun
8022
8023
8024@defun gdbm-exists? gdbm-object key
8025@c MOD dbm.gdbm
8026@end defun
8027
8028
8029@defun gdbm-strerror errno
8030@c MOD dbm.gdbm
8031@end defun
8032
8033
8034@defun gdbm-setopt gdbm-object option value
8035@c MOD dbm.gdbm
8036@end defun
8037
8038@defvar GDBM_CACHESIZE
8039@c MOD dbm.gdbm
8040@end defvar
8041
8042@defvar GDBM_FASTMODE
8043@c MOD dbm.gdbm
8044@end defvar
8045
8046@defvar GDBM_SYNCMODE
8047@c MOD dbm.gdbm
8048@end defvar
8049
8050@defvar GDBM_CENTFREE
8051@c MOD dbm.gdbm
8052@end defvar
8053
8054@defvar GDBM_COALESCEBLKS
8055@c MOD dbm.gdbm
8056@end defvar
8057
8058@defun gdbm-version
8059@c MOD dbm.gdbm
8060@end defun
8061
8062@defun gdbm-errno
8063@c MOD dbm.gdbm
8064@end defun
8065
8066@c ----------------------------------------------------------------------
8067@node NDBM interface, Original DBM interface, GDBM interface, Library modules - Utilities
8068@section @code{dbm.ndbm} - NDBM interface
8069@c NODE NDBMインタフェース, @code{dbm.ndbm} - NDBMインタフェース
8070
8071@deftp {Module} dbm.ndbm
8072@mdindex dbm.ndbm
8073Provides interface to the 'new' dbm library, a.k.a. ndbm.
8074Extends @code{dbm}.
8075@end deftp
8076
8077@deftp {Class} <ndbm>
8078@clindex ndbm
8079@c MOD dbm.ndbm
8080@c EN
8081Inherits @code{<dbm>}.  Provides an implementation for NDBM library.
8082This module is only installed when your system already has NDBM.
8083@c JP
8084@code{<dbm>} を継承します。NDBM ライブラリのための実装を提供します。
8085このモジュールはあなたのシステムにすでに NDBM がある場合にのみ
8086インストールされます。
8087@c COMMON
8088@end deftp
8089
8090@c EN
8091Besides the unified DBM interface (@pxref{Generic DBM interface}),
8092this module provides the following low-level functions that provides
8093direct access to the ndbm API.  See ndbm manual for details of these
8094APIs.
8095@c JP
8096統合された DBM インターフェース (@pxref{Generic DBM interface}) の
8097他に、このモジュールでは NDBM API への直接のアクセスを提供する以下の
8098低レベルな手続きを提供しています。これらの API の詳細については NDBM の
8099マニュアルを見て下さい。
8100@c COMMON
8101
8102@defun ndbm-open path flags mode
8103@c MOD dbm.ndbm
8104@end defun
8105
8106@defun ndbm-close ndbm-object
8107@c MOD dbm.ndbm
8108@end defun
8109
8110@defun ndbm-closed? ndbm-object
8111@c MOD dbm.ndbm
8112@end defun
8113
8114@defun ndbm-store ndbm-object key content :optional flag
8115@c MOD dbm.ndbm
8116@end defun
8117
8118@defun ndbm-fetch ndbm-object key
8119@c MOD dbm.ndbm
8120@end defun
8121
8122@defun ndbm-delete ndbm-object key
8123@c MOD dbm.ndbm
8124@end defun
8125
8126@defun ndbm-firstkey ndbm-object
8127@c MOD dbm.ndbm
8128@end defun
8129
8130@defun ndbm-nextkey ndbm-object
8131@c MOD dbm.ndbm
8132@end defun
8133
8134@defun ndbm-error ndbm-object
8135@c MOD dbm.ndbm
8136@end defun
8137
8138@defun ndbm-clear-error ndbm-object
8139@c MOD dbm.ndbm
8140@end defun
8141
8142@c ----------------------------------------------------------------------
8143@node Original DBM interface, Filtering file content, NDBM interface, Library modules - Utilities
8144@section @code{dbm.odbm} - Original DBM interface
8145@c NODE オリジナルのDBMインタフェース, @code{dbm.odbm} - オリジナルのDBMインタフェース
8146
8147@deftp {Module} dbm.odbm
8148@mdindex dbm.odbm
8149Provides interface to the legacy dbm library.
8150Extends @code{dbm}.
8151@end deftp
8152
8153@deftp {Class} <odbm>
8154@clindex odbm
8155@c MOD dbm.odbm
8156@c EN
8157Inherits @code{<dbm>}.  Provides an implementation for legacy DBM
8158library.
8159This module is only installed when your system already has DBM.
8160
8161The biggest limitation of the legacy DBM is that you can only open
8162one database at a time.  You can create a multiple @code{<odbm>}
8163instances, but you can open at most one of it at a time, or
8164you'll get an error.
8165@c JP
8166@code{<dbm>} を継承しています。レガシーな DBM ライブラリのための実装を
8167提供します。このモジュールは、あなたのシステムにすでに DBM がある場合にのみ
8168インストールされます。
8169
8170レガシー DBM の最大の制限は、データベースを一時に一つしか開けないことです。
8171複数の @code{<odbm>} のインスタンスを作ることができますが、一時に一つしか
8172開くことが出来ず、一つ以上開こうとするとエラーになります。
8173@c COMMON
8174@end deftp
8175
8176@c EN
8177Besides the unified DBM interface (@pxref{Generic DBM interface}),
8178this module provides the following low-level functions that provides
8179direct access to the dbm API.  See dbm manual for details of these
8180APIs.
8181@c JP
8182統合された DBM インターフェース (@pxref{Generic DBM interface}) の
8183他に、このモジュールでは DBM API への直接のアクセスを提供する以下の
8184低レベルな手続きを提供しています。これらの API の詳細については DBM の
8185マニュアルを見て下さい。
8186@c COMMON
8187
8188@defun odbm-init path
8189@c MOD dbm.odbm
8190@end defun
8191
8192@defun odbm-close
8193@c MOD dbm.odbm
8194@end defun
8195
8196@defun odbm-store key value
8197@c MOD dbm.odbm
8198@end defun
8199
8200@defun odbm-fetch key
8201@c MOD dbm.odbm
8202@end defun
8203
8204@defun odbm-delete key
8205@c MOD dbm.odbm
8206@end defun
8207
8208@defun odbm-firstkey
8209@c MOD dbm.odbm
8210@end defun
8211
8212@defun odbm-nextkey key
8213@c MOD dbm.odbm
8214@end defun
8215
8216
8217@c ----------------------------------------------------------------------
8218@c @node Pseudo DBM interface, gauche.charconv - Character code conversion, Original DBM interface, Library modules
8219@c @section @code{dbm.pdbm} - Pseudo DBM interface
8220
8221@c ----------------------------------------------------------------------
8222@node Filtering file content, Filesystem utilities, Original DBM interface, Library modules - Utilities
8223@section @code{file.filter} - Filtering file content
8224@c NODE ファイルのフィルタ, @code{file.filter} - ファイルのフィルタ
8225
8226@deftp {Module} file.filter
8227@mdindex file.filter
8228@c EN
8229This module provides utilities for a common pattern in
8230filter-type commands, that is, to take an input, to process
8231the content, and to write the result.   The common occurring
8232pattern is:
8233
8234@itemize @bullet
8235@item
8236Input may be a specified file, or an input port
8237(the current input port by default).
8238@item
8239Output may be a specified file, or an output port
8240(the current output port by default).
8241@item
8242Output may be a temporary file, which will be renamed
8243upon completion of the processing.
8244@item
8245Output file may be removed when an error occurs
8246in the processing.
8247@end itemize
8248@c JP
8249このモジュールは、フィルター型のコマンド、
8250すなわち入力を読み込み、処理をして結果を書き出すような場合に
8251共通するパターンに使えるユーティリティ手続きを提供します。
8252共通するパターンとは:
8253
8254@itemize @bullet
8255@item
8256入力は指定されたファイルかポートで、デフォルトはカレント入力ポート。
8257@item
8258出力は指定されたファイルかポートで、デフォルトはカレント出力ポート。
8259@item
8260出力は一時ファイルに書き出すこともできて、
8261その場合は処理が終了した時点で指定されたファイルにリネーム。
8262@item
8263処理途中でエラーが起こった場合に出力ファイルを削除
8264@end itemize
8265@c COMMON
8266@end deftp
8267
8268@defun file-filter proc :key input output temporary-file keep-output? rename-hook
8269@c MOD file.filter
8270@c EN
8271Calls @var{proc} with two arguments, an input port and
8272an output port.   Returns the result(s) of @var{proc}.
8273The input port and output port are chosen depending on the keyword arguments.
8274@c JP
8275二つの引数、入力ポートと出力ポートを引数として@var{proc}を呼び出し、
8276その結果を返します。
8277入力ポートと出力ポートはキーワード引数により決定されます。
8278@c COMMON
8279
8280@table @code
8281@item input
8282@c EN
8283The argument must be either an input port or a string
8284that specifies a file name.
8285If it's an input port, it is passed to @var{proc} as is.
8286If it's a string, the named file is opened for input and the resulting
8287port is passed to @var{proc}, and the port is closed when @var{proc}
8288returns.
8289If this argument is omitted, the current input port is passed.
8290@c JP
8291この引数は入力ポートかファイル名を示す文字列でなければなりません。
8292入力ポートの場合、それはそのまま@var{proc}に渡されます。
8293文字列が渡された場合は、そのファイル名を持つファイルを入力用にオープンし、
8294そのポートが@var{proc}に渡され、またこのポートは@var{proc}が戻った時に閉じられます。
8295この引数が省略された場合は、現在の入力ポートが渡されます。
8296@c COMMON
8297@item output
8298@c EN
8299The argument must be either an output port or a string
8300that specifies a file name.
8301If it's an output port, it is passed to @var{proc} as is.
8302If it's a string, the named file is opened for output
8303(unless @var{temporary-file} is given, in that case
8304a temporary file is opened instead), and the resulting port
8305is passed to @var{proc}.  This port is closed when @var{proc} returns.
8306If this argument is omitted, the current output port is passed.
8307@c JP
8308この引数は出力ポートかファイル名を示す文字列でなければなりません。
8309出力ポートの場合、それはそのまま@var{proc}に渡されます。
8310文字列が渡された場合は、そのファイル名を持つファイルを出力用にオープンし、
8311そのポートが@var{proc}に渡されます (但し、@var{temporary-file}
8312引数が渡された時はそれに指定されるファイルが一時ファイルとしてオープンされます)。
8313オープンされたポートは@var{proc}が戻った時に閉じられます。
8314この引数が省略された場合は、現在の出力ポートが渡されます。
8315@c COMMON
8316@item temporary-file
8317@c EN
8318The value must be a boolean or a string.  If a non-false value
8319is given, and output is a file, then a fresh temporary file is
8320created and opened for output and passed to @var{proc}.
8321When @var{proc} returns normally, the file is renamed
8322to the name given to @var{output} keyword argument.
8323
8324If @code{#t} is given, a temporary file name is generated
8325based on the name of the output file.
8326If a string file name is given to this argument, the name
8327is used for @code{sys-mkstemp}.
8328
8329If the given file name begins with characters except @code{"/"}, @code{"./"}
8330or @code{"../"}, the directory of the file name given to @var{output} argument
8331is attached before it.
8332
8333The default value is @code{#f} (do not use a temporary file).
8334@c JP
8335値は真偽値か文字列でなければなりません。@code{#f}でない値が渡され、
8336かつ出力がファイルである場合、新たな一時ファイルが出力用に作成され@var{proc}に
8337渡されます。
8338そして@var{proc}が正常に返って来た時点で、一時ファイルは@var{output}に指定された
8339ファイルへとリネームされます。
8340
8341この引数が@code{#t}の場合、一時ファイル名は出力ファイル名をもとに作られます。
8342この引数が文字列の場合はそれが@code{sys-mkstemp}に渡されます。
8343
8344もし一時ファイル名が@code{"/"}、@code{"./"}、@code{"../"}以外の
8345文字で始まっていた場合は、@var{output}に与えられたファイル名のディレクトリが
8346一時ファイルの前に追加されます。
8347
8348デフォルトの値は@code{#f} (一時ファイルを使わない) です。
8349@c COMMON
8350@item keep-output?
8351@c EN
8352If a true value is given, the output is not deleted even
8353when @var{proc} signals an error.
8354By default, the output (or the temporary file when
8355@var{temporary-file} is given) will be deleted on error.
8356@c JP
8357真の値が与えられた場合、@var{proc}がエラーになった場合でも出力ファイルを削除しません。
8358デフォルトでは、出力ファイル(もしくは@var{temporary-file}が与えられた場合は
8359そのファイル)はエラーの場合には削除されます。
8360@c COMMON
8361@item leave-unchanged
8362@c EN
8363When a temporary file is used, and a true value is given to this argument,
8364the existing output file is left intact when the generated output in
8365the temporary file exactly matches the original content of the output
8366file.  It is useful if touching output file may trigger some actions
8367(e.g. by @code{make}) and you want to avoid invoking unnecessary
8368actions.  The default value is @code{#f} (always replace the output).
8369@c JP
8370一時ファイルを使う場合に、この引数に真の値が与えられると、
8371出力ファイルが既に存在して一時ファイルに生成された内容と全く同じだった場合に、
8372出力ファイルをそのままにします。これは、出力ファイルに触ることで何らかの
8373アクションが起きるようになっている場合に(例: @code{make})、
8374不必要なアクションを起こさないために便利です。
8375デフォルトの値は@code{#f} (常に出力ファイルを置き換える) です。
8376@c COMMON
8377@end table
8378@end defun
8379
8380@defun file-filter-fold proc seed :key reader input output temporary-file keep-output? rename-hook
8381@c MOD file.filter
8382@c EN
8383A convenience wrapper of @code{file-filter}.
8384Call @var{proc} for each item read from input
8385by @var{reader} (@code{read-line} by default).  The argument
8386@var{proc} receives is the item, the seed value and the output port;
8387@var{proc} can emit the output, as well as returning some value
8388that is passed along as the seed value.  Other keyword arguments
8389are passed to @code{file-filter}.
8390
8391For example, the following code reads each line from @file{file.txt} and
8392displays lines matching @code{#/regexp/} with line numbers.
8393@c JP
8394@file{file-filter}の便利なラッパー手続きです。
8395入力から@var{reader}によって読まれるデータに対して次々に@var{proc}を
8396呼び出します。@var{reader}のデフォルトは@code{read-line}です。
8397@var{proc}の引数は、読まれたデータ、シード値、出力ポートです。
8398@var{proc}は何かを出力することもできますし、値を返せばそれが
8399次のシード値として受け渡されてゆきます。他のキーワード引数は
8400@code{file-filter}にそのまま渡されます。
8401
8402例えば次のコードは、@file{file.txt}を1行づつ読み、@code{#/regexp/}に
8403マッチする行を行番号つきで出力します。
8404@c COMMON
8405
8406@example
8407(file-filer-fold
8408  (^[line nc out]
8409    (when (#/regexp/ line) (format out "~3d: ~a\n" nc line))
8410    (+ nc 1))
8411  1 :input "file.txt")
8412@end example
8413@end defun
8414
8415@defun file-filter-map proc :key reader input output temporary-file keep-output? rename-hook
8416@defunx file-filter-for-each proc :key reader input output temporary-file keep-output? rename-hook
8417@c MOD file.filter
8418@c EN
8419Utilities similar to @code{file-filter-fold},
8420like @code{map} and @code{for-each} to @code{fold}.
8421
8422The procedure @var{proc} is called with two arguments,
8423an item read from the input and an output port.
8424The results of @var{proc} are collected as a list and returned
8425by @code{file-filter-map}, and discarded by @code{file-filter-for-each}.
8426
8427The meaning of keyword arguments are the same as @code{file-filter-fold}.
8428@c JP
8429@code{file-filter-fold}に似たユーティリティです。
8430@code{fold}に対する@code{map}、@code{for-each}に相当します。
8431
8432手続き@var{proc}は二つの引数、入力から読まれたデータと出力ポートを受けとります。
8433@var{proc}の結果は、@code{file-filter-map}では集められてリストとして
8434戻り値となり、@code{file-filter-for-each}では捨てられます。
8435
8436キーワード引数の意味は@code{file-filter-fold}と同じです。
8437@c COMMON
8438@end defun
8439
8440
8441@c ----------------------------------------------------------------------
8442@node Filesystem utilities, Mathematic constants, Filtering file content, Library modules - Utilities
8443@section @code{file.util} - Filesystem utilities
8444@c NODE ファイルシステムユーティリティ, @code{file.util} - ファイルシステムユーティリティ
8445
8446@deftp {Module} file.util
8447@mdindex file.util
8448@c EN
8449Provides convenient utility functions handling files and directories.
8450Those functions are built on top of the primitive system
8451procedures described in @ref{Filesystems}.
8452@c JP
8453ファイルやディレクトリを扱う便利な手続き群を提供します。
8454これらの手続きは@ref{Filesystems}で述べられたプリミティブなシステム手続きの上に
8455構築されています。
8456@c COMMON
8457
8458@c EN
8459Many procedures in this module takes a keyword argument @var{follow-link?},
8460which specifies the behavior when the procedure sees a symbolic link.
8461If true value is given to @var{follow-link?} (which is the default),
8462the procedure operates on the file referenced by the link; if false is
8463given, it operates on the link itself.
8464@c JP
8465このモジュール内の多くの手続きは@var{follow-link?}というキーワード引数を取ります。
8466これは手続きがシンボリックリンクに出会ったときの動作を指定します。@var{follow-link?}が
8467真であれば、手続きはリンクの指す先のファイルに作用します。これがデフォルトの振舞いです。
8468@var{follow-link?}に@code{#f}が渡された場合は手続きはリンクそのものに作用します。
8469@c COMMON
8470@end deftp
8471
8472@c EN
8473Note on the naming convention: Some Scheme implementations "create"
8474new directories and files, while the others "make" them.
8475Some implementations "delete" them, while the others "remove" them.
8476It seems that both conventions are equally popular.
8477So Gauche provides @emph{both}.
8478@c JP
8479名前つけ規則に関する注記:ファイルやディレクトリを
8480作成するのに@code{"create"}という語を使う処理系と@code{"make"}を
8481使う処理系があります。ファイルやディレクトリを削除するのにも@code{"remove"}と
8482@code{"delete"}の流派があります。どちらも同じくらい広く使われているようなので、
8483Gaucheでは@emph{両方の}名前を提供することにしました。
8484@c COMMON
8485
8486@menu
8487* Directory utilities::
8488* Pathname utilities::
8489* File attribute utilities::
8490* File operations::
8491* Temporary files and directories::
8492* Lock files::
8493@end menu
8494
8495@node Directory utilities, Pathname utilities, Filesystem utilities, Filesystem utilities
8496@subsection Directory utilities
8497@c NODE ディレクトリユーティリティ
8498
8499@defun current-directory :optional new-directory
8500@c MOD file.util
8501@c EN
8502When called with no argument, this returns the pathname of the current
8503working directory.  When called with a string argument @var{new-directory},
8504this sets the current working directory of the process to it.
8505If the process can't change directory to @var{new-directory}, an error is
8506signaled.
8507
8508This function is in ChezScheme, MzScheme and some other Scheme
8509implementations.
8510
8511SRFI-170 defines @code{current-directory} without arguments, to return
8512the current working directory.
8513@c JP
8514引数無しで呼ばれた場合、カレントディレクトリを返します。
8515文字列@var{new-directory}が与えられた場合はプロセスのカレントディレクトリを
8516@var{new-directory}に変更します。変更が出来なかった場合はエラーとなります。
8517
8518この関数はChezSchemeやMzSchemeなどいくつかのScheme処理系に見られます。
8519
8520SRFI-170は引数を取らない@code{current-directory}を定義しています。
8521現在のディレクトリを返すのは一緒です。
8522@c COMMON
8523@end defun
8524
8525@defun home-directory :optional user
8526@c MOD file.util
8527@c EN
8528Returns the home directory of the given @var{user},
8529which may be a string user name or an integer user id.
8530If @var{user} is omitted, the current user is assumed.
8531If the given user cannot be found, or the home directory
8532of the user cannot be determined, @code{#f} is returned.
8533@c JP
8534名前または整数のユーザidで与えられたユーザ@var{user}のホームディレクトリを
8535返します。@var{user}が省略された場合はカレントユーザが使われます。
8536与えられたユーザが見付けられないか、ホームディレクトリを決定できなかった場合は
8537@code{#f}が返されます。
8538@c COMMON
8539
8540@c EN
8541On Windows native platforms, this function is only supported
8542to query the current user's directory.
8543@c JP
8544Windowsネイティブ環境では、この関数はカレントユーザに対してのみ動作します。
8545@c COMMON
8546@end defun
8547
8548@defun directory-list path :key children? add-path? filter filter-add-path?
8549@c MOD file.util
8550@c EN
8551Returns a list of entries in the directory @var{path}.
8552The result is sorted by dictionary order.
8553
8554By default, only the basename (the last component) of the entries
8555returned.   If @var{add-path?} is given and true, @var{path} is appended
8556to each entry.  If @var{children?} is given and true, @code{"."} and
8557@code{".."} are excluded from the result.
8558
8559If @var{filter} is given, it must be a predicate that takes one argument.
8560It is called on every element of the directory entry,
8561and only the entries on which
8562@var{filter} returns true are included in the result.
8563The argument passed to @var{filter} is a basename of the directory entry
8564by default, but when @var{filter-add-path?} is true, @var{path} is
8565appended to the entry.
8566
8567If @var{path} is not a directory, an error is signaled.
8568@c JP
8569ディレクトリ@var{path}中のエントリのリストを返します。
8570リストは文字列順にソートされます。
8571
8572デフォルトではエントリのベースネーム(パスの最後のコンポーネント)のみが
8573返されますが、キーワード引数@var{add-path?}に真の値が与えられた時は
8574@var{path}が各エントリの前に追加されます。
8575@var{children?}に真の値が与えられた時は、カレントディレクトリと親ディレクトリが
8576リストから除かれます。
8577
8578@var{filter}引数は、もし与えられれば、一つの引数を取る
8579手続きでなければなりません。ディレクトリ中の各エントリを引数としてその手続きが呼ばれ、
8580真を返したエントリのみが結果に含まれます。
8581@var{filter}に与えられるエントリはデフォルトではベース名のみですが、
8582引数@var{filter-add-path?}が真ならば@var{path}が前に追加された名前となります。
8583
8584@var{path}がディレクトリでない場合はエラーが報告されます。
8585@c COMMON
8586
8587@example
8588(directory-list "test")
8589 @result{} ("." ".." "test.scm" "test.scm~")
8590
8591(directory-list "test" :add-path? #t)
8592 @result{} ("test/." "test/.." "test/test.scm" "test/test.scm~")
8593
8594(directory-list "test" :children? #t)
8595 @result{} ("test.scm" "test.scm~")
8596
8597(directory-list "test" :children? #t :add-path? #t
8598   :filter (lambda (e) (not (string-suffix? "~" e))))
8599 @result{} ("test/test.scm")
8600@end example
8601@end defun
8602
8603@defun directory-list2 path :key children? add-path? filter follow-link?
8604@c MOD file.util
8605@c EN
8606Like @code{directory-list}, but returns two values; the first one is a list
8607of subdirectories, and the second one is a list of the rest.
8608The keyword arguments @var{children?}, @code{add-path?} and @var{filter}
8609are the same as @code{directory-list}.
8610
8611Giving false value to @var{follow-link?} makes @code{directory-list2}
8612not follow the symbolic links; if the @var{path} contains a
8613symlink to a directory,
8614it will be included in the first list if @var{follow-link?}
8615is omitted or true,
8616while it will be in the second list if @var{follow-link?} is false.
8617@c JP
8618@code{directory-list}に似ていますが、ふたつの値を返します。最初の値は
8619@var{path}内にあるサブディレクトリのリストで、次の値はそれ以外のエントリのリストです。
8620キーワード引数@var{children?}、@code{add-path?}、@var{filter}は
8621@code{directory-list}と同じ意味をもちます。
8622
8623偽の値を@var{follow-link?}に与えると、@var{path}内のシンボリックリンクを
8624辿りません;すなわち、@var{path}内にディレクトリへのシンボリックリンクがあった場合、
8625デフォルト、もしくは@var{follow-link?}に真の値が与えられた場合は
8626それは最初のリスト(サブディレクトリ)に入りますが、@var{follow-link?}
8627に偽の値が与えられた場合は後者のリスト(その他のエントリ)に入ります。
8628@c COMMON
8629@end defun
8630
8631@defun directory-fold path proc seed :key lister follow-link?
8632@c MOD file.util
8633@c EN
8634A fundamental directory traverser.
8635Conceptually it works as follows, in recursive way.
8636@c JP
8637ディレクトリ探索の最も基本的な手続きです。基本的な動作は以下に示すような再帰的なものです。
8638@c COMMON
8639
8640@c EN
8641@itemize @bullet
8642@item
8643If @var{path} is not a directory, calls
8644@code{(@var{proc} @var{path} @var{seed})} and returns the result.
8645@item
8646If @var{path} is a directory, calls
8647@code{(@var{lister} @var{path} @var{seed})}.  The procedure @var{lister}
8648is expected to return two values: a list of pathnames, and the
8649next seed value.   Then
8650@code{directory-fold} is called on each returned pathname,
8651passing the returned seed value to the @var{seed} argument of the
8652next call of @code{directory-fold}.
8653Returns the result of the last seed value.
8654@end itemize
8655@c JP
8656@itemize @bullet
8657@item
8658@var{path}がディレクトリでない場合は@code{(@var{proc} @var{path} @var{seed})} を
8659評価し、結果を返します。
8660@item
8661@var{path}がディレクトリであった場合、まず
8662@code{(@var{lister} @var{path} @var{seed})} を評価します。
8663手続き@var{lister}は2つの値、パス名のリストと次のseedとなる値を
8664返さなければなりません。
8665続いて、@code{directory-fold}が各パス名に対して再帰的に呼ばれます。
8666各呼び出しの結果が次の再帰呼び出しの@var{seed}の値に使われます。
8667@end itemize
8668@c COMMON
8669
8670@c EN
8671The default procedure of @var{lister} is just a call to @code{directory-list},
8672as follows.
8673@c JP
8674デフォルトの@var{lister}は@code{directory-list}を次のように呼び出すものです。
8675@c COMMON
8676@example
8677(lambda (path seed)
8678  (values (directory-list path :add-path? #t :children? #t)
8679          seed))
8680@end example
8681
8682@c EN
8683Note that @var{lister} shouldn't return the given path itself (@code{"."})
8684nor the parent directory (@code{".."}), or the recursion wouldn't
8685terminate.  Also note @var{lister} is expected to return a path accessible
8686from the current directory, i.e. if @var{path} is @code{"/usr/lib/foo"} and
8687it contains @code{"libfoo.a"} and @code{"libfoo.so"}, @var{lister} should
8688return @code{'("/usr/lib/foo/libfoo.a" "/usr/lib/foo/libfoo.so")}.
8689@c JP
8690@var{lister}は@var{path}自身への参照 (@code{"."}) やその親ディレクトリへの参照を
8691返してはなりません。また、@var{lister}の戻り値は現在のディレクトリからアクセス可能な
8692パス名でなければなりません。例えば@var{path}が@code{"/usr/lib/foo"}であり、
8693そのディレクトリが@code{"libfoo.a"}と@code{"libfoo.so"}を含んでいた場合、
8694@var{lister}は@code{'("/usr/lib/foo/libfoo.a" "/usr/lib/foo/libfoo.so")}
8695のようなリストを返す必要があります。
8696@c COMMON
8697
8698@c EN
8699The keyword argument @var{follow-link?} is used to determine whether
8700@var{lister} should be called on a symbolic link pointing to a directory.
8701When @var{follow-link?} is true (default), @var{lister} is called
8702with the symbolic link if it points to a directory.
8703When @var{follow-link?} is false, @var{proc} is not called.
8704@c JP
8705キーワード引数@var{follow-link?}はディレクトリを指しているシンボリックリンクに対して
8706@var{lister}を呼ぶかどうかを決定します。@var{follow-link?}が真(デフォルト値)である
8707場合はそのようなシンボリックリンクに対しても@var{lister}が呼ばれます。
8708一方、@var{follow-link?}が偽であればシンボリックリンクに対しては@var{proc}が呼ばれます。
8709@c COMMON
8710
8711@c EN
8712The following example returns a list of pathnames of the emacs backup files
8713(whose name ends with "~") under the given path.
8714@c JP
8715次の例は、与えられたpath以下からemacsのバックアップファイル ("~"で終る名を持つファイル)
8716のリストを返します。
8717@c COMMON
8718@example
8719(use srfi-13) ;; for string-suffix?
8720(directory-fold path
8721                (lambda (entry result)
8722                  (if (string-suffix? "~" entry)
8723                      (cons entry result)
8724                      result))
8725                '())
8726@end example
8727
8728@c EN
8729The following example lists all the files and directories under the
8730given pathname.   Note the use of @var{lister} argument to include
8731the directory path itself in the result.
8732@c JP
8733次の例は与えられたpath以下全てのファイルとディレクトリ名をリストにして
8734返します。@var{lister}引数を使ってディレクトリ名そのものを結果に
8735含めていることに注目して下さい。
8736@c COMMON
8737@example
8738(directory-fold path cons '()
8739  :lister (lambda (path seed)
8740            (values (directory-list path :add-path? #t :children? #t)
8741                    (cons path seed))))
8742@end example
8743
8744@end defun
8745
8746@defun make-directory* name :optional perm
8747@defunx create-directory* name :optional perm
8748@c MOD file.util
8749@c EN
8750Creates a directory @var{name}.  If the intermediate path to the
8751directory doesn't exist, they are also created
8752(like @code{mkdir -p} command on Unix).   If the directory
8753@var{name} already exist, these procedure does nothing.
8754@var{Perm} specifies the integer flag for permission bits of the
8755directory.
8756@c JP
8757ディレクトリ@var{name}を作成します。@var{name}に至るパスが存在しない
8758場合は必要なディレクトリが作成されます (Unixの@code{mkdir -p}コマンドと
8759同様です)。ディレクトリ@var{name}が既に存在していた場合は何もしません。
8760@var{perm}は作成されるディレクトリのパーミッションビットを指定します。
8761@c COMMON
8762@end defun
8763
8764
8765@defun remove-directory* name
8766@defunx delete-directory* name
8767@c MOD file.util
8768@c EN
8769Deletes directory @var{name} and its content recursively
8770(like @code{rm -r} command on Unix).   Symbolic links are not
8771followed.
8772@c JP
8773ディレクトリ@var{name}とその内容を再帰的に消去します
8774(Unixの@code{rm -r}コマンドと同様です)。シンボリックリンクは辿られません。
8775@c COMMON
8776@end defun
8777
8778@defun copy-directory* src dst :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
8779@c MOD file.util
8780@c EN
8781If @var{src} is a regular file, copies its content to @var{dst}, just like
8782@code{copy-file} does.  If @var{src} is a directory, recursively
8783descends it and copy the file tree to @var{dst}.  Basically
8784it mimics the behavior of @code{cp -r} command.
8785
8786If there's any symbolic links under @var{src}, the link itself
8787is copied instead of the file pointed to by it, unless a true value
8788is given to the @var{follow-link?} keyword argument,
8789i.e. the default value of @var{follow-link?} is @code{#f}.
8790(Note that this is opposite to the @code{copy-file}, in which
8791@var{follow-link?} is true by default.)
8792@c JP
8793@var{src}が通常のファイルであれば、@code{copy-file}と同じように
8794その内容を@var{dst}にコピーします。しかし@var{src}がディレクトリの場合は、
8795再帰的にディレクトリを辿り、その全てを@var{dst}へとコピーします。
8796@code{cp -r}コマンドに相当するものだと考えて良いでしょう。
8797
8798@var{src}がディレクトリの場合、デフォルトではその下にあるシンボリックリンクは
8799辿られず、リンクそのものがコピーされます。リンク先の内容をもコピーしたい
8800場合は@var{follow-link?}キーワード引数に真の値を与えてください。
8801つまり、@var{follow-link?}キーワード引数のデフォルト値は@code{#f}です。
8802(このデフォルト値は@code{copy-file}と逆であることに注意してください。
8803@code{copy-file}では@var{follow-link?}はデフォルトで真であり、
8804リンクそのものをコピーしたい場合に明示的に@code{#f}を与える必要があります。)
8805@c COMMON
8806
8807@c EN
8808The meanings of the other keyword arguments are the same as
8809@code{copy-file}.  See the entry of @code{copy-file} for the details.
8810@c JP
8811他のキーワード引数の意味は@code{copy-file}と同じです。
8812詳細は@code{copy-file}を参照してください。
8813@c COMMON
8814@end defun
8815
8816@defun create-directory-tree dir spec
8817@c MOD file.util
8818@c EN
8819Creates a directory tree under @var{dir} according to @var{spec}.
8820This procedure is useful to set up certain directory hierarchy at once.
8821
8822The @var{spec} argument is an S-expression with the following structure:
8823
8824@example
8825<spec> : <name>                             ; empty file
8826       | (<name> <option> ...)              ; empty file
8827       | (<name> <option> ... <string>)     ; file with content
8828       | (<name> <option> ... <procedure>)  ; file with generated content
8829       | (<name> <option> ... (<spec> ...)) ; directory
8830
8831<name> : string or symbol
8832
8833<option> ... : keyword-value alternating list
8834@end example
8835@c JP
8836@var{spec}で指定されるディレクトリツリーを@var{dir}の下に作成します。
8837特定のディレクトリ構造を一気にセットアップする際に便利です。
8838
8839@var{spec}引数は次に示される構造をもつS式です。
8840
8841@example
8842<spec> : <name>                             ; 空のファイル
8843       | (<name> <option> ...)              ; 空のファイル
8844       | (<name> <option> ... <string>)     ; 固定内容のファイル
8845       | (<name> <option> ... <procedure>)  ; 内容を生成するファイル
8846       | (<name> <option> ... (<spec> ...)) ; ディレクトリ
8847
8848<name> : 文字列かシンボル
8849
8850<option> ... : キーワードと値の交代リスト
8851@end example
8852@c COMMON
8853
8854@c EN
8855With the first and second form of @var{spec}, an empty file is created
8856with the given name.
8857With the third form of @var{spec}, the string becomes the
8858content of the file.
8859
8860With the fourth form of @var{spec}, the procedure is called with the
8861pathname as an argument, and output to the current output
8862port within the procedure is written to the created file.
8863The pathname is relative to the @var{dir} argument.
8864At the time the procedure is called, its parent directory
8865is already created.
8866
8867The last form of @var{spec} creates a named directory,
8868then creates its children recursively according to the specs.
8869@c JP
8870@var{spec}の最初と2番目の形式では、名前@var{name}を持つ空のファイルが作られます。
88713番目の形式では与えられた文字列がファイルの内容となります。
8872
88734番目の形式では、手続きがファイルのパス名を引数として呼び出され、
8874その手続きがcurrent output portに出力した内容がファイルの内容となります。
8875引数に渡されるパス名は@var{dir}引数からの相対パスです。
8876手続きが呼ばれる時、その親ディレクトリは既につくられています。
8877
8878最後の形式は、名前@var{name}を持つディレクトリを作成し、
8879その子供として再帰的に指定された@var{spec}によるファイル/ディレクトリを作成します。
8880@c COMMON
8881
8882@c EN
8883With @var{option}s you can control attributes of created files/directories.
8884Currently the following options are recognized.
8885
8886@table @code
8887@item :mode @var{mode}
8888Takes integer as permission mode bits.
8889@item :owner @var{uid}
8890@itemx :group @var{gid}
8891Takes integer uid/gid of the owner/group of the file/directory.
8892Calling process may need special privilege to change the owner
8893and/or group.
8894@item :symlink @var{path}
8895This is only valid for file spec, and it causes
8896@code{create-directory-tree} to create a named symbolic link
8897whose content is @var{path}.
8898@end table
8899@c JP
8900@var{option}によって、作られるファイル/ディレクトリの属性を細かく指定できます。
8901今のところ、次のオプションが認識されます。
8902
8903@table @code
8904@item :mode @var{mode}
8905整数@var{mode}でパーミッションのモードビットを指定します。
8906@item :owner @var{uid}
8907@itemx :group @var{gid}
8908整数@var{uid}/@var{gid}で作成されるエントリのオーナー/グループを指定します。
8909作成されるエントリのオーナー/グループを変更するには、
8910呼び出すプロセスに特権が必要かもしれません。
8911@item :symlink @var{path}
8912ファイルを作成する@var{spec}でのみ有効なオプションで、
8913@var{path}を指すシンボリックリンクを作成します。
8914@end table
8915@c COMMON
8916@end defun
8917
8918@defun check-directory-tree dir spec
8919@c MOD file.util
8920@c EN
8921Checks if a directory hierarchy according to @var{spec} exists
8922under @var{dir}.  Returns @code{#t} if it exists, or @code{#f} otherwise.
8923
8924The format of @var{spec} is the same
8925as @code{create-directory-tree} described above.
8926
8927If @var{spec} contains options, the attributes of existing
8928files/directories are also checked if they match the given options.
8929@c JP
8930@var{spec}で記述されるディレクトリ階層が@var{dir}の下に存在するかどうかを
8931調べ、存在すれば@code{#t}、そうでなければ@code{#f}を返します。
8932
8933@var{spec}の形式は上で説明した@code{create-directory-tree}と同じです。
8934
8935@var{spec}がオプションを含んでいる場合、該当するファイル/ディレクトリの
8936属性もそのオプションに合致するかどうかチェックされます。
8937@c COMMON
8938@end defun
8939
8940
8941@node Pathname utilities, File attribute utilities, Directory utilities, Filesystem utilities
8942@subsection Pathname utilities
8943@c NODE パスネームユーティリティ
8944
8945@defun build-path base-path component @dots{}
8946@c MOD file.util
8947@c EN
8948Appends pathname components @var{component} to the @var{base-path}.
8949@var{Component} can be a symbol @code{up} or @code{same};
8950in Unix, they are synonym to @code{".."} and @code{"."}.
8951This API is taken from MzScheme.
8952@c JP
8953パス名のコンポーネント@var{component}を@var{base-path}に追加します。
8954@var{Component}はシンボル@code{up}または@code{same}であっても
8955構いません; Unixではそれらは@code{".."}または@code{"."}と等価です。
8956このAPIはMzSchemeから採られました。
8957@c COMMON
8958@end defun
8959
8960@defun absolute-path? path
8961@defunx relative-path? path
8962@c MOD file.util
8963@c EN
8964Returns @code{#t} if @var{path} is absolute or relative, respectively.
8965@c JP
8966@var{path}がそれぞれ絶対パスまたは相対パスならば@code{#t}を返します。
8967@c COMMON
8968@end defun
8969
8970@defun expand-path path
8971@c MOD file.util
8972@c EN
8973Expands tilda-notation of @var{path} if it contains one.
8974Otherwise, @var{path} is returned.  This function does not
8975check if @var{path} exists and/or readable.
8976@c JP
8977@var{path}がチルダ表記を含んでいたらそれを展開したものを返します。
8978そうでなければ@var{path}そのものを返します。この手続きは@var{path}が
8979存在しアクセス可能であるかどうかはチェックしません。
8980@c COMMON
8981@end defun
8982
8983@defun resolve-path path
8984@c MOD file.util
8985@c EN
8986Expands @var{path} like @code{expand-path},
8987then resolve symbolic links for every components
8988of the path.  If @var{path} does not exist, or contains dangling link,
8989or contains unreadable directory, an error is signaled.
8990@c JP
8991@var{path}を@code{expand-path}と同様に展開し、
8992続いて@var{path}の各コンポーネントに対してそれがシンボリックリンクであればリンク先の
8993ものに置き換えてゆきます。@var{path}が存在しないパスを指していたり、
8994シンボリックリンクの先が存在しなかったり、読み出せないディレクトリがあった場合は
8995エラーとなります。
8996@c COMMON
8997@end defun
8998
8999@defun simplify-path path
9000@c MOD file.util
9001@c EN
9002Remove 'up' (@code{".."}) components and 'same' (@code{"."}) components
9003from @var{path} as much as possible.
9004This function does not access the filesystem.
9005@c JP
9006@var{path}から、親ディレクトリへの参照(@code{".."})と自分自身への参照(@code{"."})を
9007出来る限り取り除きます。この手続きはファイルシステムへはアクセスしません。
9008@c COMMON
9009@end defun
9010
9011@defun decompose-path path
9012@c MOD file.util
9013@c EN
9014Returns three values; the directory part of @var{path},
9015the basename without extension of @var{path}, and
9016the extension of @var{path}.    If the pathname doesn't have an extension,
9017the third value is @code{#f}.  If the pathname ends with a directory
9018separator, the second and third values are @code{#f}. (Note: This treatment
9019of the trailing directory separator differs from
9020@code{sys-dirname}/@code{sys-basename}; those follow popular shell's
9021convention, which ignores trailing slashes.)
9022@c JP
9023パス名@var{path}のディレクトリ部、拡張子を除いたファイル名、
9024そして拡張子の3つの値を返します。パス名が拡張子を持たない場合、
9025最後の値は@code{#f}になります。パス名がディレクトリセパレータで
9026終わっている場合は2番目と3番目の値が@code{#f}になります。
9027(後置されたディレクトリセパレータに関するこの取扱いは、
9028@code{sys-dirname}/@code{sys-basename}と異なることに注意して下さい。
9029@code{sys-dirname}等は後置されたディレクトリセパレータを無視するという
9030シェル等の慣習に従っています。)
9031@c COMMON
9032@example
9033(decompose-path "/foo/bar/baz.scm")
9034  @result{} "/foo/bar", "baz", "scm"
9035(decompose-path "/foo/bar/baz")
9036  @result{} "/foo/bar", "baz", #f
9037
9038(decompose-path "baz.scm")
9039  @result{} ".", "baz", "scm"
9040(decompose-path "/baz.scm")
9041  @result{} "/", "baz", "scm"
9042
9043;; Boundary cases
9044(decompose-path "/foo/bar/baz.")
9045  @result{} "/foo/bar", "baz", ""
9046(decompose-path "/foo/bar/.baz")
9047  @result{} "/foo/bar", ".baz", #f
9048(decompose-path "/foo/bar.baz/")
9049  @result{} "/foo/bar.baz", #f, #f
9050@end example
9051@end defun
9052
9053@defun path-extension path
9054@defunx path-sans-extension path
9055@c MOD file.util
9056@c EN
9057Returns an extension of @var{path},
9058and  a pathname of @var{path} without extension, respectively.
9059If @var{path} doesn't have an extension, @code{#f} and @var{path}
9060is returned respectively.
9061@c JP
9062それぞれ、@var{path}の拡張子と、@var{path}から拡張子を除いたものを返します。
9063@var{path}が拡張子を持っていない場合はそれぞれ@code{#f}と@var{path}が返されます。
9064@c COMMON
9065
9066@example
9067(path-extension "/foo/bar.c")       @result{} "c"
9068(path-sans-extension "/foo/bar.c")  @result{} "/foo/bar"
9069
9070(path-extension "/foo/bar")         @result{} #f
9071(path-sans-extension "/foo/bar")    @result{} "/foo/bar"
9072@end example
9073@end defun
9074
9075@defun path-swap-extension path newext
9076@c MOD file.util
9077@c EN
9078Returns a pathname in which the extension of @var{path} is replaced
9079by @var{newext}.  If @var{path} doesn't have an extension,
9080"." and @var{newext} is appended to @var{path}.
9081
9082If @var{newext} is @code{#f}, it returns @var{path} without extension.
9083@c JP
9084@var{path}の拡張子が@var{newext}に置換されたものが返されます。@code{path}が
9085拡張子を持たない場合は、@var{path}に "." と@var{newext}が追加されます。
9086
9087@var{newext}が@code{#f}の場合は、@var{path}の拡張子が除かれたものが
9088返されます。
9089@c COMMON
9090
9091@example
9092(path-swap-extension "/foo/bar.c" "o")  @result{} "/foo/bar.o"
9093(path-swap-extension "/foo/bar.c" "")   @result{} "/foo/bar."
9094(path-swap-extension "/foo/bar.c" #f)   @result{} "/foo/bar"
9095
9096(path-swap-extension "/foo/bar" "o")  @result{} "/foo/bar.o"
9097(path-swap-extension "/foo/bar" "")   @result{} "/foo/bar."
9098(path-swap-extension "/foo/bar" #f)   @result{} "/foo/bar"
9099@end example
9100@end defun
9101
9102@defun find-file-in-paths name :key paths pred extensions
9103@c MOD file.util
9104@c EN
9105Looks for a file that has name @var{name} in the given list of pathnames
9106@var{paths} and that satisfies a predicate @var{pred}.  If found,
9107the absolute pathname of the file is returned.  Otherwise, @code{#f}
9108is returned.
9109
9110If @var{name} is an absolute path, only the existence of @var{name}
9111and whether it satisfies @var{pred} are checked.
9112
9113The default value of @var{paths} is taken from the environment variable
9114@code{PATH}, and the default value of @var{pred} is @code{file-is-executable?}
9115(@pxref{File attribute utilities}).  That is, @code{find-file-in-paths}
9116searches the named executable file in the command search paths
9117by default.
9118@c JP
9119名前@var{name}を持ち、述語@var{pred}を満たすファイルをパス名のリスト@var{paths}
9120から探します。見つかった場合はファイルの絶対パス名を、見つからなかった場合は
9121@code{#f}を返します。
9122
9123@var{name}が絶対パス名で与えられた場合はそれが存在するかどうかと
9124@var{pred}を満たすかどうかのみがチェックされます。
9125
9126@var{paths}のデフォルト値は環境変数@code{PATH}から取られます。また、
9127@var{pred}のデフォルト値は@code{file-is-executable?}
9128(@ref{File attribute utilities}参照)です。すなわち、デフォルトでは
9129この手続きはコマンドサーチパスから実行可能ファイルを探すのに使えます。
9130@c COMMON
9131
9132@example
9133(find-file-in-paths "ls")
9134  @result{} "/bin/ls"
9135
9136@c EN
9137;; @r{example of searching user preference file of my application}
9138@c JP
9139;; @r{アプリケーション"myapp"のユーザプレファレンスファイルを探す例}
9140@c COMMON
9141(find-file-in-paths "userpref"
9142  :paths `(,(expand-path "~/.myapp")
9143           "/usr/local/share/myapp"
9144           "/usr/share/myapp")
9145  :pred  file-is-readable?)
9146@end example
9147
9148@c EN
9149The @var{extensions} keyword argument may list alternative extensions
9150added to @var{name}.  For example, the following example searches
9151not only @file{notepad}, but also @file{notepad.exe} and @file{notepad.com},
9152in the PATH.  If an alternate name is found,
9153the returned pathname contains the extension.
9154@c JP
9155@var{extensions}キーワード引数には、@var{name}に追加して探すべき拡張子の
9156リストを指定できます。例えば次の例では、@file{notepad}に加え
9157@file{notepad.exe}と@file{notepad.com}がPATHから探されます。
9158拡張子つきの名前が見つかった場合、返されるパスは拡張子を含んだものとなります。
9159@c COMMON
9160
9161@example
9162(find-file-in-paths "notepad" :extensions '("exe" "com"))
9163@end example
9164
9165@c EN
9166For each path, the name and the alternative names are checked in order.
9167That is,
9168if there are @file{/bin/b.com} and @file{/usr/bin/b.exe} and @var{paths}
9169is @code{("/bin" "/usr/bin")}, you'll get @file{/bin/b.com} when you
9170search @file{b} with extensions @code{("exe" "com")}.
9171@c JP
9172各パスについて、@var{name}および拡張子つきの名前が順にチェックされます。
9173すなわち、@file{/bin/b.com}と@file{/usr/bin/b.exe}があって
9174@var{paths}が@code{("/bin" "/usr/bin")}である場合、
9175@var{extensions}に@code{("exe" "com")}を与えて@file{b}を探すと、
9176@file{/bin/b.com}が返ります。
9177@c COMMON
9178@end defun
9179
9180@defun null-device
9181@c MOD file.util
9182@c EN
9183Returns a name of the @emph{null} device.
9184On unix platforms (including cygwin) it returns @code{"/dev/null"},
9185and on Windows native platforms (including mingw) it returns @code{"NUL"}.
9186@c JP
9187nullデバイス名を返します。cygwinを含むunixプラットフォームでは
9188@code{"/dev/null"}、mingwを含むWindowsネイティブプラットフォームでは
9189@code{"NUL"}が返されます。
9190@c COMMON
9191@end defun
9192
9193@defun console-device
9194@c MOD file.util
9195@c EN
9196Returns a name of the console device.
9197On unix platforms (including cygwin) it returns @code{"/dev/tty"},
9198and on Windows native platforms (including mingw) it returns @code{"CON"}.
9199
9200This function does not guarantee the device is actually available
9201to the calling process.
9202@c JP
9203コンソールデバイス名を返します。cygwinを含むunixプラットフォームでは
9204@code{"/dev/tty"}、mingwを含むWindowsネイティブプラットフォームでは
9205@code{"CON"}が返されます。
9206
9207そのデバイスが実際に現在のプロセスから利用可能であるかどうかはチェックされません。
9208@c COMMON
9209@end defun
9210
9211
9212@node File attribute utilities, File operations, Pathname utilities, Filesystem utilities
9213@subsection File attribute utilities
9214@c NODE ファイル属性ユーティリティ
9215
9216@defun file-type path :key follow-link?
9217@defunx file-perm path :key follow-link?
9218@defunx file-mode path :key follow-link?
9219@defunx file-ino path :key follow-link?
9220@defunx file-dev path :key follow-link?
9221@defunx file-rdev path :key follow-link?
9222@defunx file-nlink path :key follow-link?
9223@defunx file-uid path :key follow-link?
9224@defunx file-gid path :key follow-link?
9225@defunx file-size path :key follow-link?
9226@defunx file-atime path :key follow-link?
9227@defunx file-mtime path :key follow-link?
9228@defunx file-ctime path :key follow-link?
9229@c MOD file.util
9230@c EN
9231These functions return the attribute of file/directory specified by
9232@var{path}.  The attribute name corresponds to the slot name of
9233@code{<sys-stat>} class (@pxref{File stats}).
9234If the named path doesn't exist, @code{#f} is returned.
9235
9236If @var{path} is a symbolic link, these functions queries the
9237attributes of the file pointed by the link, unless
9238an optional argument @var{follow-link?} is given and false.
9239
9240MzScheme and Chicken have @code{file-size}.  Chicken also has
9241@code{file-modification-time}, which is @code{file-mtime}.
9242@c JP
9243これらの手続きは@var{path}で示されるファイルやディレクトリのアトリビュートを
9244返します。アトリビュート名は@code{<sys-stat>}のスロット名に対応しています。
9245@ref{File stats}を参照して下さい。@var{path}で示されるファイルが
9246存在しなければ@code{#f}が返されます。
9247
9248@var{path}がシンボリックリンクだった場合、オプショナルな引数
9249@var{follow-link?} に偽の値が与えられていない限り、これらの手続きは
9250リンクの指す先のファイルに関する情報を返します。
9251
9252MzSchemeとChickenには@code{file-size}があります。
9253Chickenには@code{file-modification-time}があり、これは@code{file-mtime}と
9254同じです。
9255@c COMMON
9256@end defun
9257
9258@defun file-is-readable? path
9259@defunx file-is-writable? path
9260@defunx file-is-executable? path
9261@c MOD file.util
9262@c EN
9263Returns @code{#t} if @var{path} exists and readable/writable/executable
9264by the current effective user, respectively.
9265This API is taken from STk.
9266@c JP
9267@var{path}が存在して、現在の実効ユーザがそれぞれ読み取り/書き込み/実行可能なら@code{#t}を
9268返します。
9269このAPIはSTkから取られました。
9270@c COMMON
9271@end defun
9272
9273@defun file-is-symlink? path
9274@c MOD file.util
9275@c EN
9276Returns @code{#t} if @var{path} exists and a symbolic link.
9277See also @code{file-is-regular?} and @code{file-is-directory?} in
9278@ref{File stats}.
9279@c JP
9280@var{path}が存在して、それがシンボリックリンクなら@code{#t}を返します。
9281(参照:@ref{File stats}の@code{file-is-regular?}, @code{file-is-directory?}).
9282@c COMMON
9283@end defun
9284
9285@defun file-eq? path1 path2
9286@defunx file-eqv? path1 path2
9287@defunx file-equal? path1 path2
9288@c MOD file.util
9289@c EN
9290Compares two files specified by @var{path1} and @var{path2}.
9291@code{file-eq?} and @code{file-eqv?} checks if @var{path1} and @var{path2}
9292refers to the identical file, that is, whether they are on the same
9293device and have the identical inode number.  The only difference is
9294when the last component of @var{path1} and/or @var{path2} is a symbolic
9295link, @code{file-eq?} doesn't resolve the link (so compares the links
9296themselves) while @var{file-eqv?} resolves the link and compares the
9297files referred by the link(s).
9298@c JP
9299@var{path1}と@var{path2}で示されるファイルを比較します。
9300@code{file-eq?}と@code{file-eqv?}は@var{path1}と@var{path2}が
9301全く同一のファイルを参照しているかどうか、すなわち、同じデバイス上にあり同じ
9302inode番号を持つかどうかをチェックします。二つの手続きの違いは、
9303@code{path1}や@var{path2}の最後のコンポーネントがシンボリックリンクで
9304あった場合に、@var{file-eq?}はリンクそのものの比較をするが
9305@code{file-eqv?}はリンクを辿った先のファイルの比較をする、という点です。
9306@c COMMON
9307
9308@c EN
9309@code{file-equal?} compares @var{path1} and @var{path2} considering their
9310content, that is, when two are not the identical file in the sense of
9311@code{file-eqv?}, @code{file-equal?} compares their content and returns
9312@code{#t} if all the bytes match.
9313@c JP
9314@code{file-equal?}は@var{path1}と@var{path2}をその内容まで考慮して比較します。
9315すなわち、二つのファイルが@code{file-eqv?}の意味で同一でなかった場合、
9316@code{file-equal?}はファイルの内容を比較し、全てが一致した場合に@code{#t}を返します。
9317@c COMMON
9318
9319@c EN
9320The behavior of @code{file-equal?} is undefined
9321when @var{path1} and @var{path2} are both directories.
9322Later, it may be extended to scan the directory contents.
9323@c JP
9324@var{path1}と@var{path2}ともにディレクトリが与えられた場合の
9325@code{file-equal?}の動作は未定義です。将来、ディレクトリ内容を
9326スキャンするような拡張が加えられるかもしれません。
9327@c COMMON
9328@end defun
9329
9330@deffn {Generic Function} file-mtime=? f1 f2
9331@deffnx {Generic Function} file-mtime<? f1 f2
9332@deffnx {Generic Function} file-mtime<=? f1 f2
9333@deffnx {Generic Function} file-mtime>? f1 f2
9334@deffnx {Generic Function} file-mtime>=? f1 f2
9335@c MOD file.util
9336@c EN
9337Compares file modification time stamps.  There are a bunch of methods defined,
9338so each argument can be either one of the followings.
9339
9340@itemize @bullet
9341@item
9342String pathname.   The mtime of the specified path is used.
9343@item
9344@code{<sys-stat>} object (@pxref{File stats}).
9345The mtime is taken from the stat structure.
9346@item
9347@code{<time>} object.  The time is used as the mtime.
9348@item
9349Number.  It is considered as the number of seconds since Unix Epoch, and
9350used as mtime.
9351@end itemize
9352@c JP
9353二つのファイルの変更時間を比較します。それぞれの引数に対して、
9354次のような型のオブジェクトが渡せるようなメソッドが定義されています。
9355
9356@itemize @bullet
9357@item
9358文字列のパス名。そのパス名で示されるファイルから変更時間が取られます。
9359@item
9360@code{<sys-stat>}オブジェクト (@pxref{File stats})。
9361stat構造体から変更時間が取られます。
9362@item
9363@code{<time>}オブジェクト。その示す時間が変更時間と考えられます。
9364@item
9365数値。変更時間をUnix Epochからの秒数で表したものと見なされます。
9366@end itemize
9367@c COMMON
9368
9369@example
9370@c EN
9371;; @r{compare "foo.c" is newer than "foo.o"}
9372@c JP
9373;; @r{"foo.c" より "foo.o" が新しいかどうか調べる}
9374@c COMMON
9375(file-mtime>? "foo.c" "foo.o")
9376
9377@c EN
9378;; @r{see if "foo.log" is updated within last 24 hours}
9379@c JP
9380;; @r{"foo.log"が過去24時間以内に更新されたかどうかを調べる}
9381@c COMMON
9382(file-mtime>? "foo.c" (- (sys-time) 86400))
9383@end example
9384@end deffn
9385
9386@deffn {Generic Function} file-ctime=? f1 f2
9387@deffnx {Generic Function} file-atime=? f1 f2
9388@findex file-ctime<?
9389@findex file-ctime<=?
9390@findex file-ctime>?
9391@findex file-ctime>=?
9392@findex file-atime<?
9393@findex file-atime<=?
9394@findex file-atime>?
9395@findex file-atime>=?
9396@c MOD file.util
9397@c EN
9398Same as @code{file-mtime=?}, except these checks file's change time
9399and access time, respectively.
9400All the variants of @code{<}, @code{<=}, @code{>}, @code{>=} are also
9401defined.
9402@c JP
9403@code{file-mtime=?}と同じですが、ファイルの属性変更時間とアクセス時間に
9404関して比較します。
9405@code{<}, @code{<=}, @code{>}, @code{>=}を使う関数も同様に定義されています。
9406@c COMMON
9407@end deffn
9408
9409@node File operations, Temporary files and directories, File attribute utilities, Filesystem utilities
9410@subsection File operations
9411@c NODE ファイル操作
9412
9413@defun touch-file path :key (time #f) (type #f) (create #t)
9414@defunx touch-files paths :key (time #f) (type #f) (create #t)
9415@c MOD file.util
9416@c EN
9417Updates timestamp of @var{path}, or each path in the list @var{paths},
9418to the current time.  If the specified path
9419doesn't exist, a new file with size zero is created, unless
9420the keyword argument @var{create} is @code{#f}.
9421
9422If the keyword argument @var{time} is given and not @code{#f}, it
9423must be a nonnegative real number.  It is used as the timestamp value
9424instead of the current time.
9425
9426The keyword argument @var{type} can be @code{#f} (default), a symbol
9427@code{atime} or @code{mtime}.  If it is a symbol, only the access time
9428or modification time is updated.
9429
9430Note: @code{touch-files} processes one file at a time, so the timestamp
9431of each file may not be exactly the same.
9432
9433These procedures are built on top of the system call
9434@code{sys-utime} (@pxref{File stats}).
9435@c JP
9436@var{path}もしくはリスト@var{paths}中の各パスの
9437タイムスタンプを現在の時刻に更新します。
9438指定されたパスが存在しなかった場合、キーワード引数@var{create}が@code{#f}でなければ、
9439その名前で大きさゼロのファイルが作成されます。
9440
9441キーワード引数@var{time}が与えられて@code{#f}でない場合、それは
9442非負の実数でなければなりません。現在の時刻のかわりにその値がタイムスタンプとして使われます。
9443
9444キーワード引数@var{type}は@code{#f}(デフォルト)か、シンボル@code{atime}もしくは
9445@code{mtime}です。シンボルの場合は、それぞれアクセス時刻か変更時刻のみが更新されます。
9446
9447註:@code{touch-files}はファイルをひとつづつ処理するので、各ファイルの
9448タイムスタンプが完全に同一にはならない可能性があります。
9449
9450これらの手続きはシステムコール@code{sys-utime}を使って作られています
9451(@ref{File stats}参照)。
9452@c COMMON
9453@end defun
9454
9455@defun copy-file src dst :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
9456@c MOD file.util
9457@c EN
9458Copies file from @var{src} to @var{dst}.  The source file @var{src} must exist.
9459The behavior when the destination @var{dst} exists varies by the keyword
9460argument @var{if-exists};
9461
9462@table @code
9463@item :error
9464(Default) Signals an error when @var{dst} exists.
9465@item :supersede
9466Replaces @var{dst} to the copy of @var{src}.
9467@item :backup
9468Keeps @var{dst} by renaming it.
9469@item :append
9470Append the @var{src}'s content to the end of @var{dst}.
9471@item #f
9472Doesn't copy and returns @code{#f} when @var{dst} exists.
9473@end table
9474@c JP
9475ファイル@var{src}を@var{dst}へコピーします。コピー元ファイル@var{src}は
9476存在していなければなりません。コピー先ファイル@var{dst}が存在していた場合の
9477ふるまいはキーワード引数@var{if-exists}によって以下のように指定されます。
9478
9479@table @code
9480@item :error
9481(デフォルト) @var{dst}が存在していたらエラーを通知する。
9482@item :supersede
9483@var{dst}を@var{src}のコピーで置き換える。
9484@item :backup
9485@var{dst}の名前を変えてキープする。
9486@item :append
9487@var{dst}の末尾に@var{src}の内容を追加する。
9488@item #f
9489@var{dst}が存在していたらコピーをせず@code{#f}を返す。
9490@end table
9491@c COMMON
9492
9493@c EN
9494@code{Copy-file} returns @code{#t} after completion.
9495@c JP
9496@code{copy-file}はコピーが完了したら@code{#t}を返します。
9497@c COMMON
9498
9499@c EN
9500If @var{src} is a symbolic link, @code{copy-file} follows the
9501symlink and copies the actual content by default.  An error
9502is raised if @var{src} is a dangling symlink.
9503
9504Giving @code{#f} to the keyword argument @var{follow-link?}
9505makes @code{copy-file} to copy the link itself.
9506It is possible that @var{src} is a dangling
9507symlink in this case.
9508@c JP
9509@var{src}がシンボリックリンクであった場合、@code{copy-file}は
9510デフォルトでリンクを辿ります。つまり、ファイルの実体がコピーされます。
9511@var{src}が存在しないパスを指すシンボリックリンクであった場合は
9512エラーが通知されます。
9513
9514キーワード引数@var{follow-link?}に@code{#f}を与えることで、
9515@code{copy-link}にシンボリックリンクそのものをコピーさせることも
9516できます。この場合、@var{src}が存在しないパスを指すシンボリックリンクで
9517あっても構いません。
9518@c COMMON
9519
9520@c EN
9521If @var{if-exists} is @code{:backup}, the keyword argument @var{backup-suffix}
9522specifies the suffix attached to the @var{dst} to be renamed.
9523The default value is @code{".orig"}.
9524@c JP
9525@var{if-exists}が@code{:backup}である場合、
9526@var{dst}がリネームされる名前は
9527@var{dst}にキーワード引数@var{backup-suffix}で指定されるサフィックスを
9528付けたものとなります。デフォルト値は@code{".orig"}です。
9529@c COMMON
9530
9531@c EN
9532By default, @code{copy-file} starts copying to @var{dst} directly.
9533However, if the keyword argument @var{safe} is a true value,
9534it copies the file to a temporary file in the same directory of @var{dst},
9535then renames it to @var{dst} when copy is completed.
9536(When @var{safe} is true and @var{if-exists} is @code{:append},
9537we first copy the content of @var{dst} to a temporary file if @var{dst}
9538exists, appends the content of @var{src}, then renames the result to @var{dst}).
9539If copy is interrupted for some reason, the filesystem is "rolled back"
9540properly.
9541
9542@c JP
9543デフォルトでは@code{copy-file}は直接@var{dst}にコピーを行いますが、
9544キーワード引数@var{safe}に真の値が与えられた場合は、@var{dst}と同じディレクトリ
9545内の一時ファイルにまずコピーし、それが完了した時点で@var{dst}へとリネームします。
9546(@var{safe}が真でかつ@var{if-exists}が@code{:append}であった場合は、
9547@var{dst}があればまずその内容を一時ファイルにコピーし、そこに@var{src}の内容を
9548追加し、最後にそれを@var{dst}へリネームします。)
9549コピーが何らかの理由で中断された場合、ファイルシステムはコピー前の状態へと
9550「ロールバック」されます。
9551@c COMMON
9552
9553@c EN
9554If the keyword argument @var{keep-timestamp} is true, @code{copy-file}
9555sets the destination's timestamp to the same as the source's timestamp
9556after copying.
9557@c JP
9558キーワード引数@var{keep-timestamp}に真の値が与えられた場合は、
9559@code{copy-file}はコピー後にコピー先のファイルのタイムスタンプを
9560コピー元のタイムスタンプに合わせます。
9561@c COMMON
9562
9563@c EN
9564If the keyword argument @var{keep-mode} is true, the destination file's
9565permission bits are set to the same as the source file's.  If it is false
9566(default), the destination file's permission remains the same if
9567the destination already exists and the @var{safe} argument is false,
9568otherwise it becomes @code{#o666} masked by umask settings.
9569@c JP
9570キーワード引数@var{keep-mode}に真の値が与えられた場合は、
9571コピー先のファイルのパーミッションビットはコピー元のそれに合わせられます。
9572@var{keep-mode}が偽の場合(デフォルト)は、コピー先が既に存在して
9573@var{safe}引数が偽の場合にコピー先のもとのパーミッションが保持され、
9574そうでなければ@code{#o666}がumaskセッティングによってマスクされた
9575値となります。
9576@c COMMON
9577@end defun
9578
9579@c @defun copy-files files dstdir :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
9580@c @c EN
9581@c Copies each file in a list @var{files} to the destination @var{dstdir}, which
9582@c must be an existing directory.  The keyword arguments are passed
9583@c to @code{copy-file}.
9584@c @c JP
9585@c リスト@var{files}中の各ファイルをディレクトリに@var{dstdir}にコピーします。
9586@c @var{dstdir}は既に存在しなければなりません。
9587@c キーワード引数はそのまま@code{copy-file}に渡されます。
9588@c @c COMMON
9589@c @end defun
9590
9591@defun move-file src dst :key if-exists backup-suffix
9592@c MOD file.util
9593@c EN
9594Moves file @var{src} to @var{dst}.   The source @var{src} must exist.
9595The behavior when @var{dst} exists varies by the keyword argument
9596@var{if-exists}, as follows.
9597@table @code
9598@item :error
9599(Default) Signals an error when @var{dst} exists.
9600@item :supersede
9601Replaces @var{dst} by @code{src}.
9602@item :backup
9603Keeps @var{dst} by renaming it.
9604@item #f
9605Doesn't move and returns @code{#f} when @var{dst} exists.
9606@end table
9607@c JP
9608ファイル@var{src}を@var{dst}へ移動します。移動元ファイル@var{src}は
9609存在していなければなりません。移動先ファイル@var{dst}が存在した場合の
9610ふるまいはキーワード引数@var{if-exists}によって以下のように指定されます。
9611@table @code
9612@item :error
9613(デフォルト) @var{dst}が存在していたらエラーを通知する。
9614@item :supersede
9615@var{dst}を@code{src}で置き換える。
9616@item :backup
9617@var{dst}の名前を変えてキープする。
9618@item #f
9619@var{dst}が存在していたら移動をせず@code{#f}を返す。
9620@end table
9621@c COMMON
9622
9623@c EN
9624@code{Move-file} returns @code{#t} after completion.
9625@c JP
9626@code{move-file}は移動が完了したら@code{#t}を返します。
9627@c COMMON
9628
9629@c EN
9630If @var{if-exists} is @code{:backup}, the keyword argument @var{backup-suffix}
9631specifies the suffix attached to the @var{dst} to be renamed.
9632The default value is @code{".orig"}.
9633@c JP
9634@var{if-exists}が@code{:backup}である場合、@var{dst}がリネームされる
9635名前は@var{dst}にキーワード引数@var{backup-suffix}で指定されるサフィックスを
9636付けたものとなります。デフォルト値は@code{".orig"}です。
9637@c COMMON
9638
9639@c EN
9640The file @var{src} and @var{dst} can be on the different filesystem.
9641In such a case, @code{move-file} first copies @var{src} to the
9642temporary file on the same directory as @var{dst}, then renames
9643it to @var{dst}, then removes @var{src}.
9644@c JP
9645ファイル@var{src}と@var{dst}は別のファイルシステム上にあっても構いません。
9646その場合、@code{move-file}はまず@var{src}を@var{dst}と同じディレクトリの
9647一時ファイルにコピーし、それを@var{dst}にリネームし、それから
9648@var{src}を消去します。
9649@c COMMON
9650@end defun
9651
9652@c @defun move-files files dstdir :key if-exists backup-suffix
9653@c @c EN
9654@c Moves each file in a list @var{files} to @var{dstdir},
9655@c which must be an existing directory.  Keyword arguments
9656@c are passed to @code{move-file}.
9657@c @c JP
9658@c リスト@var{files}中の各ファイルをディレクトリ@var{dstdir}に移動します。
9659@c @var{dstdir}は既に存在しなければなりません。
9660@c キーワード引数はそのまま@code{move-file}に渡されます。
9661@c @c COMMON
9662@c @end defun
9663
9664@defun remove-file filename
9665@defunx delete-file filename
9666[R7RS file]
9667@c MOD file.util
9668@c EN
9669Removes the named file.  An error is signalled if @var{filename}
9670does not exist, is a directory, or cannot be deleted with other
9671reasons such as permissions.
9672R7RS defines @code{delete-file}.
9673
9674Compare with @code{sys-unlink} (@pxref{Directory manipulation}),
9675which doesn't raise an error when the named file doesn't exist.
9676@c JP
9677指定された名前のファイルを消去します。ファイルが存在しなかったり、ディレクトリであったり、
9678パーミッションがなく消去できなかった場合等にはエラーが報告されます。
9679@code{delete-file}はR7RSで定義されています。
9680
9681@code{sys-unlink}と似ていますが、@code{sys-unlink}はファイルが無かった場合に
9682エラーをあげず@code{#f}を返すことに注意。(@ref{Directory manipulation}参照。)
9683@c COMMON
9684@end defun
9685
9686@defun remove-files paths
9687@defunx delete-files paths
9688@c MOD file.util
9689@c EN
9690Removes each path in a list @var{paths}.  If the path is
9691a file, it is @code{unlink}ed.  If it is a directory,
9692its contents are recursively removed by @code{remove-directory*}.
9693If the path doesn't exist, it is simply ignored.
9694
9695@code{delete-files} is just an alias of @code{remove-files}.
9696@c JP
9697リスト@var{paths}中の各パスを削除します。パスがファイルの場合は
9698@code{unlink}し、ディレクトリの場合は@code{remove-directory*}を
9699使って再帰的にその内容を消去します。存在しないパスは単に無視されます。
9700
9701@code{delete-files}は@code{remove-files}の別名です。
9702@c COMMON
9703@end defun
9704
9705
9706@defun file->string filename options @dots{}
9707@defunx file->list reader filename options @dots{}
9708@defunx file->string-list filename options @dots{}
9709@defunx file->sexp-list filename options @dots{}
9710@c MOD file.util
9711@c EN
9712Convenience procedures to read from a file @var{filename}.
9713They first open the named file, then call @code{port->string},
9714@code{port->list}, @code{port->string-list} and @code{port->sexp-list}
9715on the opened file, respectively.  (@pxref{Input utility functions}).
9716The file is closed if all the content is read or an error is
9717signaled during reading.
9718@c JP
9719ファイル @var{filename} から読み込むための便利手続き。
9720これらの手続きは、まず、指定された名前のファイルをオープンし、その
9721オープンしたファイルに対してそれぞれ @code{port->string}、
9722@code{port->list}、@code{port->string-list} および @code{port->sexp-list}
9723を呼びます(@ref{Input utility functions}参照)。すべての内容が読み込まれる
9724かまたは読み込み中にエラーシグナルがあがれば、ファイルはクローズされます。
9725@c COMMON
9726
9727@c EN
9728Those procedures take the same keyword arguments as
9729@code{call-with-input-file}.
9730When the named file doesn't exist, the behavior depends on
9731@var{:if-does-not-exist} keyword argument---an error is signaled
9732if it is @code{:error}, and @code{#f} is returned if the argument is
9733@code{#f}.
9734@c JP
9735これらの手続きは@code{call-with-input-file}と同じキーワード引数を取ります。
9736ファイルが見つからなかった場合の振舞いは
9737キーワード引数@code{:if-does-not-exist}によって指定できます。
9738それが@code{:error}ならエラーが報告され、
9739@code{#f}なら@code{#f}が返されます。
9740@c COMMON
9741@end defun
9742
9743@defun string->file filename string options @dots{}
9744@defunx list->file writer filename lis options @dots{}
9745@defunx string-list->file filename lis options @dots{}
9746@defunx sexp-list->file filenme lis options @dots{}
9747@c MOD file.util
9748@c EN
9749Opposite of @code{file->string} etc.  They are convenient
9750to quickly write out things into a file.
9751
9752NB: The name @code{string->file} etc. might suggest they would take the
9753object to be written as the first argument.  We decided to put @var{filename}
9754first, since in the situations where these procedures are used,
9755it is more likely that one want to write literal data, which would be
9756bigger than the filename itself.
9757
9758The options part is passed to @code{call-with-output-file} as is.
9759For example, the following code appends the text when @file{foo.txt}
9760already exists:
9761@c JP
9762@code{file->string}等の逆を行う手続きです。
9763手軽にファイルに何かを書き出したい時に便利です。
9764
9765註: @code{string->file}等の名前からして、
9766書き出されるオブジェクトを第一引数にする方が慣習にあっているかもしれません。
9767けれども、実際にこれらの手続きが使われる場面では、書き出されるオブジェクトとして
9768リテラルデータが来る場合も多く、だとするとより短いファイル名を先にした方が
9769読み書きしやすいだろうと考え、@var{filename}を先に持ってきてあります。
9770
9771@var{options} @dots{}部分はそのまま@code{call-with-output-file}に
9772渡されます。次の例は@file{foo.txt}が存在していればそれにデータを書き足します。
9773@c COMMON
9774
9775@example
9776(string->file "foo.txt" "New text to append\n"
9777              :if-exists :append)
9778@end example
9779
9780@c EN
9781The @code{list->file} takes @var{writer} argument, which is a procedure
9782that receives two arguments, an element from the list @var{lis}, and an
9783output port.  It should write out the element to the port in a suitable
9784way.  The @code{string-list->file} and @code{sexp-list->file} are
9785specialized versions of @code{list->file}, where @code{string-list->file}
9786uses @code{(^[s p] (display s p) (newline p))} as @var{writer},
9787and @code{sexp-list->file} uses
9788@code{(^[s p] (write s p) (newline p))} as @var{writer}.
9789@c JP
9790@code{list->file}が取る@var{writer}引数は、リスト@var{lis}からのひとつの要素と
9791出力ポートの二つの引数を取る手続きで、適切な形式で要素をポートに書き出します。
9792@code{string-list->file}と@code{sexp-list->file}は
9793@code{list->file}の特化したバージョンで、
9794@code{string-list->file}はwriterとして@code{(^[s p] (display s p) (newline p))}を、
9795@code{sexp-list->file}はwriterとして@code{(^[s p] (write s p) (newline p))}を
9796使います。
9797@c COMMON
9798@end defun
9799
9800
9801@node Temporary files and directories, Lock files, File operations, Filesystem utilities
9802@subsection Temporary files and directories
9803@c NODE 一時ファイルとディレクトリ
9804
9805@deffn {Parameter} temporary-directory
9806@c MOD file.util
9807@c EN
9808A parameter that keeps the name of the directory that can be used
9809to create a temporary files.   The default value is
9810the one returned from @code{sys-tmpdir} (@pxref{Pathnames}).
9811The difference of @code{sys-tmpdir} is that, since this is a parameter,
9812it can be overridden by application during execution.
9813Libraries are recommended to use this instead of @code{sys-tmpdir}
9814for greater flexibility.
9815@c JP
9816一時ファイルを作るのに適したディレクトリ名を保持しているパラメータです。
9817デフォルトの値は@code{sys-tmpdir}の戻り値です (@ref{Pathnames}参照)。
9818@code{sys-tmpdir}との違いは、これはパラメータなので
9819アプリケーションが実行時に変更できることです。
9820ライブラリは柔軟性を高めるためにできるだけ@code{sys-tmpdir}よりは
9821こちらを利用するのが良いでしょう。
9822@c COMMON
9823@end deffn
9824
9825@defun call-with-temporary-file proc :key directory prefix
9826@c MOD file.util
9827@c EN
9828Creates a temporary file with a unique name and opens it for output,
9829then calls @var{proc} with the output port and the temporary file's name.
9830The temporary file is removed after either @var{proc} returns
9831or raises an uncaught error.
9832Returns the value(s) @var{proc} returns.
9833
9834The temporary file is created in the directory @var{directory},
9835with the name @var{prefix} followed by several random alphanumeric characters.
9836When omitted, the value of @code{(temporary-directory)} is used
9837for @var{directory}, and @code{"gtemp"} for @var{prefix}.
9838
9839The name passed to @var{proc} consists of @var{directory} and
9840the file's name.  So whether the name is absolute or relative pathname
9841depends on the value of @var{directory}.
9842
9843@example
9844(call-with-temporary-file (^[_ name] name)
9845 @result{} @r{Something like "/tmp/gtemp4dSpMh"}
9846@end example
9847
9848You can keep the output file by renaming it in @var{proc}.  But if doing so,
9849make sure to specify @var{directory} so that the temporary file
9850is created in the same directory as the final output; rename
9851may not work across filesystems.
9852
9853Internally, it calls @code{sys-mkstemp} to create a unique file.
9854@xref{Directory manipulation}, for the details.
9855@c JP
9856一意な名前を持つ一時ファイルを作成し、出力用にオープンして、
9857その出力ポートと名前を引数として@var{proc}を呼びます。
9858一時ファイルは、@var{proc}から戻った場合でも、@var{proc}がエラーを投げた場合でも、
9859消去されます。
9860@var{proc}の返す値(複数可)が@code{call-with-temporary-file}の戻り値となります。
9861
9862一時ファイルはディレクトリ@var{directory}以下に作られ、
9863その名前は@var{prefix}の後にいくつかの英数字を付け加えたものになります。
9864省略された場合、@code{(temporary-directory)}の値が@var{directory}に、
9865@code{"gtemp"}が@var{prefix}に使われます。
9866
9867@var{proc}に渡される名前は@var{directory}とファイル名をつなげたパス名です。
9868絶対パスになるか相対パスになるかは@var{directory}の値によります。
9869
9870@example
9871(call-with-temporary-file (^[_ name] name)
9872 @result{} @r{例えば "/tmp/gtemp4dSpMh"}
9873@end example
9874
9875出力したファイルを取っておきたい場合は、@var{proc}の中でリネームしてください。
9876その場合、最終的なファイルと同じディレクトリに一時ファイルを作るように、
9877@var{directory}引数を指定するのを忘れないように。
9878ファイルシステムをまたぐリネームはうまくいかない場合があります。
9879
9880内部的に、この手続きは@code{sys-mkstemp}を呼んで一意なファイルを作っています。
9881@code{sys-mkstemp}については@ref{Directory manipulation}参照。
9882@c COMMON
9883@end defun
9884
9885@defun call-with-temporary-directory proc :key directory prefix
9886@c MOD file.util
9887@c EN
9888Creates a temporary directory with unique name,
9889then calls @var{proc} with the name.
9890The temporary directory and its contents are removed
9891after either @var{proc} returns
9892or raises an uncaught error.
9893Returns the value(s) @var{proc} returns.
9894
9895The temporary directory is created in the directory @var{directory},
9896with the name @var{prefix} followed by several random alphanumeric characters.
9897When omitted, the value of @code{(temporary-directory)} is used
9898for @var{directory}, and @code{"gtemp"} for @var{prefix}.
9899
9900The name passed to @var{proc} consists of @var{directory} and
9901the directory name.  So whether the name is absolute or relative pathname
9902depends on the value of @var{directory}.
9903
9904Internally, it calls @code{sys-mkdtemp} to create a unique file.
9905@xref{Directory manipulation}, for the details.
9906@c JP
9907一意な名前を持つ一時ディレクトリを作成し、
9908その名前を引数として@var{proc}を呼びます。
9909一時ディレクトリは、@var{proc}から戻った場合でも、@var{proc}がエラーを投げた場合でも、
9910消去されます。
9911@var{proc}の返す値(複数可)が@code{call-with-temporary-directory}の戻り値となります。
9912
9913一時ディレクトリはディレクトリ@var{directory}以下に作られ、
9914その名前は@var{prefix}の後にいくつかの英数字を付け加えたものになります。
9915省略された場合、@code{(temporary-directory)}の値が@var{directory}に、
9916@code{"gtemp"}が@var{prefix}に使われます。
9917
9918@var{proc}に渡される名前は@var{directory}とファイル名をつなげたパス名です。
9919絶対パスになるか相対パスになるかは@var{directory}の値によります。
9920
9921内部的に、この手続きは@code{sys-mkdtemp}を呼んで一意なディレクトリを作っています。
9922@code{sys-mkstemp}については@ref{Directory manipulation}参照。
9923@c COMMON
9924@end defun
9925
9926@node Lock files,  , Temporary files and directories, Filesystem utilities
9927@subsection Lock files
9928@c NODE ロックファイル
9929
9930@c EN
9931Exclusivity of creating files or directories is often used
9932for inter-process locking.   The following procedure provides
9933a packaged interface for it.
9934@c JP
9935ファイルやディレクトリを作成する排他性は、しばしばプロセス間のロックに
9936使われます。以下の手続きはパッケージ化されたインタフェースを提供します。
9937@c COMMON
9938
9939@defun with-lock-file lock-name thunk :key type retry-interval @
9940                      retry-limit secondary-lock-name retry2-interval @
9941                      retry2-limit perms abandon-timeout
9942@c MOD file.util
9943@c EN
9944Exclusively creates a file or a directory (@emph{lock file})
9945with @var{lock-name}, then executes @var{thunk}.
9946After @var{thunk} returns, or an error is thrown in it,
9947the lock file is removed.  When @var{thunk} returns normally,
9948its return values become the return values of @code{with-lock-file}.
9949@c JP
9950@var{lock-name}という名前を持つファイルもしくはディレクトリ (ここでは
9951@emph{ロックファイル}と呼びます) を排他的に作成し、
9952@var{thunk}を実行します。@var{thunk}から戻ってくるか、エラーが投げられたら、
9953ロックファイルは削除されます。@var{thunk}が正常に戻ってきた場合、
9954その戻り値が@code{with-lock-file}の戻り値となります。
9955@c COMMON
9956
9957@c EN
9958If the lock file already exists, @code{with-lock-file} waits and retries
9959getting the lock until timeout reaches.  It can be configured by
9960the keyword arguments.
9961@c JP
9962ロックファイルが既に存在していた場合、@code{with-lock-file}はタイムアウトになるまで
9963少し待ってリトライすることを続けます。細かい動作はキーワード引数で指定できます。
9964@c COMMON
9965
9966@c EN
9967There's a chance that @code{with-lock-file} leaves the lock file
9968when it gets a serious error situation and doesn't have the opportunity
9969to clean up.  You can allow @code{with-lock-file} to @emph{steal}
9970the lock if its timestamp is too old; say, if you know that the
9971applications usually locks just for seconds, and you find the lock
9972file is 10 minutes old, then it's likely that the previous
9973process was terminated abruptly and couldn't clean it up.
9974You can also configure this behavior by the keyword arguments.
9975@c JP
9976@code{with-lock-file}実行中に深刻なエラーによって、ロックファイルを消せずに
9977プロセスが終了してしまう可能性があります。そのため、
9978@code{with-lock-file}は、ロックファイルのタイムスタンプが非常に古い場合には
9979ロックを@emph{盗む}ことを許しています。例えば、通常アプリケーションはたかだか数秒しか
9980ロックしないはずなのに、10分前のタイムスタンプを持つロックファイルを見つけたとしたら、
9981以前のプロセスがクリーンアップをせずに落ちてしまったことは十分考えられるでしょう。
9982この振る舞いも、キーワード引数で制御することができます。
9983@c COMMON
9984
9985@c EN
9986Internally, @emph{two} lock files are used to implement this
9987stealing behavior safely.  The creation and removal of the primary
9988lock file (named by @var{lock-name} argument) are guarded by
9989the secondary lock file (named by @var{secondary-lock-file} argument,
9990defaulted by @code{.2} suffix attached to @var{lock-name}).
9991The secondary lock prevents more than one process steals
9992the same primary lock file simultaneously.
9993@c JP
9994内部的には、安全な「盗ロック」を実現するために、二つのロックファイルが使われています。
9995主ロックファイル(@var{lock-name}で指定される名前を持つもの)の作成と削除の
9996操作がそれぞれ、副ロックファイル(@var{secondary-lock-file}で指定される名前を
9997持つもの。指定が省略された場合は@var{lock-name}にサフィックス@code{.2}をつけたもの)
9998によって保護されます。
9999副ロックは、二つ以上のプロセスが主ロックファイルを同時に盗もうとした場合を保護します。
10000@c COMMON
10001
10002@c EN
10003The secondary lock is acquired for a very short period so there's
10004much less chance to be left behind by abnormal terminations.
10005If it happens, however, we just give up; we don't steal the
10006secondary lock.
10007@c JP
10008副ロックファイルによるロックはほぼ常に極めて短い期間に
10009限定されるため、事故により副ロックファイルが残されてしまう可能性は
10010主ロックファイルに比べ非常に小さいです。それでももし副ロックファイルが
10011残されてしまった場合は、@code{with-lock-file}は単に諦めます。副ロックファイルまで
10012盗むことはしません。
10013@c COMMON
10014
10015@c EN
10016If @code{with-lock-file} couldn't get a lock before timeout,
10017a @code{<lock-file-failure>} condition is thrown.
10018@c JP
10019@code{with-lock-file}がタイムアウトまでにロックを獲得できなけば、
10020@code{<lock-file-failure>}コンディションが投げられます。
10021@c COMMON
10022
10023@c EN
10024Here's a list of keyword arguments.
10025@c JP
10026以下のキーワード引数が認識されます。
10027@c COMMON
10028
10029@table @var
10030@item type
10031
10032@c EN
10033It can be either one of the symbols @code{file} or @code{directory}.
10034@c JP
10035シンボル@code{file}か@code{directory}のどちらか。
10036@c COMMON
10037
10038@c EN
10039If it is @code{file}, we use a lock file, relying on the @code{O_EXCL}
10040exclusive creation flag of @code{open(2)}.
10041This is the default value.
10042It works for most platforms;
10043however, some NFS implementation may not implement the exclusive
10044semantics properly.
10045@c JP
10046@code{file}を指定した場合、@code{open(2)}の@code{O_EXCL}フラグを使う
10047排他的ファイル作成を利用したロックファイルを使います。これがデフォルトの動作です。
10048ほとんどのプラッフォームで動作しますが、NFSの実装の一部に、
10049排他的ファイル作成のセマンティクスが正しく実装されていない場合があります。
10050@c COMMON
10051
10052@c EN
10053If it is @code{directory}, we use a lock directory, relying on the
10054atomicity of @code{mkdir(2)}.  It should work for any platforms,
10055but it may be slower than @code{file}.
10056@c JP
10057@code{directory}を指定した場合は、@code{mkdir(2)}の排他性を利用した
10058ロックディレクトリを使います。これはどんなプラットフォームでも動作する
10059はずですが、@code{file}を指定した場合より遅いかもしれません。
10060@c COMMON
10061
10062@item retry-interval
10063@itemx retry-limit
10064
10065@c EN
10066Accepts a nonnegative real number that specifies either
10067the interval to attempt to acquire the primary lock, or the maximum
10068time we should keep retrying, respectively, in seconds.
10069The default value is 1 second interval and 10 second limit.
10070To prevent retrying, give 0 to @var{retry-limit}.
10071@c JP
10072時間を秒で指定する非負の実数を取ります。前者は主ロック獲得を再試行する
10073時間間隔、後者は再試行を繰り返す総時間を指定します。
10074デフォルトはそれぞれ、1秒と10秒です。再試行をしないようにするには、
10075@var{retry-limit}に0を渡してください。
10076@c COMMON
10077
10078@item secondary-lock-name
10079
10080@c EN
10081The name of the secondary lock file (or directory).  If omitted,
10082@var{lock-name} with a suffix @code{.2} attached is used.
10083Note: The secondary lock name must be agreed on all programs that
10084locks the same (primary) lock file.  I recommend to leave this
10085to the default unless there's a good reason to do otherwise.
10086@c JP
10087副ロックファイル(もしくはディレクトリ)の名前を指定します。
10088省略された場合は、@var{lock-name}にサフィックス@code{.2}をつけたものが使われます。
10089副ロックファイルの名前は、同じ(主)ロックファイルを使うプログラム全てで
10090一致していなければなりません。
10091特に変える必要が無ければデフォルトのままにするのが良いでしょう。
10092@c COMMON
10093
10094@item retry2-interval
10095@itemx retry2-limit
10096
10097@c EN
10098Like @var{retry-interval} and @var{retry-limit}, but these specify
10099interval and timeout for the secondary lock file.  The possibility
10100of secondary lock file collision is usually pretty low, so
10101you would hardly need to tweak these.  The default values are
101021 second interval and 10 second limit.
10103@c JP
10104@var{retry-interval}と@var{retry-limit}に似ていますが、
10105こちらは副ロックファイルの再試行間隔と最長再試行時間を指定します。
10106副ロックが衝突する確率は通常極めて低いので、これらのパラメータを
10107調整する必要は滅多に無いでしょう。デフォルトの値はそれぞれ
101081秒と10秒です。
10109@c COMMON
10110
10111@item perms
10112
10113@c EN
10114Specify the permission bitmask of the lock file or directory,
10115in a nonnegative exact integer.  The default is @code{#o644} for
10116a lock file and @code{#o755} for a lock directory.
10117
10118Note that to control who can acquire/release/steal the lock,
10119what matters is
10120the permission of the directory in which the lock file/directory,
10121not the permission of the lock file/directory itself.
10122@c JP
10123ロックファイルもしくはディレクトリのパーミッションを、非負正確整数の
10124ビットマスクで指定します。デフォルトは、ロックファイルに対して@code{#o644}、
10125ロックディレクトリに対しては@code{#o755}です。
10126
10127ロックを獲得/解放したり盗んだりするには、ロックファイル自身のパーミッションではなく、
10128ロックファイルが置かれるディレクトリのパーミッションが関係することに注意してください。
10129@c COMMON
10130
10131@item abandon-timeout
10132
10133@c EN
10134Specifies the period in seconds in a nonnegative real number.
10135If the primary lock file is
10136older than that, @code{with-lock-file} steals the lock.
10137To prevent stealing, give @code{#f} to this argument.
10138The default value is 600 seconds.
10139@c JP
10140時間の長さ(秒)を非負の実数で指定します。
10141@code{with-lock-file}がロックファイルを見つけて、そのタイムスタンプが
10142現在の時刻マイナスこの時間よりも古いものだった場合、ロックを盗みます。
10143ロックを盗むことを禁止したければこの引数に@code{#f}を渡してください。
10144デフォルトは600秒です。
10145@c COMMON
10146
10147@end table
10148
10149@end defun
10150
10151@deftp {Condition type} <lock-file-failure>
10152@c MOD file.util
10153@c EN
10154A condition indicating that @code{with-lock-file} couldn't
10155obtain the lock.  Inherits @code{<error>}.
10156@c JP
10157@code{with-lock-file}がロックを獲得できなかった場合に投げられる
10158コンディションです。@code{<error>}を継承します。
10159@c COMMON
10160
10161@defivar <lock-file-failure> lock-file-name
10162@c EN
10163The primary lock file name.
10164@c JP
10165獲得しようとした主ロックファイルの名前です。
10166@c COMMON
10167@end defivar
10168@end deftp
10169
10170@c EN
10171Gauche also provides OS-supported file locking feature,
10172@code{fcntl} lock, via @code{gauche.fcntl} module.
10173Whether you want to use @code{fcntl} lock or @code{with-lock-file}
10174will depend on your application.
10175@c JP
10176Gaucheは、OSによりサポートされる@code{fcntl}ロックの機能も、
10177@code{gauche.fcntl}モジュールによって提供しています。
10178@code{fcntl}ロックを使うべきか@code{with-lock-file}を使うべきかは、
10179アプリケーションによります。
10180@c COMMON
10181
10182@c EN
10183These are the advantages of the @code{fcntl} lock:
10184@c JP
10185@code{fcntl}ロックの利点は次の通りです。
10186@c COMMON
10187
10188@itemize
10189@item
10190@c EN
10191The lock is removed when the process dies without explicitly unlocking it.
10192@c JP
10193プロセスが死んだ時に、ロックは自動的に解除される
10194@c COMMON
10195@item
10196@c EN
10197You can directly lock the file you're touching.
10198@c JP
10199作業するファイルそのものをロックできる。
10200@c COMMON
10201@item
10202@c EN
10203You can lock a part of a file.
10204@c JP
10205ファイルの一部だけをロックできる。
10206@c COMMON
10207@item
10208@c EN
10209You can have shared (read) and exclusive (write) locks.
10210@c JP
10211共有(読み出し)ロックと排他(書き込み)ロックが使える。
10212@c COMMON
10213@end itemize
10214
10215@c EN
10216In common situations, probably the most handy property is the
10217first one; you don't need to worry about leaving lock behind
10218unexpected process termination.
10219@c JP
10220多くの場合、最も便利なのは最初の性質でしょう。プロセスが予想外に落ちてしまった
10221場合でも、ロックが残されてしまうことを心配しないで済みます。
10222@c COMMON
10223
10224@c EN
10225However, there are a couple of shortcomings in @code{fcntl} locks.
10226@c JP
10227けれども、@code{fcntl}ロックには欠点もあります。
10228@c COMMON
10229
10230@itemize
10231@item
10232@c EN
10233It is not guaranteed to work across different platforms,
10234and/or NFS-mounted filesystems.
10235@c JP
10236異なるプラットフォームや、NFSマウントされたファイルシステム間で
10237確実に動作する保証がない。
10238@c COMMON
10239@item
10240@c EN
10241The lock is per-process, per-file, and non-recursive.
10242If you have a lock in a file,
10243then calls a library that also locks the file, the lock always
10244succeeds.  Worse, if the library unlocks the file,
10245the lock is completely removed, while the caller doesn't know
10246about it.  It also means that, in order to prevent multiple threads
10247in a process from accessing the same file, you have to use
10248mutex along the fcntl lock.
10249@c JP
10250ロックはプロセス単位、ファイル単位でかつ非再帰的である。
10251例えば、既にプロセスがロックしているファイルに対して、呼び出したライブラリ内でまたロックを
10252獲得しようとすると、それは常に成功する。さらに悪いことに、そのライブラリが
10253ロックを解放した時点で、元からロックがかかっていたかどうかに関わらず、プロセス全体が
10254ロックを手放してしまう。このことはまた、複数のスレッド間で排他的にファイルに
10255アクセスしたい場合は、fcntlロックと一緒にmutexも使う必要があるということでもある。
10256@c COMMON
10257@end itemize
10258
10259@c EN
10260Especially because of the second point, it is very difficult
10261to use @code{fcntl} lock unless you have total control over and knowledge
10262of the entire application.
10263It is ok to use the @code{fcntl} lock by the application code to lock
10264the application-specific file.
10265Library developers have difficulty, however, to make sure any potential
10266user of the library won't try to lock the same file as the library tries
10267to lock (usually it's impossible).
10268@c JP
10269二番目の欠点のせいで、アプリケーション全体を知っていてコードを好きにできる場合でなければ、
10270@code{fcntl}ロックを安全に使うことが非常に難しくなっています。
10271アプリケーションコードが、そのアプリケーションで使うためだけのファイルをロックするのに
10272@code{fcntl}ロックを使うのは何も問題ありません。
10273しかしライブラリ開発者は、ライブラリ内で@code{fcntl}ロックを使うなら、
10274そのライブラリのユーザや他のライブラリが将来に渡って同じファイルを決してロックしない
10275ということを保証しなければなりません(通常、そんなことは不可能です)。
10276@c COMMON
10277
10278@c ----------------------------------------------------------------------
10279@node Mathematic constants, Mersenne-Twister random number generator, Filesystem utilities, Library modules - Utilities
10280@section @code{math.const} - Mathematic constants
10281@c NODE 定数, @code{math.const} - 定数
10282
10283@deftp {Module} math.const
10284@mdindex math.const
10285@c EN
10286This module defines several commonly-used mathematic constants.
10287@c JP
10288いくつかの一般的に用いられる数学定数を定義しています。
10289@c COMMON
10290@end deftp
10291
10292@defvr {Constant} pi
10293@defvrx {Constant} pi/2
10294@defvrx {Constant} pi/4
10295@defvrx {Constant} pi/180
10296@defvrx {Constant} 1/pi
10297@defvrx {Constant} 180/pi
10298@c MOD math.const
10299@c EN
10300Bound to pi, pi/2, pi/4, pi/180, 1/pi and 180/pi, respectively.
10301@c JP
10302それぞれ、π、π/2、π/4、π/180、1/π、180/πです。
10303@c COMMON
10304@end defvr
10305
10306@defvr {Constant} e
10307@c MOD math.const
10308Napier's constant.
10309@end defvr
10310
10311@c ----------------------------------------------------------------------
10312@node Mersenne-Twister random number generator, Prime numbers, Mathematic constants, Library modules - Utilities
10313@section @code{math.mt-random} - Mersenne Twister Random number generator
10314@c NODE Mersenne Twister乱数発生器, @code{math.mt-random} - Mersenne Twister乱数発生器
10315
10316@deftp {Module} math.mt-random
10317@mdindex math.mt-random
10318@c EN
10319Provides a pseudo random number generator (RNG) based on
10320"Mersenne Twister" algorithm developed by Makoto Matsumoto and
10321Takuji Nishimura.   It is fast, and has huge period of 2^19937-1.
10322See @url{https://dl.acm.org/citation.cfm?id=272995}, for details about the algorithm.
10323@c JP
10324Makoto MatsumotoとTakuji Nishimuraにより開発された、
10325``Mersenne Twister''アルゴリズムに基づく、
10326仮想的な乱数発生器(RNG)を提供します。
10327高速で、2^19937-1という極めて長大な周期を持ちます。
10328アルゴリズムの詳細については、@url{https://dl.acm.org/citation.cfm?id=272995}を参照して下さい。
10329@c COMMON
10330
10331@c EN
10332For typical use cases of random number generators,
10333we recommend to use @code{srfi-27} which is implemented
10334on top of this module and provides portable API.
10335You should use this module directly only when you need
10336functions that aren't available through @code{srfi-27}.
10337@c JP
10338乱数発生器の通常の用途には、@code{srfi-27}を使うことをお勧めします。
10339@code{srfi-27}はこのモジュールの上に実装されていますが、ポータブルなAPIを提供しています。
10340@code{srfi-27}にない機能が必要な時のみこのモジュールを直接使うようにしてください。
10341@c COMMON
10342@end deftp
10343
10344@deftp {Class} <mersenne-twister>
10345@clindex mersenne-twister
10346@c MOD math.mt-random
10347@c EN
10348A class to encapsulate the state of Mersenne Twister RNG.
10349Each instance of this class has its own state, and can be used
10350as an independent source of random bits if initialized
10351by individual seed.
10352
10353The random seed value can be given at the instantiation time
10354by @code{:seed} initialization argument, or by using
10355@code{mt-random-set-seed!} described below.
10356@c JP
10357Mersenne Twister RNGの状態をカプセル化するクラスです。
10358このクラスのそれぞれのインスタンスは独自の状態を持ち、
10359個別のシードで初期化されていれば、それぞれがランダムビットの
10360独立したソースになり得ます。
10361
10362ランダムシードの値は初期化引数@code{:seed}により初期化時に与えるか、
10363以下で説明する@code{mt-random-set-seed!}を使います。
10364@c COMMON
10365
10366@example
10367(define m (make <mersenne-twister> :seed (sys-time)))
10368
10369(mt-random-real m) @result{} 0.10284287848537865
10370(mt-random-real m) @result{} 0.463227748348805
10371(mt-random-real m) @result{} 0.8628500643709712
10372@dots{}
10373@end example
10374@end deftp
10375
10376@defun mt-random-set-seed! mt seed
10377@c MOD math.mt-random
10378@c EN
10379Sets random seed value @var{seed} to the Mersenne Twister RNG (MTRNG) @var{mt}.
10380@var{Seed} can be an arbitrary positive exact integer,
10381or arbitrary length of u32vector (@pxref{Homogeneous vectors}).
10382If it is a u32vector, up to 624 elements are used for initialization.
10383@c JP
10384メルセンヌツイスターRNG @var{mt}にランダムシードの値@var{seed}をセットします。
10385@var{seed}は任意の正の正確整数か、任意長のu32vector
10386(@ref{Homogeneous vectors}参照)が使えます。
10387u32vectorの場合は、初期化のために624個までの要素が使われます。
10388@c COMMON
10389
10390@c EN
10391Internally, MTRNG keeps its state in array of 32-bit integers.  When a fixnum
10392is given, its lower 32bit is used to generate a linear congruential series
10393to fill the state space.  If you do so, there is an algorithm
10394that only samples a couple of result from MTRNG to calculate the original
10395seed value, hence can predict entire sequence.  If you want the random
10396sequence harder to predict, prepare your own u32vector seed filled with
10397high-entroby bits.
10398
10399Note that Mersenne Twister is never intended for cryptograhpy, you shouldn't
10400use it for security-sensitive purposes.
10401@c JP
10402MTRNGは32ビット整数配列を内部状態として持っています。fixnumが@var{seed}として
10403与えられた場合、その下位32bitを初期値とする線形合同法で得られる数列で内部状態が初期化されます。
10404そういた場合、MTRNGの二つの出力だけからシード値を逆算するアルゴリズムがあり、
10405全ての乱数列の値が予測できてしまいます。
10406もし乱数列をもっと予測しづらくしたいなら、u32vectorをエントロピーの高いビットで満たして
10407それをシードとして使ってください。
10408
10409メルセンヌツイスターは暗号学的に安全であることを意図して作られてはいません。
10410セキュリティが重要な用途には使わないでください。
10411@c COMMON
10412
10413@c EN
10414NB: Up to 0.9.9, when @var{seed} is a bignum, we roll our own way to
10415fold it in 32bit integer and then called Mersenne-Twister's initialization
10416function.  It loses the entropy, so we changed it and now all the bits
10417in the bignum is used for the seed.
10418@c JP
10419註: 0.9.9までは、@var{seed}にbignumが渡された場合、そこから独自のアルゴリズムで
1042032bitの値を生成してメルセンヌツイスタの初期化関数を呼んでいました。
10421しかしそれだとエントロピーを捨てることになるので、現在は
10422全てのビットがシード値に使われるように変更されています。
10423@c COMMON
10424@end defun
10425
10426@defun mt-random-get-state mt
10427@defunx mt-random-set-state! mt state
10428@c MOD math.mt-random
10429@c EN
10430Retrieves and reinstalls the state of Mersenne Twister RNG @var{mt}.
10431The state is represented by a u32vector of 625 elements.  The state
10432can be stored elsewhere, and then restored to an instance of
10433@code{<mersenne-twister>} to continue to generate the pseudo random
10434sequence.
10435@c JP
10436Mersenne Twister RNG @var{mt}を取り出して再インストールします。
10437状態は、625要素のu32vectorで表現されます。
10438状態はどこにでも保存することができ、仮想的なランダムシーケンスの
10439生成を続行するために、@code{<mersenne-twister>}のインスタンスとして
10440リストアできます。
10441@c COMMON
10442@end defun
10443
10444@defun mt-random-real mt
10445@defunx mt-random-real0 mt
10446@c MOD math.mt-random
10447@c EN
10448Returns a random real number between 0.0 and 1.0.
104491.0 is not included in the range.  @code{Mt-random-real} doesn't
10450include 0.0 either, while @code{mt-random-real0} does.
10451Excluding 0.0 is from the draft SRFI-27.
10452@c JP
104530.0と1.0の間のランダムな実数を返します。
104541.0は範囲に含まれません。
10455@code{mt-random-real}は、0.0も範囲に含みませんが、
10456@code{mt-random-real0}は含みます。
104570.0を含まないのは、SRFI-27ドラフトに依拠しています。
10458@c COMMON
10459@end defun
10460
10461@defun mt-random-integer mt range
10462@c MOD math.mt-random
10463@c EN
10464Returns a random exact positive integer between 0 and @var{range}-1.
10465@var{Range} can be any positive exact integer.
10466@c JP
104670から@var{range}-1までの正の正確整数をランダムに返します。
10468@var{range}はいかなる正の正確整数でも構いません。
10469@c COMMON
10470@end defun
10471
10472@defun mt-random-fill-u32vector! mt u32vector
10473@defunx mt-random-fill-f32vector! mt f32vector
10474@defunx mt-random-fill-f64vector! mt f64vector
10475@c MOD math.mt-random
10476@c EN
10477Fills the given uniform vector by the random numbers.
10478For @code{mt-random-fill-u32vector!}, the elements are filled
10479by exact positive integers between 0 and 2^32-1.
10480For @code{mt-random-fill-f32vector!} and
10481@code{mt-random-fill-f64vector!}, it is filled by an inexact
10482real number between 0.0 and 1.0, exclusive.
10483
10484If you need a bunch of random numbers at once, these are much
10485faster than getting one by one.
10486@c JP
10487与えられたユニフォームベクタをランダムな数値で埋めます。
10488@code{mt-random-fill-u32vector!}では、要素は0と2^32-1の間の
10489正の正確整数で埋められます。
10490@code{mt-random-fill-f32vector!}と@code{mt-random-fill-f64vector!}
10491では、0.0と1.0(含まれない)の間の不正確実数で埋められます。
10492@c COMMON
10493@end defun
10494
10495@c ----------------------------------------------------------------------
10496@node Prime numbers, Windows support, Mersenne-Twister random number generator, Library modules - Utilities
10497@section @code{math.prime} - Prime numbers
10498@c NODE 素数, @code{math.prime} - 素数
10499
10500@deftp {Module} math.prime
10501@mdindex math.prime
10502@c EN
10503This module provides utilities related to prime numbers.
10504@c JP
10505このモジュールは、素数を扱うユーティリティ関数を提供します。
10506@c COMMON
10507@end deftp
10508
10509@c EN
10510@subheading Sequence of prime numbers
10511@c JP
10512@subheading 素数のシーケンス
10513@c COMMON
10514
10515@defvar *primes*
10516@c MOD math.prime
10517@c EN
10518An infinite lazy sequence of primes.
10519@c JP
10520素数の無限遅延シーケンスです。
10521@c COMMON
10522
10523@example
10524;; show 10 prime numbers from 100-th one.
10525(take (drop *primes* 100) 10)
10526 @result{} (547 557 563 569 571 577 587 593 599 601)
10527@end example
10528@end defvar
10529
10530@defun reset-primes
10531@c MOD math.prime
10532@c EN
10533Once you take a very large prime out of @code{*primes*}, all primes
10534before that has been calculated remains in memory, since the
10535head of sequence is held in @code{*primes*}.  Sometimes you know
10536you need no more prime numbers and you wish those calculated ones
10537to be garbage-collected.  Calling @code{reset-primes} rebinds
10538@code{*primes*} to unrealized lazy sequence, allowing the previously
10539realized primes to be GCed.
10540@c JP
10541@code{*primes*}から大きな素数を取り出すと、それ以前の素数も全てメモリに
10542残り続けます。@code{*primes*}変数がシーケンスの頭を抱えているからです。
10543もう素数を必要としないことがわかっている場合、それらのメモリがガベージコレクト
10544されることが望ましいかもしれません。@code{reset-primes}手続きは
10545@code{*primes*}をまだ現実化されていない遅延シーケンスに再束縛し、
10546次のGCで計算済みの素数シーケンスが回収されるようにします。
10547@c COMMON
10548@end defun
10549
10550@defun primes
10551@c MOD math.prime
10552@c EN
10553Returns a fresh lazy sequence of primes.  It is useful when
10554you need certain primes in a short period of time---if you don't keep
10555a reference to the head of the returned sequence, it will be garbage
10556collected after you've done with the primes.
10557(Note that calculation of a prime number needs the
10558sequence of primes from the beginning,
10559so even if your code only keep a reference
10560in the middle of the sequence, the entire sequence will be kept
10561in the thunk within the lazy sequence---you have to release all
10562references in order to make the sequence GCed.)
10563
10564On the other hand,
10565each sequence returned by @code{primes} are realized individually,
10566duplicating calculation.
10567
10568The rule of thumb is---if you use primes repeatedly throughout
10569the program, just use @code{*primes*} and you'll save calculation.
10570If you need primes one-shot, call @code{primes} and abandon it
10571and you'll save space.
10572@c JP
10573新たな素数の遅延シーケンスを返します。
10574その時だけ素数を使いたい、という時に便利です。返されたシーケンスへの
10575参照が無くなれば、シーケンスはガベージコレクトされます。
10576(ある素数の計算には素数のシーケンスが最初から必要なので、
10577たとえシーケンスの頭ではなく途中への参照だけを持っていたとしても、
10578遅延シーケンスの中のサンクにはシーケンスの頭への参照が保持されています。
10579シーケンスがGCされるためには、いかなる部分への参照も残さないようにしなければなりません)。
10580
10581@code{primes}が返す各シーケンスは独立しているので、素数の計算もそれぞれで
10582(重複して)行われることになります。
10583
10584単純なルールとして、プログラム中で何度も素数を使う必要があるのなら
10585変数@code{*primes*}を利用するのが良いでしょう。各素数の計算は一度しか
10586行われず、余分な計算を省くことができます。しかしその場だけ素数が欲しいなら、
10587@code{primes}を呼んで、仕事が済んだらシーケンスを捨ててしまえば、
10588不要なシーケンスがメモリに残りつづけることを心配しなくても済みます。
10589@c COMMON
10590@end defun
10591
10592@c EN
10593@subheading Testing primality
10594@c JP
10595@subheading 素数かどうかを調べる
10596@c COMMON
10597
10598@defun small-prime? n
10599@c MOD math.prime
10600@c EN
10601For relatively small positive integers
10602(below @code{*small-prime-bound*}, to be specific), this procedure
10603determines if the input is prime or not, quickly and deterministically.
10604If @var{n} is on or above the bound, this procedure returns @code{#f}.
10605
10606This can be used to quickly filter out known primes; it never returns
10607@code{#t} on composite numbers (while it may return @code{#f} on
10608large prime numbers).
10609Miller-Rabin test below can tell if the input is composite for sure,
10610but it may return @code{#t} on some composite numbers.
10611@c JP
10612比較的小さな正整数 (@code{*small-prime-bound*}以下の正整数) に対して、
10613それが素数であるかどうかを判定し、素数なら@code{#t}を返します。
10614@var{n}がそれ以上である場合は常に@code{#f}を返します。
10615
10616この手続きは確実に素数であるとわかるものを素早く判別する時に便利です。
10617@code{#t}が返れば確実に素数であるとわかるからです (入力が大きな素数の時に
10618@code{#f}を返すことはありえますが)。
10619これに対し、下に述べるMiller-Rabin法では、合成数は確実に判別できますが、
10620素数であるかどうかは確実には言えません。
10621@c COMMON
10622@end defun
10623
10624@defvar *small-prime-bound*
10625@c MOD math.prime
10626@c EN
10627For all positive integers below this value
10628(slightly above 3.4e14 in the current implementation),
10629@code{small-prime?} can determines whether it is a prime or not.
10630@c JP
10631これより小さな数に対しては、@var{small-prime?}は決定的に
10632素数かどうかを判別します。現在の実装ではこの数は3.4e14よりちょっと大きな数です。
10633@c COMMON
10634@end defvar
10635
10636
10637@defun miller-rabin-prime? n :key num-tests random-integer
10638@c MOD math.prime
10639@c EN
10640Check if an exact integer @var{n} is a prime number, using
10641probabilistic Miller-Rabin algorithm (@var{n} must be greater than 1).
10642If this procedure returns @code{#f},
10643@var{n} is a composite number.  If this procedure returns @code{#t},
10644@var{n} is @emph{likely} a prime, but there's a small probability
10645that it is a false positive.
10646@c JP
106472以上の正確な整数@var{n}が素数かどうかを、確率的なMiller-Rabin法を使って判定します。
10648この手続きが@code{#f}を返したなら、@var{n}は確実に合成数です。
10649この手続きが@code{#t}を返した場合、@var{n}はおそらく素数ですが、
10650疑陽性である確率もわずかにあります。
10651@c COMMON
10652
10653@c EN
10654Note that if @var{n} is smaller than a certain number
10655(@code{*small-prime-bound*}), the algorithm is
10656deterministic; if it returns @code{#t}, @var{n} is certainly a prime.
10657@c JP
10658ただし、@code{n}がある数(@code{*small-prime-bound*})
10659より小さければ、アルゴリズムは決定的で、@code{#t}が返る@var{n}は確実に素数です。
10660@c COMMON
10661
10662@c EN
10663If @var{n} is greater than or equal to
10664@code{*small-prime-bound*},
10665we use a probabilistic test.  We choosing random base integer
10666to perform Miller-Rabin test up to 7 times by default.
10667You can change the number of tests by the keyword argument
10668@var{num-tests}.  The error probability
10669(to return @code{#t} for a composite number)
10670is at most @code{(expt 4 (- num-tests))}.
10671@c JP
10672@var{n}が@code{*small-prime-bound*}以上の場合は
10673確率的テストを用います。デフォルトでは7回、ランダムにベース整数値を選んで
10674Miller-Rabinテストを適用します。試行回数は@var{num-tests}キーワード引数で
10675変更可能です。合成数に対して誤って@code{#t}を返してしまう確率は
10676たかだか@code{(expt 4 (- num-tests))}です。
10677@c COMMON
10678
10679@c EN
10680For a probabilistic test, @code{miller-rabin-prime?} uses
10681its own fixed random seed by default.  We chose fixed seed
10682so that the behavior can be reproducible.  To change the random
10683sequence, you can provide your own random integer generator
10684to the @var{random-integer} keyword argument.   It must be
10685a procedure that takes a positive integer @var{k} and returns
10686a random integer from 0 to @var{k-1}, including.
10687@c JP
10688確率的テストでは、@var{miller-rabin-prime?}はデフォルトで
10689この手続き固有の、固定したランダムシードを使います。固定値なのは再現性を確保するためです。
10690異なる乱数系列を使いたければ、ランダムな整数生成手続きを
10691@var{random-integer}キーワード引数に与えてください。
10692手続きは正整数@var{k}を取り、0から@var{k-1}までのランダムな整数値を
10693返すものでなければなりません。
10694@c COMMON
10695@end defun
10696
10697@defun bpsw-prime? n
10698@c MOD math.prime
10699@c EN
10700Check if an exact integer @var{n} is a prime number, using
10701Baillie-PSW primality test
10702(@url{http://www.trnicely.net/misc/bpsw.html}).   It is deterministic,
10703and returns the definitive answer below 2^64 (around 1.8e19).
10704For larger integers this can return @code{#t} on a composite number,
10705although such number hasn't been found yet.  This never returns @code{#f}
10706on a prime number.
10707
10708This is slower than Miller-Rabin but fast enough for casual use,
10709so it is handy when you want a definitive answer below the above range.
10710@c JP
10711@var{n}が素数かどうかをBaillie-PSW法を用いて判定します
10712(@url{http://www.trnicely.net/misc/bpsw.html})。
10713このアルゴリズムは2^64 (約1.8e19) 以下の入力に対しては決定的であり、
10714正しい答えを返します。入力がそれ以上の場合、合成数に対して@code{#t}が返る可能性が
10715あります (具体的な数はまだ見つかっていませんが)。素数に対して@code{#f}が返ることは
10716決してありません。
10717
10718Miller-Rabin法より遅いですがカジュアルに使う分には十分に速いので、
10719上記の入力範囲で確実な答えを得たい場合は便利でしょう。
10720@c COMMON
10721@end defun
10722
10723@c EN
10724@subheading Factorization
10725@c JP
10726@subheading 素因数分解
10727@c COMMON
10728
10729@defun naive-factorize n :optional divisor-limit
10730@c MOD math.prime
10731@c EN
10732Factorize a positive exact integer @var{n} by trying to divide it with
10733all primes up to @code{(sqrt n)}.  Returns a list of prime factors
10734(each of which is equal to or greater than 2),
10735smaller ones first.
10736@c JP
10737正整数@var{n}を、@code{(sqrt n)}までの素数で順に割ってみることで
10738素因数分解します。戻り値は小さい順に並べられた素因数(2以上の整数)のリストです。
10739@c COMMON
10740
10741@example
10742(naive-factorize 142857)
10743  @result{} (3 3 3 11 13 37)
10744@end example
10745
10746@c EN
10747Note that @code{(naive-factorize 1)} is @code{()}.
10748@c JP
10749@code{(naive-factorize 1)}は@code{()}を返します。
10750@c COMMON
10751
10752@c EN
10753Although this is pretty naive method, this works well as far as
10754any of @var{n}'s factors are up to the order of around @code{1e7}.
10755For example, the following example runs in about 0.4sec on 2.4GHz Core2
10756machine.
10757(The first time will take about 1.3sec to realize lazy prime sequences.)
10758@c JP
10759この方法は極めてナイーブなものですが、目安としてどの素因数も@code{1e7}程度以下であれば
10760それなりに使えます。例えば次の例は2.4GHz Core2マシンで0.4秒で答えが返ります
10761(ただし、初回の実行は遅延素数シーケンスの実現化があるので1.3秒ほどかかりますが)。
10762@c COMMON
10763
10764@example
10765(naive-factorize 3644357367494986671013))
10766  @result{} (10670053 10670053 32010157)
10767@end example
10768
10769@c EN
10770Of course, if @var{n} includes any factors above that order,
10771the performance becomes abysmal.   So it is better to use this
10772procedure below 1e14 or so.
10773@c JP
10774もちろん@var{n}がより大きなオーダーの素因数を含んでいると、性能は急激に
10775悪化します。安全に使うには@var{n}を1e14程度のオーダーに止めておくのが良いでしょう。
10776@c COMMON
10777
10778@c EN
10779Alternatively, you can give @var{divisor-limit} argument that specifies
10780the upper bound of the prime number to be tried.  If it is given,
10781@code{naive-factorize} leaves a factor @var{f} as is if it can't be
10782divided by any primes less than or equal to @var{divisor-limit}.
10783So, the last element of the returned list may be composite number.
10784This is handy to exclude trivial factors before applying more sophisticated
10785factorizing algorithms.
10786@c JP
10787オプショナル引数@var{divisor-limit}を与えると、試行する素数の上限を指定
10788できます。この引数がある場合、@code{naive-factorize}は因数@var{f}が
10789@var{divisor-limit}以下の素数で割りきれなければ、そこで諦めて@var{f}を
10790結果に含めます。この場合、結果の最後の要素は合成数であるかもしれないわけです。
10791これは、より高度な素因数分解アルゴリズムを適用する前にありきたりの素因数を
10792除外するのに便利です。
10793@c COMMON
10794
10795@example
10796(naive-factorize 825877877739 1000)
10797  @result{} (3 43 6402154091)
10798
10799;; whereas
10800(naive-factorize 825877877739)
10801  @result{} (3 43 4591 1394501)
10802@end example
10803
10804@c EN
10805The procedure also memoizes the results on smaller @var{n} to make
10806things faster.
10807@c JP
10808この手続きは高速化のために小さな@var{n}に対する結果はメモ化しています。
10809@c COMMON
10810@end defun
10811
10812@defun mc-factorize n
10813@c MOD math.prime
10814@c EN
10815Factorize a positive exact integer @var{n} using the algorithm
10816described in
10817R. P. Brent, An improved Monte Carlo factorization algorithm, BIT 20 (1980), 176-184. @url{http://maths-people.anu.edu.au/~brent/pub/pub051.html}.
10818@c JP
10819正整数@var{n}をモンテカルロ素因数分解法
10820(R. P. Brent, An improved Monte Carlo factorization algorithm, BIT 20 (1980), 176-184. @url{http://maths-people.anu.edu.au/~brent/pub/pub051.html})により
10821素因数分解します。
10822@c COMMON
10823
10824@c EN
10825This one is capable to handle much larger range than
10826@code{naive-factorize}, somewhere around 1e20 or so.
10827
10828Since this method is probabilistic, the execution time may vary
10829on the same @var{n}.  But it will always return the definitive
10830results as far as every prime factor of @var{n} is smaller than 2^64.
10831
10832At this moment, if @var{n} contains a prime factor greater than
108332^64, this routine would keep trying factorizing it forever.
10834Practical applications should have some means to interrupt the
10835function and give it up after some time bounds.
10836This will be addressed once we have deterministic primality test.
10837@c JP
10838この手続きは@code{naive-factorize}よりも大きな数に使えます
10839(目安としては1e20程度まで)。
10840
10841アルゴリズムは確率的なので、同じ@var{n}に対しても実行時間はばらつきますが、
10842@var{n}の素因数が全て2^64より小さければ、かならず確定的な答えを返します。
10843
10844今のところ、@var{n}が2^64以上の素因数を含んでいる場合、この手続きは
10845永遠にそれを分割しようとしてループしてしまいます。現実的なアプリケーションは
10846何らかの方法で一定の時間でルーチンを中断して諦めるメカニズムが必要でしょう。
10847全ての入力に大して確定的な素数判定が実装されれば、この欠陥も修正されます。
10848@c COMMON
10849@end defun
10850
10851
10852@c EN
10853@subheading Miscellaneous
10854@c JP
10855@subheading その他の関数
10856@c COMMON
10857
10858@defun jacobi a n
10859@c MOD math.prime
10860@c EN
10861Calculates Jacobi symbol @code{(@var{a}/@var{n})}
10862(@url{http://en.wikipedia.org/wiki/Jacobi_symbol}).
10863@c JP
10864Jacobi symbol @code{(@var{a}/@var{n})} を計算します
10865(@url{http://en.wikipedia.org/wiki/Jacobi_symbol})。
10866@c COMMON
10867@end defun
10868
10869@defun totient n
10870@c MOD math.prime
10871@c EN
10872Euler's totient function of nonnegative integer @var{n}.
10873
10874The current implementation relies on @code{mc-factorize} above,
10875so it may take very long if @var{n} contains large prime factors.
10876@c JP
10877オイラーのトーシェント関数です。@var{n}は非負整数です。
10878
10879現在の実装は上の@code{mc-factorize}を使っており、
10880@var{n}が大きな素因数を持っている場合は非常に長い時間がかかります。
10881@c COMMON
10882@end defun
10883
10884
10885@c ----------------------------------------------------------------------
10886@node Windows support, PEG parser combinators, Prime numbers, Library modules - Utilities
10887@section @code{os.windows} - Windows support
10888@c NODE Windowsのサポート, @code{os.windows} - Windowsのサポート
10889
10890@deftp {Module} os.windows
10891@mdindex os.windows
10892This module is only available on Windows-native Gauche, and
10893provides Windows-specific procedures.
10894You can check @code{gauche.os.windows} feature with
10895 @code{cond-expand} macro (@pxref{Feature conditional})
10896to conditionalize windows-specific code.
10897
10898@example
10899(cond-expand
10900  [gauche.os.windows
10901   (use os.windows)
10902   ... Windows-specific code ...]
10903  [else
10904   ... Unix code ...])
10905@end example
10906
10907Currently there aren't enough procedures provided here, but
10908eventually we want to support simple scripting on Windows.
10909
10910Unless otherwise noted,
10911when Windows API returns an error value, a @code{<system-error>} condition
10912is thrown.
10913@end deftp
10914
10915@menu
10916* Windows dialogs::
10917* Windows console API::
10918@end menu
10919
10920@node Windows dialogs, Windows console API, Windows support, Windows support
10921@subsection Windows dialogs
10922
10923Currenly we only have MessageBox API.
10924
10925@defun sys-message-box window message :optional caption flags
10926@c MOD os.windows
10927Calls Windows MessageBox API.   The @var{window} argument should
10928be a handle for a window, or @code{#f}; at the moment we don't
10929provide any API that retrieves window handles, so you should always
10930pass @code{#f} here.  The @var{message} argument takes a string
10931for the content of the message box.  Optional @var{caption}
10932argument takes a string to be used in the window title.
10933
10934The @var{flags} argument is an integer; it should be @code{logior}
10935of values from one or more of the following groups.  See the
10936Windows reference manual for the details.
10937
10938@table @emph
10939@item Buttons
10940@code{MB_ABORTRETRYIGNORE},
10941@code{MB_CANCELTRYCONTINUE},
10942@code{MB_HELP},
10943@code{MB_OK} (default),
10944@code{MB_OKCANCEL},
10945@code{MB_RETRYCANCEL},
10946@code{MB_YESNO},
10947@code{MB_YESNOCANCEL}
10948@item Icon
10949Default is no icon.  Possible values:
10950@code{MB_ICONEXCLAMATION},
10951@code{MB_ICONWARNING},
10952@code{MB_ICONINFORMATION},
10953@code{MB_ICONASTERISK},
10954@code{MB_ICONQUESTION},
10955@code{MB_ICONSTOP},
10956@code{MB_ICONERROR},
10957@code{MB_ICONHAND}
10958@item Default button
10959@code{MB_DEFBUTTON1} (default),
10960@code{MB_DEFBUTTON2},
10961@code{MB_DEFBUTTON3},
10962@code{MB_DEFBUTTON4}
10963@item Modality
10964@code{MB_APPLMODAL} (default),
10965@code{MB_SYSTEMMODAL},
10966@code{MB_TASKMODAL}
10967@item Other options
10968@code{MB_DEFAULT_DESKTOP_ONLY},
10969@code{MB_RIGHT},
10970@code{MB_RTLREADING},
10971@code{MB_SETFOREGROUND},
10972@code{MB_TOPMOST},
10973@code{MB_SERVICE_NOTIFICATION}
10974@end table
10975
10976Return value is one of the following integer constants,
10977indicating which button is pressed:
10978@code{IDABORT},
10979@code{IDCANCEL},
10980@code{IDCONTINUE},
10981@code{IDIGNORE},
10982@code{IDNO},
10983@code{IDOK},
10984@code{IDRETRY},
10985@code{IDTRYAGAIN}, or
10986@code{IDYES}
10987@end defun
10988
10989@node Windows console API,  , Windows dialogs, Windows support
10990@subsection Windows console API
10991
10992Most of these procedures corresponds to Windows Console API one-to-one.
10993See the Windows reference for the detail description of what each API does.
10994
10995@subsubheading Attaching and detaching
10996
10997@defun sys-alloc-console
10998@defunx sys-free-console
10999[Windows]
11000@c MOD os.windows
11001Calls @code{AllocConsole} and @code{FreeConsole}, respectively.
11002@end defun
11003
11004@defun sys-generate-console-ctrl-event event pgid
11005[Windows]
11006@c MOD os.windows
11007@end defun
11008
11009@defvr {Constant} CTRL_C_EVENT
11010@defvrx {Constant} CTRL_BREAK_EVENT
11011[Windows]
11012@c MOD os.windows
11013@end defvr
11014
11015@subsubheading Console codepage
11016
11017@defun sys-get-console-cp
11018@defunx sys-get-console-output-cp
11019@defunx sys-set-console-cp codepage
11020@defunx sys-set-console-output-cp codepage
11021[Windows]
11022@c MOD os.windows
11023@end defun
11024
11025@defun sys-get-console-cursor-info handle
11026@defunx sys-set-console-cursor-info handle size visible
11027[Windows]
11028@c MOD os.windows
11029@end defun
11030
11031@defun sys-set-console-cursor-position handle x y
11032[Windows]
11033@c MOD os.windows
11034@end defun
11035
11036@subsubheading Console mode
11037
11038@defun sys-get-console-mode handle
11039@defunx sys-set-console-mode handle mode
11040[Windows]
11041@c MOD os.windows
11042@end defun
11043
11044@defvr {Constant} ENABLE_LINE_INPUT
11045@defvrx {Constant} ENABLE_ECHO_INPUT
11046@defvrx {Constant} ENABLE_PROCESSED_INPUT
11047@defvrx {Constant} ENABLE_WINDOW_INPUT
11048@defvrx {Constant} ENABLE_MOUSE_INPUT
11049@defvrx {Constant} ENABLE_PROCESSED_OUTPUT
11050@defvrx {Constant} ENABLE_WRAP_AT_EOL_OUTPUT
11051[Windows]
11052@c MOD os.windows
11053@end defvr
11054
11055@subsubheading Screen buffer
11056
11057@defun sys-create-console-screen-buffer desired-access share-mode inheritable
11058[Windows]
11059@c MOD os.windows
11060@end defun
11061
11062@defvr {Constant} GENERIC_READ
11063@defvrx {Constant} GENERIC_WRITE
11064[Windows]
11065@c MOD os.windows
11066@end defvr
11067
11068@defvr {Constant} FILE_SHARE_READ
11069@defvrx {Constant} FILE_SHARE_WRITE
11070[Windows]
11071@c MOD os.windows
11072@end defvr
11073
11074@defun sys-set-console-active-screen-buffer handle
11075[Windows]
11076@c MOD os.windows
11077@end defun
11078
11079@defun sys-scroll-console-screen-buffer handle scroll-rectangle clip-rectangle x y fill
11080[Windows]
11081@c MOD os.windows
11082@end defun
11083
11084@deftp {Class} <win:console-screen-buffer-info>
11085@clindex win:console-screen-buffer-info
11086[Windows]
11087@c MOD os.windows
11088
11089@defivar {<win:console-screen-buffer-info>} size.x
11090@defivarx {<win:console-screen-buffer-info>} size.y
11091@end defivar
11092
11093@defivar {<win:console-screen-buffer-info>} cursor-position.x
11094@defivarx {<win:console-screen-buffer-info>} cursor-position.y
11095@end defivar
11096
11097@defivar {<win:console-screen-buffer-info>} attributes
11098@end defivar
11099
11100@defivar {<win:console-screen-buffer-info>} window.left
11101@defivarx {<win:console-screen-buffer-info>} window.top
11102@defivarx {<win:console-screen-buffer-info>} window.right
11103@defivarx {<win:console-screen-buffer-info>} window.bottom
11104@end defivar
11105
11106@defivar {<win:console-screen-buffer-info>} maximum-window-size.x
11107@defivarx {<win:console-screen-buffer-info>} maximum-window-size.y
11108@end defivar
11109
11110@end deftp
11111
11112@defvr {Constant} FOREGROUND_BLUE
11113@defvrx {Constant} FOREGROUND_GREEN
11114@defvrx {Constant} FOREGROUND_RED
11115@defvrx {Constant} FOREGROUND_INTENSITY
11116@defvrx {Constant} BACKGROUND_BLUE
11117@defvrx {Constant} BACKGROUND_GREEN
11118@defvrx {Constant} BACKGROUND_RED
11119@defvrx {Constant} BACKGROUND_INTENSITY
11120[Windows]
11121@c MOD os.windows
11122@end defvr
11123
11124@defun sys-get-console-screen-buffer-info handle
11125[Windows]
11126@c MOD os.windows
11127@end defun
11128
11129@defun sys-get-largest-console-window-size handle
11130[Windows]
11131@c MOD os.windows
11132@end defun
11133
11134@defun sys-set-screen-buffer-size handle x y
11135[Windows]
11136@c MOD os.windows
11137@end defun
11138
11139@subsubheading Console input/output
11140
11141@deftp {Class} <win:input-record>
11142@clindex win:input-record
11143[Windows]
11144@c MOD os.windows
11145
11146@defivar {<win:input-record>} event-type
11147@end defivar
11148
11149@defivar {<win:input-record>} key.down
11150@defivarx {<win:input-record>} key.repeat-count
11151@defivarx {<win:input-record>} key.virtual-key-code
11152@defivarx {<win:input-record>} key.virtual-scan-code
11153@defivarx {<win:input-record>} key.unicode-char
11154@defivarx {<win:input-record>} key.ascii-char
11155@defivarx {<win:input-record>} key.control-key-state
11156@end defivar
11157
11158@defivar {<win:input-record>} mouse.x
11159@defivarx {<win:input-record>} mouse.y
11160@defivarx {<win:input-record>} mouse.button-state
11161@defivarx {<win:input-record>} mouse.control-key-state
11162@defivarx {<win:input-record>} mouse.event-flags
11163@end defivar
11164
11165@defivar {<win:input-record>} window-buffer-size.x
11166@defivarx {<win:input-record>} window-buffer-size.y
11167@end defivar
11168
11169@defivar {<win:input-record>} menu.command-id
11170@end defivar
11171
11172@defivar {<win:input-record>} focus.set-focus
11173@end defivar
11174
11175@end deftp
11176
11177@defun sys-get-number-of-console-input-events handle
11178[Windows]
11179@c MOD os.windows
11180@end defun
11181
11182@defun sys-get-number-of-console-mouse-buttons
11183[Windows]
11184@c MOD os.windows
11185@end defun
11186
11187@defun sys-peek-console-input handle
11188@defunx sys-read-console-input handle
11189[Windows]
11190@c MOD os.windows
11191@end defun
11192
11193@defun sys-read-console handle buf
11194[Windows]
11195@c MOD os.windows
11196@end defun
11197
11198@defun sys-read-console-output handle buf w h x y region
11199[Windows]
11200@c MOD os.windows
11201@end defun
11202
11203@defun sys-read-console-output-attribute handle buf x y
11204[Windows]
11205@c MOD os.windows
11206@end defun
11207
11208@defun sys-read-console-output-character handle len x y
11209[Windows]
11210@c MOD os.windows
11211@end defun
11212
11213@defun sys-set-console-text-attribute handle attr
11214[Windows]
11215@c MOD os.windows
11216@end defun
11217
11218@defun sys-set-console-window-info handle absolute window
11219[Windows]
11220@c MOD os.windows
11221@end defun
11222
11223@defun sys-write-console handle string
11224[Windows]
11225@c MOD os.windows
11226@end defun
11227
11228@defun sys-write-console-output-character handle string x y
11229[Windows]
11230@c MOD os.windows
11231@end defun
11232
11233@defun sys-fill-console-output-character handle char len x y
11234[Windows]
11235@c MOD os.windows
11236@end defun
11237
11238@defun sys-fill-console-output-attribute handle attr len x y
11239[Windows]
11240@c MOD os.windows
11241@end defun
11242
11243@defun sys-flush-console-input-buffer handle
11244[Windows]
11245@c MOD os.windows
11246@end defun
11247
11248@defun sys-get-console-title
11249[Windows]
11250@c MOD os.windows
11251@end defun
11252
11253@defun sys-set-console-title string
11254[Windows]
11255@c MOD os.windows
11256@end defun
11257
11258@subsubheading Standard handles
11259
11260@defun sys-get-std-handle which
11261@defunx sys-set-std-handle which handle
11262[Windows]
11263@c MOD os.windows
11264@end defun
11265
11266@defvr {Constant} STD_INPUT_HANDLE
11267@defvrx {Constant} STD_OUTPUT_HANDLE
11268@defvrx {Constant} STD_ERROR_HANDLE
11269[Windows]
11270@c MOD os.windows
11271@end defvr
11272
11273
11274@c ----------------------------------------------------------------------
11275@node PEG parser combinators, RFC822 message parsing, Windows support, Library modules - Utilities
11276@section @code{parser.peg} - PEG parser combinators
11277@c NODE PEGパーザコンビネータ, @code{parser.peg} - PEGパーザコンビネータ
11278
11279@deftp {Module} parser.peg
11280@mdindex parser.peg
11281@c EN
11282This module implements a parser combinator library
11283to build parsers based on Parsing Expression Grammar, or PEG.
11284@c JP
11285このモジュールは、Parsing Expression Grammar (PEG)に基づいたパーザを組み立てる
11286コンビネータライブラリを実装しています。
11287@c COMMON
11288
11289@c EN
11290PEG is a @emph{formal grammar} to define a language, like regular
11291expressions or context-free grammars.
11292An interesting characteristic of PEG is that it can
11293be directly mapped to a recursive decent parser, which is exactly
11294what this library does---each production rule is a Scheme expression
11295that takes parsers and returns a combined parser.  One advantage of
11296this approach is that you can freely mix ordinary Scheme code
11297within the parser, that is, there's no special ``parser description
11298language'' distinct from the base Scheme language, nor you need to
11299run separate tools like parser generators to obtain a runnable parser code.
11300@c JP
11301PEGは、正規表現や文脈自由文法と同様の@emph{形式言語}です。
11302PEGが興味深いのは、文法記述がそのまま再帰下降パーザに移し替えられるところで、
11303このライブラリはまさにそれをやっています。各生成規則は、パーザを受け取って
11304結合されたパーザを返すScheme式です。
11305このアプローチの利点は、Schemeコードと文法記述を混ぜて書けることです。
11306特別な「パーザー記述言語」を別に学ぶ必要も、パーザジェネレータのような別ツールを
11307使ってソースコードを生成する必要もありません。
11308@c COMMON
11309
11310@c EN
11311Although PEG can directly parse the character string, the parser
11312combinators are not tied to it.  In fact, most of the combinators
11313work transparently for any
11314sequence of tokens, where the exact meanings of tokens depend on
11315the application; you can have separate lexer that generates
11316token sequence that PEG parser can parse, for example.
11317@c JP
11318PEGは文字列を直接パーズすることもできますが、
11319パーザコンビネータは文字列のパーズ限定ではありません。実際、多くのコンビネータは
11320「トークン」の列 (具体的なトークンの意味はアプリケーションが決められます) に対して
11321透過的に動作します。例えば字句解析器を別に作ってトークンの列を生成し、
11322それをPEGでパーズする、ということもできます。
11323@c COMMON
11324
11325@c EN
11326This library is specifically written to get a good performance
11327on Gauche.  The parser created by @code{parser.peg} is
11328no slower than the parser written manually from scratch.
11329However, you have to watch out some traps; see
11330@ref{PEG performance tips}, for the details.
11331@c JP
11332このライブラリは、Gaucheで性能が出るように書かれています。
11333@code{parser.peg}で作られたパーザは、手書きのパーザと遜色ない性能を持ちます。
11334但し、いくつか気をつけるべき点はあります。それについては
11335@ref{PEG performance tips}を参照してください。
11336@c COMMON
11337@end deftp
11338
11339@menu
11340* PEG Walkthrough::
11341* PEG parser drivers::
11342* What is a PEG parser::
11343* PEG primitive parser builders::
11344* PEG ropes::
11345* PEG choice::
11346* PEG sequencing combinators::
11347* PEG repetition combinators::
11348* PEG miscellaneous combinators::
11349* PEG performance tips::
11350@end menu
11351
11352@node PEG Walkthrough, PEG parser drivers, PEG parser combinators, PEG parser combinators
11353@subsection Walkthrough
11354@c NODE PEGひとめぐり
11355
11356@c EN
11357In this section we cover the basic concepts and tools of @code{parser.peg}.
11358The code of examples is in @file{examples/pegintro.scm} if you have the
11359source tree of Gauche.
11360@c JP
11361本節では、@code{parser.peg}の基本的なコンセプトと道具を説明します。
11362例に使ったコードは、Gaucheのソースツリーの@file{examples/pegintro.scm}にあります。
11363@c COMMON
11364
11365@c EN
11366In @code{parser.peg}, a parser is merely a Scheme procedure
11367that takes a list of tokens as an argument and returns
11368a result (well, in fact, it returns three values, but we'll go
11369into the details later.)
11370@c JP
11371@code{parser.peg}では、パーザとは単なるSchemeの手続きです。それは
11372トークンのリストを引数に取り、結果を返します
11373(実際は3つの値を返します。それについては後で詳しく述べます)。
11374@c COMMON
11375
11376@c EN
11377Typically you don't need to write parser procedures directly.
11378Instead, you can use procedures that
11379generates parsers.   A parser can be as simple as the
11380following, which accepts a character @code{#\a}.
11381@c JP
11382パーザ手続きを直接書く必要は滅多にありません。
11383代わりに、パーザを生成する手続きがたくさん用意されているのでそれを使います。
11384例えば、文字@code{#\a}を受理するパーザはこう書けます。
11385@c COMMON
11386
11387@example
11388($. #\a)   ; @result{} a parser
11389@end example
11390
11391@c EN
11392Here, @emph{accept} means the parser checks if the head of input has
11393a character @code{#\a}, and if it is, it succeeds, and if not, it fails.
11394@c JP
11395ここで@emph{受理する}とは、パーザが入力の先頭をチェックして、
11396それが文字@code{#\a}ならば成功し、そうでなければ失敗するという意味です。
11397@c COMMON
11398
11399@c EN
11400A parser can be invoked by a @emph{parser driver}.  For example,
11401you can use @code{peg-parse-string} to invoke the above parser
11402on a string:
11403@c JP
11404パーザは@emph{パーザドライバ}によって呼び出せます。例えば
11405@code{peg-parse-string}を使って、上のパーザで文字列をパーズしてみましょう。
11406@c COMMON
11407
11408@example
11409gosh> (peg-parse-string ($. #\a) "abc")
11410#\a
11411@end example
11412
11413@c EN
11414The parsing succeeds, and returns the matched value---@code{#\a} in this case.
11415If the parser can't accept the input, the driver throws an error
11416@code{<parse-error>}.
11417@c JP
11418パーズは成功し、マッチした値 (@code{#\a}) が返りました。
11419パーザが期待する入力でなかった場合には、ドライバは@code{<parse-error>}を投げます。
11420@c COMMON
11421
11422@example
11423gosh> (peg-parse-string ($char #\a) "xyz")
11424*** PARSE-ERROR: expecting #\a at 0, but got #\x
11425@end example
11426
11427@c EN
11428A parser can also be constructed by combining simpler parsers,
11429using @emph{parser combinators}.   For example, @code{$seq} takes
11430zero or more parsers and apply them sequentially, returning
11431the last result.
11432@c JP
11433単純なパーザを@emph{パーザコンビネータ}で組み合わせて、より複雑なパーザを作ることができます。
11434例えば、@code{$seq}はいくつかのパーザを受け取り、「それらを順に適用して
11435最後の結果を返すパーザ」を作って返します。
11436@c COMMON
11437
11438@example
11439gosh> (peg-parse-string ($seq ($. #\a) ($. #\b) ($. #\c)) "abc")
11440#\c
11441@end example
11442
11443@c EN
11444The combinator @code{$many} takes a parser and returns a new parser
11445that accepts zero or more occurrence of the string the original parser
11446accepts.
11447@c JP
11448コンビネータ@code{$many}はパーザを取ると、それのゼロ回以上の繰り返しを受理する
11449パーザを作って返します。
11450@c COMMON
11451
11452@example
11453gosh> (peg-parse-string ($many ($. #\a)) "aaaaabc")
11454(#\a #\a #\a #\a #\a)
11455gosh> (peg-parse-string ($many ($. #\a)) "xxxxxyz")
11456()
11457@end example
11458
11459@c EN
11460A parser is just an ordinary Scheme procedure, so it can be bound
11461to a variable, then can be used to construct more complex parsers.
11462@c JP
11463パーザは通常のSchemeの手続きなので、変数に束縛し、それをより複雑なパーザを作るのに使えます。
11464@c COMMON
11465
11466@example
11467(define digits    ($many1 ($. #[\d])))
11468(define ws        ($many_ ($. #[\s])))
11469(define separator ($seq ws ($. #\,) ws))
11470@end example
11471
11472@c EN
11473I leave explanation of @code{$many1} and
11474@code{$many_} for the later section,
11475but you may be able to guess what those parsers do;
11476@code{digits} accepts a sequence of one or more digits, and
11477@code{ws} accepts sequence of zero or more whitespaces.   The @code{separator}
11478parser accepts a comma, optionally surrounded by whitespaces.
11479@c JP
11480@code{$many1}と@code{$many_}の説明は後回しにしますが、
11481何となくこれらのパーザの動作は推測できるのではないでしょうか。
11482@code{digits}は1個以上の数字の並びを、
11483@code{ws}は0個以上の空白文字の並びを受理するパーザです。
11484@code{separator}パーザは0個以上の空白で囲まれたコンマを受容します。
11485@c COMMON
11486
11487@c EN
11488The @code{digits} parser returns a list of accepted
11489characters:
11490@c JP
11491@code{digits}は受理した文字のリストを返します。
11492@c COMMON
11493
11494@example
11495gosh> (peg-parse-string digits "12345")
11496(#\1 #\2 #\3 #\4 #\5)
11497@end example
11498
11499@c EN
11500Can we create a parser that returns an integer as
11501a parsed result?    Yes, we can use the @code{$let} macro.
11502@c JP
11503パーズの結果として整数値を返すようにできるでしょうか。
11504@code{$let}マクロを使えばできます。
11505@c COMMON
11506
11507@example
11508(define integer
11509  ($let ([ds digits])
11510    ($return (x->integer (list->string ds)))))
11511@end example
11512
11513@c EN
11514The @code{$let} works somewhat like @code{and-let*}; it takes
11515a form of @code{($let ([@var{var} @var{parser}] @dots{}) @var{expr} @dots{})},
11516applying the @var{parser}s in order, binding the result of each
11517parser to @var{var}.  If any of the @var{parser} fails, the entire
11518parser created by @code{$let} macro fails.  When all the @var{parser} succeeds,
11519each result is  bound to @var{var} and @var{expr} @dots{} are
11520evaluated.  The last @var{expr} must yield a parser.
11521@c JP
11522@code{$let}は@code{and-let*}のように動作します。
11523@code{($let ([@var{var} @var{parser}] @dots{}) @var{expr})}という形式を取り、
11524@var{parser}を順に入力に適用してゆきます。
11525@var{parser}のどれかひとつでも失敗したら全体が失敗します。
11526全ての@var{parser}が成功したら、それぞれの結果が@var{var}に束縛された環境下で
11527@var{expr} @dots{}が評価されます。最後の@var{expr}はパーザを返さねばなりません。
11528@c COMMON
11529
11530@c EN
11531The @code{$return} procedure creates a parser
11532that doesn't consume input, always succeeds
11533and returns the given value.  The name is taken from
11534Haskell's monads.  Note that is is just an ordinary procedure
11535and not like a control-transfer syntax like traditional language's
11536@code{return}.  You may think it just as type conversion
11537procedure from a Scheme object to a parser.
11538@c JP
11539@code{$return}手続きは、入力を消費せず、常に成功し、引数をパーズ結果とする
11540パーザを作ります。この名前はHaskellのモナドからきました。
11541他の多くの言語にあるreturnのように制御の流れを変えるのではなく、単なる手続きであることに
11542注意してください。任意のSchemeオブジェクトをパーザに変える変換手続きと考えても良いでしょう。
11543@c COMMON
11544
11545@example
11546gosh> (peg-parse-string integer "12345")
1154712345
11548@end example
11549
11550@c EN
11551Now you can combine those parsers to build more complex one, such
11552as a comma-separated list of integers:
11553@c JP
11554これらのパーザを組み合わせて、さらに複雑なパーザを作ることができます。
11555例えばコンマで区切られた整数のリストです:
11556@c COMMON
11557
11558@example
11559(define integers1 ($seq integer
11560                        ($many ($seq separator integer))))
11561
11562gosh> (peg-parse-string integers1 "123, 456, 789")
11563(456 789)
11564@end example
11565
11566@c EN
11567Oops, where's 123?  Well, remember that
11568@code{$seq} discards the results but the last one.
11569We can use @code{$let} again to keep all the results.
11570@c JP
11571あれ、最初の123がどっかいっちゃいました。そうそう、
11572@code{$seq}は最後のパーザの値以外は捨てるのでした。
11573@code{$let}を使って結果を集めることができます。
11574@c COMMON
11575
11576@example
11577(define integers2 ($let ([n  integer]
11578                         [ns ($many ($seq separator integer))])
11579                     ($return (cons n ns))))
11580
11581gosh> (peg-parse-string integers2 "123, 456, 789")
11582(123 456 789)
11583@end example
11584
11585@c EN
11586(Unlike @code{let} where the order of its init expressions are
11587not defined, @code{$let} guarantees the parsers are applied sequentially.
11588The reason it is not called @code{$let*} is the scope;
11589we also have @code{$let*}, which we'll explain shortly.)
11590@c JP
11591(@code{let}ではinit式の評価順序は決まっていませんが、
11592@code{$let}はパーザを書かれた順に適用することを保証しています。
11593これを@code{$let*}と呼んでいないのはスコープのためです。
11594すぐ後で@code{$let*}も紹介します。)
11595@c COMMON
11596
11597@c EN
11598Another way to gather the results of parsers is a combinator @code{$lift}.
11599It is used as @code{($lift proc parser @dots{})}, where @var{proc}
11600is an ordinary procedure which receives the result of @var{parser} @dots{}
11601as arguments.  The return value of @var{proc} becomes the result of
11602the entire parser.  Unlike @code{$let}, @var{proc} doesn't need to
11603return a parser.
11604@c JP
11605パーザの結果を集めるもうひとつの方法は@code{$lift}コンビネータです。
11606@code{($lift proc parser @dots{})} のように使います。ここで
11607@var{proc}は普通の手続きで、@var{parser} @dots{}の結果を引数として受け取り、
11608@var{proc}の返した結果が全体のパーザの結果になります。
11609@code{$let}と違って、@var{proc}はパーザを返す必要はありません。
11610@c COMMON
11611
11612@example
11613(define integers3 ($lift cons
11614                         integer
11615                         ($many ($seq separator integer))))
11616@end example
11617
11618@c EN
11619The parsers so far doen't handle the case when the list contains no
11620integers.   Using @code{$or} combinator, which represents a choice,
11621we can modify it to handle zero-element case.
11622@c JP
11623これまでのパーザは入力に整数が全く含まれていない場合を考慮していませんでした。
11624選択を表す@code{$or}コンビネータを使って、整数が無いケースをサポートできます。
11625@c COMMON
11626
11627@example
11628(define integers4 ($or ($let ([n  integer]
11629                              [ns ($many ($seq separator integer))])
11630                         ($return (cons n ns)))
11631                       ($return '())))
11632@end example
11633
11634@c EN
11635By the way, ``list of stuff separated by something'' is a very common
11636pattern, so we can extract the pattern to name it:
11637@c JP
11638ところで、「何かで区切られた何かのリスト」というのは頻繁に出てくるので、次のように
11639パターンを取り出しておくことができます:
11640@c COMMON
11641
11642@example
11643(define (sep-by stuff separator)
11644  ($or ($let ([n  stuff]
11645              [ns ($many ($seq separator stuff))])
11646         ($return (cons n ns)))
11647       ($return '())))
11648@end example
11649
11650@c EN
11651Then the list of integers can be written this simple:
11652@c JP
11653すると整数のリストのパーザはこんなに簡単になります:
11654@c COMMON
11655
11656@example
11657(define integers5 (sep-by integer separator))
11658@end example
11659
11660@c EN
11661In fact, @code{parser.peg} provides @code{$sep-by} to do the above,
11662but we've just shown the definition to demonstrate
11663the power of the combinatorial approach;
11664you can use ordinary procedural abstraction to factor out common patterns.
11665@c JP
11666実は@code{parser.peg}には上と同じことができる@code{$sep-by}というのが
11667既に用意されているんですが、コンビネータを使う方法の強みを示すために
11668あえて実装してみました。
11669共通のパターンに通常の手続きを使った抽象化を使えるのが利点です。
11670@c COMMON
11671
11672@c EN
11673There's one catch in the @code{$or} form.
11674It tries the next alternative only when the
11675parser fails @emph{without consuming the input}.  Once the input is
11676consumed, @code{$or} commits to that choice.   For example,
11677the following fails even if the input seems to match the
11678second alternative:
11679@c JP
11680@code{$or}についてはひとつ注意があります。ある選択肢が失敗した時、
11681@emph{それが入力を消費していない場合に限り}、次の選択肢が試されるということです。
11682入力が少しでも消費されたら、@code{$or}はその選択肢にコミットし、
11683その先で失敗しても他の選択肢を試しません。下の例では、
116842番目の@code{$seq}が入力にマッチするにもかかわらず、パーズは失敗します。
11685@c COMMON
11686
11687@example
11688(define paren  ($. #\())
11689(define thesis ($. #\)))
11690
11691(peg-parse-string ($or ($seq paren ($."ab") thesis)
11692                       ($seq paren ($."cd") thesis))
11693                  "(cd)")
11694 @result{} *** PARSE-ERROR: expecting ab at 1, but got #\c
11695@end example
11696
11697@c EN
11698It's because when @code{$or} tries the first branch, it reads the initial
11699open paren from the input, so @code{$or} commits to the first branch.
11700When the branch fails, @code{$or} doesn't bother to try the second branch.
11701(In other words, @code{$or} does not backtrack.)
11702@c JP
11703@code{$or}の最初の選択肢で、先頭の開き括弧はマッチに成功して入力が消費されます。
11704その後でマッチが失敗するわけですが、既に入力が消費されているので、
11705@code{$or}は他の選択肢を考慮することなく全体を失敗させます。
11706(言い換えれば、@code{$or}はバックトラックを行いません。)
11707@c COMMON
11708
11709@c EN
11710You may factor out the common prefix:
11711@c JP
11712一つの手は、共通部分を括り出すことです。
11713@c COMMON
11714
11715@example
11716($seq paren
11717      ($or ($."ab") ($."cd"))
11718      thesis)
11719@end example
11720
11721
11722@c EN
11723But it may complicates the syntax, and it is not always trivial to
11724factor out like above.  The better way is to use the @code{$try}
11725combinator: @code{($try @var{p})} runs a parser @var{p}, and if
11726it fails, @code{$try} rolls back the input as if it didn't
11727consume input at all.  Using with @code{$or}, you can do arbitrary
11728lookahead and backtrack.
11729@c JP
11730ただ、これは文法を複雑化させることがありますし、
11731いつでも簡単にできるとは限りません。よりうまい方法は@code{$try}コンビネータを
11732使うことです。 @code{($try @var{p})}はパーザ@var{p}を走らせ、それが
11733失敗したら入力を元の時点まで巻き戻します。@code{$or}と一緒につかえば、
11734いくらでも先読みとバックトラックができます。
11735@c COMMON
11736
11737@example
11738($or ($try ($seq paren ($."ab") thesis))
11739     ($seq paren ($."cd") thesis))
11740@end example
11741
11742@c EN
11743Now, let's get back to the integer list example and make
11744it more interesting.
11745Suppose the list of integers are surrounded by parentheses,
11746brackets or curly-braces.  Opening one and closing one must correspond.
11747@c JP
11748さて整数のリストの例をもうちょっとおもしろくしてみましょう。
11749リストは小括弧、中括弧、大括弧のどれかで囲まれていて、開き括弧と閉じ括弧は対応
11750していなければならない、とします。
11751@c COMMON
11752
11753@example
11754(define begin-list
11755  ($seq0 ($. #[\(\[\@{]) ws))
11756
11757(define (end-list opener)
11758  ($seq ws (case opener
11759            [(#\() ($. #\))]
11760            [(#\[) ($. #\])]
11761            [(#\@{) ($. #\@})])))
11762
11763(define int-list
11764  ($let* ([opener begin-list]                ;*1
11765          [ints ($sep-by integer separator)] ;*2
11766          [ (end-list opener) ])             ;*3
11767    ($return ints)))
11768@end example
11769
11770@c EN
11771The opening bracket is parsed by the parser @code{begin-list}.
11772The @code{$seq0} combinator is similar to @code{seq}, but returns
11773the result of the first parser instead of the last one
11774(it's @code{begin0} to @code{begin}).
11775@c JP
11776開き括弧は@code{begin-list}パーザが受理します。@code{$seq0}は
11777@code{$seq}とほぼ同じですが、最初のパーザの結果を返します。
11778(@code{begin}に対する@code{begin0}と同じです。)
11779@c COMMON
11780
11781@c EN
11782The closing bracket must match the opening one, so @code{end-list}
11783is a procedure that takes the opening bracket and returns a suitable
11784parser to accept the corresponding closing bracket.
11785@c JP
11786閉じ括弧は開き括弧と対応しないとならないので、@code{end-list}は
11787開き括弧を取って適切な閉じ括弧のパーザを返す手続きになっています。
11788@c COMMON
11789
11790@c EN
11791The @code{int-list} first parses the opening bracket by @code{begin-list}
11792and bind the result to @var{opener} (*1).
11793Then goes to parse comma-separated integers (*2) and bind the
11794result list to @var{ints}.
11795Finally, it parses the matching closing bracket (*3).  Note that
11796the it omits the variable, since we don't need the result of
11797closing bracket parser.
11798@c JP
11799@code{int-list}はまず開き括弧を@code{begin-list}でパーズし、その結果を
11800@var{opener}に束縛します(*1)。次にコンマ区切りの整数をパーズし、結果のリストを
11801@var{ints}に束縛します(*2)。最後に開き括弧に対応する閉じ括弧をパーズします(*3)。
11802最後のパーザは値を使わないので、変数を省略しています。
11803@c COMMON
11804
11805@c EN
11806Since we need to use the value of @var{opener} in the following bindings,
11807we use @code{$let*} here, instead of @code{$let}.  The difference is
11808the scope of the parser expressions in the binding.  Note that, however,
11809@code{$let} is a lot more easier to optimize, so you want to use
11810@code{$let} whenever possible.
11811@c JP
11812@var{opener}の値を続く束縛フォームの中で使う必要があるので、
11813ここでは@code{$let}ではなく@code{$let*}を使いました。
11814この差は@code{let}と@code{let*}の差と同じで、スコープの違いです。
11815ただ、@code{$let}の方が処理系にはうんと最適化しやすいので、
11816可能な限り@code{$let}を使う方が良いでしょう。
11817@c COMMON
11818
11819@c EN
11820Let's see it works.
11821@c JP
11822走らせてみます。
11823@c COMMON
11824
11825@example
11826gosh> (peg-parse-string int-list "[123, 456, 789]")
11827(123 456 789)
11828gosh> (peg-parse-string int-list "@{123, 456, 789@}")
11829(123 456 789)
11830gosh> (peg-parse-string int-list "(123, 456, 789@}")
11831*** PARSE-ERROR: expecting #\) at 14, but got #\@}
11832@end example
11833
11834@c EN
11835The last example shows it rejects unmatched brackets.
11836@c JP
11837最後の例は括弧の対応が取れていないと失敗する例です。
11838@c COMMON
11839
11840@c EN
11841What if we want a nested list?  In BNF, we could write
11842something like this:
11843@c JP
11844ネストしたリストをパーズするにはどうすればいいでしょう?
11845BNFならこう書けるでしょう。
11846@c COMMON
11847
11848@example
11849list : begin-list (elem (separator elem)* )? end-list
11850elem : integer | list
11851@end example
11852
11853@c EN
11854The straight translation would be he following.
11855@c JP
11856これをそのまま移し替えると次のようになります。
11857@c COMMON
11858
11859@example
11860;; First try
11861(define nested-list
11862  ($let* ([opener begin-list]
11863          [ints ($sep-by elem separator)]
11864          [ (end-list opener) ])
11865    ($return ints)))
11866(define elem  ($or integer nested-list))
11867@end example
11868
11869@c EN
11870Let's load it... Oops.
11871@c JP
11872ロードしてみましょう。おっと
11873@c COMMON
11874
11875@example
11876*** ERROR: unbound variable: elem
11877Stack Trace:
11878_______________________________________
11879  0  elem
11880        [unknown location]
11881  1  (eval expr env)
11882        at "../lib/gauche/interactive.scm":267
11883@end example
11884
11885@c EN
11886We need the parser @code{elem} to construct @code{nested-list}, but
11887we need the parser @code{nested-list} to construct @code{elem}.
11888In lazy languages like Haskell this doesn't matter, but we Schemers
11889are @emph{eager}!
11890@c JP
11891@code{nested-list}の値を計算するのに@code{elem}の値を使いますが、
11892@code{elem}の値を計算するのに@code{nested-list}の値が必要です。
11893Haskellのような怠惰な言語ならこれでも構わないんですが、
11894Schemerは熱心なんです!
11895@c COMMON
11896
11897@c EN
11898The solution is to delay the parser construction until it is
11899actually used.  The @code{$lazy} form does the job:
11900@c JP
11901解決策は、パーザの計算を必要になるまで遅らせることです。
11902@code{$lazy}フォームが必要な遅延を行います。
11903@c COMMON
11904
11905@example
11906(define nested-list
11907  ($lazy
11908    ($let* ([opener begin-list]
11909            [ints ($sep-by elem separator)]
11910            [ (end-list opener) ])
11911      ($return ints))))
11912(define elem  ($or integer nested-list))
11913
11914gosh> (peg-parse-string nested-list "(123, [456, @{@}, 789], 987)")
11915(123 (456 () 789) 987)
11916@end example
11917
11918@c EN
11919Ok, we're almost done.  Our code can parse nested list of integers,
11920checking bracket matches.  But if you give an erroneous input, the message
11921is cryptic and not helpful:
11922@c JP
11923さあ、ほとんど完成です。
11924括弧の対応をチェックしながら、ネストした整数のリストをパーズできるようになりました。
11925ただ、間違いのある入力を与えた時に出されるエラーメッセージがわかりにくいですね。
11926@c COMMON
11927
11928@example
11929gosh> (peg-parse-string nested-list "(123, [456, @{@}, 789), 987)")
11930*** PARSE-ERROR: expecting one of (#[0-9] #\]) at 19
11931Stack Trace:
11932_______________________________________
11933  0  (eval expr env)
11934        at "../lib/gauche/interactive.scm":267
11935@end example
11936
11937@c EN
11938We could check the reason of failure in the parser, and call
11939@code{$fail} with more reasonable error message.  Let's replace
11940@code{end-list} above with @code{end-list2} below:
11941@c JP
11942パーザの中で失敗の理由を調べて、意味のあるエラーメッセージで@code{$fail}を呼び出すことが
11943できます。上の@code{end-list}を下の@code{end-list2}に置き換えてみて下さい。
11944@c COMMON
11945
11946@example
11947(define (end-list2 opener)
11948  (define expected
11949    (assv-ref '((#\( . #\)) (#\[ . #\]) (#\@{ . #\@})) opener))
11950  ($seq ws
11951        ($let ([closer ($. #[\)\]\@}])])
11952          (if (eqv? closer expected)
11953            ($return closer)
11954            ($fail (format "Mismatched closing bracket. '~c' expected, \
11955                            but got '~c'"
11956                           expected closer))))))
11957@end example
11958
11959@c EN
11960You also have to change @code{nested-list} and @code{elem} to
11961use @code{end-list2}:
11962@c JP
11963@code{nested-list}と@code{elem}についても@code{end-list2}を使うように変更します:
11964@c COMMON
11965
11966@example
11967(define nested-list2
11968  ($lazy
11969    ($let* ([opener begin-list]
11970            [ints ($sep-by elem2 separator)]
11971            [ (end-list2 opener) ])
11972      ($return ints))))
11973
11974(define elem2  ($or integer nested-list2))
11975@end example
11976
11977@c EN
11978(You could redefine @code{end-list}, but if you do so, don't forget to
11979re-evaluate the definitions of @code{nested-list} and @code{elem}.
11980It's because the combinators
11981are caculated taking the value of other combinators when it's defined,
11982unlike typical procedural approach where you redefine one procedure and
11983other procedures will refer to the updated version after that.)
11984@c JP
11985(@code{end-list}を再定義しても良いのですが、その場合は
11986@code{nested-list}と@code{elem}の定義を再評価することを忘れないでください。
11987コンビネータは、定義時に他のコンビネータの値を使って計算されます。
11988通常の手続き定義のアプローチでは、一つの手続きの定義を差し替えたら他の手続きは
11989新しい定義を使うようになりますが、それと異なるので要注意です。)
11990@c COMMON
11991
11992@c EN
11993And now you see this error:
11994@c JP
11995これで、エラーメッセージはこんなふうになります。
11996@c COMMON
11997
11998@example
11999gosh> (peg-parse-string nested-list2 "(123, [456, @{@}, 789), 987)")
12000*** PARSE-ERROR: Mismatched closing bracket. ']' expected, but got ')' at 20
12001Stack Trace:
12002_______________________________________
12003  0  (eval expr env)
12004        at "../lib/gauche/interactive.scm":267
12005@end example
12006
12007@c EN
12008For further examples, you can take a look at some libraries in the
12009Gauche source tree that use @code{parser.peg}:
12010@c JP
12011更なる例は、Gaucheソースツリーの中で@code{parser.peg}を使っているライブラリに
12012見ることができます:
12013@c COMMON
12014
12015@itemize @bullet
12016@item
12017@file{lib/rfc/json.scm}
12018@item
12019@file{lib/text/edn.scm}
12020@item
12021@file{lib/www/css.scm}
12022@end itemize
12023
12024
12025@node PEG parser drivers, What is a PEG parser, PEG Walkthrough, PEG parser combinators
12026@subsection Parser drivers
12027@c NODE PEGパーザドライバ, パーザドライバ
12028
12029@defun peg-run-parser parser list
12030@c MOD parser.peg
12031@c EN
12032Apply @var{parser} on the input @var{list}.   If @var{parser} accepts it,
12033returns two values--the result of @var{parser}, and the rest of
12034the input.  If @var{parser} fails, raise @code{<parse-error>}.
12035@c JP
12036パーザ@var{parser}を入力@var{list}に適用します。入力が受理されたら、
12037@var{parser}の結果と、残りの入力の二つの値を返します。
12038@var{parser}が失敗したら、@code{<parse-error>}が投げられます。
12039@c COMMON
12040
12041@c EN
12042The result of @var{parse} is a value yielded by @var{parser}
12043passed to @code{rope-finalize}, so any unfinalized rope is
12044finalized before being returned.  @xref{PEG ropes}, for the details.
12045@c JP
12046@var{parse}の結果は@code{rope-finalize}を通されるので、結果中の
12047ファイナライズされていないロープは全てファイナライズされて返されます。
12048ロープについては@ref{PEG ropes}を参照してください。
12049@c COMMON
12050
12051@c EN
12052Typically, you don't want to have entire input as a list beforehand,
12053so you pass a lazy sequence as @var{list} (@pxref{Lazy sequences}).
12054If the input is a string
12055or a port, convenience procedures are defined.
12056@c JP
12057多くの場合、入力をあらかじめ全部リストで持っておきたくはないと思います。
12058その場合、遅延シーケンスを@var{list}に渡せば良いでしょう (@ref{Lazy sequences})。
12059なお、入力が文字列やポートの場合はユーティリティ手続きが定義されています。
12060@c COMMON
12061
12062@c EN
12063Input doesn't need to be a character list.  You may, for example,
12064have a separate lexer that generates a (lazy) list of tokens, and let @var{parser}
12065parse them.
12066@c JP
12067入力が文字のリストである必要はありません。
12068例えば、別の字句解析器を使ってトークンの(遅延)リストにしてから、
12069@var{parser}でそれをパーズすることもできます。
12070@c COMMON
12071@end defun
12072
12073@defun peg-parse-string parser string :optional cont
12074@defunx peg-parse-port parser iport :optional cont
12075@c MOD parser.peg
12076@c EN
12077Convenience wrappers of @code{peg-run-parser} that takes input from
12078@var{string} or @var{iport}.
12079@c JP
12080@code{peg-run-parser}で文字列@var{string}や入力ポート@var{iport}からの入力を
12081パーズするユーティリティ手続きです。
12082@c COMMON
12083
12084@c EN
12085Without @var{cont} argument or it is @code{#f},
12086it returns the parsed result and discards
12087the rest of the input.  (Hint: To make sure there's no garbage
12088following, use @code{$eos} parser.)
12089@c JP
12090@var{cont}引数が省略されるか@code{#f}であれば、
12091この手続きはパーザが受理したところ以降の入力は捨てて、パーザの結果だけ返します。
12092(ヒント: 余分なゴミが後に続いてないことを保証するには@code{$eos}パーザが使えます)。
12093@c COMMON
12094
12095@c EN
12096If you want to keep parsing after @var{parser} accepts its input,
12097pass @var{cont} a procedure; it must take two arguments, the result of
12098@var{parser} and a lazy sequence of the rest of the input.  What @var{cont}
12099returns will be the result of these procedures.
12100@c JP
12101@var{parser}が入力を受理した後、さらにパーズを続けたければ、@var{cont}に手続きを
12102渡します。その手続きは@var{parser}の結果と、残りの入力の遅延シーケンスの二つの
12103引数を取ります。@var{cont}が返すものが全体の返り値となります。
12104@c COMMON
12105
12106@c EN
12107It is an error to pass other values ot @var{cont}.
12108@c JP
12109@var{cont}にそれ以外の値を渡すのはエラーです。
12110@c COMMON
12111@end defun
12112
12113@defun peg-parser->generator parser list
12114@c MOD parser.peg
12115This is useful when you need to apply @var{parser} repeatedly over
12116the input @var{list}.    Returns a generator that generates
12117the parsed result one match at a time.
12118
12119The same input can be accepted by
12120by @code{(peg-run-parser ($many parser) list)}, but this one
12121won't return until all input is consumed.
12122@end defun
12123
12124@deftp {Condition type} <parse-error>
12125@c MOD parser.peg
12126An condition type raised by the parser driver when the given parser
12127failed ultimately.  Inherits @code{<error>}.
12128(Note that each parser won't throw this; one
12129parser's failure doesn't necessarily mean the entire parser fails.
12130It's the driver that recognizes the ultimate failure and raise this
12131condition.)
12132
12133The following slots are available:
12134
12135@defivar <parse-error> message
12136This slot is inherited from @code{<error>}.  Contains string error message.
12137@end defivar
12138
12139@defivar <parse-error> position
12140The position the failure occurs, counted by the number of tokens
12141from the beginning of the input.
12142@end defivar
12143
12144@defivar <parse-error> type
12145The type of failure.  It's either one of the follownig symbols:
12146@table @code
12147@item fail-expect
12148The parser expects one of the objects in @var{objects} slot, but
12149got a different one (stored in @var{token}).
12150@item fail-unexpect
12151The parser isn't expecting any of the objects in @var{objects} slot,
12152but got the one in @var{token}.
12153@item fail-compound
12154The parser failed multiple options.  The @var{objects} slot contains
12155a list of of @code{(type . msg)} where @var{type} is one of the
12156@code{<parse-error>} types, and
12157@var{msg} is the message associated with it.
12158@item fail-message
12159Other miscellaneous failure.  The @var{objects} slot contains
12160a mmessage.
12161@end table
12162@end defivar
12163
12164@defivar <parse-error> objects
12165Value of this slot depends on the value of @var{type} slot.
12166@end defivar
12167
12168@defivar <parse-error> token
12169The token at the head of input when failure occur.  If input already
12170reached at the end, this slot is set to @code{#<eof>}.
12171@end defivar
12172@end deftp
12173
12174@node What is a PEG parser, PEG primitive parser builders, PEG parser drivers, PEG parser combinators
12175@subsection What is a PEG parser, really?
12176
12177A PEG parser is a Scheme procedure that takes a list of items as an input,
12178and returns three values:
12179
12180@itemize
12181@item
12182Failure type.  If the parser successfully accepts the input, this value
12183is @code{#f}.  If the parser fails to accept the input,
12184this value is either one of the symbols
12185@code{fail-expect}, @code{fail-unexpect}, @code{fail-compound}
12186and @code{fail-message}.  It corresponds to the @code{type} slot
12187of @code{<parse-error>}, and determines the meaning of the second
12188return value.
12189@item
12190Value.  If the parser successfully accepts the input, this
12191value is the parser's ``result'', sometimes called a semantic
12192value.  If the parser fails to accept the input,
12193this value contains the hint of the failure.  It corresponds
12194to the @code{objects} slot of @code{<parse-error>}; see the documentation
12195of @code{<parse-error>} for the details (@pxref{PEG parser drivers}).
12196@item
12197The rest of the input list.
12198@end itemize
12199
12200Typically you don't need to write a parser as a procedure; instead,
12201you can use one of the parser builders and combinators described in
12202the following sections.
12203
12204We do provide a few utilities to write a parser from scratch, in case
12205you need to do so.
12206
12207@defun return-result value rest
12208@c MOD parser.peg
12209Call this at the tail position of the parser when it succeeds, with
12210@var{value} for the semantic value and @var{rest} for the rest of
12211input.  This is the same as @code{(values #f value rest)}, but
12212clearer to show the intention.
12213@end defun
12214
12215@defun return-failure/expect objs rest
12216@defunx return-failure/unexpect objs rest
12217@defunx return-failure/message msg rest
12218@defunx return-failure/compound fails rest
12219@c MOD parser.peg
12220Call one of these at the tail position of the parser when it fails.
12221The first argument will be in @code{objects} slot of @code{<parse-error>}.
12222
12223@itemize
12224@item
12225If you're expecting some types of objects (@var{objs}) but got anything
12226else, call @code{return-failure/expect}.  It generates @code{fail-expect}
12227type failure.
12228@item
12229If you're not expecting some types of objects (@var{objs}) but got one,
12230call @code{return-failure/unexpect}.  It generates @code{fail-unexpect}
12231type failure
12232@item
12233If you're failing because of all of multiple choices fail, you can
12234gather those failures into an assoc list
12235@code{((fail-type . objs) @dots{})}, and
12236call @code{return-failure/compound}.  It generates @code{fail-compound}
12237type failure.
12238@item
12239Finally, your failure can't be categorized to one of the above,
12240you can call @code{return-failure/message}, with the message
12241describing the reason of the failure.
12242@end itemize
12243@end defun
12244
12245@defun return-failure type objs rest
12246@c MOD parser.peg
12247This should only be used to pass down the failure form other parser.
12248See the example in @code{parse-success?} entry below.
12249@end defun
12250
12251
12252@defun parse-success? r
12253@c MOD parser.peg
12254Check the first return value of a parser to see if it is a success.
12255A typical usage is to check another parser's result and take
12256actions accordingly:
12257
12258@example
12259(receive (r v s) (parser input)
12260  (if (parse-success? r)
12261     (... do things after PARSER succeeds ...
12262       (return-result ...))
12263     (return-failure r v s)))
12264@end example
12265@end defun
12266
12267
12268@node PEG primitive parser builders, PEG ropes, What is a PEG parser, PEG parser combinators
12269@subsection Primitive parser builders
12270
12271Procedures and macros that create parsers.
12272
12273@defun $return val
12274@c MOD parser.peg
12275Returns a parser that always succeeds, without consuming
12276input, and yields @var{val} as the result of parser.
12277
12278Frequently used in @code{$let} and @code{$let*}'s body, but can be
12279used anywhere a parser is expected.
12280@end defun
12281
12282@defun $fail msg-string
12283@c MOD parser.peg
12284Returns a parser that always fails, without consuming input,
12285and uses @var{msg-string} as the failure message.
12286
12287Frequently used to produce user-friendly error messages.
12288@end defun
12289
12290@defun $satisfy pred expect :optional result
12291@c MOD parser.peg
12292This corresponds to ``semantic predicate'' in PEG; a parser
12293that can apply an arbitrary predicate on input.
12294
12295Returns a parser that works as follows:
12296@itemize @bullet
12297@item
12298If the head of input stream satisfies @var{pred},
12299call @code{(@var{result} head (@var{pred} head))} and
12300yield its return value as the result of successful parsing.
12301If @var{result} is omitted, it yields the head of input.
12302@item
12303Otherwise, the parsing fails with @var{expect} as the expected input.
12304@end itemize
12305@end defun
12306
12307@defun $. obj
12308@c MOD parser.peg
12309Creates a parser that matches a Scheme object @var{obj},
12310which may be a character, a string, or a char-set.
12311If @var{obj} is a char-set, the parser matches any character in the set.
12312
12313The resulting parser is atomic, that is, it doesn't consume
12314input when it fails.
12315@end defun
12316
12317@defun $char c
12318@defunx $char-ci c
12319@c MOD parser.peg
12320Returns a parser that accepts a single character, @var{c}.
12321@code{$char-ci} ignores case.
12322On success, the parser yields the input character.
12323The resulting parser is atomic, that is, it doesn't consume
12324input when it fails.
12325@end defun
12326
12327@defun $string str
12328@defunx $string-ci str
12329@c MOD parser.peg
12330Returns a parser that accepts an input that matches
12331a string @var{str}.  @code{$string-ci} ignores case.
12332On success, the parser yields the matched string.
12333
12334The parsing of string is atomic: When the parser fails,
12335it doesn't consume the input.  That is,
12336@code{($string "ab")} is not the same as
12337@code{($let ([a ($char #\a)] [b ($char #\b)]) ($return (string a b)))}.
12338@end defun
12339
12340@defun $one-of cset
12341@c MOD parser.peg
12342Returns a parser that accepts any character in the character set @var{cset}.
12343On success, the parser yields the accepted character.
12344@end defun
12345
12346@defun $none-of cset
12347@c MOD parser.peg
12348Returns a parser that accepts any character not in the character set @var{cset}.
12349On success, the parser yields the accepted character.
12350@end defun
12351
12352@defun $any
12353@c MOD parser.peg
12354Returns a parser that matches any one item, and yields the matched
12355input item on success.
12356It fails only when the input already reached at the end.
12357@end defun
12358
12359@defun $eos
12360@c MOD parser.peg
12361Stands for ``end of stream''.  Returns a parser that matches
12362the end of input.  It never consumes input.
12363@end defun
12364
12365
12366@defmac $match1 pattern result
12367@defmacx $match1 pattern
12368@defmacx $match1 pattern (@code{=>} fail) result
12369@defmacx $match1* pattern result
12370@defmacx $match1* pattern
12371@defmacx $match1* pattern (@code{=>} fail) result
12372@c MOD parser.peg
12373The pattern matcher macro @code{match-let1} lifted to the parser.
12374@xref{Pattern matching}, for the details of supported @var{pattern}.
12375
12376The macro @code{$match1} returns a parser that takes one item
12377from the input stream, and see if it matches @var{pattern}.
12378If it matches, evaluate @var{result} within an environment
12379where pattern variables are bound to matched content, and the
12380parser yields the value of @var{result}.  If the input doesn't
12381match @var{pattern}, or the input is empty, the parser fails without
12382consuming input.
12383
12384In the third form @code{=>} must be a literal identifier and @var{fail}
12385must be an identifier.  The identifier @var{fail} is bound to a procedure
12386that takes one string argument in @var{result}.  You can call @var{fail}
12387at the tail position of @var{result} to make the match fail, with
12388the passed argument as the message.  If @var{fail} is called,
12389no input will be consumed.
12390
12391(NB: The @code{match} macro in @code{util.match} has a similar feature,
12392but it binds @var{fail} to a continuation that abandons the current match
12393clause and go to try the next pattern.  In @code{$match1}, @var{fail}
12394is simply a procedure, so you have to call it at the tail position
12395to make it work.)
12396
12397The macro @code{$match1*} is similar to @code{$match1}, except
12398the entire input is matched @var{pattern}.   It is useful to
12399look into several items in input, instead of just one.
12400Note that if you give a pattern that consumes arbitrary length
12401of input (e.g. @code{($match1* (a ...))}, it will consume entire
12402input.
12403
12404These macros especially come handy when you have a token stream
12405generated by a separate lexer---each token can have some structure
12406(instead of just a character) and you can take advantage of @code{match}.
12407@end defmac
12408
12409
12410
12411@node PEG ropes, PEG choice, PEG primitive parser builders, PEG parser combinators
12412@subsection Ropes
12413
12414Often you want to construct a string out of the results of other parsers.
12415It can be costly to construct strings eagerly, for a string may be
12416just an intermediate one to be a part of a larger string.  We provide
12417a lightweight lazily string construction mechanism, called ropes.
12418
12419A rope is either a character, a string or a pair of ropes.  It allows
12420O(1) concatenation.  A rope becomes a string when @emph{finalized}.
12421The parser drivers such as @code{peg-run-parser} automatically finalizes
12422ropes in the parser result.
12423
12424@defun $->rope parser @dots{}
12425@c MOD parser.peg
12426The parsers must yield either a character, a string, a rope,
12427or @code{#f} or @code{()}.  This procedure
12428returns a parser that matches @var{parser} @dots{}, then gather the
12429result into a rope.  @code{#f} and @code{()} in the results are ignored.
12430@end defun
12431
12432@defun $->string parser @dots{}
12433@c MOD parser.peg
12434This is a common idiom of @code{($lift rope->string ($->rope parser @dots{}))}.
12435@end defun
12436
12437@defun $->symbol parser @dots{}
12438@c MOD parser.peg
12439Like @code{$->string}, but yields a symbol rather than a string.
12440@end defun
12441
12442@defun rope->string rope
12443@c MOD parser.peg
12444Converts a rope to a string.
12445@end defun
12446
12447@defun rope-finalize obj
12448@c MOD parser.peg
12449Converts any ropes in in @var{obj} into strings.
12450@end defun
12451
12452
12453@node PEG choice, PEG sequencing combinators, PEG ropes, PEG parser combinators
12454@subsection Choice, backtrack and assertion combinators
12455
12456@defun $or p1 p2 @dots{}
12457@c MOD parser.peg
12458Returns a choice parser.  Tries the given parser in order on input.
12459If one succeeds, immediately yields its result.
12460If one fails, and does not consume input, then tries the next one.
12461If one fails with consuming input, immediately fails.
12462
12463If @var{p1} @var{p2} @dots{} don't share the same prefix
12464to match, you can let it fail as soon as one parser fails with consuming
12465input.   If more than one parsers do match the same prefix,
12466you want to wrap them with @code{$try} except the last one.
12467@end defun
12468
12469@defun $try p
12470@c MOD parser.peg
12471Returns a parser that accepts the same input
12472the parser @var{p} accepts, but when @var{p} fails
12473the returned parser doesn't consume input.  Used with @code{$or},
12474you can explicitly implement a backtrack behavior.
12475@end defun
12476
12477@defun $optional p :optional fallback
12478@c MOD parser.peg
12479Returns a parser that tries @var{p} on the input.
12480If it succeeds, yielding its result.  If it fails,
12481it still succeeds, yielding @var{fallback} as the result.
12482
12483This is atomic; if @var{p} fails, it doesn't consume input.
12484@end defun
12485
12486@defun $assert p
12487@c MOD parser.peg
12488Returns a parser that accepts the same input as @var{p}
12489and returns its result on success, but never consumes the input.
12490It can be used as a lookahead assertion.
12491@end defun
12492
12493@defun $not p
12494@c MOD parser.peg
12495Returns a parser that succeeds when @var{p} fails, and that fails
12496when @var{p} succeeds.  When @var{p} succeeds, it yields an
12497``unexpected'' error.  It never consumes input in either way.
12498It can be used as a negative lookahead assertion.
12499@end defun
12500
12501@defun $expect p msg-string
12502@c MOD parser.peg
12503Returns a parser that calls a parser @var{p}, and if it succeeds
12504yields its result.  If @var{p} fails, fails with an error message
12505that says expecting @var{msg-string}.
12506Useful to produce user-friendly error messages.
12507@end defun
12508
12509
12510@node PEG sequencing combinators, PEG repetition combinators, PEG choice, PEG parser combinators
12511@subsection Sequencing combinators
12512
12513@defun $seq p1 p2 @dots{}
12514@defunx $seq0 p1 p2 @dots{}
12515@c MOD parser.peg
12516Matches @var{p1}, @var{p2}, @dots{} sequentially.  When all the parser
12517succeeds, @code{$seq} returns
12518the last result, while @var{$seq0} returns the first result.
12519Fails immediately when one of the parsers fails.
12520@end defun
12521
12522@defun $between p1 p2 p3
12523@c MOD parser.peg
12524Matches @var{p1}, @var{p2} and @var{p3} sequentially, and returns
12525the result of @var{p2}.
12526@end defun
12527
12528@defun $bind p f
12529@c MOD parser.peg
12530The basic block of parser combinators;
12531@var{p} argument is a parser, and @var{f} is a procedure
12532that takes a Scheme value and returns a parser.
12533
12534Returns a parser that first applies @var{p} on the input, and if
12535it succeeds, calls @var{f} with the result of @var{p}, and applies
12536the returned parser on the subsequent input.
12537
12538This combinator, along with @code{$return} and @code{$fail},
12539composes a MonadFail interface as in Haskell.  Theoretically any
12540combinators can be built on top of these three.  In practice,
12541however, it is not always easy to build things directly on top
12542of @code{$bind}, and more high-level forms such as @code{$let},
12543@code{$let*} and @code{$lift} are frequently used.
12544@end defun
12545
12546
12547@defmac $let (binding @dots{}) body @dots{}
12548@defmacx $let* (binding @dots{}) body @dots{}
12549@c MOD parser.peg
12550Monadic binding form.  Each @var{binding} can be one of the
12551following forms:
12552
12553@table @code
12554@item (var parser)
12555Run the @var{parser}, and if it succeeds, bind its result to a variable
12556@var{var}.  If it fails, the entire @code{$let} or @code{$let*} immdiately
12557fails.
12558
12559@item (parser)
12560The variable is omitted.  The @var{parser} is run, and if it succeeds,
12561its result is discarded and the next binding or body is evaluated.
12562If it fails, the entire @code{$let} or @code{$let*} immdiately fails.
12563
12564@item parser
12565Same as above.  This form can only be used if @var{parser} is just
12566a vairable reference.
12567@end table
12568
12569Once all the parsers in @var{binding} @dots{} succeeds, @var{body} @dots{}
12570are evaluated in the environment where @var{var} in bindings are bound
12571to the parser results.  The last expression of @var{body} must return
12572a parser.
12573
12574Unlike @code{let}, the parsers in @var{binding} @dots{} are always applied
12575to the input sequentially.  The difference of @code{$let} and
12576@code{$let*} is the scope.  With @code{$let*}, the variables bound
12577in earlier @var{binding} can be used to consturct the @var{parser} later.
12578
12579This means @code{$let} can evaluate all the parsers beforehand, while
12580@code{$let*} may need to construct parsers at the time of processing
12581input.  Creating a parser involves closure allocations, so you want
12582to use @code{$let} whenever possible.
12583
12584Note: @code{$let*} is similar to Haskell's @code{do} construct.  We chose
12585the name @code{$let} and @code{$let*}, for it is easier to see it's
12586a binding form, and also Scheme already uses @code{do} for
12587loop construct.
12588@end defmac
12589
12590@defun $lift f p @dots{}
12591@defunx $lift* f p @dots{}
12592@c MOD parser.peg
12593Lifts a procedure @var{f} onto the parsers' world.
12594
12595In a pseudo type declaration, @code{lift}'s type can be understood
12596as follows:
12597@example
12598lift :: (a b ... -> z) (Parser a) (Parser b) ... -> (Parser z)
12599@end example
12600
12601That is, @code{lift} creates a parser such that
12602it first applies parsers on the input, and if all of them succeeds,
12603it calls @var{f} with the parsers' results as arguments,
12604and the return value of @var{f} becomes the whole parser's result.
12605
12606In other words, the following equivalence holds:
12607@example
12608($lift f p0 p1 @dots{})
12609 @equiv{} ($let ([r0a p0] [r1 p1] @dots{}) ($return (f r0 r1 @dots{})))
12610@end example
12611
12612It is sometimes simpler to use @code{$lift} instead of @code{$let}.
12613For example, the following code creates a parser that matches
12614input with @var{p0} @var{p1} @dots{} sequentially, then yields
12615the list of the parser results:
12616
12617@example
12618($lift list p0 p1 @dots{})
12619@end example
12620
12621Note that after all the parsers succeeds, the whole parser is
12622destined to succeed---the procedure @var{f} can't make the parser
12623fail.  If you need to fail after all the parsers succeeds, use @code{$let}
12624or @code{$let}.
12625@end defun
12626
12627@defun $fold-parsers proc seed ps
12628@c MOD parser.peg
12629@var{Ps} is a list of parsers.  Apply those parsers sequentially
12630on the input, passing around the seed value.  That is, if we let
12631@code{v0}, @var{v1} @dots{} @var{vn} be the result of each parsers in @var{ps},
12632it returns @code{(proc vn (... (proc v2 (proc v1 seed))...))}.
12633
12634If any of the parser in @var{ps} fails, @code{$fold-parsers} fails at
12635that point.
12636
12637Conceptually, it can be written as follows:
12638
12639@example
12640(define ($fold-parsers proc seed ps)
12641  (if (null? ps)
12642    ($return seed)
12643    ($let ([v (car ps)])
12644      ($fold-parsers proc (proc v seed) (cdr ps)))))
12645@end example
12646
12647But we use more efficient implementation.
12648@end defun
12649
12650@defun $fold-parsers-right proc seed ps
12651@c MOD parser.peg
12652Similar to @code{$fold-parsers}, but the folding by @var{proc}
12653right to left.  That is, if we let
12654@code{v0}, @var{v1} @dots{} @var{vn} be the result of each parsers in @var{ps},
12655it returns @code{(proc v1 (proc v2 (... (proc vn seed)...)))}.
12656
12657If any of the parser in @var{ps} fails, @code{$fold-parsers-right} fails at
12658that point.
12659@end defun
12660
12661
12662@node PEG repetition combinators, PEG miscellaneous combinators, PEG sequencing combinators, PEG parser combinators
12663@subsection Repetition combinators
12664
12665
12666@defun $many p :optional min max
12667@defunx $many_ p :optional min max
12668@c MOD parser.peg
12669Without optional arguments, returns
12670a parser that accepts zero or more repetition of @var{p}.
12671On success, @code{$many} yields a list of mached results,
12672while @var{$many_} doesn't keep the results (and faster).
12673
12674Optinoal @var{min} and @var{max} must be nonnegative integers
12675and limit the number of occurrences of @var{p}. The numbers are inclusive.
12676For example,
12677@code{($many ($. #\a) 3)} accepts three or more @code{#\a}'s,
12678and @code{($many ($. #\a) 2 4)} accepts @code{aa}, @code{aaa} and
12679@code{aaaa}.
12680
12681Note that @code{$many} may fail if the input partially matches
12682@code{p}.
12683
12684@example
12685(peg-parse-string ($many ($seq ($. #\a) ($. #\b))) "ababcd")
12686  @result{} (#\b #\b)
12687
12688(peg-parse-string ($many ($seq ($. #\a) ($. #\b))) "ababac")
12689  @result{} *** PARSE-ERROR: expecting #\b at 5, but got #\c
12690@end example
12691
12692If you want to stop @code{$many} at the first two occurrences
12693in the latter case, use @code{$try}:
12694
12695@example
12696(peg-parse-string ($many ($try ($seq ($. #\a) ($. #\b)))) "ababac")
12697  @result{} (#\b #\b)
12698@end example
12699@end defun
12700
12701@defun $many1 p :optional max
12702@defunx $many1_ p :optional max
12703@c MOD parser.peg
12704Returns a parser that accepts one or more occurences of @var{p}.
12705On success, @code{$many1} yields a list of results of @var{p},
12706while @var{$many_} discards the results of @var{p} and faster.
12707If @var{max} is given, it specifies the maximum number of matches.
12708
12709Same as @code{($many p 1 max)} and @code{($many_ p 1 max)}.
12710Provided as a common pattern.
12711@end defun
12712
12713@defun $repeat p n
12714@defunx $repeat_ p n
12715@c MOD parser.peg
12716Returns a parser that accepts exaclty @var{n} occurences of @var{p}.
12717On success, @code{$repeat} yields a list of results of @var{p},
12718while @var{$repeat_} discards the results of @var{p} and faster.
12719
12720Same as @code{($many p n n)} and @code{($many_ p n n)}.
12721Provided as a common pattern.
12722@end defun
12723
12724@defun $many-till p pe :optional min max
12725@defunx $many-till_ p pe :optional min max
12726@c MOD parser.peg
12727Returns a parser that accepts repetition of @var{p}, until it
12728sees input that accepts @var{pe}.
12729On success, @code{$many-till} yields a list of results of @var{p},
12730while @var{$many-till_} discards the results of @var{p} and faster.
12731
12732@example
12733(define comment ($seq ($.";") ($many-till ($any) ($."\n"))))
12734@end example
12735@end defun
12736
12737@defun $sep-by p psep :optional min max
12738@defunx $end-by p psep :optional min max
12739@defunx $sep-end-by p psep :optional min max
12740@c MOD parser.peg
12741These combinators match repetition of @var{p} separated by @var{psep},
12742such as comma-separated values.
12743Returns the list of results of @var{p}.
12744Optional @var{min} and @var{max} are integers that limits the
12745number of repetitions.
12746
12747These three differ only on treatment of the last separator; @code{$sep-by}
12748accepts strictly infix syntax, that is, the input must not end
12749with the separator; while @code{$end-by} accepts strictly suffix syntax,
12750that is, the input must end with the separator; @code{$sep-end-by}
12751makes the last separator optional.
12752@end defun
12753
12754@defun $chain-left p op
12755@defunx $chain-right p op
12756@c MOD parser.peg
12757Returns a parser that parsers left-assosiative and right-associative operators,
12758respectively.
12759
12760The term of expression is parsed by a parser @var{p}, and the
12761operator is parsed by @var{op}.
12762@end defun
12763
12764@node PEG miscellaneous combinators, PEG performance tips, PEG repetition combinators, PEG parser combinators
12765@subsection Miscellaneous combinators
12766
12767@defmac $parameterize ((param expr) @dots{}) parser @dots{}
12768@c MOD parser.peg
12769Returns a parser that runs @var{parser} @dots{}, while altering
12770the parameter values of @var{param} @dots{} with the reuslt of
12771@var{expr} @dots{}, like @code{parameterize}.
12772The @var{parser} @dots{} are run as if in @code{$seq}, so only the value
12773of them is returned on success.
12774
12775You can't use ordinary @code{parameterize}, since such parameterization
12776takes effect on parser construction time, and not when the parser
12777parsing the input.
12778@end defmac
12779
12780@defun $debug name p
12781@c MOD parser.peg
12782Parses the same input as @var{p}, but reports when it is parsing
12783the input, and the result, just like @code{debug-print}.
12784
12785You can't use @code{debug-print} directly, for it will take effect
12786on the parser construction time, not when the input is parsed.
12787@end defun
12788
12789@defmac $lazy p
12790@c MOD parser.peg
12791Returns a parser that works the same as @var{p}, but delays evaluation
12792of @var{p} until needed.  It is useful when you define mutually
12793recursive parsers.
12794@end defmac
12795
12796
12797
12798@node PEG performance tips,  , PEG miscellaneous combinators, PEG parser combinators
12799@subsection Performance
12800
12801
12802
12803@c ----------------------------------------------------------------------
12804@node RFC822 message parsing, Base64 encoding/decoding, PEG parser combinators, Library modules - Utilities
12805@section @code{rfc.822} - RFC822 message parsing
12806@c NODE RFC822メッセージ形式, @code{rfc.822} - RFC822メッセージ形式
12807
12808@deftp {Module} rfc.822
12809@mdindex rfc.822
12810@c EN
12811Defines a set of functions that parses and constructs the ``Internet
12812Message Format'', a text format used to exchange e-mails.
12813The most recent specification can be found in
12814RFC5322.
12815The format was originally defined in RFC 822, and people still
12816call it ``RFC822 format'', hence I named this module.
12817In the following document, I also refer to the format as ``RFC822 format''.
12818@c JP
12819電子メールを交換する際に使用されるテキストのフォーマットである、``インターネット・
12820メッセージ・フォーマット''をパーズ/生成する手続きを定義しています。
12821最新の仕様は、RFC5322にあります。
12822このフォーマットは最初 RFC 822 で定義されたため、未だに``RFC822形式''と
12823呼ばれています。それがこのモジュール名の由来です。
12824以下では、このフォーマットを``RFC822形式''と呼びます。
12825@c COMMON
12826@end deftp
12827
12828@c EN
12829@subheading Parsing message headers
12830@c JP
12831@subheading メッセージヘッダのパーズ
12832@c COMMON
12833
12834@defun rfc822-read-headers iport :key strict? reader
12835@c MOD rfc.822
12836@c EN
12837Reads RFC822 format message from an input port @var{iport},
12838until it reaches the end of the message header.
12839The header fields are broken into a list of the following
12840format:
12841@c JP
12842入力ポート @var{iport} から、メッセージ・ヘッダの終わりに達するまで、
12843RFC822 形式のメッセージを読み込みます。
12844ヘッダ・フィールドは以下のフォーマットのリストに展開、分離されます。
12845@c COMMON
12846@example
12847((name body) @dots{})
12848@end example
12849@c EN
12850@var{Name} @dots{} are the field names, and @var{body} @dots{} are
12851the corresponding field body, both as strings.
12852Field names are converted to lower-case characters.
12853Field bodies are not modified, except the folded line is unfolded.
12854The order of fields are preserved.
12855@c JP
12856@var{Name} @dots{} はフィールド名で、@var{body} @dots{} は対応するフィールドの
12857ボディ、ともに文字列です。
12858フィールド名は小文字に変換されます。フィールドのボディは、行折り返しが
12859取り除かれる以外は変更されません。
12860フィールドの順番は保存されます。
12861@c COMMON
12862
12863@c EN
12864By default, the parser works permissively.  If EOF is encountered
12865during parsing header, it is taken as the end of the message.
12866And if a line that doesn't consist neither continuing (folded) line
12867nor start a new header field, it is simply ignored.
12868You can change this behavior by giving true value to
12869the keyword argument @var{strict?}; then the parser raises an error
12870for such a malformed header.
12871
12872The keyword argument @var{reader} takes a procedure that reads
12873a line from @var{iport}.  Its default is @code{read-line}, which
12874should be enough for most cases.
12875@c JP
12876デフォルトでは、パーザの動作は寛容です。ヘッダをパーズ中に EOF に
12877出会うとそれをメッセージの終端とみなします。継続(折り返し)行でもなく、
12878新しいヘッダフィールドの始端でもない行は無視します。このふるまいは
12879キーワード引数 @var{strict?} に真の値を渡すことで変更することができます。
12880真を渡すと、このような不正な形式のヘッダに対してエラーを発生させるように
12881なります。
12882
12883キーワード引数 @var{reader} は @var{iport} から一行読み込む手続きを
12884とります。デフォルトは @code{read-line} です。ほとんどの場合これで
12885十分のはずです。
12886@c COMMON
12887@end defun
12888
12889@defun rfc822-header->list iport :key strict? reader
12890@c MOD rfc.822
12891@c EN
12892This is an old name of @code{rfc822-read-headers}.  This is kept
12893for the backward compatibility.  The new code should use
12894@code{rfc822-read-headers} instead.
12895@c JP
12896これは@code{rfc822-read-headers}の古い名前です。
12897互換性のために残してありますが、新しいコードは
12898@code{rfc822-read-headers}を使って下さい。
12899@c COMMON
12900@end defun
12901
12902
12903@defun rfc822-header-ref header-list field-name :optional default
12904@c MOD rfc.822
12905@c EN
12906An utility procedure to get a specific field from the parsed
12907header list, which is returned by @code{rfc822-read-headers}.
12908
12909@var{Field-name} specifies the field name in a lowercase string.
12910If the field with given name is in @var{header-list}, the procedure
12911returns its value in a string.  Otherwise, if @var{default} is given,
12912it is returned, and if not, @code{#f} is returned.
12913
12914This procedure can actually be used not only for the result of
12915@code{rfc822-read-headers}, but for retrieving a value keyed
12916by strings in a list-of-list structure: @code{((name value option ...) ...)}.
12917For example, the return value of @code{parse-cookie-string}
12918can be passed to @code{rfc-822-header-ref}
12919(@pxref{HTTP cookie handling}, for @code{parse-cookie-string}).
12920@c JP
12921@code{rfc822-read-headers} が返すパーズ済みのヘッダリストから
12922特定のフィールドを得るためのユーティリティ手続きです。
12923
12924@var{Field-name} は小文字の文字列でフィールド名を指定します。
12925与えられた名前をもつフィールドが @var{header-list} 中にあれば、
12926その値を文字列で返します。そうでない場合、もし @var{default} が
12927与えられていればそれが返り、与えられていなければ @code{#f} が返されます。
12928
12929この手続きは@code{rfc822-read-headers}の結果だけでなく、
12930文字列をキーにしたリストのリスト @code{((name value option ...) ...)}
12931という構造からvalue部分を取り出すのに使えます。
12932例えば@code{parse-cookie-string}の結果を@code{rfc-822-header-ref}に渡せます。
12933(@code{parse-cookie-string}については@pxref{HTTP cookie handling}参照。)
12934@c COMMON
12935
12936@example
12937(rfc822-header-ref
12938  '(("from" "foo@@example.com") ("to" "bar@@example.com"))
12939  "from")
12940 @result{} "foo@@example.com"
12941
12942;; If no entry matches, #f is returned by default
12943(rfc822-header-ref
12944  '(("from" "foo@@example.com") ("to" "bar@@example.com"))
12945  "reply-to")
12946 @result{} #f
12947
12948;; You can give the default value for no-match case
12949(rfc822-header-ref
12950  '(("from" "foo@@example.com") ("to" "bar@@example.com"))
12951  "reply-to" 'none)
12952 @result{} none
12953
12954;; By giving the default value, you can distinguish
12955;; the no-match case and there's actually an entry with value #f.
12956(rfc822-header-ref
12957  '(("from" "foo@@example.com") ("reply-to" #f))
12958  "reply-to" 'none)
12959 @result{} #f
12960@end example
12961@end defun
12962
12963@c EN
12964@subheading Basic field parsers
12965@c JP
12966@subheading 基本的なフィールドパーザ
12967@c COMMON
12968
12969@c EN
12970Several procedures are provided to parse "structured" header fields
12971of RFC2822 messages.  These procedures deal with the body of
12972a header field, i.e. if the header field is
12973"@code{To: Wandering Schemer <schemer@@example.com>}",
12974they parse "@code{Wandering Schemer <schemer@@example.com>}".
12975
12976Most of procedures take an input port.  Usually you first parse
12977the entire header fields by @code{rfc822-read-headers},
12978obtain the body of the header by @code{rfc822-header-ref},
12979then open an input string port for the body and use those
12980procedures to parse them.
12981
12982The reason for this complexity is because you need
12983different tokenization schemes depending on the type of the field.
12984Rfc2822 also allows comments to appear between tokens for most cases,
12985so a simple-minded regexp won't do the job,
12986since rfc2822 comment can be nested
12987and can't be represented by regular grammar.
12988So, this layer of procedures are designed flexible enough
12989to handle various syntaxes.  For the standard header types,
12990high-level parsers are also provided; see "specific field parsers" below.
12991@c JP
12992RFC2822メッセージの「構造化」されたヘッダフィールドをパーズするために、
12993いくつかの手続きが提供されています。これらの手続きはヘッダフィールドの
12994本体部を処理します。たとえば、ヘッダフィールドが、
12995"@code{To: Wandering Schemer <schemer@@example.com>}" であれば、これらの
12996手続きは "@code{Wandering Schemer <schemer@@example.com>}" をパーズします。
12997
12998ほとんどの手続きは入力ポートを引数にとります。通常は最初に、ヘッダフィールド
12999全部を @code{rfc822-read-headers} でパーズし、ヘッダの本体を
13000@code{rfc822-header-ref} で取得してから、その本体用に入力文字列ポートを
13001オープンして、それをこれらの手続きを用いてパーズします。
13002
13003このように複雑になっているのは、フィールドのタイプによって別々の
13004トークン化スキームが必要になるからです。RFC2822 では多くの場合
13005トークン間にコメントがあらわれことを許しているので、初心な正規表現では
13006うまくいきません。RFC2822 のコメントはネスト可能で、正規表現では表現
13007しきれないからです。
13008そういうわけで、このレイヤの手続きは、いろいろな構文に対応できるよう
13009十分な柔軟性があるように設計されています。標準的なタイプのヘッダについては
13010高水準のパーザも提供されています。後述の「特定フィールド用パーザ」を
13011参照してください。
13012@c COMMON
13013
13014@defun rfc822-next-token iport :optional tokenizer-specs
13015@c MOD rfc.822
13016@c EN
13017A basic tokenizer.  First it skips whitespaces and/or
13018comments (@code{CFWS}) from @var{iport}, if any.  Then
13019reads one token according to @var{tokenizer-specs}.  If @var{iport}
13020reaches EOF before any token is read, EOF is returned.
13021
13022@var{Tokenizer-specs} is a list of tokenizer spec, which is
13023either a char-set or a cons of a char-set and a procedure.
13024
13025After skipping @code{CFWS}, the procedure peeks a character
13026at the head of @var{iport}, and checks it
13027against the char-sets in @var{tokenizer-specs} one by one.
13028If a char-set that contains the character belongs to is found,
13029then a token is retrieved as follows:
13030If the tokenizer spec is just a char-set, a sequence of characters
13031that belong to the char-set consists a token.
13032If it is a cons, the procedure is called with @var{iport} to
13033read a token.
13034
13035If the head character doesn't match any char-sets,
13036the character is taken from @var{iport} and returned.
13037
13038The default @var{tokenizer-specs} is as follows:
13039@c JP
13040基本的なトークナイザです。まず、もしあれば、白空白および/または
13041コメント (@code{CFWS}) を @var{iport} から読み飛ばします。それから、
13042@var{tokenizer-specs} にしたがってトークンをひとつ読み込みます。
13043トークンを読み込む前に、@var{iport} が EOF に到達したら、EOF が
13044返されます。
13045
13046@var{tokenizer-specs} はトークナイザ仕様のリストです。
13047トークナイザ仕様は、文字集合または文字集合と手続きのペアのどちらかです。
13048
13049@code{CFWS} を読み飛ばしたあと、この手続きは @var{iport} の先頭の一文字
13050を見て、@var{tokenizer-specs} のひとつひとつに対してチェックします。
13051その文字が含まれている文字集合がみつかれば、トークンを次のようにして
13052引き出します。トークナイザ仕様が文字集合だけの場合、その文字集合に
13053属している文字の並びがトークンを構成します。トークナイザ仕様が文字集合と
13054手続きのペアだったら、その手続きを @var{iport} とともに呼びだし、
13055トークンを読み込みます。
13056
13057もし、先頭の文字がどの文字集合ともマッチしなければ、その文字が
13058@var{iport} から取り出され、それが返されます。
13059
13060デフォルトの @var{tokenizer-specs} は以下のようになっています。
13061@c COMMON
13062@example
13063(list (cons #["] rfc822-quoted-string)
13064      (cons *rfc822-atext-chars* rfc822-dot-atom))
13065@end example
13066@c EN
13067Where @code{rfc822-quoted-string} and @code{rfc822-dot-atom}
13068are tokenizer procedures described below, and @code{*rfc822-atext-chars*}
13069is bound to a char-set of @code{atext} specified in rfc2822.
13070This means @code{rfc822-next-token} retrieves a token
13071either @code{quoted-string} or @code{dot-atom} specified in rfc2822
13072by default.
13073
13074Using @var{tokenizer-specs}, you can customize how the header
13075field is parsed.  For example, if you want to retrieve a token
13076that is either (1) a word constructed by alphabetic characters, or
13077(2) a quoted string, then you can call @code{rfc822-next-token}
13078by this:
13079@c JP
13080ここで @code{rfc822-quoted-string} および @code{rfc822-dot-atom} は
13081後述するトークナイザ手続きで、@code{*rfc822-atext-chars*} は RFC2822 で
13082規定された @code{atext} の文字集合に束縛されています。
13083つまり、@code{rfc822-next-token} はデフォルトでは RFC2822 で規定された
13084@code{quoted-string} あるいは @code{dot-atom} のトークンを引き出します。
13085
13086@var{tokenizer-specs} をつかって、ヘッダフィールドのパーズ方法を
13087カスタマイズすることができます。たとえば、(1) 英字で構成された単語、または
13088(2) クウォート文字列、のトークンを取り出したいときには、
13089@code{rfc822-next-token} をこんなふうに呼べます。
13090@c COMMON
13091
13092@example
13093(rfc822-next-token iport
13094   `(#[[:alpha:]] (#["] . ,rfc822-quoted-string)))
13095@end example
13096@end defun
13097
13098@defun rfc822-field->tokens field :optional tokenizer-specs
13099@c MOD rfc.822
13100@c EN
13101A convenience procedure.  Creates an input string port for
13102a field body @var{field}, and calls @code{rfc822-next-token}
13103repeatedly on it until it consumes all input, then returns
13104a list of tokens.   @var{Tokenizer-specs} is passed to
13105@code{rfc822-next-token}.
13106@c JP
13107これは便利関数です。フィールド本体 @var{field} に対応する入力文字列ポート
13108を生成し、それに対して、@code{rfc822-next-token} を全入力を消費するまで、
13109繰り返しよび、トークンのリストを返します。@var{Tokenizer-specs} は、
13110@code{rfc822-next-token} に渡されます。
13111@c COMMON
13112@end defun
13113
13114@defun rfc822-skip-cfws iport
13115@c MOD rfc.822
13116@c EN
13117A utility procedure that consumes any comments and/or whitespace
13118characters from @var{iport}, and returns the head character
13119that is neither a whitespace nor a comment.  The returned character
13120remains in @var{iport}.
13121@c JP
13122@var{iport} から、すべてのコメントおよび/または白空白文字を消費し、
13123白空白でもコメントでもない、先頭の文字を返します。返された文字は、
13124@var{iport}に残ります。
13125@c COMMON
13126@end defun
13127
13128@defvr {Constant} *rfc822-atext-chars*
13129@c MOD rfc.822
13130@c EN
13131Bound to a char-set that is a valid constituent of @code{atom}.
13132@c JP
13133@code{atom} を構成する有効な文字集合に束縛されています。
13134@c COMMON
13135@end defvr
13136
13137@defvr {Constant} *rfc822-standard-tokenizers*
13138@c MOD rfc.822
13139@c EN
13140Bound to the default @var{tokenizer-specs}.
13141@c JP
13142デフォルトの @var{tokenizer-specs} に束縛されています。
13143@c COMMON
13144@end defvr
13145
13146@defun rfc822-atom iport
13147@defunx rfc822-dot-atom iport
13148@defunx rfc822-quoted-string iport
13149@c MOD rfc.822
13150@c EN
13151Tokenizers for @code{atom}, @code{dot-atom} and @code{quoted-string},
13152respectively.  The double-quotes and escaping backslashes within
13153@code{quoted-string} are removed by @code{rfc822-quoted-string}.
13154@c JP
13155それぞれ、@code{atom}、@code{dot-atom} および @code{quoted-string} に
13156対応するトークナイザです。@code{quoted-string} 中の二重引用符および
13157エスケープのためのバックスラッシュは @code{rfc822-quoted-string} に
13158よって取り除かれます。
13159@c COMMON
13160@end defun
13161
13162@c EN
13163@subheading Specific field parsers
13164@c JP
13165@subheading 特定フィールド用パーザ
13166@c COMMON
13167
13168@defun rfc822-parse-date string
13169@c MOD rfc.822
13170@c EN
13171Takes RFC-822 type date string, and returns eight values:
13172@c JP
13173RFC822 形式の日付文字列を取り、8つの値を返します。
13174@c COMMON
13175@example
13176year, month, day-of-month, hour, minutes, seconds, timezone,
13177day-of-week.
13178@end example
13179
13180@c EN
13181@emph{Timezone} is an offset from UT in minutes.
13182@emph{Day-of-week} is a day from sunday,
13183and may be #f if that information is not available.
13184@emph{Month} is an integer between 1 and 12, inclusive.
13185If the string is not parsable, all the elements are #f.
13186@c JP
13187@emph{timezone} は UT(グリニッジ標準時)からの分単位のオフセットです。
13188@emph{day-of-week} は日曜日から数えた曜日で、情報が不足している場合は #f です。
13189@emph{month}は1から12までの整数です。
13190文字列がパーズ不可能ならば、全ての要素が #f になります。
13191@c COMMON
13192@end defun
13193
13194@defun rfc822-date->date string
13195@c MOD rfc.822
13196@c EN
13197Parses RFC822 type date format and returns SRFI-19 @code{<date>} object
13198(see @ref{SRFI-19 Date}).  If @var{string} can't be parsed,
13199returns @code{#f} instead.
13200
13201To construct rfc822 date string from SRFI-19 date, you can use
13202@code{date->rfc822-date} below.
13203@c JP
13204RFC822形式の日付フォーマットをパーズし、SRFI-19 の @code{<date>} オブジェクト
13205(@ref{SRFI-19 Date} 参照) を返します。@var{string} がパーズできないときは
13206かわりに @code{#f} を返します。
13207
13208SRFI-19の日付からRFC822形式の日付文字列を作成するには、
13209後で述べる@code{date->rfc822-date}が使えます。
13210@c COMMON
13211@end defun
13212
13213@c EN
13214@subheading Message constructors
13215@c JP
13216@subheading メッセージの構築
13217@c COMMON
13218
13219@defun rfc822-write-headers headers :key output continue check
13220@c MOD rfc.822
13221This is a sort of inverse function of @code{rfc822-read-headers}.
13222It receives a list of header data, in which each header data
13223consists of @code{(<name> <body>)}, and writes them out in RFC822 header
13224field format to the output port specified by the @var{output} keyword
13225argument.  The default output is the current output port.
13226
13227By default, the procedure assumes @var{headers} contains all the
13228header fields, and adds an empty line in the end of output
13229to indicate the end of the header.  You can pass a true value to
13230the @var{continue} keyword argument to prevent this, enabling
13231more headers can be added later.
13232
13233I said ``a sort of'' above.  That's because this function doesn't
13234(and can't) do the exact inverse.
13235Specifically, the caller is responsible for line folding and
13236make sure each header line doesn't exceed the ``hard limit'' defined
13237by RFC2822 (998 octets).  This procedure cannot do the line
13238folding on behalf of the caller, because the places where
13239line folding is possible depend on the semantics of each
13240header field.
13241
13242It is also the caller's responsibility to make sure header
13243field bodies don't have any characters except non-NUL US-ASCII
13244characters.  If you want to include characters outside of that
13245range, you should convert them in the way allowed by the
13246protocol, e.g. MIME.  The @code{rfc.mime} module
13247(@pxref{MIME message handling}) provides a convenience procedure
13248@code{mime-encode-text} for such purpose.
13249Again, this procedure cannot do the encoding automatically,
13250since the way the field
13251should be encoded depends on header fields.
13252
13253What this procedure can do is to check and report such violations.
13254By default, it runs several checks and signals an error if it finds any
13255violations of RFC2822.  You can control this checking behavior
13256by the @var{check} keyword argument.  It can take one of the
13257following values:
13258
13259@table @code
13260@item :error
13261Default.  Signals an error if a violation is found.
13262@item #f, :ignore
13263Doesn't perform any check.  Trust the caller.
13264@item @var{procedure}
13265When @code{rfc822-write-headers} finds a violation, the procedure
13266is called with three arguments; the header field name,
13267the header field body, and the type of violation explained below.
13268The procedure may correct the problem and return two values,
13269the corrected header field name and body.  The returned values
13270are checked again.  If the procedure returns the
13271header field name and body unchanged, an error is signaled
13272in the same way as @code{:error} is specified.
13273@end table
13274
13275The third argument passed to the procedure given to the @var{check}
13276argument is one of the following symbols.  New symbols may be
13277added in future versions for more checks.
13278
13279@table @code
13280@item incomplete-string
13281Incomplete string is passed.
13282@item bad-character
13283Header field contains characters outside of US-ASCII or NUL.
13284@item line-too-long
13285Line length exceeds 998 octet limit.
13286@item stray-crlf
13287The string contains CR and/or LF character that doesn't consist of
13288proper line folding.
13289@end table
13290
13291@end defun
13292
13293@defun date->rfc822-date date
13294@c MOD rfc.822
13295@c EN
13296Takes SRFI-19 @code{<date>} object (see @ref{SRFI-19 Date})
13297and returns a string of its rfc822 date representation.
13298This is a reverse operation of @code{rfc822-date->date}.
13299@c JP
13300SRFI-19の@code{<date>}オブジェクト(@ref{SRFI-19 Date}参照)
13301を取り、そのrfc822日付形式表現の文字列を返します。
13302@code{rfc822-date->date}の逆関数です。
13303@c COMMON
13304@end defun
13305
13306
13307@c ----------------------------------------------------------------------
13308@node Base64 encoding/decoding, HTTP cookie handling, RFC822 message parsing, Library modules - Utilities
13309@section @code{rfc.base64} - Base64 encoding/decoding
13310@c NODE Base64エンコーディング, @code{rfc.base64} - Base64エンコーディング
13311
13312@deftp {Module} rfc.base64
13313@mdindex rfc.base64
13314@c EN
13315This module defines a few functions to encode/decode Base64 format,
13316defined in RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}), section 6.3
13317and RFC 4648 (@uref{https://www.ietf.org/rfc/rfc4648.txt}).
13318@c JP
13319このモジュールでは、RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}) の6.3節
13320およびRFC 4648 (@uref{https://www.ietf.org/rfc/rfc4648.txt}) で
13321定義されている Base64 フォーマットへエンコード/デコードするいくつかの
13322手続きを定義しています。
13323@c COMMON
13324@end deftp
13325
13326@defun base64-encode :key line-width url-safe
13327@c MOD rfc.base64
13328@c EN
13329Reads byte stream from the current input port, encodes it in Base64
13330format and writes the result character stream to the current output port.
13331The conversion ends when it reads EOF from the current input port.
13332
13333Newline characters can be inserted to keep the maximum line width to
13334the value given to the @var{line-width} keyword argument.  The default
13335value of @var{line-width} is 76, as specified in RFC2045.  You can give
13336@code{#f} or zero to @var{line-width} to suppress line splitting.
13337@c JP
13338現在の入力ポートからバイト・ストリームを読み込み、それを Base64 フォーマットに
13339エンコードし、現在の出力ポートに文字ストリームとして書き出します。
13340現在の入力ポートから EOF を読み込むと変換を終了します。
13341
13342一行あたりの文字数が@var{line-width}に与えられた文字数を越えないように、
13343改行文字が適切に出力に挿入されます。@var{line-width}のデフォルト値は
13344RFC2045に従い76となっています。@var{line-width}に@code{#f}または@code{0}
13345を与えることで改行を抑制することができます。
13346@c COMMON
13347
13348@c EN
13349If a true value is given to @var{url-safe},
13350the input bytes will be encoded with an
13351alternative encoding table, which substitutes @code{+} instead of
13352@code{-} and @code{/} instead of @code{_}. The result will contain
13353filename and url safe characters only.  Default value of @var{url-safe}
13354is false.
13355@c JP
13356@var{url-safe}に真の値を与えると、標準の Base64 と異なったエンコーディングテーブルを使って
13357入力をエンコードします。このエンコーディングでは、@code{+}の代わりに
13358@code{-}が、@code{/}の代わりに@code{_}が使われます。このエンコーディングは
13359ファイル名やURLの一部として使うのに適しています。@var{url-safe}の
13360デフォルト値は偽です。
13361@c COMMON
13362@end defun
13363
13364@defun base64-encode-string string :key line-width url-safe
13365@c MOD rfc.base64
13366@c EN
13367Converts contents of @var{string} to Base64 encoded format.
13368Input string can be either complete or incomplete string;
13369it is always interpreted as a byte sequence.
13370@c JP
13371@var{string} の内容を Base64 でエンコードされたフォーマットに変換します。
13372入力となる文字列は、完全文字列でも不完全文字列でも良いです。
13373常にバイト・シーケンスとして扱われます。
13374@c COMMON
13375@end defun
13376
13377@defun base64-decode :key url-safe
13378@c MOD rfc.base64
13379@c EN
13380Reads character stream from the current input port, decodes it from Base64
13381format and writes the result byte stream to the current output port.
13382The conversion ends when it reads EOF or the termination character
13383(@code{=}).  The characters which does not in legal Base64 encoded character
13384set are silently ignored.
13385@c JP
13386現在の入力ポートから文字ストリームを読み込み、それを Base64 フォーマットとして
13387デコードし、現在の出力ポートにバイトストリームとして書き出します。
13388変換は EOF か、終端文字 (@code{=}) を読み込むと終了します。
13389Base64 でエンコードされた文字として適当でない文字は沈黙のまま無視されます。
13390@c COMMON
13391@end defun
13392
13393@defun base64-decode-string string :key url-safe
13394@c MOD rfc.base64
13395@c EN
13396Decodes a Base64 encoded string @var{string} and returns
13397the result as a string.
13398The conversion terminates at the end of @var{string} or
13399the termination character (@code{=}).
13400The characters which does not in legal Base64 encoded character
13401set are silently ignored.
13402@c JP
13403Base64 でエンコードされた文字列 @var{string} をデコードして文字列を返します。
13404変換は @var{string} の終わりか、終端文字 (@code{=}) で終了します。
13405Base64 でエンコードされた文字として適当でない文字は沈黙のまま無視されます。
13406@c COMMON
13407@end defun
13408
13409@c ----------------------------------------------------------------------
13410@node HTTP cookie handling, FTP, Base64 encoding/decoding, Library modules - Utilities
13411@section @code{rfc.cookie} - HTTP cookie handling
13412@c NODE HTTPクッキー, @code{rfc.cookie} - HTTPクッキー
13413
13414@deftp {Module} rfc.cookie
13415@mdindex rfc.cookie
13416@c EN
13417Defines a set of functions to parse and construct a ``cookie'' information
13418defined in RFC 6265.
13419@c JP
13420RFC 6265で定義されている「クッキー」情報を
13421パースしたり構築したりするための手続きを定義しています。
13422@c COMMON
13423@end deftp
13424
13425@defun parse-cookie-string string :optional version
13426@c MOD rfc.cookie
13427@c EN
13428Parse a cookie string @var{string}, which is the value of ``Cookie''
13429request header.  Usually, the same information is available to CGI
13430program via the environment variable @code{HTTP_COOKIE}.
13431
13432If the cookie version is known, via ``Cookie2'' request header,
13433the integer version must be passed to @var{version}.  Otherwise,
13434@code{parse-cookie-string} figures out the version from @var{string}.
13435
13436The result has the following format.
13437@c JP
13438リクエスト・ヘッダの Cookie の値のクッキー文字列 @var{string} を
13439パースします。通常、CGI プログラムでは、同じ情報は環境変数
13440@var{HTTP_COOKIE} を通して利用できます。
13441
13442リクエスト・ヘッダ Cookie2 を通してクッキーのバージョンが分かる
13443場合は、@var{version} へ整数のバージョンとして渡されなければなりません。
13444そうでなければ、@code{parse-cookie-string} は @var{string} からバージョンを
13445取り出します。
13446
13447結果は以下のフォーマットを持ちます。
13448@c COMMON
13449@example
13450((<name> <value> [:path <path>] [:domain <domain>] [:port <port>])
13451 @dots{})
13452@end example
13453@c EN
13454where @var{<name>} is the attribute name, and @var{<value>} is
13455the corresponding value.  If the attribute doesn't have value,
13456@var{<value>} is @code{#f}.  (Note that it differs from the attribute
13457having null value, @code{""}.)
13458If the attribute has path, domain or port options, it is given
13459as a form of keyword-value pair.
13460@c JP
13461@var{<name>} は属性名で、@var{<value>} は対応する値です。
13462属性が値を持たない場合、@var{<value>} は @code{#f} になります。
13463(属性が NULL 値を持つ場合は、@code{""} となることに注意。)
13464属性がパスやドメイン、ポート番号のオプションを持つ場合は、
13465キーワード-値のペアの形式で与えられます。
13466@c COMMON
13467
13468@c EN
13469Note: To retrieve the value of a specific cookie conveniently, you can use
13470@code{rfc822-header-ref} (@pxref{RFC822 message parsing}).
13471@c JP
13472註: 特定のクッキーの値を簡単に取り出すには
13473@code{rfc822-header-ref}が使えます (@ref{RFC822 message parsing}参照)。
13474@c COMMON
13475@end defun
13476
13477@defun construct-cookie-string specs :optional version
13478@c MOD rfc.cookie
13479@c EN
13480Given list of cookie specs, creates a cookie string suitable for
13481@code{Set-cookie2} or @code{Set-cookie} header.
13482
13483Optional @var{version} argument specifies cookie protocol version.
134840 for the old Netscape style format, and 1 for RFC2965 style format.
13485When omitted, version 1 is assumed.
13486
13487Each cookie spec has the following format.
13488@c JP
13489与えられたクッキーの仕様のリストから、@code{Set-cookie2} か
13490@code{Set-cookie} ヘッダに適切なクッキー文字列を作ります。
13491
13492オプションの @var{version} 引数は、クッキー・プロトコルのバージョンを
13493指定するものです。0 は古い Netscape スタイルのフォーマットで、1 は
13494RFC2965 スタイルのフォーマットです。省略された場合、1 が指定されたものと
13495されます。
13496
13497クッキーの仕様は以下のフォーマットを持ちます。
13498@c COMMON
13499@example
13500(<name> <value> [:comment <comment>] [:comment-url <url>]
13501                [:discard <bool>] [:domain <domain>]
13502                [:max-age <age>] [:path <path>]
13503                [:port <port-list>] [:secure <bool>] [:http-only <bool>]
13504                [:version <version>] [:expires <date>])
13505@end example
13506@c EN
13507Where,
13508@table @code
13509@item <name>
13510A string.  Name of the cookie.
13511@item <value>
13512Value of the cookie.  May be a string, or @code{#f} if no value is needed.
13513@item <comment> <url> <domain> <path> <port-list>
13514Strings.
13515@item <bool>
13516Boolean value
13517@item <age> <version>
13518Integers
13519@item <date>
13520Either an integer (seconds since Epoch) or a formatted date string
13521following the netscape cookie specification.
13522@end table
13523@c JP
13524@table @code
13525@item <name>
13526文字列。クッキーの名前。
13527@item <value>
13528クッキーの値。文字列か、値が必要なければ @code{#f} 。
13529@item <comment> <url> <domain> <path> <port-list>
13530文字列。
13531@item <bool>
13532真偽値。
13533@item <age> <version>
13534整数。
13535@item <date>
13536整数(エポックからの秒数)か、Netscape のクッキー仕様に従うフォーマットされた
13537日付文字列。
13538@end table
13539@c COMMON
13540
13541@c EN
13542The attribute values are quoted appropriately.  If the specified attribute
13543is irrelevant for the @var{version}, it is ignored.  So you can pass
13544the same specs to generate both old-style and new-style cookie strings.
13545
13546Return value is a list of cookie strings, each of which stands for
13547each cookie.  For old-style protocol (using @code{Set-cookie} header)
13548you must send each of them by individual header.  For new-style
13549protocol (using @code{Set-cookie2} header), you can join them
13550with comma and send it at once.  See RFC6265 for further details.
13551
13552Some examples:
13553@c JP
13554属性値は適切にクォートされます。指定された属性が @var{version} に不適切な
13555場合は無視されます。古いスタイルと新しいスタイルの両方のクッキー文字列を
13556作るために同じ仕様を渡すことができます。
13557
13558戻り値はそれぞれのクッキー文字列のリストです。(@code{Set-cookie} を使う)
13559古いスタイルのプロトコルでは、それぞれを独立したヘッダとして送らなければ
13560なりません。(@code{Set-cookie2} ヘッダを使う)新しいプロトコルでは、
13561それらをカンマで繋ぎ、一度に送ることができます。詳細は RFC6265 を見て下さい。
13562
13563いくつかの例を示します。
13564@c COMMON
13565@example
13566(construct-cookie-string
13567   `(("name" "foo" :domain "foo.com" :path "/"
13568                   :expires ,(+ (sys-time) 86400) :max-age 86400)))
13569 @result{} ("name=foo;Domain=foo.com;Path=/;Max-age=86400")
13570
13571(construct-cookie-string
13572   `(("name" "foo" :domain "foo.com" :path "/"
13573                   :expires ,(+ (sys-time) 86400) :max-age 86400))
13574   0)
13575 @result{}
13576 ("name=foo;Domain=foo.com;Path=/;Expires=Sun, 09-Sep-2001 01:46:40 GMT")
13577@end example
13578@end defun
13579
13580@c ----------------------------------------------------------------------
13581@node FTP, HMAC keyed-hashing, HTTP cookie handling, Library modules - Utilities
13582@section @code{rfc.ftp} - FTP client
13583@c NODE FTPクライアント, @code{rfc.ftp} - FTPクライアント
13584
13585@deftp {Module} rfc.ftp
13586@mdindex rfc.ftp
13587@c EN
13588This module provides a set of convenient functions to access ftp
13589servers.
13590@c JP
13591このモジュールはFTPサーバーにアクセスするための便利関数群を提供します。
13592@c COMMON
13593@end deftp
13594
13595@deftp {Class} <ftp-connection>
13596@clindex ftp-connection
13597@c MOD rfc.ftp
13598@c EN
13599An object to keep FTP connection to a server.  It has the following
13600public slots.
13601@c JP
13602ひとつのサーバーへのFTPコネクションを保持するオブジェクト。以下の公開
13603スロットがあります。
13604@c COMMON
13605
13606@defivar {<ftp-connection>} transfer-type
13607@c EN
13608FTP transfer type.  Must be one of the following symbols:
13609@code{ascii}, @code{binary} (default), and @code{image}.
13610@c JP
13611FTPの転送タイプ。以下のシンボルのどれかひとつでなければなりません。
13612@code{ascii}、@code{binary} (デフォルト)、および@code{image}。
13613@c COMMON
13614@end defivar
13615
13616@defivar {<ftp-connection>} passive
13617@c EN
13618True if the client uses passive connection.c
13619@c JP
13620パッシブコネクションを使うとき真。
13621@c COMMON
13622@end defivar
13623
13624@defivar {<ftp-connection>} log-drain
13625@c EN
13626This slot must hold a @code{<log-drain>} instance (@pxref{User-level logging})
13627or @code{#f}.  If it has a @code{<log-drain>} instance, ftp communication
13628logs are put to it.
13629@c JP
13630このスロットは@code{<log-drain>}のインスタンス(@ref{User-level logging}参照)
13631を保持しているかあるいは@code{#f}でなければなりません。@code{<log-drain>}
13632のインスタンスを保持している場合、FTP通信のログがそこに記録されます。
13633@c COMMON
13634
13635@end defivar
13636@end deftp
13637
13638@deftp {Condition Type} <ftp-error>
13639@clindex ftp-error
13640@c MOD rfc.ftp
13641@c EN
13642This type of exception is thrown when the ftp server returns an error code.
13643Inherits @code{<error>}.  The message field contains the server reply,
13644including the status code.
13645@c JP
13646このタイプの例外はFTPサーバーがエラーコードを返したときに投げられます。
13647@code{<error>}を継承しています。メッセージフィールドにはステータスコー
13648ドを含むサーバーからの返答が含まれます。
13649@c COMMON
13650@end deftp
13651
13652@defun call-with-ftp-connection host proc :key passive port username password account log-drain
13653@c MOD rfc.ftp
13654@c EN
13655A high-level convenience routine to open an ftp connection to
13656an ftp server and calls the given procedure.
13657@c JP
13658高水準の便利関数で、ひとつのFTPサーバーへのFTPコネクションをオープンし、
13659与えられた手続きを呼びます。
13660@c COMMON
13661
13662@c EN
13663The server is specified by @var{host}.  Optionally, you can add user
13664name and/or port number by the form
13665@code{@var{user}@@@var{servername}:@var{port}}.
13666If present, user and port portion in @var{host} supersedes the
13667keyword arguments.
13668@c JP
13669接続するサーバーは@var{host}で指定します。オプションでユーザー名、ポー
13670ト番号を@code{@var{user}@@@var{servername}:@var{port}}という形式で指定
13671できます。もしあれば、@var{host}の部分をキーワード引数にすることもでき
13672ます。
13673@c COMMON
13674
13675@c EN
13676If ftp connection to @var{host} is established successfully,
13677@var{proc} is called with one argument, which is an instance
13678of @code{<ftp-connection>}.  When @var{proc} returns,
13679the connection is closed and the return value(s) of @var{proc}
13680is/are returned from @code{call-with-ftp-connection}.
13681When an exception is thrown, the ftp connection is closed
13682before the exception escapes from @code{call-with-ftp-connection}.
13683@c JP
13684@var{host}へのFTPコネクション確立が成功したら、@var{proc}が引数を1つとっ
13685て呼ばれます。この引数は@code{<ftp-connection>}のインスタンスです。
13686@var{proc}から返ったときにこのコネクションはクローズされ、@var{proc}の
13687返り値が@code{call-with-ftp-connection}から返されます。例外がなげられ
13688たら、その例外が@code{call-with-ftp-connection}から外へでる前にFTPコネ
13689クションはクローズされます。
13690@c COMMON
13691
13692@c EN
13693When a true value is given to the keyword argument @var{passive},
13694created ftp connection will use passive mode to send/receive
13695data.  The default is the active mode.
13696@c JP
13697キーワード引数@var{passive}に真値を与えると、FTPコネクションはパッシブ
13698モードになります。デフォルトではアクティブモードです。
13699@c COMMON
13700
13701@c EN
13702The keyword argument @var{port}, @var{username}, and @var{password}
13703specify the port number, username, and password, respectively.
13704When omitted, the port number defaults to 21, @var{username} to
13705@code{"anonymous"}, and @var{password} to @code{"anonymous@@"}.
13706Note that the port number and/or username are ignored when
13707those information is given in the @var{host} argument.
13708@c JP
13709キーワード引数@var{port}、@var{username}および@var{password}は
13710それぞれ、ポート番号、ユーザー名、パスワードを指定するのに使います。
13711省略された場合のデフォルトは、ポート番号が21,@var{username}が
13712@code{"anonymous"}、@var{password}が@code{"anonymous@@"}にセットされま
13713す。ポート番号とユーザー名は@var{host}引数で指定されたものが優先されま
13714す。
13715@c COMMON
13716
13717@c EN
13718If the keyword argument @var{account} is given, its value
13719is passed to ftp @code{ACCT} command when requested by
13720the server at login time.  The default value is a null string @code{""}.
13721@c JP
13722キーワード引数@var{account}が与えられた場合には、その値が、ログイン時
13723にサーバーからの要求でFTPの@code{ACCT}コマンドに渡されます。デフォルト
13724では空文字列@code{""}です。
13725@c COMMON
13726
13727@c EN
13728The keyword argument @var{log-drain} is set to the created
13729ftp connection's @code{log-drain} slot.
13730@c JP
13731キーワード引数@var{log-drain}が生成したFTPコネクションの
13732@code{log-drain}スロットに設定されます。
13733@c COMMON
13734@end defun
13735
13736@defun ftp-transfer-type conn
13737@c MOD rfc.ftp
13738@c EN
13739Returns the transfer type of the ftp connection @code{conn}.
13740Can be used with setter, e.g. @code{(set! (ftp-transfer-type conn) 'ascii)}.
13741@c JP
13742指定したFTPコネクション@code{conn}の転送タイプを返します。セッターを適
13743用することもできます。たとえば、@code{(set! (ftp-transfer-type conn) 'ascii)}
13744とします。
13745@c COMMON
13746@end defun
13747
13748@defun ftp-passive? conn
13749@c MOD rfc.ftp
13750@c EN
13751Returns true iff ftp connection uses passive data retrieval.
13752@c JP
13753指定したFTPコネクションがパッシブモードである場合でその場合に限り真を
13754返します。
13755@c COMMON
13756@end defun
13757
13758@defun ftp-login host :key passive port username password account log-drain
13759@c MOD rfc.ftp
13760@c EN
13761Connects to the ftp server specified by @var{host}, authenticate the user,
13762and returns a newly created @code{<ftp-connection>} instance.
13763This procedure is called implicitly when you use
13764@code{call-with-ftp-connection}.  The semantics of
13765the @var{host} argument and the keyword arguments are
13766the same as @code{call-with-ftp-connection}.
13767@c JP
13768@var{host}で指定されたFTPサーバーに接続し、ユーザー認証をすませ、新し
13769く生成した@code{<ftp-connection>}のインスタンスを返します。この手続き
13770は@code{call-with-ftp-connection}を使ったときに暗黙の内に呼ばれます。
13771@var{host}引数およびキーワード引数のセマンティクスは
13772@code{call-with-ftp-connection}と同じです。
13773@c COMMON
13774@end defun
13775
13776@defun ftp-quit conn
13777@c MOD rfc.ftp
13778@c EN
13779Sends ftp @code{QUIT} command to the connection @var{conn} and
13780shutdown the connection.
13781This procedure is called implicitly when you use
13782@code{call-with-ftp-connection}.
13783@c JP
13784FTPの@code{QUIT}コマンドをコネクション@var{conn}に送り、コネクションを
13785シャットダウンします。この手続きは@code{call-with-ftp-connection}を使っ
13786たときに暗黙の内に呼ばれます。
13787@c COMMON
13788
13789@c EN
13790Once a connection is shut down, you cannot communicate through
13791this connection.
13792@c JP
13793いったんシャットダウンしたコネクションをつかっての通信はできません。
13794@c COMMON
13795@end defun
13796
13797@defun ftp-chdir conn dirname
13798@c MOD rfc.ftp
13799@c EN
13800Changes the remote directory to @var{dirname}.
13801@c JP
13802リモートディレクトリを@var{dirname}に変更します。
13803@c COMMON
13804@end defun
13805
13806@defun ftp-remove conn path
13807@c MOD rfc.ftp
13808@c EN
13809Removes the remote file named by @var{path}.
13810@c JP
13811@var{path}で指定したリモートファイルを削除します。
13812@c COMMON
13813@end defun
13814
13815@defun ftp-help conn :optional option @dots{}
13816@c MOD rfc.ftp
13817@c EN
13818Sends ftp @code{HELP} commands.  @var{Option}s must be strings,
13819and will be passed to the @code{HELP} command arguments.
13820@c JP
13821FTPコマンド@code{HELP}を送ります。@var{Option}は文字列でなければなりま
13822せん。これは@code{HELP}コマンドの引数にわたされます。
13823@c COMMON
13824@end defun
13825
13826@defun ftp-mkdir conn dirname
13827@c MOD rfc.ftp
13828@c EN
13829Creates a directory @var{dirname}.  Returns the created directory
13830name.
13831@c JP
13832ディレクトリ@var{dirname}を作成します。作成されたディレクトリ名が返り
13833ます。
13834@c COMMON
13835@end defun
13836
13837@defun ftp-current-directory conn
13838@c MOD rfc.ftp
13839@c EN
13840Returns the current remote directory.
13841@c JP
13842現在のリモートディレクトリを返します。
13843@c COMMON
13844@end defun
13845
13846@defun ftp-site conn arg
13847@c MOD rfc.ftp
13848@c EN
13849Sends ftp @code{SITE} command with the argument @var{arg}.
13850The @code{SITE} command's semantics depends on the server.
13851Returns the server reply.
13852@c JP
13853FTPコマンド@code{SITE}を引数@var{arg}とともに送ります。@code{SITE}コマ
13854ンドのセマンティクスはサーバーに依存します。返り値はサーバーのリプライ
13855です。
13856@c COMMON
13857@end defun
13858
13859@defun ftp-rmdir conn dirname
13860@c MOD rfc.ftp
13861@c EN
13862Removes remote directory specified by @var{dirname}.
13863Returns the server reply.
13864@c JP
13865@var{dirname}で指定したリモートディレクトリを削除します。返り値はサー
13866バーのリプライです。
13867@c COMMON
13868@end defun
13869
13870@defun ftp-stat conn :optional pathname
13871@c MOD rfc.ftp
13872@c EN
13873Sends ftp @code{STAT} command to the server.
13874RFC959 defines several different semantics of this command.
13875See RFC959 for the details.
13876Returns the server reply.
13877@c JP
13878FTPコマンド@code{STAT}をサーバーに送信します。
13879RFC959ではこのコマンドのセマンティクスをいくつか定義しています。詳細は
13880RFC959を見てください。返り値はサーバーのリプライです。
13881@c COMMON
13882@end defun
13883
13884@defun ftp-system conn
13885@c MOD rfc.ftp
13886@c EN
13887Queries the server's operating system by ftp @code{SYST} command.
13888Returns the server reply without status code.
13889@c JP
13890FTPコマンド@code{SYST}をつかってサーバーのオペレーティングシステムを問
13891合せます。返り値はステータスコードを含まないサーバーのリプライです。
13892@c COMMON
13893
13894@example
13895(call-with-ftp-connection "localhost" ftp-system)
13896  @result{} "UNIX Type: L8"
13897@end example
13898@end defun
13899
13900@defun ftp-size conn path
13901@c MOD rfc.ftp
13902@c EN
13903Queries the size of the remote file specified by @var{path}.
13904Returns the integer value.
13905
13906Note: The size may differ whether the connection is in ascii mode
13907or binary mode; furthermore, some ftp server may returns the value
13908only if the connection is in binary mode.  Make sure you have
13909desired transfer type in the connection.
13910@c JP
13911@var{path}で指定したリモートファイルのサイズを問合せます。
13912整数値が返ります。
13913
13914註:コネクションがasciiモードかbinaryモードかによって、返されるサイズは
13915異なるかもしれません。ftpサーバによっては、binaryモードでしか
13916sizeリクエストに答えないものもあります。この関数を呼ぶ際には、
13917コネクションに望みのtransfer typeがセットされているようにしてください。
13918@c COMMON
13919@end defun
13920
13921@defun ftp-mdtm conn path
13922@c MOD rfc.ftp
13923@c EN
13924Queries the modification time of the remote file specified by @var{path}.
13925This function returns the server's reply as is, including the status
13926code.  Use @code{ftp-mtime} below to obtain a parsed result.
13927@c JP
13928@var{path}で指定したリモートファイルの更新時刻を問合せます。この関数は
13929サーバーからのリプライをステータスコードも含めそのまま返します。解析済
13930みの結果が欲しいときは後述の@code{ftp-mtime}を使ってください。
13931@c COMMON
13932@end defun
13933
13934@defun ftp-mtime conn path :optional local-time?
13935@c MOD rfc.ftp
13936@c EN
13937Queries the modification time of the remote file specified by @var{path},
13938and returns the result in a @code{<date>} object
13939(@pxref{Time data types and procedures}).
13940If a true value is given to @code{local-time?}, the returned date is
13941in local time.  Otherwise, the returned date is in UTC.
13942@c JP
13943@var{path}で指定したリモートファイルの更新日時を問合せます。結果は
13944@code{<date>}オブジェクト(@ref{Time data types and procedures}参照)で
13945返ります。@code{local-time?}が真値に設定されている場合、日付はローカル
13946時刻で返ります。そうでない場合は日付はUTCです。
13947@c COMMON
13948@end defun
13949
13950@defun ftp-noop conn
13951@c MOD rfc.ftp
13952@c EN
13953Sends ftp @code{NOOP} command and returns the server's reply.
13954@c JP
13955FTPコマンド@code{NOOP}を送り、サーバーからのリプライを返します。
13956@c COMMON
13957@end defun
13958
13959@defun ftp-list conn :optional path
13960@c MOD rfc.ftp
13961@c EN
13962Returns the information about the files within the remote file
13963or directory specified by @var{path}, or the current remote directory,
13964much like @code{ls(1)} format.  Returns a list of strings, where
13965each string is for each line of the server's reply.  The exact
13966format depends on the server.
13967@c JP
13968@var{path}で指定されたリモートディレクトリあるいはリモートファイル内の
13969ファイルに関する情報を返します。@var{path}指定がない場合は現在のリモー
13970トディレクトリで、結果のフォーマットは@code{ls(1)}のフォーマットと非常
13971によく似ています。文字列のリストが返り、それぞれの文字列はサーバーのリ
13972プライの行に対応します。正確なフォーマットについてはサーバーに依存しま
13973す。
13974@c COMMON
13975@end defun
13976
13977@defun ftp-name-list conn :optional path
13978@defunx ftp-ls conn :optional path
13979@c MOD rfc.ftp
13980@c EN
13981Return the list of names in the specified @var{path}, or the current
13982remote directory, without any other information.  @code{ftp-ls}
13983is just an alias of @code{ftp-name-list} for the convenience.
13984@c JP
13985@var{path}で指定したパスもしくは現在のリモートディレクトリにあるファイ
13986ル名リストを返します。ただし、他の情報は含みません。@code{ftp-ls}は
13987@code{ftp-name-list}の別名です。便利なので定義してあります。
13988@c COMMON
13989
13990@c EN
13991Note that the server may return an error if there's no files
13992in the remote directory.
13993@c JP
13994リモートディレクトリにファイルが含まれていないときにはサーバーはエラー
13995を返すことがあることに注意してください。
13996@c COMMON
13997@end defun
13998
13999@defun ftp-get conn path :key sink flusher
14000@c MOD rfc.ftp
14001@c EN
14002Retrieves a remote file @var{path}.  The retrieved data is
14003sent to an output port given to @var{sink}.  Once all the data
14004is retrieved, a procedure given to @var{flusher} is called
14005with the port @var{sink} as an argument, and its return value(s)
14006is/are returned from @code{ftp-get}.
14007@c JP
14008リモートファイル@var{path}を検索します。検索データは@var{sink}で与えら
14009れた出力ポートに送られます。すべてのデータが検索されたあと、
14010@var{flusher}で与えられた手続きをポート@var{sink}を引数として呼びます。
14011返り値は@code{ftp-get}から返されたものです。
14012@c COMMON
14013
14014@c EN
14015The default values of @var{sink} and @var{flusher} are
14016a newly created string port and @code{get-output-string}, respectively.
14017That is, @code{ftp-get} returns the retrieved data as a string
14018by default.
14019You don't want this behavior if the retrieved file is huge.
14020@c JP
14021@var{sink}および@var{flusher}のデフォルト値はそれぞれ、新しく作成され
14022た文字列ポートと@code{get-output-string}です。すなわち、@code{ftp-get}
14023はデフォルトでは検索データを文字列として返します。巨大なファイルの場合
14024このデフォルトの挙動ではありがたくありません。
14025@c COMMON
14026@end defun
14027
14028@defun ftp-put conn from-file :optional to-file
14029@c MOD rfc.ftp
14030@c EN
14031Sends the local file specified by @var{from-file} to the remote
14032server as the name specified by @var{to-file}.  If @var{to-file}
14033is omitted, the basename of @var{from-file} is used.
14034Returns the server response.
14035@c JP
14036@var{from-file}で指定したローカルファイルを@var{to-file}で指定した名前
14037でリモートサーバーに送信します。@var{to-file}が省略された場合にはベー
14038ス名として@var{from-file}が使われます。返り値はサーバーのレスポンスで
14039す。
14040@c COMMON
14041@end defun
14042
14043@defun ftp-put-unique conn from-file
14044@c MOD rfc.ftp
14045@c EN
14046Sends the local file specified by @var{from-file} to the
14047remote server.  The remote side filename is guaranteed to
14048be unique.  Returns two values---the final server response,
14049and the remote file name.  The second value can be @code{#f}
14050if the remote host doesn't support RFC1123 (which must be rare).
14051@c JP
14052@var{from-file}で指定したローカルファイルをリモートサーバーへ送信しま
14053す。リモート側のファイル名重複しないことを保証します。返り値は2つで、
14054最終的なリモートサーバーからのレスポンスとリモートファイル名です。2つ
14055めの値は、リモートサーバーがRFC1123をサポートしていない(ほとんどない)
14056場合に@code{#f}になります。
14057@c COMMON
14058@end defun
14059
14060@defun ftp-rename conn from-name to-name
14061@c MOD rfc.ftp
14062@c EN
14063Renames the remote file specified by @var{from-name} to the
14064name @var{to-name}.  Returns the final response of the server.
14065@c JP
14066@var{from-name}で指定したリモートファイル名を@var{to-name}に変更する。
14067返り値は最終的なサーバーのレスポンスです。
14068@c COMMON
14069@end defun
14070
14071@c ----------------------------------------------------------------------
14072@node HMAC keyed-hashing, HTTP, FTP, Library modules - Utilities
14073@section @code{rfc.hmac} - HMAC keyed-hashing
14074@c NODE HMAC鍵付きハッシング, @code{rfc.hmac} - HMAC鍵付きハッシング
14075
14076@deftp {Module} rfc.hmac
14077@mdindex rfc.hmac
14078@c EN
14079This module implements HMAC algorithm,
14080Keyed-hashing for message authentication, defined in RFC 2104.
14081
14082For simple batched keyed hashing, you can use high-level API
14083@code{hmac-digest} and @code{hmac-digest-string}.
14084Or you can create @code{<hmac>} object and update its state
14085as the data coming in.
14086@c JP
14087このモジュールは、RFC 2104で定義されている、メッセージ認証のための
14088鍵付きハッシングのHMACアルゴリズムを実装しています。
14089
14090シンプルなバッチ処理での鍵付きハッシングでは、高レベルなAPIである
14091@code{hmac-digest}と@code{hmac-digest-string}が使えます。
14092あるいは、@code{<hmac>}オブジェクトを作成して、入力となるデータで
14093その状態を更新することもできます。
14094@c COMMON
14095@end deftp
14096
14097@deftp {Class} <hmac>
14098@clindex hmac
14099@c MOD rfc.hmac
14100@c EN
14101Keeps state information of HMAC algorithm.
14102Key and the hashing algorithm should be given at the construction
14103time, using @code{:key} and @code{:hasher} keyword-arguments respectively.
14104You can pass any class object that implements message digest
14105interface (@pxref{Message digester framework}),
14106such as @code{<md5>} (@pxref{MD5 message digest})
14107or @code{<sha256>} (@pxref{SHA message digest}).
14108
14109Example:
14110@c JP
14111HMACアルゴリズムの状態情報を保持します。
14112鍵とハッシングアルゴリズムは、キーワード引数@code{:key}と@code{:hasher}を
14113それぞれ使って、生成時に与えます。
14114@code{<md5>} (@ref{MD5 message digest}参照)や
14115@code{<sha256>} (@ref{SHA message digest}参照)などのような
14116ダイジェストインタフェース(@ref{Message digester framework}参照)を
14117実装するいかなるクラスオブジェクトを渡すこともできます。
14118
14119例:
14120@c COMMON
14121@example
14122(make <hmac> :key (make-byte-string 16 #x0b) :hasher <md5>)
14123@end example
14124@end deftp
14125
14126@deffn {Method} hmac-update! (hmac <hmac>) data
14127@c MOD rfc.hmac
14128@c EN
14129Updates the internal state of @var{hmac} by @var{data},
14130which must be represented by a (possibly incomplete) string.
14131@c JP
14132(不完全かもしれない)文字列で表現される@var{data}により、
14133@var{hmac}の内部状態を更新します。
14134@c COMMON
14135@end deffn
14136
14137@deffn {Method} hmac-final! (hmac <hmac>)
14138@c MOD rfc.hmac
14139@c EN
14140Finalizes the internal state of @var{hmac} and returns the
14141hashed string in incomplete string.
14142You can use @code{digest-hexify}
14143(@pxref{Message digester framework}) to obtain "hexified"
14144result.
14145Once finalized, you can't call @code{hmac-update!} or @code{hmac-final!}
14146on @var{hmac}.
14147@c JP
14148@var{hmac}の内部状態を終了させ、不完全文字列でハッシュされた文字列を
14149返します。
14150``hexified''(16進化)された結果を得るために、@code{digest-hexify}
14151(@ref{Message digester framework}参照)を使うことが
14152できます。
14153一旦終了されると、@var{hmac}に対しては@code{hmac-update!}や
14154@code{hmac-final!}を呼ぶことはできません。
14155@c COMMON
14156@end deffn
14157
14158@deffn {Method} hmac-digest :key key hasher
14159@c MOD rfc.hmac
14160@c EN
14161Creates an @code{<hmac>} object and hash the data stream
14162from the current input port, then returns the hashed result
14163in an incomplete string.
14164@c JP
14165@code{<hmac>}オブジェクトを作り、現在の入力ポートからの
14166データストリームをハッシュし、不完全文字列でそのハッシュされた
14167結果を返します。
14168@c COMMON
14169@end deffn
14170
14171@deffn {Method} hmac-digest-string string :key key hasher
14172@c MOD rfc.hmac
14173@c EN
14174Creates an @code{<hmac>} object and hash the data in @var{string},
14175then returns the hashed result in an incomplete string.
14176@c JP
14177@code{<hmac>}オブジェクトを作り、@var{string}にあるデータをハッシュし、
14178不完全文字列でそのハッシュされた結果を返します。
14179@c COMMON
14180@end deffn
14181
14182@c ----------------------------------------------------------------------
14183@node HTTP, ICMP packets, HMAC keyed-hashing, Library modules - Utilities
14184@section @code{rfc.http} - HTTP
14185
14186@deftp {Module} rfc.http
14187@mdindex rfc.http
14188@c EN
14189This module provides a simple client API for
14190HTTP/1.1, defined in RFC2616, "Hypertext Transfer Protocol -- HTTP/1.1"
14191@c JP
14192このモジュールは、RFC2616 "Hypertext Transfer Protocol -- HTTP/1.1"
14193で定義されているHTTP/1.1に対する簡単なクライアントAPIを提供します。
14194@c COMMON
14195(@uref{https://www.ietf.org/rfc/rfc2616.txt}).
14196
14197@c EN
14198Current API implements only a part of the protocol.
14199It doesn't talk with HTTP/1.0 server yet,
14200and it doesn't support HTTP/1.1 advanced features
14201such as persistent connection.
14202Support for those features may be added in the future versions.
14203@c JP
14204現在のAPIは、プロトコルの一部のみ実装されています。
14205HTTP/1.0のサーバーとはうまく通信できません。
14206また、HTTP/1.1の先進的機能、例えば永続的接続などはサポートしていません。
14207これらの機能は、将来のバージョンで追加されるでしょう。
14208@c COMMON
14209@end deftp
14210
14211@deftp {Condition Type} <http-error>
14212@clindex http-error
14213@c MOD rfc.http
14214@c EN
14215This type of condition is raised when the server terminates
14216connection prematurely or server's response has invalid
14217header fields.  Inherits @code{<error>}.
14218@c JP
14219サーバから接続が切られた場合や、サーバの返したHTTPレスポンスのフォーマットが
14220正しくない場合に投げられるコンディションです。@code{<error>}を継承します。
14221@c COMMON
14222@end deftp
14223
14224@defun http-get server request-uri :key sink flusher redirect-handler secure @dots{}
14225@defunx http-head server request-uri :key redirect-handler secure @dots{}
14226@defunx http-post server request-uri body :key sink flusher redirect-handler secure @dots{}
14227@defunx http-put server request-uri body :key sink flusher redirect-handler secure @dots{}
14228@defunx http-delete server request-uri :key sink flusher redirect-handler secure @dots{}
14229@c MOD rfc.http
14230@c EN
14231Send http GET, HEAD, POST, PUT and DELETE requests to the http @var{server},
14232respectively, and returns the server's reply.
14233
14234By default, if the server returns 300, 301, 302, 303, 305 and 307 status,
14235these procedures attempts to fetch the redirected URL by the
14236"location" reply message header if it is allowed by RFC2616.
14237This behavior can be turned off or customized by the @var{redirect-handler}
14238keyword argument;
14239see the "keyword arguments" heading below for the details.
14240@c JP
14241@var{server}に、それぞれHTTPのGET、HEAD、POST、PUT、DELETEリクエストを送り、
14242サーバの応答を返します。
14243
14244デフォルトでは、
14245サーバがステータスコード 300, 301, 302, 303, 305 の応答を返し、
14246RFC2616による自動リダイレクトが許されている場合は、
14247これらの手続きは自動的に応答のメッセージヘッダの "location" で返されるURIに対して
14248リクエストを再送します。
14249この動作は@var{redirect-handler}キーワード引数でカスタマイズしたり
14250抑制したりできます。下の"キーワード引数"を参照してください。
14251@c COMMON
14252
14253@c EN
14254@strong{Required arguments:}
14255The @var{server} argument specifies http server name in a string.
14256A server name can be optionally followed by colon and a port number.
14257You can use IP address, too; for IPv6, you have to surround the
14258address in brackets.
14259
14260Additionally, you can specify @code{"unix:/path"} where @code{/path}
14261is the absolute path to the unix domain socket; this allows to connect
14262to httpd listening on unix domain sockets.
14263@c JP
14264@strong{必須の引数:}
14265@var{server}引数では、文字列でHTTPサーバ名を指定します。
14266サーバ名は、オプションでコロンに続いてポート番号を付加できます。
14267IPアドレスも使えます。IPv6アドレスは角括弧で囲んでください。
14268
14269また、@code{"unix:/path"}という形式でUnixドメインソケットに接続することもできます。
14270@code{/path}部分にはソケットへの絶対パスを指定します。
14271@c COMMON
14272Examples: @code{"w3c.org"}, @code{"mycompany.com:8080"},
14273@code{"192.168.0.1:8000"}, @code{"[::1]:8000"}
14274
14275@c EN
14276The @var{request-uri} argument can be a string or a list.
14277If it is a string, it's @emph{request-uri} specified in
14278RFC2616; usually, this is the path part of http url.
14279The string is passed to the server as is, so the caller must
14280properly convert character encodings and perform necessary
14281url encodings.
14282
14283If @var{request-uri} is a list, it must be in the following form:
14284@c JP
14285@var{request-uri}引数は文字列かリストです。
14286文字列の場合、RFC2616で規定されているリクエストURIと解釈されます。
14287通常これはHTTP URLのパス部分です。
14288文字列はそのままサーバに渡されるので、呼び出し側で必要な
14289文字コード変換やurlエンコーディングを行う必要があります。
14290
14291@var{request-uri}がリストの場合は、次の形式でなければなりません。
14292@c COMMON
14293
14294@example
14295(@var{path} (@var{name} @var{value}) ...)
14296@end example
14297
14298@c EN
14299Here, @var{path} is a string specifying up to the path component
14300of the request-uri.
14301From provided alist of @var{name}s and @var{value}s,
14302http procedures compose a query string in
14303@code{application/x-www-form-urlencoded} format
14304as defined in HTML4, and append it to @var{path}.
14305For example, the following two requests have the same effect.
14306Note that url escaping is automatically handled in the second call.
14307@c JP
14308ここで@var{path}はリクエストURIのパスコンポーネントまでを指定する
14309文字列です。与えられた@var{name}と@var{value}のalistから、
14310httpリクエスト手続きはHTML4で定められた
14311@code{application/x-www-form-urlencoded}形式の
14312クエリ文字列を構成し、@var{path}にアペンドします。
14313例えば次のふたつのリクエストは同じ効果を持ちます。
14314二番目の呼び出しではurlエスケープが自動的に行われることに注目してください。
14315@c COMMON
14316
14317@example
14318(http-get "example.com" "/search?q=foo%20bar&n=20")
14319
14320(http-get "example.com" '("/search" (q "foo bar") (n 20)))
14321@end example
14322
14323@c EN
14324If @var{request-encoding} keyword argument is also given,
14325@var{name}s and @var{value}s
14326are converted into the specified character encoding before url escaping.
14327If it is omitted, gauche's internal character encoding is used.
14328@c JP
14329@var{request-encoding}キーワード引数が与えられた場合、
14330@var{name}と@var{value}はまずその文字エンコーディングに変換されたのちに
14331urlエスケープされます。そうでない場合はgaucheの内部
14332エンコーディングがそのまま使われます。
14333@c COMMON
14334
14335@c EN
14336Some procedures take the third argument, @var{body},
14337to specify the body of the request message.
14338It can be a string, which will be copied verbatim to the request body,
14339or a list, which will be encoded in @code{multipart/form-data} message.
14340
14341If @var{body} is a list, it is a list of parameter specs.  Each parameter
14342spec is either a list of name and value, e.g.
14343@code{("submit" "OK")} or a name followed by keyword-value list,
14344e.g. @code{("upload" :file "logo.png" :content-type "image/png")}.
14345
14346The first form is for the convenience.  It is also compatible to the
14347query parameter list in @var{request-uri}, so that you can use the
14348same format for GET and POST request.  Each value is put
14349in a MIME part with @code{text/plain} media type, with the
14350character encoding specified by @code{request-encoding} keyword argument
14351described below.
14352
14353The second form allows further control over each MIME part's attributes.
14354The following keywords are treated specially.
14355
14356@table @code
14357@item :value
14358Specifies the value of the parameter.  The convenience form,
14359@code{(@var{name} @var{val})}, is just an abbreviation of
14360@code{(@var{name} :value @var{val})}.
14361@item :file
14362Specifies the pathname of the file, whose content is inserted
14363as the value of the parameter.  Useful to upload a file.
14364This option has precedence over @code{:value}.
14365MIME type of the part is set to @code{application/octet-stream}
14366unless specified otherwise.
14367@item :content-type
14368Overrides the MIME type of the part.  A charset parameter is
14369added to the content-type if not given in this argument.
14370@item :content-transfer-encoding
14371Specifies the value of content-transfer-encoding; currently the
14372following values are supported: @code{7bit},
14373@code{binary}, @code{quoted-printable} and @code{base64}.
14374If omitted, @code{binary} is used.
14375@end table
14376
14377Other keywords are used as the header of the MIME part.
14378@c JP
14379いくつかの手続きは、リクエストメッセージのボディを指定する@var{body}を第3引数として
14380取ります。@var{body}は文字列かリストで、文字列の場合はそのまま送られ、
14381リストの場合は@code{multipart/form-data}形式にエンコードされて送られます。
14382
14383@var{body}がリストの場合、それはパラメータ指定のリストです。
14384各パラメータ指定は、@code{("submit" "OK")}のような名前と値のリスト、
14385もしくは@code{("upload" :file "logo.png" :content-type "image/png")}
14386のように名前の後にキーワード-値リストを付加したものです。
14387
14388最初の形式は使うのが簡単で、また@var{request-uri}のクエリパラメータリストと
14389同じ形式なのでGETとPOSTでルーチンを共有したい場合にも便利でしょう。
14390この形式では、各値はMIMEパートに@code{text/plain}として置かれます。
14391文字コードは下に述べる@code{request-encoding}キーワード引数により変換されます。
14392
14393二番目の形式では、MIMEパートの属性についてより細かな指定を行うことができます。
14394以下のキーワードが特別に扱われます。
14395
14396@table @code
14397@item :value
14398パラメータの値を指定します。簡潔な@code{(@var{name} @var{val})}形式は
14399@code{(@var{name} :value @var{val})}の省略形です。
14400@item :file
14401指定された名前のファイルの中身をパラメータの値として挿入します。
14402ファイルのアップロードに便利です。このオプションは@code{:value}より
14403優先されます。MIMEタイプは、指定が無ければ
14404@code{application/octet-stream}となります。
14405@item :content-type
14406MIMEタイプをオーバライドします。与えられた値にcharsetパラメータが
14407ついていない場合は自動的に付加されます。
14408@item :content-transfer-encoding
14409content-transfer-encodingを
14410@code{7bit}、@code{binary}、@code{quoted-printable}、@code{base64}の
14411いずれかで指定します。指定が無ければ@code{binary}が使われます。
14412@end table
14413
14414残りのキーワードはMIMEパートのヘッダにそのまま使われます。
14415@c COMMON
14416
14417@c EN
14418@strong{Return values:}
14419All procedures return three values.
14420
14421The first value is the status code defined in RFC2616
14422in a string (such as "200" for success, "404" for "not found").
14423@c JP
14424@strong{戻り値:}
14425全ての手続きは3つの値を返します。
14426
144271つ目は、RFC2616で定義されているステータスコードの文字列値(例えば、成功時の
14428200、"Not found"の404など)です。
14429@c COMMON
14430
14431@c EN
14432The second value is a list of parsed headers---each element of list
14433is a list of @code{(@var{header-name} @var{value} @dots{})},
14434where @var{header-name} is a string name of the header
14435(such as "content-type" or "location"), and @var{value} is
14436the corresponding value in a string.  The header name is converted
14437to lowercase letters.  The value is untouched except that "soft line breaks"
14438are removed, as defined in RFC2822.   If the server returns
14439more than one headers with the same name, their values are
14440consolidated to one list.  Except that, the order of the header list
14441in the second return value is the same as the order in the server's reply.
14442@c JP
144432つ目は、パーズされたヘッダのリストで、リストの要素は@code{(@var{header-name}
14444@var{value} @dots{})}です。@var{header-name}はヘッダの文字列名(例えば、
14445"content-type"や"location"など)で、@var{value}は対応する値の文字列値です。
14446ヘッダ名は小文字に変換されます。値は、RFC2822で定義されている無指定行区切
14447(ソフト・ライン・ブレイク)が除かれる以外はそのままです。
14448サーバが同じ名前のヘッダを1つ以上返した場合は、
144491つのリストに統合されます。それ以外では、2つ目の戻り値に
14450おけるヘッダのリストの順番は、サーバの応答での順番と同じです。
14451@c COMMON
14452
14453@c EN
14454The third value is for the message body of the server's reply.
14455By default, it is a message body itself in a string.   If the server's
14456reply doesn't have a body, the third value is @code{#f}.  You can
14457change how the message body is handled by keyword arguments; for example,
14458you can directly store the returned message body to a file without
14459creating intermediate string.  The details are explained below.
14460@c JP
144613つ目の戻り値は、サーバの応答におけるメッセージボディです。
14462デフォルトでは、文字列で表現されたメッセージボディそのものです。
14463サーバの応答がボディを持たない場合、3つ目の戻り値は@code{#f}です。
14464キーワード引数によって、メッセージボディがどのように扱われるかを制御できます。
14465例えば、中間的な文字列を作らずに、返されたメッセージボディを直接ファイルに
14466格納することが出来ます。詳細は以下で説明しています。
14467@c COMMON
14468
14469@c EN
14470@strong{Keyword arguments:}
14471By default, these procedures only attaches @code{"Host"} header
14472field to the request message.  You can give keyword arguments
14473to add more header fields.
14474@c JP
14475@strong{キーワード引数:}
14476デフォルトで、これらの手続きはリクエストメッセージに@code{"Host"}ヘッダ・フィールドを
14477追加するだけです。他のヘッダ・フィールドを追加するためにキーワード引数を
14478与えることができます。
14479@c COMMON
14480@example
14481(http-get "foo.bar.com" "/index.html"
14482  :accept-language "ja"
14483  :user-agent "My Scheme Program/1.0")
14484@end example
14485
14486@c EN
14487The following keyword arguments are recognized by the procedure
14488and do not appear in the request headers.
14489@c JP
14490以下のキーワード引数は手続きによって解釈され、リクエストヘッダには現れません。
14491@c COMMON
14492
14493@table @code
14494@item request-encoding
14495@c EN
14496When a list is given to the @var{request-uri} or @var{body} arguments,
14497the characters in names and values of the parameters are first
14498converted to the character encoding specified by this keyword
14499argument, then encoded into @code{application/x-www-form-urlencoded}
14500or @code{multipart/form-data} MIME formats.
14501If this argument is omitted, Gauche's internal character encoding is used.
14502
14503For @code{multipart/form-data}, you can override character encodings
14504for individual parameters by giving @code{content-type} header.
14505See the description of @var{body} arguments above.
14506
14507If you give a string to @var{request-uri} or @var{body},
14508it is used without encoding conversion.  It is caller's responsibility
14509to ensure desired character encodings are used.
14510@c JP
14511@var{request-uri}や@var{body}がリストで与えられた場合、パラメータの
14512名前や値はまずこの引数で指定される文字エンコーディングへと変換され、
14513その後、@code{application/x-www-form-urlencoded}や
14514@code{multipart/form-data} MIME形式にしたがったエンコーディングが行われます。
14515この引数が省略された場合はGaucheの内部文字エンコーディングが使われます。
14516
14517@code{multipart/form-data}については、パラメータに@code{content-type}ヘッダを
14518与えることでパラメータごとに文字エンコーディングの設定をオーバライドできます。
14519詳しくは上の@var{body}引数の説明を参照してください。
14520
14521@var{request-uri}や@var{body}に文字列を与えた場合は、文字エンコーディング変換は
14522行われません。呼び出し側で望みの文字コードにあらかじめ変換しておいてください。
14523@c COMMON
14524@item proxy
14525@c EN
14526Specify http proxy server in a string of a form @code{hostname} or
14527@code{hostname:port}.  If omitted, the value of the parameter
14528@code{http-proxy} is used.
14529@c JP
14530httpプロキシサーバを、@code{hostname}または@code{hostname:port}形式の
14531文字列で指定します。省略された場合、パラメータ@code{http-proxy}の値が
14532使われます。
14533@c COMMON
14534@item redirect-handler
14535@c EN
14536Specifies how the redirection is handled when the server responds with
145373xx status code.
14538You can pass @code{#f}, @code{#t} or a procedure.  The default is @code{#t}.
14539
14540If @code{#f} is given, no redirect attempt will be made; the 3xx status
14541code and response is just returned from @code{http-*} procedures as they are.
14542
14543If a procedure is given, it is called when the response status code
14544is 3xx.  The procedure takes four arguments, the request method (in symbol,
14545e.g. @code{GET}), the response status code (in string, e.g. @code{"302"}),
14546the parsed response headers and the response body (a string
14547if there's a body, or @code{#f} if the response doesn't have a body).
14548
14549The procedure can return a pair or @code{#f}.
14550If it is a pair, it should be @code{(method . url)}, where @var{method}
14551is a symbol (e.g. @code{GET}) and @var{url} is a string representing url.
14552If a pair is returned, the @code{http-*} procedures tries to send
14553the request with the given method (it allows a redirection of POST request
14554to be GET, for example).  If it is @code{#f}, no further attempt of
14555redirection is made.
14556
14557If @var{redirect-handler} is @code{#t}, which is the default,
14558then it works as if the value of the parameter
14559@code{http-default-redirect-handler} is passed to @var{redirect-handler}.
14560The parameter contains a procedure with reasonable default behavior.
14561See the @code{http-default-redirect-handler} entry below for the details.
14562
14563A loop in redirection is detected automatically and @code{<http-error>}
14564is thrown.
14565@c JP
14566サーバが3xxステータスコードを返した場合のリダイレクトの処理を指定します。
14567@code{#f}, @code{#t}もしくは手続きを渡すことができます。省略時は@code{#t}となります。
14568
14569@code{#f}が渡された場合は、リダイレクトは処理されません。3xxステータスコードを
14570持つレスポンスもそのまま@code{http-*}から返されます。
14571
14572手続きが渡された場合は、サーバが3xxステータスコードを返すとその手続きが4つの引数で
14573呼ばれます。最初の引数はリクエストメソッド(シンボル、例:@code{GET})、
14574次がレスポンスステータスコード(文字列、例:@code{"302"})、
14575次がパーズされたレスポンスヘッダ、そして最後がレスポンスボディです(レスポンスボディが
14576あれば文字列、なければ@code{#f})。
14577
14578この手続きは、ペアか@code{#f}を返さねばなりません。ペアの場合、それは
14579@code{(method . url)}という形で、@var{method}がシンボルによるリクエストメソッド、
14580@var{url}が文字列で次にリクエストすべきURLを表します。
14581ペアが返されれば、@code{http-*}手続きはそのURLへ、指定されたメソッドでリクエストを
14582再送します。(メソッドを返すことで、例えばPOSTリクエストのリダイレクトをGETリクエストに
14583置き換えることが可能です)。
14584手続きが@code{#f}を返した場合、リダイレクトは行われません。
14585
14586@var{redirect-handler}が@code{#t}(デフォルト値)の場合、
14587パラメータ@code{http-default-redirect-handler}の値が
14588@var{redirect-handler}に渡されたかのように振る舞います。
14589このパラメータの初期値は、標準的なリダイレクトの振る舞いをする手続きになっています。
14590下の@code{http-default-redirect-handler}の項目を参照してください。
14591
14592リダイレクトのループは自動的に検出され、@code{<http-error>}が投げられます。
14593@c COMMON
14594@item no-redirect
14595@c EN
14596This is an obsoleted keyword argument kept only for the backward
14597compatibility.  If a true value is given, it has the same effect
14598as specifying @code{#f} to @var{redirect-handler}.
14599@c JP
14600これは互換性のためだけに残されている、古い引数です。真の値を与えると、
14601@var{redirect-handler}に@code{#f}を渡したのと同じ効果を持ちます。
14602@c COMMON
14603@item secure
14604@c EN
14605If a true value is given, the secure connection is used.  The value
14606specifies the secure transport agent to establish https connection.
14607It can be @code{#t} or a symbol @code{tls} or @code{stunnel}.
14608If @code{#f} is given (default), non-secure plain http is used.
14609See the ``Secure connection'' section below.
14610@c JP
14611真の値が与えられた場合、セキュアな接続が使われます。
14612値によってhttps接続につかうトランスポートエージェントを指定できます。
14613有効な値は@code{#t}もしくはシンボルの@code{tls}か@code{stunnel}です。
14614@code{#f}が与えられた場合(デフォルト)はセキュアでない通常のhttpが使われます。
14615詳しくは下の「セキュアな接続」の項を参照してください。
14616@c COMMON
14617@item auth-user, auth-password
14618@c EN
14619If given, the authorization header using Basic Authentication
14620(RFC2617) is added to the request.
14621In future, we might add support for other authentication scheme.
14622@c JP
14623これらのキーワード引数が与えられた場合、Basic認証用のAuthorizationヘッダが
14624リクエストに付加されます。将来はBasic認証以外の認証方式もサポートするかもしれません。
14625@c COMMON
14626@item sink, flusher
14627@c EN
14628You can customize how the reply message body is handled by these
14629keyword arguments.  You have to pass an output port to @var{sink},
14630and a procedure that takes two arguments to @var{flusher}.
14631
14632When the procedure starts receiving the message body, it
14633feeds the received chunk to @var{sink}.  When the procedure
14634receives entire message body, @var{flusher} method is called
14635with @var{sink} and a list of message header fields (in the
14636same format to be returned in the second value from the procedure).
14637The return value of @var{flusher} becomes the third return value
14638from the procedure.
14639
14640So, the default value of @var{sink} is a newly opened string
14641port and the default value of @var{flusher} is
14642@code{(lambda (sink headers) (get-output-string sink))}.
14643
14644The following example saves the message body directly to a file,
14645without allocating (potentially very big) string buffer.
14646@c JP
14647これらのキーワード引数によりリプライメッセージ・ボディがどのように扱われるかを
14648カスタマイズできます。@var{sink}には出力ポートを、@var{flusher}には2引数を
14649取る手続きを渡さなければなりません。
14650
14651手続きがメッセージ・ボディを受信し始めると、@var{sink}へ受け取った
14652データ片をフィードします。手続きがメッセージ・ボディを受信し終わると、
14653@var{flusher}に与えられた手続きが、@var{sink}と(手続きからの2つ目の
14654戻り値と同じフォーマットの)メッセージ・ヘッダ・フィールドのリストとともに
14655呼び出されます。@var{flusher}の戻り値が、手続きからの3つ目の戻り値と
14656なります。
14657
14658したがって、@var{sink}のデフォルト値は、新しく開かれた文字列ポートで、
14659@var{flusher}のデフォルト値は@code{(lambda (sink headers) (get-output-string sink))}
14660とも言えます。
14661
14662以下のサンプルは、(とても大きい可能性のある)文字列バッファを作らずに、
14663メッセージ・ボディを直接ファイルに保存します。
14664@c COMMON
14665@example
14666(call-with-output-file "page.html"
14667  (lambda (out)
14668    (http-get "www.schemers.org" "/"
14669       :sink out :flusher (lambda _ #t))))
14670@end example
14671
14672@end table
14673
14674@end defun
14675
14676The module also provides some utility procedures.
14677
14678@deffn {Parameter} http-user-agent :optional value
14679@c MOD rfc.http
14680@c EN
14681The value of this parameter is used as a default value
14682to pass to the user-agent header.
14683The default value is something like @code{gauche.http/*},
14684where @code{*} is Gauche's version.
14685An application is encouraged to set this parameter appropriately.
14686@c JP
14687user-agentヘッダに渡される値のデフォルト値を指定するパラメータです。
14688デフォルトの値は@code{gauche.http/*} (@code{*}部分はGaucheのバージョン)
14689になっています。
14690各アプリケーションは適切な値を設定するようにしてください。
14691@c COMMON
14692@end deffn
14693
14694@deffn {Parameter} http-proxy :optional value
14695@c MOD rfc.http
14696@c EN
14697This value is used as the default http proxy name by @code{http-get} etc.
14698The default value is @code{#f} (no proxy).
14699@c JP
14700このパラメータの値が@code{http-get}等のhttpプロキシのデフォルトの値として
14701使われます。デフォルトの値は@code{#f} (プロキシを使用しない) です。
14702@c COMMON
14703@end deffn
14704
14705@deffn {Parameter} http-default-redirect-handler :optional value
14706@c MOD rfc.http
14707@c EN
14708Specifies the behavior of redirection if no @code{redirect-handler} keyword
14709argument is given to the @code{http-*} procedures.
14710If you change this value, it must be a procedure that follows the
14711protocol of @code{redirect-handler}; see the description of @code{http-*}
14712procedures above.
14713@c JP
14714@code{http-*}手続きに@code{redirect-handler}キーワード引数が与えられなかった
14715場合のデフォルトの動作を指定します。この値を変える場合、それは
14716@code{redirect-handler}引数のプロトコルに従う手続きでなければなりません。
14717上の@code{http-*}手続きの項目を参照してください。
14718@c COMMON
14719
14720@c EN
14721The default behavior is as follows:
14722@c JP
14723デフォルトの動作は以下の通りです。
14724@c COMMON
14725
14726@table @asis
14727@item @code{300}, @code{301}, @code{305}, @code{307}
14728@c EN
14729Redirect to the url given to the @code{location} header only if
14730the original request method is @code{GET} or @code{HEAD}.
14731@c JP
14732元のリクエストが@code{GET}か@code{HEAD}の場合に限り、同じリクエストを使って
14733@code{location}ヘッダに与えられたURLにリダイレクトします。
14734@c COMMON
14735@item @code{302}
14736@c EN
14737Redirect to the url given to the @code{location} header.  If
14738the original request method is @code{HEAD}, it is used again.
14739Otherwise, @code{GET} method is used.
14740
14741Strictly speaking, this is a violation of RFC2616.  However, as the note
14742in RFC2616 says, many user agent do this, so we follow the flock.
14743(We may change this in future.)
14744@c JP
14745@code{location}ヘッダに与えられたURLにリダイレクトします。
14746元が@code{HEAD}リクエストなら@code{HEAD}を、それ以外なら@code{GET}リクエストを
14747使います。
14748
14749厳密に言えばこれはRFC2616違反ですが、RFC2616の注記にもあるように、
14750多くのユーザエージェントがこの振る舞いをするので、それに合わせてあります。
14751(将来は変えるかもしれません。)
14752@c COMMON
14753@item @code{303}
14754@c EN
14755Redirect to the url given to the @code{location} header.  If
14756the original request method is @code{HEAD}, it is used again.
14757Otherwise, @code{GET} method is used.
14758@c JP
14759@code{location}ヘッダに与えられたURLにリダイレクトします。
14760元が@code{HEAD}リクエストなら@code{HEAD}を、それ以外なら@code{GET}リクエストを
14761使います。
14762@c COMMON
14763@item other than above
14764@c EN
14765No redirection is made.
14766@c JP
14767リダイレクトしません。
14768@c COMMON
14769@end table
14770
14771@c EN
14772The following code is an example of intercepting the default
14773behavior in a specific request:
14774@c JP
14775次のコードは、デフォルトの振る舞いを特定のリクエストでインターセプトする例です。
14776@c COMMON
14777
14778@example
14779(http-get server uri
14780  :redirect-handler
14781  (^[method status headers body]
14782    (if (and (equal? status "302")
14783             (not (member method '(GET HEAD))))
14784        #f
14785        ((http-default-request-handler) method status headers body))))
14786@end example
14787@end deffn
14788
14789
14790@defun http-compose-query path params :optional encoding
14791@c MOD rfc.http
14792@c EN
14793A helper procedure to create a request-uri from
14794a list of query parameters.  @var{Encoding} specifies
14795the character encodings to be used.
14796@c JP
14797クエリパラメータのリストからリクエストURIを生成する補助関数です。
14798@var{encoding}引数はクエリパラメータの文字エンコーディングを指定します。
14799@c COMMON
14800
14801@example
14802(http-compose-query "/search" '((q "$foo") (n 20)))
14803 @result{} "/search?q=%24foo&n=20"
14804
14805(http-compose-query "" '((x "a b") (x 2)))
14806 @result{} "?x=a%20b&x=2"
14807@end example
14808
14809@c EN
14810If @var{path} is @code{#f}, only the query parameter part
14811is returned (compare the following example and the last
14812example):
14813@c JP
14814@var{path}が@code{#f}の場合は、クエリパラメータの部分だけが返されます
14815(次の例と直前の例を比べてみてください)。
14816@c COMMON
14817
14818@example
14819(http-compose-query #f '((x "a b") (x 2)))
14820 @result{} "x=a%20b&x=2"
14821@end example
14822@end defun
14823
14824@defun http-compose-form-data params port :optional encoding
14825@c MOD rfc.http
14826@c EN
14827A helper procedure to create @code{multipart/form-data}
14828from a list of parameters.  The format of @var{params} argument
14829is the same as the list format of @var{body} argument of
14830http request procedures.  The result is written to an output
14831port @var{port}, and the boundary string used to compose
14832MIME message is returned.  Alternatively you can pass @code{#f}
14833to the @var{port} to get the result in a string.
14834In that case, two values are returned, the MIME message string
14835and the boundary string.
14836@c JP
14837@code{multibyte/form-data}形式にエンコードされたデータを
14838パラメータのリストから組み立てるための補助手続きです。
14839@var{params}の形式はhttpリクエスト手続きの@var{body}部にリストを渡す場合の形式と同様です。
14840結果は出力ポート@var{port}に書き出され、
14841MIMEメッセージを構築するのに必要なboundary stringが返されます。
14842@var{port}に@code{#f}を渡した場合は、
14843boundary stringとデータをエンコードした文字列の二つの値が返されます。
14844@c COMMON
14845
14846@c EN
14847@var{Encoding} specifies the character encodings to be used.
14848When omitted, Gauche's native encoding is used.
14849@c JP
14850@var{encoding}は文字エンコーディングを指定します。
14851省略時はGaucheのネイティブエンコーディングが使われます。
14852@c COMMON
14853
14854@example
14855(define p (open-output-string))
14856
14857(http-compose-form-data '((name "Preludes and Fugues")
14858                          (composer "Shostakovich, Dmitri")
14859                          (opus "87"))
14860                         p)
14861  @result{} "boundary-fh87o52rp6zkubp2uhdmo"
14862
14863(get-output-string p)
14864  @result{}
14865  "\r\n--boundary-fh87o52rp6zkubp2uhdmo\r\nContent-type: te
14866   xt/plain; charset=utf-8\r\nContent-transfer-encoding: bi
14867   nary\r\ncontent-disposition: form-data; name=title\r\n\r\n
14868   Preludes and Fugues\r\n--boundary-fh87o52rp6zkubp2uhdmo...
14869@c EN
14870;; (result is truncated)
14871@c JP
14872;; (以下省略)
14873@c COMMON
14874@end example
14875@end defun
14876
14877@defun http-status-code->description code
14878@c MOD rfc.http
14879@c EN
14880Returns a brief description of http status code @code{code},
14881which may be an integer or a string (e.g. @code{"404"}).
14882If @code{code} isn't one of known code, @code{#f} is returned.
14883@c JP
14884HTTPステータスコード@code{code}の簡単な説明を返します。
14885@code{code}は整数か、整数を表す文字列です(例: @code{"404"})。
14886@code{code}が知られているものでなかった場合は@code{#f}が返されます。
14887@c COMMON
14888
14889@example
14890(http-status-code->description 404)
14891  @result{} "Not Found"
14892@end example
14893@end defun
14894
14895
14896@c EN
14897@subheading Secure connection
14898@c JP
14899@subheading セキュアな接続
14900@c COMMON
14901
14902@c EN
14903When you pass a true value to @code{secure} keyword argument,
14904the request-making APIs such as @code{http-get} use a secure
14905connection.  That is, it connects with @code{https} instead of
14906@code{http}.  The actual value for the keyword argument can be one of the
14907followings:
14908@c JP
14909@code{http-get}等httpリクエスト発行APIの@code{secure}キーワード引数に、
14910真の値を渡した場合、セキュアなコネクションが使われます。
14911すなわち、@code{http}ではなく@code{https}で接続されるということです。
14912実際に@code{secure}キーワード引数に渡せる値は以下の通りです。
14913@c COMMON
14914
14915@table @code
14916@item #t
14917@itemx tls
14918@c EN
14919The @code{rfc.tls} module is used for the secure connection.
14920@xref{Transport layer security}, for the details---you might need to
14921set CA certificate bundle path.
14922@c JP
14923@code{rfc.tls}モジュールを使ってセキュアな接続を行います。
14924詳しくは@ref{Transport layer security}を参照してください。
14925CA証明書のパスを設定する必要があるかもしれません。
14926@c COMMON
14927@item stunnel
14928@c EN
14929The external process @code{stunnel} is spawned and used for the
14930secure connection.
14931@c JP
14932@code{stunnel}プロセスをサブプロセスとして起動してそれを通じてセキュアな接続を作ります。
14933@c COMMON
14934@item #f
14935@c EN
14936Secure connection is not used.
14937@c JP
14938セキュアな接続を行いません。
14939@c COMMON
14940@end table
14941
14942@c EN
14943If specified secure connection subsystem isn't available in the running Gauche,
14944an error is signaled.
14945Use the following procedure to check if you can use secure
14946connections:
14947@c JP
14948指定されたセキュア接続を行うサブシステムが実行中のGaucheでは使えない場合は、
14949エラーが報告されます。
14950サブシステムが使えるかどうかをチェックしたい場合は次の手続きを使ってください。
14951@c COMMON
14952
14953@defun http-secure-connection-available? :optional type
14954@c MOD rfc.http
14955@c EN
14956The @var{type} argument may be @code{tls} or @code{stunnel}.
14957If omitted, @code{tls} is assumed.
14958Returns @code{#t} if running Gauche can use secure connection of the given type,
14959@code{#f} otherwise.
14960@c JP
14961@var{type}引数は@code{tls}か@code{stunnel}でなければなりません。
14962省略時は@code{tls}とみなされます。
14963指定のセキュア接続を行うサブシステムが実行中のGaucheで使える場合は@code{#t}が、
14964使えない場合は@code{#f}が返されます。
14965@c COMMON
14966@end defun
14967
14968@c ----------------------------------------------------------------------
14969@node ICMP packets, IP packets, HTTP, Library modules - Utilities
14970@section @code{rfc.icmp} - ICMP packets
14971@c NODE ICMPパケット, @code{rfc.icmp} - ICMPパケット
14972
14973@deftp {Module} rfc.icmp
14974@mdindex rfc.icmp
14975@c MOD rfc.icmp
14976@c EN
14977This module provides some basic utilities to construct and parse ICMP
14978packets.
14979@c JP
14980このモジュールではICMPパケットの構築および解析用の基本的ユーティリティ
14981を提供しています。
14982@c COMMON
14983@end deftp
14984
14985@c EN
14986For the functions below, @var{buffer} should be a writable
14987u8vector of the enough size.
14988@c JP
14989以下の関数の@var{buffer}は十分なサイズの書き込み可能なu8vectorでなけれ
14990ばなりません。
14991@c COMMON
14992
14993@c EN
14994Parsing functions takes @var{offset} as well as @var{buffer},
14995which specifies the beginning of the ICMP packet.  Using the offset
14996you can carry the whole IP packet in @var{buffer}, without
14997creating a new buffer to extract ICMP portion.
14998@c JP
14999解析用の関数は@var{buffer}のほかに@var{offset}を引数としてとります。こ
15000れはICMPパケットの開始位置を示すものです。このオフセットを用いて、ICMP
15001部分を取り出して新しいバッファを作るということなしに、IPパケット全体を
15002@var{buffer}内に格納できます。
15003@c COMMON
15004
15005@defun icmp4-fill-echo! buffer ident sequence data
15006@c MOD rfc.icmp
15007@c EN
15008Fills @var{buffer} with the ICMPv4 Echo Request packet.
15009@var{Data} must be a u8vector.  The checksum field is
15010left to be zero, which can be filled by @code{icmp4-fill-checksum!}.
15011@c JP
15012@var{buffer}にICMPv4のエコーリクエストパケットを詰め込みます。
15013@var{Data}はu8vectorでなければなりません。チェックサムフィールドはゼロ
15014のままです。チェックサムは@code{icmp4-fill-checksum!}を使って埋め込み
15015ます。
15016@c COMMON
15017@end defun
15018
15019@defun icmp4-fill-checksum! buffer size
15020@c MOD rfc.icmp
15021@c EN
15022Calculates the ICMPv4 checksum of the packet in the @var{buffer},
15023of @var{size} length (the size of the packet, not the buffer),
15024and fills the checksum field of the packet.
15025@c JP
15026@var{buffer}中の@var{size}(バッファではなくパケットの長さ)分のパケット
15027のICMPv4チェックサムを計算し、そのパケットのチェックサムフィールドをう
15028めます。
15029@c COMMON
15030@end defun
15031
15032@defun icmp6-fill-echo! buffer ident sequence data
15033@c MOD rfc.icmp
15034@c EN
15035Fills @var{buffer} with the ICMPv6 Echo Request packet.
15036@var{Data} must be a u8vector.  The checksum field is
15037left to be zero, which is to be filled by the kernel
15038(so you don't need to fill by yourself).
15039@c JP
15040@var{buffer}にICMPv6のエコーリクエストパケットを詰め込みます。
15041@var{Data}はu8vectorでなければなりません。チェックサムフィールドは
15042ゼロのままで、ここはカーネルが埋めることになっています。したがって、
15043ユーザーが自分で埋める必要はありません。
15044@c COMMON
15045@end defun
15046
15047@defun icmp-packet-type buffer offset
15048@defunx icmp-packet-code buffer offset
15049@defunx icmp-packet-ident buffer offset
15050@defunx icmp-packet-sequence buffer offset
15051@c MOD rfc.icmp
15052@c EN
15053Extracts type, code, ident and sequence fields of ICMP packet.
15054These functions are common to both ICMPv4/v6.
15055@c JP
15056それぞれICMPパケットのタイプ、コード、識別子、シーケンスフィールドを抜
15057き出します。これらの関数はICMPv4/v6で共通です。
15058@c COMMON
15059@end defun
15060
15061@defun icmp4-describe-packet buffer offset
15062@defunx icmp6-describe-packet buffer offset
15063@c MOD rfc.icmp
15064@c EN
15065Prints out a simple text description of the given ICMPv4 and v6 packet,
15066respectively.
15067@c JP
15068それぞれ与えられたICMPv4およびICMPv6パケットの簡単な説明を印字します。
15069@c COMMON
15070@end defun
15071
15072@defun icmp4-message-type->string type
15073@defunx icmp4-unreach-code->string code
15074@defunx icmp4-redirect-code->string code
15075@defunx icmp4-router-code->string code
15076@defunx icmp4-exceeded-code->string code
15077@defunx icmp4-parameter-code->string code
15078@defunx icmp4-security-code->string code
15079@defunx icmp6-message-type->string type
15080@defunx icmp6-unreach-code->string code
15081@defunx icmp6-exceeded-code->string code
15082@defunx icmp6-parameter-code->string code
15083@c MOD rfc.icmp
15084@c EN
15085Returns a text description of ICMPv4 and ICMPv6 types and codes.
15086@c JP
15087ICMPv4およびICMPv6のタイプとコードの説明テキストを返します。
15088@c COMMON
15089@end defun
15090
15091@c ----------------------------------------------------------------------
15092@node IP packets, JSON parsing and construction, ICMP packets, Library modules - Utilities
15093@section @code{rfc.ip} - IP packets
15094@c NODE IPパケット, @code{rfc.ip} - IPパケット
15095
15096@deftp {Module} rfc.ip
15097@mdindex rfc.ip
15098@c EN
15099This module provides some basic utilities to parse raw IP packets.
15100@c JP
15101このモジュールは生のIPパケットを解析する基本的なユーティリティを提供し
15102ます。
15103@c COMMON
15104@end deftp
15105
15106@c EN
15107The @var{packet} argument in the following functions must be
15108any type of uniform vector (@pxref{Uniform vectors}), containing
15109a raw IP packet including its IP header.
15110Those functions work for both IPv4 and IPv6 packets; however,
15111reading from a raw IPv6 socket returns a packet without IPv6 header,
15112so you usually don't need to use these functions.
15113@c JP
15114次からの関数における@var{packet}引数はユニフォームベクタ
15115(@ref{Uniform vectors}参照)型でなければなりません。これにはIPヘッダを
15116含む生のIPパケットが入ります。以下の関数はIPv4およびIPv6パケットの両方
15117で動きます。しかしながら、生のIPv6ソケットから読むときは、IPv6ヘッダを
15118含まないパケットが返ります。とうわけで、通常これらの関数が必要になるこ
15119とはないでしょう。
15120@c COMMON
15121
15122@c EN
15123The @var{offset} argument specifies the beginning of the IP packet
15124in @var{packet}.  If @var{packet} contains only one IP packet
15125you can pass 0.  It is not an optional argument, since these routines
15126may be used in speed-sensitive inner loop.
15127@c JP
15128@c COMMON
15129
15130@defun ip-version packet offset
15131@c MOD rfc.ip
15132@c EN
15133Returns the IP version number (either 4 or 6) of the given IP packet.
15134@c JP
15135与えられたIPパケットのIPバージョン番号(4または6)が返ります。
15136@c COMMON
15137@end defun
15138
15139@defun ip-header-length packet offset
15140@c MOD rfc.ip
15141@c EN
15142Returns the size of IP header of the given packet in octets,
15143including any IP header options.
15144@c JP
15145与えられたパケットのIPヘッダ(IPヘッダオプションもすべて含む)のオクテッ
15146トで数えたサイズを返します。
15147@c COMMON
15148@end defun
15149
15150@defun ip-protocol packet offset
15151@c MOD rfc.ip
15152@c EN
15153Returns the IP protocol number of the given packet.
15154@c JP
15155与えられたパケットのIPプロトコル番号を返します。
15156@c COMMON
15157@end defun
15158
15159@defun ip-source-address packet offset
15160@defunx ip-destination-address packet offset
15161@c MOD rfc.ip
15162@c EN
15163Returns the source and destination address in the given packet
15164in an integer, respectively.
15165@c JP
15166与えられたパケットの送信元アドレスと送信先アドレスをそれぞれ整数で返し
15167ます。
15168@c COMMON
15169@end defun
15170
15171
15172@c ----------------------------------------------------------------------
15173@node JSON parsing and construction, MD5 message digest, IP packets, Library modules - Utilities
15174@section @code{rfc.json} - JSON parsing and construction
15175@c NODE JSONのパーズと構築, @code{rfc.json} - JSONのパーズと構築
15176
15177@deftp {Module} rfc.json
15178@mdindex rfc.json
15179@c EN
15180Procedures to parse JSON (RFC7159) data to S-expressions,
15181and convert S-expressions to JSON representation, are provided.
15182@c JP
15183RFC7159で規定される、JSON形式をパーズしてS式に直す手続きと、
15184S式をJSON形式に変換する手続きが提供されます。
15185@c COMMON
15186@end deftp
15187
15188@deftp {Condition type} <json-parse-error>
15189@c MOD rfc.json
15190@c EN
15191The parser @code{parse-json} and @code{parse-json-string} raise
15192this condition when they encounter
15193invalid JSON syntax.  It inherits @code{<error>}, and adds the following
15194slot.
15195@c JP
15196パーズ手続き@code{parse-json}と@code{parse-json-string}は、
15197無効なJSON構文に出会った時にこのコンディションを投げます。
15198@code{<error>}を継承し、次のスロットを追加で持ちます。
15199@c COMMON
15200
15201@defivar {<json-parse-error>} position
15202@c EN
15203The input position, counted in characters, where the error occurred.
15204@c JP
15205エラーが起きた入力位置(文字数)。
15206@c COMMON
15207@end defivar
15208@end deftp
15209
15210@deffn {Parameter} json-nesting-depth-limit
15211[SRFI-180]
15212@c MOD rfc.json
15213@c EN
15214Its value must be a real number, specifying the maximum nesting depth
15215of JSON text that can be parsed by @code{parse-json}.  If the input
15216exceeds the value, an @code{<json-parse-error>} is thrown.
15217The default value is @code{+inf.0}.
15218@c JP
15219このパラメータの値は実数でなければなりません。
15220@code{parse-json}がパーズするJSONテキストに許される最大のネストの深さを指定します。
15221入力のネスト深さがこのパラメータの値を越えた場合、@code{<json-parse-error>}が
15222投げられます。
15223デフォルトは@code{+inf.0}です。
15224@c COMMON
15225@end deffn
15226
15227
15228@defun parse-json :optional input-port
15229@c MOD rfc.json
15230@c EN
15231Reads and parses the JSON representation from @var{input-port} (default is
15232the current input port), and returns the result in an S-expression.
15233May raise a @code{<json-parse-error>} condition when parse error occurs,
15234or the nesting level exceeds the value of @code{json-nesting-depth-limit}.
15235@c JP
15236JSON表記を@var{input-port} (省略された場合はcurrent-input-port)から
15237読み込みパーズして、結果をS式で返します。
15238パーズエラーが起きたり、ネストレベルが@code{json-nesting-depth-limit}の
15239値を超過した場合は@code{<json-parse-error>}コンディションを投げます。
15240@c COMMON
15241
15242@c EN
15243The following table shows how JSON datatypes are
15244mapped to Scheme objects.
15245@c JP
15246下のテーブルに、JSONのデータ型がどのようにSchemeにマップされるかを示します。
15247@c COMMON
15248
15249@table @asis
15250@c EN
15251@item @code{true}, @code{false}, @code{null}
15252Symbols @code{true}, @code{false} and @code{null}.
15253(Customizable by @code{json-special-handler})
15254@item Arrays
15255Scheme vectors.  (Customizable by @code{json-array-handler})
15256@item Objects
15257Scheme assoc-lists, in which keys are strings, and values
15258are Scheme objects.  (Customizable by @code{json-object-handler})
15259@item Numbers
15260Scheme inexact real numbers.
15261@item Strings
15262Scheme strings.
15263@c JP
15264@item @code{true}, @code{false}, @code{null}
15265シンボル@code{true}, @code{false} and @code{null}。
15266(@code{json-special-handler}で変更可能)
15267@item 配列
15268Schemeのベクタ。 (@code{json-array-handler}で変更可能)
15269@item オブジェクト
15270Schemeの連想リスト。キーは文字列で、値はSchemeオブジェクト。
15271(@code{json-object-handler}で変更可能)
15272@item 数値
15273Schemeの不正確な実数。
15274@item 文字列
15275Schemeの文字列。
15276@c COMMON
15277@end table
15278
15279@c EN
15280Since the parser used internally in @code{parse-json} prefetches
15281characters, some characters after the parsed JSON expression
15282may already been read from @var{port} when @code{parse-json} returns.
15283That is, you cannot call @code{parse-json} repeatedly on @var{port}
15284to read subsequent JSON expressions.  Use @code{parse-json*} if you
15285need to read multiple JSON expressions.
15286@c JP
15287@code{parse-json}内で使っているパーザは文字の先読みを行う可能性があるので、
15288@code{parse-json}が戻って来た時点で、パーズされたJSON式以降のいくつかの文字が
15289@var{port}から既に読まれてしまっている可能性があります。
15290すなわち、複数のJSON式を読み出すのに、@var{port}に対して@code{parse-json}
15291を繰り返し呼び出すのはうまくいきません。複数のJSON式をパーズしたい場合は
15292@code{parse-json*}を使ってください。
15293@c COMMON
15294@end defun
15295
15296@defun parse-json* :optional input-port
15297@c MOD rfc.json
15298@c EN
15299Read JSON repeatedly from @var{input-port} until it reaches EOF,
15300and returns parsed results as a list.
15301@c JP
15302@var{input-port}から、EOFに達するまでJSON式を繰り返し読み取り、
15303パーズ結果をリストにして返します。
15304@c COMMON
15305@end defun
15306
15307@defun parse-json-string str
15308@c MOD rfc.json
15309@c EN
15310Parses the JSON string and returns the result in an S-expression.
15311May raise a @code{<json-parse-error>} condition when parse error occurs.
15312
15313See @code{parse-json} above for the mappings from JSON datatypes
15314to Scheme types.
15315@c JP
15316文字列@var{str}をJSONとしてパーズし、結果をS式で返します。
15317パーズエラーが起きた場合は@code{<json-parse-error>}コンディションを投げます。
15318
15319JSONのデータ型とSchemeの型とのマッピングについては上の@code{parse-json}
15320を参照してください。
15321@c COMMON
15322@end defun
15323
15324@deffn {Parameter} json-array-handler
15325@deffnx {Parameter} json-object-handler
15326@deffnx {Parameter} json-special-handler
15327@c MOD rfc.json
15328@c EN
15329The value of these parameters must be a procedure that takes
15330one argument: for @code{json-array-handler}, it is a list of
15331elements of a JSON array, for @code{json-object-handler},
15332it is a list of conses of key and value of a JSON object,
15333and for @code{json-special-handler}, it is one of the
15334symbols @code{false}, @code{true} or @code{null}.
15335
15336Whenever @code{parse-json} reads a JSON array, a JSON object,
15337or one of those special values,
15338it calls corresponding parameter to get a Scheme object.
15339
15340The default value of these parameters are @code{list->vector},
15341@code{identity}, and @code{identity}, respectively.
15342
15343The following example maps JSON objects to hash tables.
15344@c JP
15345これらのパラメータの値は、引数をひとつ取る手続きでなければなりません。
15346@code{json-array-handler}の値の手続きに渡される引数は、
15347JSON配列の要素のリストです。
15348@code{json-object-handler}では
15349JSONオブジェクトのキーと値をconsしたもののリスト、
15350@code{json-special-handler}では
15351シンボル@code{false}, @code{true}, @code{null}のいずれかです。
15352
15353@code{parse-json}はJSON配列やオブジェクト、false、true、nullに
15354出会う度に、
15355このパラメータの値の手続きを起動して、JSONに対応するSchemeオブジェクトを
15356得ます。
15357
15358これらのパラメータのデフォルト値はそれぞれ@code{list->object}、
15359@code{identity}、@code{identity}です。
15360
15361次の例では、JSONオブジェクトをハッシュテーブルに変換しています。
15362@c COMMON
15363
15364@example
15365(parameterize ([json-object-handler (cut alist->hash-table <> 'string=?)])
15366  (parse-json-string "@{\"a\":1, \"b\":2@}"))
15367 @result{} #<hash-table ...>
15368@end example
15369@end deffn
15370
15371
15372@deftp {Condition type} <json-construct-error>
15373@c MOD rfc.json
15374@c EN
15375The converters @code{construct-json} and
15376@code{construct-json-string} raise this condition
15377when they cannot convert given Scheme object to JSON.
15378It inherits @code{<error>}, and adds the following slot.
15379@c JP
15380@code{construct-json}と@code{construct-json-string}は、
15381JSONに変換できないSchemeオブジェクトを見つけるとこのコンディションを投げます。
15382@code{<error>}を継承し、次のスロットを追加で持ちます。
15383@c COMMON
15384
15385@defivar {<json-construct-error>} object
15386@c EN
15387The Scheme object that cannot convert to JSON representation.
15388@c JP
15389JSON表現に変換できなかったSchemeオブジェクト。
15390@c COMMON
15391@end defivar
15392@end deftp
15393
15394@defun construct-json obj :optional output-port
15395@defunx construct-json-string obj
15396@c MOD rfc.json
15397@c EN
15398Creates JSON representation of Scheme object @var{obj}.
15399@code{construct-json} writes out the result to @var{output-port},
15400whose default is the current output port.  @code{construct-json-string}
15401returns the result in a string.
15402
15403If @var{obj} contains a Scheme object that cannot be mapped
15404to JSON representation, a @code{<json-construct-error>} condition
15405is raised.
15406
15407Scheme objects are mapped to JSON as follows:
15408@c JP
15409Schemeオブジェクト@var{obj}のJSON表現を作ります。
15410@code{construct-json}は結果を@var{output-port}に書き出します。デフォルトは
15411current-output-portです。@code{construct-json-string}は結果を文字列で返します。
15412
15413@var{obj}がJSONにマップできないオブジェクトを含んでいた場合は
15414@code{<json-construct-error>}コンディションが投げられます。
15415
15416Schemeオブジェクトは以下のようにJSONへと変換されます。
15417@c COMMON
15418
15419@table @asis
15420@c EN
15421@item symbol @code{false}, @code{#f}
15422@code{false}
15423@item symbol @code{true}, @code{#t}
15424@code{true}
15425@item symbol @code{null}
15426@code{null}
15427@item list, instance of @code{<dictionary>}
15428JSON object (list must be an assoc list of key and value).
15429@item string
15430string
15431@item real number
15432number
15433@item instance of @code{<sequence>} (except strings and lists)
15434JSON array
15435@c JP
15436@item シンボル@code{false}, @code{#f}
15437@code{false}
15438@item シンボル@code{true}, @code{#t}
15439@code{true}
15440@item シンボル@code{null}
15441@code{null}
15442@item リスト、 @code{<dictionary>}のインスタンス
15443JSONオブジェクト (リストはキーと値の連想リストでなければならない)
15444@item 文字列
15445文字列
15446@item 実数
15447数値
15448@item @code{<sequence>}のインスタンス (文字列とリストを除く)
15449JSON配列
15450@c COMMON
15451@end table
15452
15453@end defun
15454
15455@c ----------------------------------------------------------------------
15456@node MD5 message digest, MIME message handling, JSON parsing and construction, Library modules - Utilities
15457@section @code{rfc.md5} - MD5 message digest
15458@c NODE MD5メッセージダイジェスト, @code{rfc.md5} - MD5メッセージダイジェスト
15459
15460@deftp {Module} rfc.md5
15461@mdindex rfc.md5
15462@c EN
15463This module implements MD5 message digest algorithm, defined in
15464RFC 1321 (@uref{https://www.ietf.org/rfc/rfc1321.txt}).
15465The module extends util.digest
15466(@pxref{Message digester framework}).
15467@c JP
15468このモジュールは、RFC 1321 (@uref{https://www.ietf.org/rfc/rfc1321.txt}) で
15469定義されている、MD5メッセージダイジェストアルゴリズムを実装しています。
15470このモジュールは、util.digest (@ref{Message digester framework}参照)
15471を拡張しています。
15472@c COMMON
15473@end deftp
15474
15475@deftp {Class} <md5>
15476@clindex md5
15477@c MOD rfc.md5
15478@c EN
15479The instance of this class keeps internal state of MD5 digest algorithm.
15480
15481This class implements @code{util.digest} framework interface,
15482@code{digest-update!}, @code{digest-final!},
15483@code{digest}, and @code{digest-string}.
15484@xref{Message digester framework}, for detailed explanation
15485of these methods.
15486@c JP
15487このクラスのインスタンスは、MD5ダイジェストアルゴリズムの内部状態を
15488保持しています。
15489
15490このクラスは、@code{util.digest}フレームワークのインターフェースである、
15491@code{digest-update!}、@code{digest-final!}、@code{digest}、
15492@code{digest-string}を実装しています。
15493これらのメソッドの詳細な説明は、@ref{Message digester framework}
15494を参照して下さい。
15495@c COMMON
15496@end deftp
15497
15498@c EN
15499Besides the digester framework, this module provides to
15500short-cut procedures.
15501@c JP
15502ダイジェスタフレームワークに加えて、このモジュールはショートカット手続きを
15503提供します。
15504@c COMMON
15505
15506@defun md5-digest
15507@c MOD rfc.md5
15508@c EN
15509Reads data from the current input port until EOF, and returns
15510its digest in an incomplete string.
15511@c JP
15512現在の入力ポートからEOFまで読み込み、そのダイジェストを不完全文字列で
15513返します。
15514@c COMMON
15515@end defun
15516
15517@defun md5-digest-string string
15518@c MOD rfc.md5
15519@c EN
15520Digest the data in @var{string}, and returns the result
15521in an incomplete string.
15522@c JP
15523@var{string}にあるデータをダイジェストし、その結果を不完全文字列で
15524返します。
15525@c COMMON
15526@end defun
15527
15528@c ----------------------------------------------------------------------
15529@node MIME message handling, Quoted-printable encoding/decoding, MD5 message digest, Library modules - Utilities
15530@section @code{rfc.mime} - MIME message handling
15531@c NODE MIMEメッセージ処理, @code{rfc.mime} - MIMEメッセージ処理
15532
15533@deftp {Module} rfc.mime
15534@mdindex rfc.mime
15535@c EN
15536This module provides utility procedures to handle
15537Multipurpose Internet Mail Extensions (MIME) messages,
15538defined in RFC2045 thorough RFC2049.
15539Provided APIs include procedures to parse or compose MIME-specific
15540header fields, and parse or compose MIME-encoded message bodies.
15541@c JP
15542RFC2045からRFC2049で定義されている、
15543多目的インターネットメール拡張(Multipurpose Internet Mail Extensions; MIME)
15544メッセージを扱う便利な手続きです。MIME特有のヘッダフィールドやメッセージボディを
15545パーズしたり作成したりするAPIが提供されます。
15546@c COMMON
15547
15548@c EN
15549This module mainly focuses on providing low-level building-block procedures,
15550on top of which application-specific modules are to be built.
15551For example, @code{rfc.http} uses this module to compose
15552@code{multipart/form-data} message for the body of POST requests
15553(@pxref{HTTP}).
15554@c JP
15555このモジュールは主としてビルディングブロックとなる低レベルの手続きに
15556フォーカスしており、アプリケーション特有のモジュールがこの上に
15557構築されることを意図しています。例えば@code{rfc.http}はPOSTリクエストの
15558ボディを@code{multipart/form-data}として構築する際にこのモジュールを
15559利用します(@ref{HTTP}参照)。
15560@c COMMON
15561
15562@c EN
15563This module is supposed to be used with @code{rfc.822} module
15564(@pxref{RFC822 message parsing}).
15565@c JP
15566このモジュールは、@code{rfc.822}モジュールと一緒に使うことを
15567想定しています(@ref{RFC822 message parsing}参照)。
15568@c COMMON
15569@end deftp
15570
15571@subheading Utilities for header fields
15572
15573@c EN
15574A few utility procedures to parse and generate MIME-specific header fields.
15575@c JP
15576MIME特有のヘッダフィールドをパーズしたり生成したりする便利な手続き。
15577@c COMMON
15578
15579@defun mime-parse-version field
15580@c MOD rfc.mime
15581@c EN
15582If @var{field} is a valid header field for MIME-Version, returns
15583its major and minor versions in a list.  Otherwise, returns @code{#f}.
15584It is allowed to pass @code{#f} to @var{field}, so that
15585you can directly pass the result of @code{rfc822-header-ref} to it.
15586Given parsed header list by @code{rfc822-read-headers}, you can
15587get mime version (currently, it should be @code{(1 0)}) by the
15588following code.
15589@c JP
15590@var{field}がそのMIMEバージョンのヘッダフィールドとして有効であれば、
15591そのメジャーバージョン番号とマイナーバージョン番号をリストにして
15592返します。そうでなければ、@code{#f}を返します。
15593@var{field}には@code{#f}を渡せるので、@code{rfc822-header-ref}の
15594戻り値を直接渡すこともできます。@code{rfc822-read-headers}により
15595返されるパーズ済みヘッダのリストを渡すことで、以下のように
15596MIMEのバージョンを得ることができます。(現在は、@code{(1 0)}です。)
15597@c COMMON
15598@example
15599(mime-parse-version (rfc822-header-ref headers "mime-version"))
15600@end example
15601
15602@c EN
15603Note: simple regexp such as @code{#/\d+\.\d+/} doesn't do this job,
15604for @var{field} may contain comments between tokens.
15605@c JP
15606注意: @var{field}はトークンの間にコメントを含むかもしれないので、
15607@code{#/\d+\.\d+/}のような単純な正規表現では不十分です。
15608@c COMMON
15609@end defun
15610
15611@defun mime-parse-content-type field
15612@c MOD rfc.mime
15613@c EN
15614Parses the "content-type" header field, and returns a list such as:
15615@c JP
15616``content-type''ヘッダフィールドをパーズし、次のようなリストを
15617返します。
15618@c COMMON
15619@example
15620(@i{type} @i{subtype} (@i{attribute} . @i{value}) @dots{})
15621@end example
15622@c EN
15623where @i{type} and @i{subtype} are MIME media type and
15624subtype in a string, respectively
15625@c JP
15626ここで、@i{type}と@i{subtype}はそれぞれ、MIMEメディアタイプと
15627サブタイプを文字列で表したものになります。
15628@c COMMON
15629
15630@example
15631(mime-parse-content-type "text/html; charset=iso-2022-jp")
15632 @result{} ("text" "html" ("charset" . "iso-2022-jp"))
15633@end example
15634
15635@c EN
15636If @var{field} is not a valid content-type field, @code{#f} is
15637returned.
15638@c JP
15639@var{field}が有効なcontent-typeフィールドでない場合は、
15640@code{#f}が返ります。
15641@c COMMON
15642@end defun
15643
15644@defun mime-parse-content-disposition field
15645@c MOD rfc.mime
15646@c EN
15647Parses Content-disposition header field as specified in RFC2183.
15648@c JP
15649RFC2183に定められたContent-Dispositionヘッダフィールドをパーズします。
15650@c COMMON
15651(mime-parse-content-disposition "attachment; filename=genome.jpeg;\
15652  modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";")
15653 @result{} ("attachment"
15654      ("filename" . "genome.jpeg")
15655      ("modification-date" . "Wed, 12 Feb 1997 16:29:51 -0500"))
15656@end defun
15657
15658
15659@defun mime-parse-parameters :optional iport
15660@defunx mime-compose-parameters params :optional oport :key start-column
15661@c MOD rfc.mime
15662@c EN
15663These are low-level utility procedures to parse and compose @emph{parameter}
15664part of header fields (as appeared in RFC2045 Section 5.1 etc).
15665
15666@code{Mime-parse-parameters} reads the parameter
15667part of the header body from an input port @var{iport}, and
15668returns an assoc list of the parameter names and values.
15669Conversely, @code{mime-compose-parameters} takes an assoc
15670list of names and values, compose parameter part and
15671emit it to @var{oport}.   When omitted, the current input
15672port and the current output port are used for @var{iport}
15673and @var{oport}, respectively.  You can pass @code{#f} to
15674@var{oport} and @code{mime-compose-parameters} returns the
15675result in a string instead of emitting it to a port.
15676@c JP
15677これらは、(RFC2045の5.1節にあるような)ヘッダフィールドの値の@emph{parameter}
15678部分をパーズしたり作成したりするための低レベルのユーティリティ手続きです。
15679
15680@code{mime-parse-parameters}はヘッダフィールドの値のパラメータ部分を
15681入力ポート@var{iport}から読んでパーズし、パラメータの名前と値の
15682連想リストを返します。
15683@code{mime-compose-parameters}はその逆で、連想リストをとり、
15684パラメータ部分を構成して@var{oport}へと書き出します。
15685@var{iport}、@var{oport}はそれぞれ省略された場合、
15686@code{current-input-port}と@code{current-output-port}を
15687デフォルトとします。また、@var{oport}に@code{#f}を渡すと
15688@code{mime-compose-parameters}は結果をポートに書き出すかわりに
15689文字列として返します。
15690@c COMMON
15691
15692@example
15693(call-with-input-string
15694   "; name=foo; filename=\"foo/bar/baz\""
15695   mime-parse-parameters)
15696 @result{} (("name" . "foo") ("filename" . "foo/bar/baz"))
15697
15698(mime-compose-parameters
15699 '(("name" . "foo") ("filename" . "foo/bar/baz"))
15700 #f)
15701 @result{} "; name=foo; filename=\"foo/bar/baz\""
15702@end example
15703
15704@c EN
15705@code{Mime-compose-parameters} tries to insert folding line breaks
15706between parameters to avoid the header line becomes too long.
15707You can pass the beginning column position of the parameter
15708part via @var{start-column} argument.
15709@c JP
15710@var{mime-compose-parameters}はヘッダ行が長くなりすぎる場合に
15711パラメータ間に折り返し改行を入れようとします。パラメータ部分が始まる
15712カラム数は@var{start-column}で与えることができます。
15713@c COMMON
15714
15715@c EN
15716We plan to make these procedures handle RFC2231's parameter value
15717extension transparently in future.
15718@c JP
15719将来は、これらの手続きにRFC2231のパラメータ値拡張を透過的に処理させる予定です。
15720@c COMMON
15721@end defun
15722
15723
15724@defun mime-decode-word word
15725@c MOD rfc.mime
15726@c EN
15727Decodes RFC2047-encoded word.  If @var{word} isn't an encoded word,
15728it is returned as is.
15729
15730Note that this procedure decodes only if the entire @var{word} is
15731an ``encoded word'' defined in RFC2047.  If you are dealing with
15732a field that may contain multiple encoded word and/or unencoded parts,
15733use @code{mime-decode-text} below.
15734@c JP
15735RFC2047でエンコードされた@var{word}をデコードします。
15736@var{word}がRFC2047でエンコードされたものでない場合は、そのまま
15737返されます。
15738
15739この手続きは@var{word}全体がRFC2047の規定する``encoded-word''である場合にのみ
15740デコードを行うことに注意してください。複数のエンコードされた部分や
15741エンコードされていない部分が混ざっているフィールドを扱う場合は、
15742下に示す@code{mime-decode-text}を使います。
15743@c COMMON
15744
15745@example
15746(mime-decode-word "=?iso-8859-1?q?this=20is=20some=20text?=")
15747 @result{} "this is some text"
15748@end example
15749
15750@end defun
15751@defun mime-decode-text text
15752@c MOD rfc.mime
15753@c EN
15754Returns a string in which
15755all encoded words contained within @var{text} are decoded.
15756This procedure can deal with a header field body that may contain
15757mixture of non-encoded and encoded parts, and/or multiple encoded
15758parts.  One of such header field is the Subject field of email.
15759
15760@example
15761(mime-decode-text "This is =?US-ASCII?q?some=20text?=")
15762 @result{} "This is some text"
15763@end example
15764@c JP
15765@var{text}中に含まれるすべてのencoded wordをデコードした文字列を返します。
15766この手続きは、エンコードされていない部分とエンコードされている部分が混ざっていたり、
15767複数のエンコードされている部分を持つヘッダフィールドボディを処理することが
15768できます。そのようなフィールドの例はemailのSubjectフィールドです。
15769
15770@example
15771(mime-decode-text "Yamada Taro (=?utf-8?B?5bGx55SwIOWkqumDjg==?=)")
15772 @result{} "Yamada Taro (山田 太郎)"
15773@end example
15774@c COMMON
15775
15776@c EN
15777Care should be taken if you apply this procedure to a ``structured''
15778header field body (see RFC2822 section 2.2.2).
15779The proper way of parsing a structured header field body is
15780to tokenize it first, then to decode each word using @code{mime-decode-word}.
15781since the decoded text may contain characters that affects the tokenization.
15782(However, if you can just show the header field in human readable way
15783for informational purposes, you may just use @code{mime-decode-text}
15784on entire header field for the convenience).
15785@c JP
15786この手続きを「構造化された」ヘッダフィールドボディ (RFC2822 2.2.2節参照)
15787に適用する際には注意が必要です。
15788構造化されたヘッダフィールドボディをパーズする正式な方法は、
15789最初にトークンに分割して、それから各wordを
15790@code{mime-decode-word}を使ってデコードするというものです。
15791なぜならデコード後のテキスト中に、パージングに影響を与える文字が含まれている
15792かもしれないからです。
15793(ただし、単に参考情報を人間にわかりやすいように表示するだけの目的の場合は、
15794簡便のためにヘッダフィールド全体をこの手続きで一度にデコードしてしまっても
15795良いでしょう)。
15796@c COMMON
15797@end defun
15798
15799@defun mime-encode-word word :key charset transfer-encoding
15800@c MOD rfc.mime
15801@c EN
15802Encodes @var{word} in the RFC2047 format.  The keyword
15803argument @var{charset} specifies the character encoding scheme
15804in string or symbol.
15805whose default is @code{utf-8}.  If @var{charset} differs from
15806Gauche's internal encoding and @var{word} is a complete string,
15807the procedure converts the character encoding to @var{charset},
15808then performs transfer encoding.
15809@c JP
15810@var{word}をRFC2047フォーマットにエンコードします。キーワード引数
15811@var{charset}は文字列かシンボルで文字エンコーディングスキームを指定します。
15812デフォルトは@code{utf-8}です。@var{charset}の指定がGaucheの
15813内部文字エンコーディングと異なっており、@var{word}が完全な文字列である場合は、
15814まず@var{word}が@var{charset}のエンコーディングへと変換され、
15815その上でトランスファーエンコーディングがかけられます。
15816@c COMMON
15817
15818@example
15819(mime-encode-word "this is some text")
15820 @result{} "=?utf-8?B?dGhpcyBpcyBzb21lIHRleHQ=?="
15821@end example
15822
15823@c EN
15824The keyword argument @var{transfer-encoding} specifies how
15825the octets are encoded to transfer-safe characters.  You can
15826give a symbol @code{b}, @code{B} or @code{base64} for Base64,
15827and @code{Q}, @code{q}, @code{quoted-printable} for Quoted-printable
15828transfer encodings.  An error is raised if you pass values other
15829than those.  The default is Base64 encoding.
15830@c JP
15831キーワード引数@var{transfer-encoding}は各オクテットを伝達上安全な
15832文字列へどエンコードする方法を指定します。サポートされている値は、
15833Base64を指定するシンボル@code{b}、@code{B}、@code{base64}、
15834およびQuoted printableを指定する
15835@code{Q}、@code{q}、@code{quoted-printable}です。
15836これ以外の値を渡した場合はエラーが通知されます。デフォルトはBase64です。
15837@c COMMON
15838
15839@c EN
15840This procedure does not consider the length of the resulting
15841encoded word, which RFC2047 recommends to be less than 75 octets.
15842Use @code{mime-encode-text} below to conform the line length limit.
15843@c JP
15844この手続きは結果のencoded wordの長さを気にしませんが、
15845RFC2047によればencoded wordは75オクテットまでに収めることが
15846要請されています。この要請に対応するには下に示す
15847@code{mime-encode-text}を使って下さい。
15848@c COMMON
15849
15850@c EN
15851(Note: In most Gauche procedures, a keyword argument @code{encoding}
15852is used to specify character encodings.  In this context we have
15853two encodings, however, and to avoid the confusion we chose to use
15854the terms ``charset'' and ``transfer-encoding'' that appear in
15855RFC documents.)
15856@c JP
15857(註:ほとんどのGaucheの手続きでは、キーワード引数@code{encoding}により
15858文字エンコーディングを指定します。しかしこの手続きの文脈では
158592つの「エンコーディング」が存在しているので、混乱を避けるために
15860RFC文書で使われている``charset''および``transfer-encoding''の用語を
15861使うこととしました。)
15862@c COMMON
15863@end defun
15864
15865@defun mime-encode-text text :key charset transfer-encoding line-width start-column force
15866@c MOD rfc.mime
15867@c EN
15868Encode @var{text} in RFC2047 format if necessary, and considering
15869line folding if the result gets too long.
15870
15871The keyword arguments @var{charset} and @var{transfer-encoding} are the same
15872as @code{mime-encode-word}.
15873@c JP
15874@var{text}を、必要ならばRFC2047フォーマットに従いエンコードします。
15875また、結果が長すぎる場合の行の折り返しも考慮します。
15876
15877キーワード引数@var{charset}と@var{transfer-encoding}の意味は
15878@code{mime-encode-word}と同じです。
15879@c COMMON
15880
15881@c EN
15882If the @var{text} only consists of printable ASCII characters,
15883no encoding is done, and only line folding is considered.
15884However, if a true value is given to the @var{force} argument,
15885even ASCII-only @var{text} is encoded.
15886@c JP
15887もし@var{word}が印字可能なASCII文字のみで構成されていた場合は
15888エンコーディングは行われず、行の折り返しのみが処理されます。
15889但し、@var{force}引数に真の値が与えられた場合はASCIIのみの@var{text}も
15890エンコードされます。
15891@c COMMON
15892
15893@c EN
15894The @var{line-width} specifies the maximum line width of the result.
15895Its default is 76.
15896If the encoded word gets too long, it is splitted to multiple encoded
15897words and CR LF SPC sequence (``folding white space'' defined in RFC2822)
15898are inserted inbetween.
15899You can suppress this behavior by passing @code{#f} or @code{0} to
15900@var{line-width}.
15901Since encoded word needs some overhead characters, it doesn't make much sense
15902to specify small value to @code{line-width}.  Current implementation
15903rejects @code{line-width} smaller than 30.
15904@c JP
15905@var{line-width}は結果に現れる行の最大値を指定します。デフォルトは76です。
15906encoded wordがこれを越える場合は、複数のencoded wordへと結果は分割され、
15907間にCR LF SPCシーケンス(RFC2822で定義される``folding white space'')が挿入されます。
15908@var{line-width}に@code{#f}か@code{0}を渡すことで
15909行の折り返しを抑制することができます。
15910encoded wordには文字数でいくらかのオーバヘッドがあるため、
15911あまり小さい@code{line-width}には意味がありません。現在の実装では
1591230以下の値は拒否されます。
15913@c COMMON
15914
15915@c EN
15916The @var{start-column} keyword argument can be used to
15917shorten the first of folded
15918lines to make room for header field name.  For example, if
15919you want to encode the body of a Subject header field,
15920you can pass the value of @code{(string-length "Subject: ")} so that
15921the encoded result can directly concatenated after the header
15922field name.  The default value is 0.
15923@c JP
15924@var{start-column}キーワード引数は、ヘッダフィールド名を入れるために
15925エンコード結果の最初の行だけを短くするのに使えます。
15926例えばSubjectヘッダフィールドのボディをエンコードする際に、
15927@code{(string-length "Subject: ")}の値を渡してやれば、
15928結果を直接"Subject: "の後に連結することができるわけです。
15929デフォルトの値は0です。
15930@c COMMON
15931
15932@c EN
15933This procedure is not designed to encode parts of structured
15934header fields, which have further restrictions such as which parts
15935can be encoded and where the folding white spaces can be inserted.
15936The robust way is to encode some parts first, then construct
15937a structured header fields, considering line folding.
15938@c JP
15939この手続きはstructured header fieldをエンコードするようには設計
15940されていません。structured header fieldには、どの部分がエンコード
15941可能でどの部分にfolding white spaceが挿入可能かについてさらなる
15942制約があるためです。安全な方法は、まず必要な部分をエンコードし、
15943それから折り返しを考慮しつつstructured header fieldを組み立てることです。
15944@c COMMON
15945@end defun
15946
15947@subheading Streaming parser
15948
15949@c EN
15950The streaming parser is designed so that you can decide how
15951to do with the message body before the entire message is read.
15952@c JP
15953メッセージ全体が読み込まれる前にメッセージボディをどのように
15954扱うかをコントロールできるように、ストリームパーザが用意されて
15955います。
15956@c COMMON
15957
15958@defun mime-parse-message port headers handler
15959@c MOD rfc.mime
15960@c EN
15961The fundamental streaming parser.  @var{Port} is an input port
15962from where the message is read.  @var{Headers} is a list of headers
15963parsed by @code{rfc822-read-headers}; that is, this procedure
15964is supposed to be called after the header part of the message
15965is parsed from @var{port}:
15966@c JP
15967基本的なストリームパーザです。@var{port}は、メッセージを読み込む
15968入力ポートです。@var{headers}は@code{rfc822-read-headers}により
15969パーズされたヘッダのリストです。つまり、この手続きは、
15970@var{port}から読み込まれたメッセージのヘッダ部分がパーズされた
15971後に使われることを想定しています。
15972@c COMMON
15973@example
15974(let* ((headers (rfc822-read-headers port)))
15975  (if (mime-parse-version (rfc822-header-ref headers "mime-version"))
15976     ;; parse MIME message
15977     (mime-parse-message port headers handler)
15978     ;; retrieve a non-MIME body
15979     ...))
15980@end example
15981
15982@c EN
15983@code{Mime-parse-message} analyzes @var{headers}, and calls
15984@var{handler} on each message body with two arguments:
15985@c JP
15986@code{mime-parse-message}は@var{headers}を解析し、
15987メッセージボディのそれぞれについて、2引数をもって
15988@var{handler}を呼び出します。
15989@c COMMON
15990
15991@example
15992(handler @var{part-info} @var{xport})
15993@end example
15994
15995@c EN
15996@var{Part-Info} is a @code{<mime-part>} structure described below
15997that encapsulates the information of this part of the message.
15998@c JP
15999@var{part-info}は、以下で説明するような、メッセージのこのパートの
16000情報をカプセル化した@code{<mime-part>}ストラクチャです。
16001
16002@c EN
16003@var{Xport} is an input port, initially points to the beginning
16004of the body of message.  The handler can read from the port
16005as if it is reading from the original @var{port}.  However,
16006@var{xport} recognizes MIME boundary internally, and returns EOF
16007when it reaches the end of the part.
16008(Do not read from the original @var{port} directly, or it will mess up
16009the internal state of @var{vport}).
16010@c JP
16011@var{xport}は入力ポートで、最初はメッセージボディの先頭を指しています。
16012ハンドラはこのポートからメッセージボディを読み込むことが出来ます。
16013@var{xport}はMIMEバウンダリを認識し、パートの最後に到達したら
16014EOFを返します。
16015(元の@var{port}から直接読み込まないようにして下さい。
16016そうしてしまうと、@var{vport}の内部状態がおかしくなります)。
16017@c COMMON
16018
16019@c EN
16020@var{Handler} can read the part into the memory, or
16021save it to the disk, or even discard the part.
16022Whatever it does, it has to read from @var{vport} until it
16023returns EOF.
16024
16025The return value of @var{handler} will be set in
16026the @code{content} slot of @var{part-info}.
16027@c JP
16028@var{handler}は、パートをメモリに読み込んだり、ディスクに保存したり、
16029あるいはそのパートを無視したりできます。ただ、何をするにせよ、
16030@var{vport}がEOFを返すまでデータを読まなければなりません。
16031
16032@var{handler}の戻り値は、@var{part-info}の@code{content}スロットに
16033セットされます。
16034
16035@c EN
16036If the message has nested multipart messages, @var{handler} is
16037called for each "leaf" part, in depth-first order.  @var{Handler}
16038can know its nesting level by examining @var{part-info} structure.
16039@c JP
16040メッセージが、ネストしたマルチパートメッセージを含んでいる場合は、
16041@var{handler}は深さ優先でそれぞれの``葉''のパートに対して呼ばれます。
16042@var{handler}は、@var{part-info}ストラクチャを調べることで、
16043そのネストのレベルを知ることができます。
16044
16045@c EN
16046The message doesn't need to be a multipart type; if it is a
16047MIME @code{message} type, @var{handler} is called on the body
16048of enclosed message.  If it is other media types such as @code{text}
16049or @code{application}, @var{handler} is called on the (only) message body.
16050@c JP
16051メッセージはマルチパートである必要はありません。メッセージが
16052MIME @code{message}タイプである場合は、@var{handler}は囲まれたメッセージの
16053ボディに対して呼ばれます。メッセージが、@code{text}や@code{application}
16054などの他のメディアタイプの場合は、@var{handler}は単にメッセージボディに
16055対して呼ばれます。
16056@c COMMON
16057@end defun
16058
16059@deftp {Class} <mime-part>
16060@clindex mime-message
16061@c MOD rfc.mime
16062@c EN
16063A structure that encloses metainformation about a MIME part.
16064It is constructed when the header of the part is read, and
16065passed to the handler that reads the body of the part.
16066
16067It has the following slots:
16068@c JP
16069MIMEパートのメタ情報を含むストラクチャです。
16070これは、そのパートのヘッダが読み込まれた時点で構築され、
16071そのパートのボディを読み込むハンドラに渡されます。
16072
16073以下のスロットを持ちます。
16074@c COMMON
16075
16076@defivar {<mime-part>} type
16077@c EN
16078MIME media type string.  If @code{content-type} header is omitted
16079to the part, an appropriate default value is set.
16080@c JP
16081MIMEメディアタイプの文字列。そのパートの@code{content-type}ヘッダが
16082省略された場合は、適切なデフォルト値がセットされます。
16083@c COMMON
16084@end defivar
16085
16086@defivar {<mime-part>} subtype
16087@c EN
16088MIME media subtype string.  If @code{content-type} header is omitted
16089to the part, an appropriate default value is set.
16090@c JP
16091MIMEメディアのサブタイプの文字列。そのパートの@code{content-type}
16092ヘッダが省略された場合は、適切なデフォルト値がセットされます。
16093@c COMMON
16094@end defivar
16095
16096@defivar {<mime-part>} parameters
16097@c EN
16098Associative list of parameters given to @code{content-type} header field.
16099@c JP
16100@code{content-type}ヘッダフィールドに渡されるパラメータの連想リスト。
16101@c COMMON
16102@end defivar
16103
16104@defivar {<mime-part>} transfer-encoding
16105@c EN
16106The value of @code{content-transfer-encoding} header field.
16107If the header field is omitted, an appropriate default value is set.
16108@c JP
16109@code{content-transfer-encoding}ヘッダフィールドの値。
16110このヘッダフィールドが省略された場合は、適切なデフォルト値が
16111セットされます。
16112@c COMMON
16113@end defivar
16114
16115@defivar {<mime-part>} headers
16116@c EN
16117The list of header fields, as parsed by @code{rfc822-read-headers}.
16118@c JP
16119@code{rfc822-read-headers}によりパーズされた、ヘッダフィールドのリスト。
16120@c COMMON
16121@end defivar
16122
16123@defivar {<mime-part>} parent
16124@c EN
16125If this is a part of multipart message or encapsulated message,
16126points to the enclosing part's @code{<mime-part>} structure.
16127Otherwise @code{#f}.
16128@c JP
16129それがマルチパートメッセージあるいはカプセル化されたメッセージの
16130パートである場合は、それを含んでいるパートの@code{<mime-part>}
16131ストラクチャを指します。そうでなければ@code{#f}を返します。
16132@c COMMON
16133@end defivar
16134
16135@defivar {<mime-part>} index
16136@c EN
16137Sequence number of this part within the same parent.
16138@c JP
16139同じ親を持つパートの中でのそのパートのシーケンス番号。
16140@c COMMON
16141@end defivar
16142
16143@defivar {<mime-part>} content
16144@c EN
16145If this part is multipart/* or message/* media type,
16146this slot contains a list of parts within it.
16147Otherwise, the return value of @var{handler} is stored.
16148@c JP
16149そのパートのメディアタイプがmultipart/*あるいはmessage/*で
16150ある場合は、このスロットにはそれに含まれるパートのリストが
16151入っています。そうでなければ、@var{handler}の戻り値が
16152格納されています。
16153@c COMMON
16154@end defivar
16155
16156@defivar {<mime-part>} source
16157@c EN
16158This slot is only used when composing a MIME message.
16159The caller can set this slot a name of the file to be inserted
16160into this part, instead of setting the entire content of the
16161file to the @code{content} slot.   See
16162@code{mime-compose-message} below for the more details.
16163@c JP
16164このスロットはMIMEメッセージを作成する時のみ使われます。
16165呼び出し元は、このスロットにファイル名をセットすることで、
16166MIMEメッセージのこのパートにファイルの内容を挿入することができます。
16167詳しくは下の@code{mime-compose-message}の項を参照してください。
16168@c COMMON
16169@end defivar
16170@end deftp
16171
16172@defun mime-retrieve-body part-info xport outp
16173@c MOD rfc.mime
16174@c EN
16175A procedure to retrieve message body.  It is intended to
16176to be a building block of @var{handler} to be passed to
16177@code{mime-parse-message}.
16178
16179@var{Part-info} is a @code{<mime-part>} object.
16180@var{Xport} is an input port passed to the handler,
16181from which the MIME part can be read.
16182@c JP
16183メッセージボディを取得するための手続きです。
16184@code{mime-parse-message}へ渡される、@var{handler}の
16185ビルディングブロックとなることを意図しています。
16186
16187@var{part-info}は、@code{<mime-part>}のオブジェクトです。
16188@var{xport}はハンドラに渡された入力ポートで、
16189そこからMIMEパートが読みこまれるものです。
16190
16191@c EN
16192This procedure read from @var{xport}
16193until it returns EOF.  It also looks at the
16194@code{transfer-encoding} of @var{part-info}, and decodes
16195the body accordingly; that is, base64 encoding and
16196quoted-printable encoding is handled.  The result is
16197written out to an output port @var{outp}.
16198
16199This procedure does not handle charset conversion.
16200The caller must use CES conversion port as @var{outp}
16201(@pxref{Character code conversion}) if desired.
16202@c JP
16203この手続きは、@var{xport}からEOFに達するまで読み込み、
16204@var{part-info}の@code{transfer-encoding}も見て、
16205ボディを適切にデコードします。つまり、base64やquoted-printable
16206のエンコーディングは適切に処理されます。結果が出力ポート@var{outp}へと
16207出力されます。
16208
16209この手続きは文字集合の変換は扱いません。
16210必要であれば、呼び出し側が@var{outp}としてCES変換ポートを
16211使う必要があります(@ref{Character code conversion}参照)。
16212
16213@c COMMON
16214@end defun
16215
16216@c EN
16217A couple of convenience procedures are defined for typical
16218cases on top of @code{mime-retrieve-body}.
16219@c JP
16220典型的なケースのために、いくつかの便利な手続きが@code{mime-retrieve-body}
16221の上に定義されています。
16222@c COMMON
16223
16224@defun mime-body->string part-info xport
16225@defunx mime-body->file part-info xport filename
16226@c MOD rfc.mime
16227@c EN
16228Reads in the body of mime message, decoding transfer encoding,
16229and returns it as a string or writes it to a file, respectively.
16230@c JP
16231MIMEメッセージのボディを読み込み、転送(transfer)エンコーディングを
16232デコードし、それぞれ文字列として返すか、ファイルへ書き出します。
16233@c COMMON
16234@end defun
16235
16236@c EN
16237The simplest form of MIME message parser would be like this:
16238@c JP
16239MIMEメッセージパーザの最もシンプルな使い方は次のように
16240なります。
16241@c COMMON
16242
16243@example
16244(let ((headers (rfc822-read-headers port)))
16245  (mime-parse-message port headers
16246                      (cut mime-body->string <> <>)))
16247@end example
16248
16249@c EN
16250This reads all the message on memory (i.e. the "leaf" @code{<mime-part>}
16251objects' @code{content} field would hold the part's body as a string),
16252and returns the top @code{<mime-part>} object.  Content transfer encoding
16253is recognized and handled, but character set conversion isn't done.
16254
16255You may want to feed the message body to a file directly,
16256or even want to skip some body according to mime media types and/or
16257other header information.  Then you can put the logic in the handler
16258closure.  That's the reason that this module provides building
16259blocks, instead of all-in-one procedure.
16260@c JP
16261これは、メッセージの全てをメモリに読み込み、
16262一番上層の@code{<mime-part>}オブジェクトを返します。
16263(``葉''である@code{<mime-part>}オブジェクトの@code{content}フィールドは、
16264そのパートのボディを文字列として保持しています。)
16265内容の転送エンコーディング(content transfer encoding)は認識され処理
16266されますが、文字集合の変換は行われません。
16267
16268メッセージボディを直接ファイルに書き出したり、MIMEメディアタイプや
16269他のヘッダ情報に基づいていくつかのボディをスキップしたいかもしれません。
16270その場合は、ロジックをハンドラのクロージャに入れることができます。
16271それが、このモジュールが、オールインワンの手続きではなく、
16272ビルディングブロックを提供している理由です。
16273@c COMMON
16274
16275@subheading Message composer
16276
16277@defun mime-compose-message parts :optional port :key boundary
16278@defunx mime-compose-message-string parts :key boundary
16279@c MOD rfc.mime
16280Composes a MIME multipart message.  @code{Mime-compose-message}
16281emits the result to an output port @var{port}, whose default
16282is the current output port.  @code{Mime-compose-message-string}
16283makes the result into a string.   You can give a boundary string
16284via @var{boundary} argument; when omitted, a fresh boundary string
16285is automatically generated by @code{mime-make-boundary} below.
16286
16287@code{Mime-compose-message} returns the boundary string.
16288@code{Mime-compose-message-string} returns two values, the result
16289string and the boundary string.
16290
16291The content of the message is provided by the @var{parts} argument,
16292which can be a list of instances of @code{<mime-part>} (see above)
16293or lists that describe parts.  The list form is supported for
16294the caller's convenience, and internally it is converted to
16295a list of @code{<mime-part>}s.
16296
16297The syntax of each part element in @var{parts} are defined as follow.
16298
16299@example
16300<part>           : <mime-part> | <mime-part-desc>
16301
16302<mime-part>      : @r{an instance of the class} <mime-part>
16303
16304<mime-part-desc> : (<content-type> (<header> ...) <body>)
16305<content-type>   : (<type> <subtype> <header-param> ...)
16306<header-param>   : (<key> . <value>) ...
16307<header>         : (<header-name> <encoded-header-value>)
16308                 | (<header-name> (<header-value> <header-param> ...))
16309<body>           : @r{a string}
16310                 | (file <filename>)
16311                 | (subparts <part> ...)
16312@end example
16313
16314Note: In the first form of @code{<header>},
16315@code{<encoded-header-value>} must already be encoded using RFC2047
16316or RFC2231 if the original value contains non-ascii characters.
16317In the second form, we plan to do RFC2231 encoding on behalf of
16318the caller; but the current version does not implement it.  The
16319caller should not pass encoded words in this form, since it may
16320result double-encoding when we implement the auto encoding feature;
16321for the time being, the second form restricts ASCII-only values.
16322
16323If @code{<body>} is a string, it is used as the part's content.
16324If @code{<body>} is @code{(file @var{filename})}, the content is
16325read from the named file.   If @code{<body>} is
16326@code{(subparts @var{part} @dots{})}, the part becomes nested
16327MIME part.
16328
16329It is the caller's responsibility to give the proper content.
16330For example, if @code{<body>} is in the third form, the
16331part must have @code{multipart} content type.
16332
16333The caller needs to provide proper @code{content-transfer-encoding}
16334header, depending on the application.  If none is given, the content
16335is inserted into the message as is, which may be appropriate for
16336some applications, but if you want to use the result in email
16337message you certainly want to encode binary part with base64,
16338for example.
16339@end defun
16340
16341@defun mime-make-boundary
16342@c MOD rfc.mime
16343@c EN
16344Returns a unique string that can be used as a boundary of a MIME multipart
16345message.
16346@c JP
16347MIMEマルチパートメッセージのboundaryとして使えるユニークな文字列を返します。
16348@c COMMON
16349@end defun
16350
16351
16352@c ----------------------------------------------------------------------
16353@node Quoted-printable encoding/decoding, SHA message digest, MIME message handling, Library modules - Utilities
16354@section @code{rfc.quoted-printable} - Quoted-printable encoding/decoding
16355@c NODE Quoted-printableエンコーディング, @code{rfc.quoted-printable} - Quoted-printableエンコーディング
16356
16357@deftp {Module} rfc.quoted-printable
16358@mdindex rfc.quoted-printable
16359@c EN
16360This module defines a few functions to encode/decode Quoted-printable format,
16361defined in RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}), section 6.7.
16362@c JP
16363このモジュールでは、RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}) の
16364セクション6.7で定義されている、Quoted-printableフォーマットにエンコード/から
16365デコードするためのいくつかの関数を定義しています。
16366@c COMMON
16367@end deftp
16368
16369@defun quoted-printable-encode :key line-width binary
16370@c MOD rfc.quoted-printable
16371@c EN
16372Reads byte stream from the current input port, encodes it in Quoted-printable
16373format and writes the result character stream to the current output port.
16374The conversion ends when it reads EOF from the current input port.
16375@c JP
16376現在の入力ポートからバイトストリームを読み込み、それをQuoted-printable
16377フォーマットにエンコードし、現在の出力ポートへ結果の文字ストリームを
16378書き出します。この変換は、現在の入力ポートからEOFを読み出すと終了します。
16379@c COMMON
16380@c EN
16381The keyword argument @var{line-width} specifies the maximum
16382line width of the generated output in characters.  If the encoded
16383output creates a long line, the procedure inserts a ``soft line break''
16384so that the each line is equal to or shorter than this number.
16385Soft line breaks are removed when quoted-printable text is
16386decoded.
16387The default line width is 76.  (The minimum meaningful number of
16388line-width is 4).  You can suppress soft line breaks by
16389giving @code{#f} or @code{0} to @var{line-width}.
16390@c JP
16391キーワード引数@var{line-width}は、出力に現れる行の最大長を指定します。
16392エンコードされた行の長さがこの値を越えそうな場合は、「ソフトラインブレーク」が
16393適宜挿入され、各行の長さがこの値を越えないように調整されます。
16394ソフトラインブレークはquoted-printableフォーマットのデコード時に
16395取り除かれます。
16396@var{line-width}のデフォルト値は76です。(最小の意味のある値は4です。)
16397@var{line-width}に@code{#f}または@code{0}を渡せば、
16398ソフトラインブレークは挿入されません。
16399@c COMMON
16400@c EN
16401By default, @code{quoted-printable-encode} generates @code{CR-LF} sequence
16402for each line break in the input (``hard line break'').
16403When a true value is given to the keyword argument @var{binary},
16404however, octets @code{#x0a} and @code{#x0d} in the input are encoded
16405as @code{=0A} and @code{=0D}, respectively.  See RFC2045 section 6.7
16406for the details.
16407@c JP
16408デフォルトでは、@code{quoted-printable-encode}は入力中の改行に対して
16409@code{CR-LF}シーケンスを出力します(「ハードラインブレーク」)。
16410しかし、@var{binary}キーワード引数に真の値が与えられた場合、
16411入力中のオクテット@code{#x0a}および@code{#x0d}はそれぞれ
16412@code{=0A}、@code{=0D}のようにエンコードされます。
16413詳しくはRFC2045の6.7節を参照してください。
16414@c COMMON
16415@end defun
16416
16417@defun quoted-printable-encode-string string :key line-width binary
16418@c MOD rfc.quoted-printable
16419@c EN
16420Converts contents of @var{string} to Quoted-printable encoded format.
16421Input string can be either complete or incomplete string;
16422it is always interpreted as a byte sequence.
16423
16424The keyword arguments are the same as @code{quoted-printable-encode}.
16425@c JP
16426@var{string}の内容をQuoted-printableエンコードされたフォーマットに
16427変換します。入力の文字列は、完全文字列でも不完全文字列でも構いません。
16428常にバイトシーケンスとして処理されます。
16429
16430キーワード引数は@code{quoted-printable-encode}と同じです。
16431@c COMMON
16432@end defun
16433
16434@defun quoted-printable-decode
16435@c MOD rfc.quoted-printable
16436@c EN
16437Reads character stream from the current input port,
16438decodes it from Quoted-printable
16439format and writes the result byte stream to the current output port.
16440The conversion ends when it reads EOF.
16441If it encounters illegal character sequence (such as '=' followed
16442by non-hexadecimal characters), it copies them literally to the output.
16443@c JP
16444現在の入力ポートから文字ストリームを読み込み、それをQuoted-printable
16445フォーマットからデコードし、結果のバイトストリームを現在の出力ポートへ
16446書き出します。
16447この変換は、EOFを読み出すと終了します。
16448不正なシーケンス('='の後に16進文字が続かない、など)に出会うと、それらを
16449リテラルのまま出力へコピーします。
16450@c COMMON
16451@end defun
16452
16453@defun quoted-printable-decode-string string
16454@c MOD rfc.quoted-printable
16455@c EN
16456Decodes a Quoted-printable encoded string @var{string} and returns
16457the result as a string.
16458@c JP
16459Quoted-printableエンコードされた文字列@var{string}をデコードし、
16460その結果を文字列で返します。
16461@c COMMON
16462@end defun
16463
16464@c ----------------------------------------------------------------------
16465@node SHA message digest, Transport layer security, Quoted-printable encoding/decoding, Library modules - Utilities
16466@section @code{rfc.sha} - SHA message digest
16467@c NODE SHAメッセージダイジェスト, @code{rfc.sha} - SHAメッセージダイジェスト
16468
16469@deftp {Module} rfc.sha
16470@mdindex rfc.sha
16471@c EN
16472This module implements US Secure Hash Algorithm
16473defined in RFC 4634.  It provides SHA-1, SHA-224, SHA-256,
16474SHA-384 and SHA-512 (the latter four are sometimes referred
16475as SHA-2 collectively).
16476
16477The module extends util.digest
16478(@pxref{Message digester framework}).
16479@c JP
16480このモジュールは、RFC 4634で定義されている
16481US Secure Hash Algorithmを実装しています。
16482提供されるアルゴリズムはSHA-1, SHA-224, SHA-256, SHA-384および
16483SHA-512です (後の4つを総称してSHA-2と呼ぶこともあります)。
16484
16485このモジュールは、util.digest (@ref{Message digester framework}参照)
16486を拡張しています。
16487@c COMMON
16488@end deftp
16489
16490@deftp {Module} rfc.sha1
16491@mdindex rfc.sha1
16492@c EN
16493This is the old module that provided only SHA-1.  It is kept as
16494an alias of @code{rfc.sha} for the backward compatibility.  New code
16495should use @code{rfc.sha}.
16496@c JP
16497これはSHA-1だけを提供していた古いモジュールです。互換性のため、
16498この名前は@code{rfc.sha}の別名として残されています。
16499新たに書くコードは@code{rfc.sha}を使ってください。
16500@c COMMON
16501@end deftp
16502
16503
16504@deftp {Class} <sha1>
16505@deftpx {Class} <sha224>
16506@deftpx {Class} <sha256>
16507@deftpx {Class} <sha384>
16508@deftpx {Class} <sha512>
16509@clindex sha1
16510@clindex sha224
16511@clindex sha256
16512@clindex sha384
16513@clindex sha512
16514@c MOD rfc.sha
16515@c EN
16516An instance of these class keeps internal state of SHA digest algorithm.
16517
16518This class implements @code{util.digest} framework interface,
16519@code{digest-update!}, @code{digest-final!},
16520@code{digest}, and @code{digest-string}.
16521@xref{Message digester framework}, for detailed explanation
16522of these methods.
16523@c JP
16524これらのクラスのインスタンスは、SHAダイジェストアルゴリズムの内部状態を
16525保持しています。
16526
16527このクラスは、@code{util.digest}フレームワークのインターフェース、
16528@code{digest-update!}、@code{digest-final!}、@code{digest}、
16529@code{digest-string}を実装しています。
16530これらのメソッドの詳細な説明は、@ref{Message digester framework}を
16531参照して下さい。
16532@c COMMON
16533@end deftp
16534
16535@c EN
16536Besides the digester framework, this module provides to
16537short-cut procedures.
16538@c JP
16539ダイジェスタフレームワークに加えて、このモジュールはショートカット
16540手続きを提供します。
16541@c COMMON
16542
16543@defun sha1-digest
16544@defunx sha224-digest
16545@defunx sha256-digest
16546@defunx sha384-digest
16547@defunx sha512-digest
16548@c MOD rfc.sha
16549@c EN
16550Reads data from the current input port until EOF, and returns
16551its digest in an incomplete string.
16552@c JP
16553現在の入力ポートからデータをEOFまで読み込み、そのダイジェストを
16554不完全文字列で返します。
16555@c COMMON
16556@end defun
16557
16558@defun sha1-digest-string string
16559@defunx sha224-digest-string string
16560@defunx sha256-digest-string string
16561@defunx sha384-digest-string string
16562@defunx sha512-digest-string string
16563@c MOD rfc.sha
16564@c EN
16565Digest the data in @var{string}, and returns the result
16566in an incomplete string.
16567@c JP
16568@var{string}のデータをダイジェストし、その結果を不完全文字列で
16569返します。
16570@c COMMON
16571@end defun
16572
16573@c ----------------------------------------------------------------------
16574@node Transport layer security, URI parsing and construction, SHA message digest, Library modules - Utilities
16575@section @code{rfc.tls} - Transport layer security
16576@c NODE トランスポート・レイヤ・セキュリティ, @code{rfc.tls} - トランスポート・レイヤ・セキュリティ
16577
16578@deftp {Module} rfc.tls
16579@mdindex rfc.tls
16580@c EN
16581This module handles secure connection over TCP socket.
16582This module is used by @code{rfc.http} to realize https connection
16583(@pxref{HTTP}).
16584@c JP
16585このモジュールはTCPソケット上のセキュアな接続を処理します。
16586@code{rfc.http}で、https接続を実現するのに使われています
16587(@ref{HTTP}参照)。
16588@c COMMON
16589@end deftp
16590
16591@subheading CA certificates
16592
16593@c EN
16594You need CA certificates to verify server certificates properly.
16595Gauche doesn't have its own CA certificates, and relies on the
16596system's certificate store by default.  On Unix-based systems,
16597we search several known locations: On popular Linux distributions
16598we recommend you to install @code{ca-certificates} package (or similar one).
16599On OSX, we recommend to install openssl via Homebrew.  On Windows,
16600we use system's certificate store via Wincrypt API.
16601@c JP
16602サーバの認証を適切に行うためには、CA証明書が必要です。
16603Gaucheは自前でCA証明書を持っておらず、デフォルトでシステムのCA証明書バンドルを利用します。
16604Unixベースのシステムでは、いくつかのよくあるパスを探索します。
16605例えばLinuxディストリビューションなら@code{ca-certificates}やそれに類する
16606パッケージをインストールしておくと良いでしょう。
16607OSXではopensslをHomebrewでインストールしておくのをおすすめします。
16608WindowsではWincrypt API経由でシステムの証明書ストアを使います。
16609@c COMMON
16610
16611@c EN
16612With the default configuration, Gauche checks the availability of the system's
16613certificate store at initilization and use one if available.  You can explicitly
16614give the path of CA certificate bundle, or disable it and provide
16615individual certificate per connection.
16616@c JP
16617デフォルトのコンフィグレーションでは、Gaucheは初期化時にシステムのCA証明書バンドルを探し、
16618見つかればそれを使うようになっています。かわりとなるCA証明書バンドルのパスを指定したり、
16619接続毎に独自の証明書を与えることもできます。
16620@c COMMON
16621
16622@c EN
16623If, for some reasons, you cannot install system-wide CA certificate bundle,
16624you can also download Curl's CA certificate bundle
16625@url{https://curl.haxx.se/ca/cacert.pem}, and install it in
16626Gauche installation directory.  We have a convenience script.
16627After installing Gauche, run the following command:
16628@c JP
16629もし、何らかの理由で、システム全体で使えるCA証明書バンドルがインストールできない場合、
16630独自にCurlのCA証明書バンドルを@url{https://curl.haxx.se/ca/cacert.pem}から
16631ダウンロードしてGaucheのインストールディレクトリに置いておくことができます。
16632便利なスクリプトが用意してあります。
16633Gaucheをインストールした後、次のコマンドを実行してください。
16634@c COMMON
16635
16636@example
16637gosh rfc/tls/get-cacert.scm
16638@end example
16639
16640@c EN
16641You need curl installed on your system.  If you've installed
16642Gauche with root priviledge, you'll be asked sudo password to install
16643the CA bundle file.
16644
16645If you decided to do this, make sure you run the above command occasionally
16646to get updated CA certificate bundles, for certificates may expire or
16647be revoked.
16648@c JP
16649curlがシステムにインストールされている必要があります。また、Gaucheをインストールする時に
16650root権限で行ったのであれば、このコマンドがCA証明書バンドルをインストールする時に
16651sudoのパスワードを尋ねるでしょう。
16652
16653もしこの方法を取ることに決めたなら、時々このコマンドを実行してCA証明書バンドルを
16654最新版に更新するのを忘れないようにしてください。
16655CA証明書は期限が切れたり無効化されることがあります。
16656@c COMMON
16657
16658@deffn {Parameter} tls-ca-bundle-path :optional path
16659@c MOD rfc.tls
16660@c EN
16661Holds CA certificate bundle to be used.  The value
16662can be either a string path to a CA bundle file, a symbol @code{system},
16663or @code{#f}.
16664@c JP
16665CA証明書バンドルのパスを保持しています。値は、CA証明書バンドルファイルの
16666パス名、シンボル@code{system}、あるいは@code{#f}のいずれかです。
16667@c COMMON
16668
16669@c EN
16670If it is @code{system}, Gauche uses system's default bundle.
16671An error is signaled on connection
16672if Gauche can't find one.
16673@c JP
16674この値が@code{system}の場合、Gaucheはシステムのデフォルトの証明書バンドルを
16675使おうとします。もしそれが見つからなければ接続時にエラーが報告されます。
16676@c COMMON
16677
16678@c EN
16679If it is @code{#f}, CA certificate won't be loaded automatically,
16680and you have to manually load one using @code{tls-load-object}.
16681(Note: This option is only valid with @code{<ax-tls>}.  If you're using
16682@code{<mbed-tls>}, you need valid CA certificate bundle.)
16683@c JP
16684この値が@code{#f}の場合、CA証明書は自動的にロードされないので、
16685@code{tls-load-object}を使って自分で適切な証明書をロードしてやる必要があります。
16686(このオプションは@code{<ax-tls>}のみ有効です。
16687@code{<mbed-tls>}を使う場合は、必ず有効なCA証明書バンドルが必要です。)
16688@c COMMON
16689
16690@c EN
16691With the default configuration, Gauche scans the system CA bundle
16692when @code{rfc.tls} module is initialized, and if it finds one,
16693@code{tls-ca-bundle-path} is set to @code{system}; otherwise,
16694@code{tls-ca-bundle-path} is set to @code{#f}.  So if you're using
16695with default configuration and you see its value is @code{system},
16696you can count on the system CA certificate bundle.
16697@c JP
16698デフォルトのコンフィグレーションでは、Gaucheは@code{rfc.tls}モジュール初期化時に
16699システムのCA証明書バンドルが使えるかどうか調べて、使えるなら@code{tls-ca-bundle-path}の
16700初期値を@code{system}に、使えないなら@code{#f}にセットします。
16701したがって、デフォルトのコンフィグレーションで使っている限り、
16702この値が@code{system}であればシステムのCA証明書を使えると考えて良いでしょう。
16703@c COMMON
16704
16705@c EN
16706This default behavior may be altered if Gauche is configured
16707with @code{--with-ca-bundle} option.  You can execute
16708@code{gauche-config --reconfigure} command to see if
16709special @code{--with-ca-bundle} option is given.
16710@c JP
16711このデフォルトの振る舞いはconfigure時に@code{--with-ca-bundle}オプションで
16712変えられます。使っているGaucheのコンフィグレーションが変えられているかどうかは、
16713@code{gauche-config --reconfigure}コマンドを実行して@code{--with-ca-bundle}
16714オプションがあるかどうかを見ればわかります。
16715@c COMMON
16716@end deffn
16717
16718
16719@subheading Supported TLS subsystems
16720
16721@c EN
16722Gauche supports two TLS subsystems - one based on AxTLS
16723(@url{http://axtls.sourceforge.net/}), and the other based on
16724MbedTLS (@url{https://tls.mbed.org/}).  Whether they're included
16725depends on the configuration options.  By default, AxTLS support
16726is compiled in, and MbedTLS support is included if the build
16727platform has MbedTLS library installed.
16728@c JP
16729Gaucheは二つのTLSサブシステムをサポートしています。
16730ひとつはAxTLS(@url{http://axtls.sourceforge.net/})、
16731もうひとつはMbedTLS(@url{https://tls.mbed.org/})です。
16732configureのオプションによって組み込まれるものが変わりますが、
16733デフォルトではAxTLSは常に組み込まれ、
16734MbedTLSはビルド時にシステムにインストールされていれば組み込まれます。
16735@c COMMON
16736
16737@c EN
16738AxTLS library has advanage of being included in Gauche, so that
16739it won't depend on external library, however, its supported ciphers
16740are limited, and it can't connect to some https sites.  MbedTLS has
16741wider cipher support, but it requires MbedTLS dynamic libraries
16742(e.g. @file{libmbedtls.so}) at runtime.
16743@c JP
16744AxTLSライブラリはGaucheの一部としてコンパイルされるので、
16745使うのに外部ライブラリに依存しないという利点がありますが、
16746サポートしている暗号スイートが限られていて、時々接続できないhttpsサイトがあります。
16747一方、MbedTLSは幅広い暗号スイートをサポートしていますが、実行時に
16748MbedTLSの動的ライブラリ(@file{libmbedtls.so}など)を必要とします。
16749@c COMMON
16750
16751@c EN
16752Gauche chooses available TLS subsystem at runtime, so the user usually
16753does not need to worry about the difference.  If you're building Gauche
16754by yourself, we recommend to use the default configuration, on a system
16755that has MbedTLS installed.   That will give you the most flexible choice.
16756@c JP
16757Gaucheは実行時に使える範囲で適切なTLSサブシステムを選択するので、
16758ユーザが違いを意識する必要はほとんどありません。自分でGaucheをビルドする場合は、
16759MbedTLSがインストールされた環境で、デフォルトのコンフィグレーションでビルドすることを
16760推奨します。それが最も柔軟な選択となるでしょう。
16761@c COMMON
16762
16763@c EN
16764Whether the running Gauche has any of TLS support can be checked with
16765a feature identifier @code{gauche.net.tls}.  Availability of each
16766individual subsystems can be checked with feature identifiers
16767@code{gauche.net.tls.axtls} and @code{gauche.net.tls.mbedtls}, respectively.
16768@xref{Feature conditional}, for more about feature identifiers.
16769@c JP
16770Gaucheに何らかのTLSサポートが組み込まれているかどうかは機能識別子
16771@code{gauche.net.tls}で、それぞれのサブシステムが使えるかどうかは
16772機能識別子@code{gauche.net.tls.axtls}と@code{gauche.net.tls.mbedtls}で
16773検査できます。機能識別子については@ref{Feature conditional}を参照してください。
16774@c COMMON
16775
16776@deftp {Class} <tls>
16777@clindex tls
16778@c MOD rfc.tls
16779An abstract base class of TLS implementations.
16780@end deftp
16781
16782@deftp {Class} <ax-tls>
16783@clindex ax-tls
16784@c MOD rfc.tls
16785A class that implements axTLS subsystem interface.
16786@end deftp
16787
16788@deftp {Class} <mbed-tls>
16789@clindex mbed-tls
16790@c MOD rfc.tls
16791A class that implements mbedTLS subsystem interface.
16792@end deftp
16793
16794@deffn {Parameter} default-tls-class :optional class
16795@c MOD rfc.tls
16796Set/get the default TLS subsystem to be used.  Without arguments, it
16797return a class (either @code{<ax-tls>} or @code{<mbed-tls>} to be used.
16798With one argument, which must be either @code{<ax-tls>} or @code{<mbed-tls>},
16799changes the default and returns the previous value.
16800@end deffn
16801
16802@subheading TLS interface
16803
16804@defun make-tls initargs @dots{}
16805@c MOD rfc.tls
16806Creates and returns a new TLS instance of the class @code{default-tls-class}.
16807The returned TLS instance can be used for the tls procedures below.
16808
16809The arguments must be a keyword-value list, and passed to the constructor
16810of the TLS class.
16811
16812@table @code
16813@item :server-name
16814Server name to be used for TLS Server Name Indication extension.
16815@item :num-sessions
16816[AxTLS only]
16817The number of sessions ot be used for session caching.
168180 indicates no sessino caching.
16819@item :options
16820[AxTLS only]
16821Bitflags of options.  Logical OR of the following numeric constants.
16822@end table
16823
16824@table @code
16825@item SSL_SERVER_VERIFY_LATER
16826(client only) Let handshake success even the server authentication fails.
16827@item SSL_CLIENT_AUTHENTICATION
16828(server only) Request client sertificate to be authenticated.
16829@end table
16830@end defun
16831
16832@defun tls-connect tls socket
16833@c MOD rfc.tls
16834Establishes TLS connection as a client.  The @var{tls} argument must
16835be an unconnected TLS object, and the @var{socket} argument must
16836be a @emph{connected} socket.  On success, it returns @var{tls},
16837which is in connected state.  It can be used to read/write data
16838from/to the connected peer.
16839
16840The @var{socket} is owned by @var{tls} object and should not be directly
16841accessed after calling this procedure.
16842@end defun
16843
16844@defun tls-accept tls socket
16845@c MOD rfc.tls
16846Establishes TLS connection as a server.  The @var{tls} argument must
16847be an unconnected TLS object, and the @var{socket} argument must
16848be a @emph{listening} socket.  On success, it returns @var{tls},
16849which is in connected state.  It can be used to read/write data
16850from/to the connected peer.
16851@end defun
16852
16853@defun tls-close tls
16854@c MOD rfc.tls
16855Shuts down the underling connection.  The peer will notified
16856the connection is closed.
16857Once @var{tls} is closed, it can no longer be used, but the reosurces
16858won't be collected until @var{tls} is GC-ed or @code{tls-destroy} is
16859called.  We recommend the user call @code{tls-destroy} explicitly.
16860@end defun
16861
16862@defun tls-destroy tls
16863@c MOD rfc.tls
16864Releases resources associated to @var{tls}.
16865@end defun
16866
16867@defun tls-input-port tls
16868@defunx tls-output-port tls
16869@c MOD rfc.tls
16870If @var{tls} is connected, it returns input and output port to communicate
16871with the peer, respectively.
16872
16873If @var{tls} is not connected, @code{#f} is returned.
16874@end defun
16875
16876@defun tls-load-object tls type filename :optional password
16877@c MOD rfc.tls
16878This procedure is only meaningful for @code{<axl-tls>}.  For @code{<mbed-tls>},
16879this procedure does nothing.
16880
16881Load private keys or certificates stored in a file specified by
16882@var{filenames}.  The type of object is specified by @var{type}
16883argument with one of the following numberic constants.  If the file
16884requires a password, it should be given to @var{password}.
16885
16886@table @code
16887@item SSL_OBJ_X509_CERT
16888@item SSL_OBJ_X509_CACERT
16889@item SSL_OBJ_RSA_KEY
16890@item SSL_OBJ_PKCS8
16891@item SSL_OBJ_PKC12
16892@end table
16893@end defun
16894
16895@defvr {Constant} SSL_OBJ_X509_CERT
16896@defvrx {Constant} SSL_OBJ_X509_CACERT
16897@defvrx {Constant} SSL_OBJ_RSA_KEY
16898@defvrx {Constant} SSL_OBJ_PKCS8
16899@defvrx {Constant} SSL_OBJ_PKCS12
16900@c MOD rfc.tls
16901@end defvr
16902
16903@c ----------------------------------------------------------------------
16904@node URI parsing and construction, UUID, Transport layer security, Library modules - Utilities
16905@section @code{rfc.uri} - URI parsing and construction
16906@c NODE URIの解析と作成, @code{rfc.uri} - URIの解析と作成
16907
16908@deftp {Module} rfc.uri
16909@mdindex rfc.uri
16910@c EN
16911Provides a set of procedures to parse and construct Uniform Resource Identifiers
16912defined in RFC 2396 (@uref{https://www.ietf.org/rfc/rfc2396.txt}),
16913as well as Data URI scheme defined in RFC2397.
16914@c JP
16915RFC 2396 (@uref{https://www.ietf.org/rfc/rfc2396.txt})で定義されている
16916Uniform Resource Identifiers、
16917またRFC 2397で定義されているData URI Schemeをパーズおよび構築する
16918手続き群を提供します。
16919@c COMMON
16920@end deftp
16921
16922First, lets review the structure of URI briefly.
16923The following graph shows how the URI is constructed:
16924
16925@example
16926URI-+-scheme
16927    |
16928    +-specific--+--authority-+--userinfo
16929                |            +--host
16930                |            +--port
16931                +--path
16932                +--query
16933                +--fragment
16934@end example
16935
16936Not all URIs have this full hierarchy.  For example,
16937@code{mailto:admin@@example.com} has only @emph{scheme} (@code{mailto})
16938and @emph{specific} (@code{admin@@example.com}) parts.
16939
16940Most popular URI schemes, however, organize resources
16941in a tree, so they adopt @emph{authority} (which usually identifies
16942the server) and the hierarchical @emph{path}.  In the URI
16943@code{http://example.com:8080/search?q=key#results}, the authority
16944part is @code{example.com:8080}, the path is @code{/search},
16945the query is @code{key} and the fragment is @code{results}.
16946The userinfo can be provided before hostname, such as @code{anonymous}
16947in @code{ftp://anonymous@@example.com/pub/}.
16948
16949We have procedures that decompose a URI into those parts,
16950and that compose a URI from those parts.
16951
16952@c EN
16953@subheading Parsing URI
16954@c JP
16955@subheading URIのパーズ
16956@c COMMON
16957
16958@defun uri-ref uri parts
16959@c MOD rfc.uri
16960Extract specific part(s) from the given URI.  You can fully
16961decompose URI by the procedures described below, but in actual
16962applications, you often need only some of the parts.  This procedure
16963comes handy for it.
16964
16965The @var{parts} argument may be a symbol, or a list of symbols,
16966to name the desired parts.  The recognized symbos are as follows.
16967
16968@table @code
16969@item scheme
16970The scheme part, as string.
16971@item authority
16972The authority part, as string.
16973If URI doesn't have the part, @code{#f}.
16974@item userinfo
16975The userinfo part, as string.  If URI doesn't have the part, @code{#f}.
16976@item host
16977The host part, as string.  If URI doesn't have the part, @code{#f}.
16978@item port
16979The port part, as integer.  If URI doesn't have the part, @code{#f}.
16980@item path
16981The path part, as string.  If URI isn't hierarchical, this returns
16982the specific part.
16983@item query
16984The query part, as string. If URI doesn't have the part, @code{#f}.
16985@item fragment
16986The fragment part, as string.  If URI doesn't have the part, @code{#f}.
16987@item scheme+authority
16988The scheme and authority part.
16989@item host+port
16990The host and port part.
16991@item userinfo+host+port
16992The userinfo, host and port part.
16993@item path+query
16994The path and query part.
16995@item path+query+fragment
16996The path, query and fragment part.
16997@end table
16998
16999@example
17000(define uri "http://foo:bar@@example.com:8080/search?q=word#results")
17001
17002(uri-ref uri 'scheme)             @result{} "http"
17003(uri-ref uri 'authority)          @result{} "//foo:bar@@example.com:8080/"
17004(uri-ref uri 'userinfo)           @result{} "foo:bar"
17005(uri-ref uri 'host)               @result{} "example.com"
17006(uri-ref uri 'port)               @result{} 8080
17007(uri-ref uri 'path)               @result{} "/search"
17008(uri-ref uri 'query)              @result{} "q=word"
17009(uri-ref uri 'fragment)           @result{} "results"
17010(uri-ref uri 'scheme+authority)   @result{} "http://foo:bar@@example.com:8080/"
17011(uri-ref uri 'host+port)          @result{} "example.com:8080"
17012(uri-ref uri 'userinfo+host+port) @result{} "foo:bar@@example.com:8080"
17013(uri-ref uri 'path+query)         @result{} "/search?q=word"
17014(uri-ref uri 'path+query+fragment)@result{} "/search?q=word#results"
17015@end example
17016
17017You can extract multiple parts at once by specifying a list of parts.
17018A list of parts is returned.
17019
17020@example
17021(uri-ref uri '(host+port path+query))
17022  @result{} ("example.com:8080" "/search?q=word")
17023@end example
17024@end defun
17025
17026
17027@defun uri-parse uri
17028@defunx uri-scheme&specific uri
17029@defunx uri-decompose-hierarchical specific
17030@defunx uri-decompose-authority authority
17031@c MOD rfc.uri
17032@c EN
17033General parser of URI.  These functions does not decode
17034URI encoding, since the parts to be decoded differ among
17035the uri schemes.   After parsing uri, use @code{uri-decode} below
17036to decode them.
17037@c JP
17038URIの一般的なパーザです。これらの関数はURIエンコーディングを
17039デコードしません。URIスキームによってどの部分をデコードすべきかが
17040異なるからです。パージングを行った後に、後述の@code{uri-decode}等を
17041使ってデコードを行ってください。
17042@c COMMON
17043
17044@c EN
17045@code{uri-parse} is the most handy procedure.  It breaks the uri
17046into the following parts and returns them as multiple values.
17047If the uri doesn't have the corresponding
17048parts, @code{#f} are returned for the parts.
17049
17050@itemize @bullet
17051@item
17052URI scheme as a string
17053(e.g. @code{"mailto"} in @code{"mailto:foo@@example.com"}).
17054@item
17055User-info in the authority part (e.g. @code{"anonymous"}
17056in @code{ftp://anonymous@@ftp.example.com/pub/foo}).
17057@item
17058Hostname in the authority part (e.g. @code{"ftp.example.com"}
17059in @code{ftp://anonymous@@ftp.example.com/pub/foo}).
17060@item
17061Port number in the authority part, as an integer (e.g. @code{8080}
17062in @code{http://www.example.com:8080/}).
17063@item
17064Path part (e.g. @code{"/index.html"} in
17065@code{http://www.example.com/index.html}).
17066@item
17067Query part (e.g. @code{"key=xyz&lang=en"} in
17068@code{http://www.example.com/search?key=xyz&lang=en}).
17069@item
17070Fragment part (e.g. @code{"section4"} in
17071@code{http://www.example.com/document.html#section4}).
17072@end itemize
17073@c JP
17074@code{uri-parse}は最も手軽な手続きで、uriを以下に示す部分に
17075分割し、多値で返します。
17076もし該当する部分がuriに無かった場合は、その部分には@code{#f}が返ります。
17077@itemize @bullet
17078@item
17079URIスキームを文字列で。
17080(例: @code{"mailto:foo@@example.com"}の@code{"mailto"})。
17081@item
17082authorityパートのuser-infoを文字列で。
17083(例: @code{ftp://anonymous@@ftp.example.com/pub/foo}の@code{"anonymous"})。
17084@item
17085authorityパートのhostnameを文字列で。
17086(例: @code{ftp://anonymous@@ftp.example.com/pub/foo}の
17087@code{"ftp.example.com"})。
17088@item
17089authorityパートのport番号を整数で。
17090(例: @code{http://www.example.com:8080/}の@code{8080})。
17091@item
17092pathパート。
17093(例: @code{http://www.example.com/index.html}の@code{"/index.html"})。
17094@item
17095queryパート。
17096(例: @code{http://www.example.com/search?key=xyz&lang=en}の
17097@code{"key=xyz&lang=en"})。
17098@item
17099fragmentパート。
17100(例: @code{http://www.example.com/document.html#section4}の
17101@code{"section4"})。
17102@end itemize
17103@c COMMON
17104
17105@c EN
17106The following procedures are finer grained and break up
17107uris with different stages.
17108@c JP
17109以下の手続きはより詳細に、段階をふんでuriを分割してゆくものです。
17110@c COMMON
17111
17112@c EN
17113@code{uri-scheme&specific} takes a URI @var{uri}, and
17114returns two values, its scheme part and its scheme-specific part.
17115If @var{uri} doesn't have a scheme part, @code{#f} is returned for it.
17116@c JP
17117@code{uri-scheme&specific} は URI @var{uri} を引数に取り、
17118スキーム部分と、そのスキーム特有の部分を表す2つの値を返します。
17119@var{uri} がスキーム部分を持たない場合、@code{#f} を返します。
17120@c COMMON
17121@example
17122(uri-scheme&specific "mailto:sclaus@@north.pole")
17123  @result{} "mailto" @r{and} "sclaus@@north.pole"
17124(uri-scheme&specific "/icons/new.gif")
17125  @result{} #f @r{and} "/icons/new.gif"
17126@end example
17127
17128@c EN
17129If the URI scheme uses hierarchical notation, i.e.
17130``@code{//@var{authority}/@var{path}?@var{query}#@var{fragment}}'',
17131you can pass
17132the scheme-specific part to @code{uri-decompose-hierarchical}
17133and it returns four values, @var{authority}, @var{path}, @var{query}
17134and @var{fragment}.
17135@c JP
17136URI が階層的な記法を用いている場合、すなわち、
17137``@code{//@var{authority}/@var{path}?@var{query}#@var{fragment}}''
17138のような場合、スキーム特有の部分を @code{uri-decompose-hierarchical}
17139に渡すと、@var{authority}、@var{path}、@var{query}、@var{fragment}
17140の4つの値が返ります。
17141@c COMMON
17142@example
17143(uri-decompose-hierarchical "//www.foo.com/about/company.html")
17144  @result{} "www.foo.com"@r{,} "/about/company.html"@r{,} #f @r{and} #f
17145(uri-decompose-hierarchical "//zzz.org/search?key=%3fhelp")
17146  @result{} "zzz.org"@r{,} "/search"@r{,} "key=%3fhelp" @r{and} #f
17147(uri-decompose-hierarchical "//jjj.jp/index.html#whatsnew")
17148  @result{} "jjj.jp"@r{,} "/index.html"@r{,} #f @r{and} "whatsnew"
17149(uri-decompose-hierarchical "my@@address")
17150  @result{} #f@r{,} #f@r{,} #f @r{and} #f
17151@end example
17152
17153@c EN
17154Furthermore, you can parse @var{authority} part of the
17155hierarchical URI by @code{uri-decompose-authority}.
17156It returns @var{userinfo}, @var{host} and @var{port}.
17157@c JP
17158さらに、階層的 URI の @var{authority} の部分を
17159@code{uri-decompose-authority} に渡すと、@var{userinfo}、
17160@var{host}、@var{port} が返ります。
17161@c COMMON
17162@example
17163(uri-decompose-authority "yyy.jp:8080")
17164  @result{} #f@r{,} "yyy.jp" @r{and} "8080"
17165(uri-decompose-authority "[::1]:8080")  ;@r{(IPv6 host address)}
17166  @result{} #f@r{,} "::1" @r{and} "8080"
17167(uri-decompose-authority "mylogin@@yyy.jp")
17168  @result{} "mylogin"@r{,} "yyy.jp" @r{and} #f
17169@end example
17170@end defun
17171
17172
17173@defun uri-decompose-data uri
17174@c MOD rfc.uri
17175@c EN
17176Parse a Data URI string @var{uri}.  You can either pass the entire
17177uri including @code{data:} scheme part, or just the specific part.
17178If the passed uri is invalid as a data uri, an error is signalled.
17179
17180Returns two values: parsed content type and the decoded data.
17181The data is a string if the content type is @code{text/*}, and
17182a u8vector otherwise.
17183
17184The content-type is parsed by @code{mime-parse-content-type}
17185(@pxref{MIME message handling}).  The result format is a list as follows:
17186@c JP
17187Data URI文字列@var{uri}をパーズします。@code{data:}スキームは有っても無くても
17188構いません。渡されたuriがdata uriとして無効な文字列であればエラーが投げられます。
17189
17190二つの値、パーズされたContent-Typeおよびデコードされたデータを返します。
17191Content-Typeが@code{text/*}であればデコードされたデータは文字列で、
17192そうでなければu8vectorで返されます。
17193
17194Content-Typeは@code{mime-parse-content-type}でパーズされます
17195(@ref{MIME message handling}参照)。結果のデータ形式は次のようなリストです。
17196@c COMMON
17197
17198@example
17199@code{(@i{type} @i{subtype} (@i{attribute} . @i{value}) @dots{})}.
17200@end example
17201
17202@c EN
17203Here are a couple of examples:
17204@c JP
17205いくつか例を示します。
17206@c COMMON
17207
17208@example
17209(uri-decompose-data
17210 "data:text/plain;charset=utf-8;base64,KGhlbGxvIHdvcmxkKQ==")
17211  @result{} ("text" "plain" ("charset" . "utf-8")) @r{and} "(hello world)"
17212
17213(uri-decompose-data
17214 "data:application/octet-stream;base64,AAECAw==")
17215  @result{} ("application" "octet-stream") @r{and} #u8(0 1 2 3)
17216@end example
17217
17218@end defun
17219
17220
17221@c EN
17222@subheading Constructing URI
17223@c JP
17224@subheading URIの構築
17225@c COMMON
17226
17227@defun uri-compose :key scheme userinfo host port authority path path* query fragment specific
17228@c MOD rfc.uri
17229@c EN
17230Compose a URI from given components.
17231There can be various combinations of components to create a valid
17232URI---the following diagram shows the possible 'paths' of
17233combinations:
17234@c JP
17235与えられたコンポーネントから URI を構成します。
17236妥当な URI を作成するためのコンポーネントの組み合わせはたくさんあります。
17237以下のダイアグラムは、考え得る組み合わせの方法を示しています。
17238@c COMMON
17239
17240@example
17241        /-----------------specific-------------------\
17242        |                                            |
17243 scheme-+------authority-----+-+-------path*---------+-
17244        |                    | |                     |
17245        \-userinfo-host-port-/ \-path-query-fragment-/
17246@end example
17247
17248@c EN
17249If @code{#f} is given to a keyword argument, it is
17250equivalent to the absence of that keyword argument.
17251It is particularly useful to pass the results of
17252parsed uri.
17253
17254If a component contains a character that is not appropriate
17255for that component, it must be properly escaped before
17256being passed to @code{url-compose}.
17257
17258Some examples:
17259@c JP
17260キーワード引数に @code{#f} が与えられた場合、それはキーワード引数が
17261指定されないことと等価です。これは URI をパーズした結果を渡す場合に
17262特に有用です。
17263
17264コンポーネントに適切でない文字が含まれている場合は、
17265@code{url-compose} に渡す前に正しくエスケープされなければなりません。
17266
17267いくつかの例を示します。
17268@c COMMON
17269@example
17270(uri-compose :scheme "http" :host "foo.com" :port 80
17271             :path "/index.html" :fragment "top")
17272  @result{} "http://foo.com:80/index.html#top"
17273
17274(uri-compose :scheme "http" :host "foo.net"
17275             :path* "/cgi-bin/query.cgi?keyword=foo")
17276  @result{} "http://foo.net/cgi-bin/query.cgi?keyword=foo"
17277
17278(uri-compose :scheme "mailto" :specific "a@@foo.org")
17279  @result{} "mailto:a@@foo.org"
17280
17281(receive (authority path query fragment)
17282   (uri-decompose-hierarchical "//foo.jp/index.html#whatsnew")
17283 (uri-compose :authority authority :path path
17284              :query query :fragment fragment))
17285  @result{} "//foo.jp/index.html#whatsnew"
17286@end example
17287@end defun
17288
17289
17290@defun uri-merge base-uri relative-uri relative-uri2 @dots{}
17291@c MOD rfc.uri
17292@c EN
17293Arguments are strings representing
17294full or part of URIs.  This procedure resolves @var{relative-uri}
17295in relative to @var{base-uri}, as defined in RFC3986 Section 5.2.
17296``Relative Resolution''.
17297
17298If more @var{relative-uri2}s are given, first @var{relative-uri}
17299is merged to @var{base-uri}, then the next argument is merged
17300to the resulting uri, and so on.
17301@c JP
17302引数は、完全な、あるいは部分的なURIを表す文字列です。
17303この手続きは、RFC3986 Section 5.2. ``Relative Resolution'' に
17304示されるアルゴリズムに従い、@var{relative-uri}を@var{base-uri}からの相対
17305として解決します。
17306
17307@var{relative-uri2} @dots{} が与えられた場合は、まず@var{relative-uri}
17308が@var{base-uri}を基準に解決され、その結果を新たな基準として次の
17309@var{relative-uri2}を解決し、以下同様に続けます。
17310@c COMMON
17311
17312@example
17313(uri-merge "http://example.com/foo/index.html" "a/b/c")
17314 @result{} "http://example.com/foo/a/b/c"
17315
17316(uri-merge "http://example.com/foo/search?q=abc" "../about#me")
17317 @result{} "http://example.com/about#me"
17318
17319(uri-merge "http://example.com/foo" "http://example.net/bar")
17320 @result{} "http://example.net/bar"
17321
17322(uri-merge "http://example.com/foo/" "q" "?xyz")
17323 @result{} "http://example.com/foo/q?xyz"
17324@end example
17325@end defun
17326
17327@defun uri-compose-data data :key content-type encoding
17328@c MOD rfc.uri
17329@c EN
17330Creates a Data URI of the given @var{data}, with specified content-type
17331and transfer encoding.  Returns a string.
17332
17333The @var{data} argument must be a string or a u8vector.
17334
17335The @var{content-type} argument can be @code{#f} (default),
17336a string that represents a content type (e.g. @code{"text/plain;charset=utf-8"}),
17337or a list form of parsed content type
17338(e.g. @code{("application" "octet-stream")}.  If it is @code{#f},
17339@code{text/plain} with the gauche's native character encoding is
17340used when @var{data} is a complete string, and @code{application/octet-stream}
17341is used otherwise.
17342
17343The @var{encoding} argument can be either @code{#f} (default),
17344or a symbol @code{uri} or @code{base64}.  This is for transfer encoding,
17345not character encoding.  If it is @code{#f}, URI encoding is used
17346for text data and base64 encoding is used for binary data.
17347@c JP
17348与えられた@var{data}からData URIを構築して文字列で返します。
17349
17350@var{data}引数は文字列かu8vectorでなければなりません。
17351
17352@var{content-type}キーワード引数は、@code{#f} (デフォルト)、
17353content typeを表現する文字列 (例: @code{"text/plain;charset=utf-8"})、
17354もしくはパーズされたcontent type (例: @code{("application" "octet-stream")})です。
17355@code{#f}である場合は、@var{data}が完全な文字列であれば
17356@code{text/plain}にGaucheのネイティブ文字エンコーディングに基づく@code{charset}を
17357つけたもの、@var{data}がそれ以外であれば@code{application/octet-stream}が
17358使われます。
17359
17360@var{encoding}キーワード引数は@code{#f} (デフォルト)、
17361もしくはシンボル@code{uri}または@code{base64}です。これは文字エンコーディングではなく
17362トランスファーエンコーディングであることに注意。
17363@code{#f}の場合は、テキストデータなら@code{uri}が、バイナリデータなら@code{base64}が
17364使われます。
17365@c COMMON
17366
17367@example
17368(uri-compose-data "(hello world)")
17369 @result{} "data:text/plain;charset=utf-8,%28hello%20world%29"
17370
17371(uri-compose-data "(hello world)" :encoding 'base64)
17372 @result{} "data:text/plain;charset=utf-8;base64,KGhlbGxvIHdvcmxkKQ=="
17373
17374(uri-compose-data '#u8(0 1 2 3))
17375 @result{} "data:application/octet-stream;base64,AAECAw=="
17376@end example
17377@end defun
17378
17379
17380@c EN
17381@subheading URI Encoding and decoding
17382@c JP
17383@subheading URIのエンコードとデコード
17384@c COMMON
17385
17386@defun uri-decode :key :cgi-decode
17387@defunx uri-decode-string string :key :cgi-decode :encoding
17388@c MOD rfc.uri
17389@c EN
17390Decodes ``URI encoding'', i.e. @code{%}-escapes.
17391@code{uri-decode} takes input from the current input port,
17392and writes decoded result to the current output port.
17393@code{uri-decode-string} takes input from @var{string} and
17394returns decoded string.
17395
17396If @var{cgi-decode} is true, also replaces @code{+} to a space character.
17397
17398To @code{uri-decode-string} you can provide the external character
17399encoding by the @var{encoding} keyword argument.  When it is given,
17400the decoded octet sequence is assumed to be in the specified encoding
17401and converted to the Gauche's internal character encoding.
17402@c JP
17403URI エンコーディング、すなわち、@code{%}でエスケープされた URI 文字列を
17404デコードします。@code{uri-decode} は現在の入力ポートから入力を受け取り、
17405デコードした結果を現在の出力ポートに書き出します。
17406@code{uri-decode-string} は @var{string} を入力とし、デコードした
17407文字列を返します。
17408
17409@var{cgi-decode} が真の場合は、@code{+} がスペース文字に置換されます。
17410
17411@code{uri-decode-string}には、外部の文字エンコーディングを指定する
17412@var{encoding}キーワード引数を与えることができます。この引数が与えれた
17413場合、デコードされたオクテットの列を指定された文字エンコーディングであると
17414してGaucheの内部文字エンコーディングへと変換したものが返されます。
17415@c COMMON
17416@end defun
17417
17418@defun uri-encode :key :noescape
17419@defunx uri-encode-string string :key :noescape :encoding
17420@c MOD rfc.uri
17421@c EN
17422Encodes unsafe characters by @code{%}-escape.  @code{uri-encode}
17423takes input from the current input port and writes the result to
17424the current output port.  @code{uri-encode-string} takes input
17425from @var{string} and returns the encoded string.
17426
17427By default, characters that are not specified ``unreserved'' in
17428RFC3986 are escaped.  You can pass different character
17429set to @var{noescape} argument to keep from being encoded.
17430For example, the older RFC2396 has several more ``unreserved''
17431characters, and passing @code{*rfc2396-unreserved-char-set*} (see below)
17432prevents those characters from being escaped.
17433
17434The multibyte characters are encoded as the octet stream of Gauche's
17435native multibyte representation by default.  However, you can pass
17436the @code{encoding} keyword argument to @code{uri-encode-string},
17437to convert @var{string} to the specified character encoding.
17438@c JP
17439安全でない文字を、@code{%}によるエスケープでエンコードします。
17440@code{uri-encode} は現在の入力ポートから入力を受け取り、
17441結果を現在の出力ポートに書き出します。
17442@code{uri-encode-string} は @var{string} を入力とし、エンコードした
17443文字列を返します。
17444
17445デフォルトでは、RFC3986 で"非予約文字"として規定されていない文字は
17446エスケープされます。@var{noescape} 引数に異なる文字集合を渡すことで、
17447それらがエンコードされるのを抑止することができます。
17448例えば古いRFC2396では"非予約文字"がいくつか多かったのですが、
17449@code{*rfc2396-unreserved-char-set*} (下記参照) を渡すことで
17450それらの文字がエスケープされるのを防ぐことができます。
17451
17452マルチバイト文字は、デフォルトではGauche のネイティブなマルチバイト表現の
17453オクテット・ストリームとしてエンコードされます。ただし
17454@code{uri-encode-string}には@var{encoding}キーワード引数を渡すことができて、
17455その場合はまず@var{string}が指定された文字エンコーディングへと変換されます。
17456@c COMMON
17457@end defun
17458
17459@defvr {Constant} *rfc2396-unreserved-char-set*
17460@defvrx {Constant} *rfc3986-unreserved-char-set*
17461@c MOD rfc.uri
17462@c EN
17463These constants are bound to character sets that represents
17464``unreserved'' characters defined in RFC2396 and RFC3986, respectively.
17465(See @ref{Character sets}, and @ref{R7RS character sets}, for
17466operations on character sets).
17467@c JP
17468これらの定数はそれぞれ、RFC2396とRFC3986で定義されている
17469「非予約文字」の文字集合に束縛されています。
17470(文字集合の操作については、@ref{Character sets}および@ref{R7RS character sets}
17471を参照して下さい。)
17472@c COMMON
17473@end defvr
17474
17475@c ----------------------------------------------------------------------
17476@node UUID, Zlib compression library, URI parsing and construction, Library modules - Utilities
17477@section @code{rfc.uuid} - UUID
17478@c NODE UUID, @code{rfc.uuid} - UUID
17479
17480@deftp {Module} rfc.uuid
17481@mdindex rfc.uuid
17482This module implements UUID defined in RFC4122.
17483
17484It provides generators of UUID version 1 and 4, and writer/parser
17485of the string represenation of UUIDs.
17486@end deftp
17487
17488@deftp {Class} <uuid>
17489@c MOD rfc.uuid
17490Class of UUID instances.
17491@end deftp
17492
17493@defun uuid-value uuid
17494@c MOD rfc.uuid
17495Returns the raw value of @var{uuid} as 16-element @code{u8vector}.
17496You shouldn't mutate the returned u8vector.
17497@end defun
17498
17499@defun uuid-version uuid
17500@c MOD rfc.uuid
17501Returns the version number of @var{uuid}.
17502@end defun
17503
17504@defvar uuid-comparator
17505@c MOD rfc.uuid
17506A comparator to compare and hash uuids.  @xref{Basic comparators}.
17507@end defvar
17508
17509@defun uuid-random-source-set! random-source
17510@c MOD rfc.uuid
17511We use PRNG to generate UUIDs.  By default, we internally creates
17512a random source and randomize it.  You can pass in your own
17513random source instead (@pxref{Sources of random bits}, for the details).
17514@end defun
17515
17516@defun uuid1 :optional node-id
17517@c MOD rfc.uuid
17518Generates a uuid with version 1 algorithm (timestamp and node id based).
17519The optional @var{node-id} argument must be 48bit exact integer
17520specifing the node ID (IEEE802 MAC address of the machine).
17521If it is omitted, we generate a process-global
17522random node ID (with the multicast bit set to 1, so that it won't
17523conflict with existing MAC address).
17524@end defun
17525
17526@defun uuid4
17527@c MOD rfc.uuid
17528Generates a uuid with version 4 algorithm (random numbers).
17529@end defun
17530
17531@defun nil-uuid
17532@c MOD rfc.uuid
17533Returns a nil-UUID (all bits zero).
17534@end defun
17535
17536@defun parse-uuid string
17537@c MOD rfc.uuid
17538Takes a string representation of UUID, parses it and returns
17539an uuid instance.  If the string isn't a valid UUID representation,
17540an error is thrown.
17541
17542Other than @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format,
17543it recognizes the one with @code{urn:uuid:} prefix,
17544the one enclosed by curly braces, and the one without hyphens.
17545@end defun
17546
17547@defun write-uuid uuid :optional port
17548@c MOD rfc.uuid
17549Writes out a string representation of @var{uuid},
17550in @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format, to the given
17551port.  If the port is omitted, current output port is used.
17552@end defun
17553
17554@defun uuid->string uuid
17555@c MOD rfc.uuid
17556Returns a string representation of @var{uuid},
17557in @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format.
17558@end defun
17559
17560@c ----------------------------------------------------------------------
17561@node Zlib compression library, SLIB, UUID, Library modules - Utilities
17562@section @code{rfc.zlib} - zlib compression library
17563@c NODE zlib圧縮ライブラリ, @code{rfc.zlib} - zlib圧縮ライブラリ
17564
17565@deftp {Module} rfc.zlib
17566@mdindex rfc.zlib
17567@c EN
17568This module provides bindings to zlib compression library.
17569Most features of zlib can be used through this module.
17570
17571Zlib supports reading and writing of
17572Zlib compressed data format (RFC1950),
17573DEFLATE compressed data format (RFC1951),
17574and GZIP file format (RFC1052).  It also provides
17575procedures to calculate CRC32 and Adler32 checksums.
17576
17577Compression and decompression are done through specialized ports.
17578There are number of parameters to fine-tune compression; refer
17579to zlib documentation for the details.
17580@c JP
17581このモジュールは、Zlib圧縮ライブラリに対するバインディングを提供します。
17582Zlibのほとんどの機能がこのモジュールを通して利用可能です。
17583
17584Zlibは、ZLIB圧縮データフォーマット(RFC1950)、DEFLATE圧縮データフォー
17585マット(RFC1951)、GZIPファイルフォーマット(RFC1952)の読み書きをサポー
17586トするライブラリです。また、CRC32とAdler32チェックサムの計算のための
17587関数も提供します。
17588
17589圧縮・展開機能はポートを通して提供されます。圧縮をチューンするパラ
17590メータの詳細については、Zlibのドキュメントも合わせて参照してください。
17591@c COMMON
17592@end deftp
17593
17594@subheading Condition types
17595
17596@c EN
17597The following condition types are defined to represent errors
17598during processing by zlib.
17599@c JP
17600Zlib処理中のエラーを示すために、以下のコンディションタイプが定義されています。
17601@c COMMON
17602
17603@deftp {Condition Type} <zlib-error>
17604@c MOD rfc.zlib
17605@c EN
17606Subclass of @code{<error>} and superclass of the following
17607condition types.  This class is an abstract class to catch any of the
17608zlib-specific errors.  Zlib-specific errors raised by
17609procedures in @code{rfc.zlib} are always an instance (or a compound
17610condition including) one of the following specific classes.
17611@c JP
17612@code{<error>}のサブクラスで、以下のコンディションタイプのスーパークラスです。
17613このクラスはzlib特有のエラーをまとめて捕捉するための抽象クラスとして設けられています。
17614@code{rfc.zlib}が投げるZlib固有のエラーは常に以下の特定のクラスのインスタンス、
17615もしくはそのインスタンスを含む複合コンディションです。
17616@c COMMON
17617@end deftp
17618
17619@deftp {Condition Type} <zlib-need-dict-error>
17620@deftpx {Condition Type} <zlib-stream-error>
17621@deftpx {Condition Type} <zlib-data-error>
17622@deftpx {Condition Type} <zlib-memory-error>
17623@deftpx {Condition Type} <zlib-version-error>
17624@c MOD rfc.zlib
17625@c EN
17626Subclasses of @code{<zlib-error>}.  Those condition type correspond
17627to zlib's
17628@code{Z_NEED_DICT_ERROR},
17629@code{Z_STREAM_ERROR},
17630@code{Z_DATA_ERROR},
17631@code{Z_MEMORY_ERROR}, and
17632@code{Z_VERSION_ERROR} errors.
17633@c JP
17634@code{<zlib-error>}のサブクラスです。それぞれ、Zlibの
17635@code{Z_NEED_DICT_ERROR}、
17636@code{Z_STREAM_ERROR}、
17637@code{Z_DATA_ERROR}、
17638@code{Z_MEMORY_ERROR}、
17639@code{Z_VERSION_ERROR}
17640に対応します。
17641@c COMMON
17642
17643@c EN
17644When an error occurs during reading data, a compound
17645condition of a subclass of @code{<zlib-error>} and
17646@code{<io-read-error>} is raised.
17647When an error occurs without I/O, a simple condition
17648of a subclass of @code{<zlib-error>} is raised.
17649Errors unrelated to zlib, such as invalid argument error,
17650would be a simple @code{<error>} condition.
17651@c JP
17652データの読み出し時にエラーが発生した場合、
17653@code{<zlib-error>}のサブクラスと
17654@code{<io-read-error>}の合成コンディションが投げられます。入力が伴わ
17655ない場合、例えば圧縮ストリームの初期化エラーのときには、合成され
17656ていない@code{<zlib-error>}のサブクラスが投げられます。ただの引数の型の
17657エラーのように、Zlibの関数が呼び出されない場合は、ただの@code{<error>}が
17658投げられるかもしれません。
17659@c COMMON
17660@end deftp
17661
17662@subheading Compression/decompression ports
17663
17664@deftp {Class} <deflating-port>
17665@deftpx {Class} <inflating-port>
17666@clindex deflating-port
17667@clindex inflating-port
17668@c MOD rfc.zlib
17669@c EN
17670Compression and decompression functions are provided
17671via ports.  A @emph{deflating port} is an output port
17672that compresses the output data.  An @emph{inflating port}
17673is an input that reads compressed data and decompress it.
17674
17675When an inflating port encounters a corrupted compressed
17676data, a compound condition of @code{<io-read-error>}
17677and @code{<zlib-data-error>} is raised during read operation.
17678@c JP
17679圧縮と展開の機能はポートを通じて提供されます。
17680@emph{deflating port}は出力されたデータを圧縮する出力ポートです。
17681@emph{inflating port}は圧縮されたデータソースからデータを展開しつつ
17682読み込む入力ポートです。
17683
17684inflating portが読み出す圧縮データが壊れていた場合、読み出し時に
17685@code{<io-read-error>}と@code{<zlib-data-error>}の
17686合成コンディションが投げられます。
17687@c COMMON
17688@end deftp
17689
17690
17691@defun open-deflating-port drain :key compression-level buffer-size window-bits memory-level strategy dictionary owner?
17692@c MOD rfc.zlib
17693@c EN
17694Creates and returns an instance of @code{<deflating-port>},
17695an output port that compresses the output data and sends
17696the compressed data to another output port @var{drain}.
17697This combines the functionality of zlib's @code{deflateInit2()}
17698and @code{deflateSetDictionary()}.
17699@c JP
17700新たな@code{<deflating-port>}のインスタンス、
17701すなわち書き込まれたデータを圧縮し出力ポート@var{drain}に書き出す出力ポートを作成して、
17702そのポートを返します。Zlibの関数@code{deflateInit2()}と
17703@code{deflateSetDictionary()}とを合わせた手続きです。
17704@c COMMON
17705
17706@c EN
17707You can specify an exact integer between 1 and 9 (inclusive) to
17708@var{compression-level}.  Larger integer means larger compression ratio.
17709When omitted, a default compression level is used, which is usually 6.
17710@c JP
17711@var{compression-level}には1から9の整数を指定することができ、
17712大きい数が高い圧縮率を意味します。引数が省略された場合は、
17713デフォルトの圧縮レベルと見なされます。これは通常6です。
17714@c COMMON
17715
17716@c EN
17717The following constants are defined to specify @var{compression-level}
17718conveniently:
17719@c JP
17720@var{compression-level}をわかりやすく指定するために以下の定数が定義されています。
17721@c COMMON
17722
17723@defvr {Constant} Z_NO_COMPRESSION
17724@defvrx {Constant} Z_BEST_SPEED
17725@defvrx {Constant} Z_BEST_COMPRESSION
17726@defvrx {Constant} Z_DEFAULT_COMPRESSION
17727@c MOD rfc.zlib
17728@end defvr
17729
17730@c EN
17731The @var{buffer-size} argument specifies the buffer size of the port in bytes.
17732The default is 4096.
17733@c JP
17734@var{buffer-size}は、ポートのバッファサイズを指定します。デフォルトは4096バイトです。
17735@c COMMON
17736
17737@c EN
17738The @var{window-bits} argument specifies the size of the window in
17739exact integer.   Typically the value should be
17740between 8 and 15, inclusive, and it specifies the base two logarithm
17741of the window size used in compression.
17742Larger number yields better compression ratio, but more memory usage.
17743The default value is 15.
17744@c JP
17745@var{window-bits}はウィンドウサイズを指定します。
17746通常この値は8から15までの整数で、圧縮に使われるウィンドウサイズの
177472を底とするlogをとった値です。
17748大きい数であるだけ圧縮率が高くなりますが、
17749そのぶんメモリの使用量が増加します。デフォルトは15です。
17750@c COMMON
17751
17752@c EN
17753There are a couple of special modes specifiable by @var{window-bits}.
17754When an integer between -8 and -15 is given to
17755@var{window-bits}, the port produces a raw deflated data,
17756that lacks zlib header and trailer.  In this case, Adler32 checksum isn't
17757calculated.  The actual window size is determined by the absolute value of
17758@var{window-bits}.
17759@c JP
17760@var{window-bits}よって、2つばかり特別なモードを指定することができます。
17761@var{window-bits}に-8から-15の整数を指定された場合は、
17762ZLIBヘッダとトレイラのない生のdeflateデータを作成します。
17763この場合Adler32チェックサムも計算されません。
17764実際のウィンドウサイズは@var{window-bits}の絶対値によって計算されます。
17765@c COMMON
17766
17767@c EN
17768When @var{window-bits} is between 24 and 31, the port uses GZIP encoding;
17769that is, instead of zlib wrapper,
17770the compressed data is enveloped by simple gzip header and trailer.
17771The gzip header added by this case doesn't have filenames, comments,
17772header CRC and other data, and have zero modified time, and 255 (unknown)
17773in the OS field.  The @code{zstream-adler32} procedure will return
17774CRC32 checksum instead of Adler32.
17775The actual window size is determined by @var{window-bits}-16.
17776@c JP
17777@var{window-bits}が24から31の間である場合、
17778ポートはgzipエンコーディングを使うようになります。すなわち、
17779zlibラッパの代わりに、シンプルなgzipヘッダとトレイラが圧縮データの前後に書き出されます。
17780gzipヘッダはファイル名やその他のデータ、コメントを持たず、変更時刻は0、
17781ヘッダCRCはなし、OS名は不明を意味する255になります。gzipストリームが書き出
17782されるときは、@code{zstream-adler32}で取得できるチェックサムはAdler32
17783ではなくCRC32になります。
17784実際のウィンドウサイズは @var{window-bits}-16 で決定されます。
17785@c COMMON
17786
17787@c EN
17788The @var{memory-level} argument specifies how much memory
17789should be allocated to keep the internal state during compression.
177901 means smallest memory, which causes slow and less compression.
177919 means fastest and best compression with largest amount of memory.
17792The default value is 8.
17793@c JP
17794@var{memory-level}は、圧縮の内部状態のためにどれだけのメモリを割り当て
17795るかを指定するパラメータです。1ではメモリの使用量は最小ですが、遅
17796くなり圧縮率が低下します。9では高速な処理のためにメモリが最も多く
17797使われます。デフォルトは8です。
17798@c COMMON
17799
17800@c EN
17801To fine tune compression algorithm, you can use the @var{strategy}
17802argument.  The following constants are defined as the valid
17803value as @var{strategy}:
17804@c JP
17805@var{strategy}で圧縮アルゴリズムをチューンできます。
17806以下の定数が@var{strategy}に有効な値として定義されています。
17807@c COMMON
17808
17809@defvr {Constant} Z_DEFAULT_STRATEGY
17810@c MOD rfc.zlib
17811@c EN
17812The default strategy, suitable for most ordinary data.
17813@c JP
17814通常のデータに適する、デフォルトのアルゴリズムを使います。
17815@c COMMON
17816@end defvr
17817
17818@defvr {Constant} Z_FILTERED
17819@c MOD rfc.zlib
17820@c EN
17821Suitable for data generated by filters.
17822Filtered data consists mostly of small values with a
17823random distribution, and this makes the compression algorithm
17824to use more huffman encoding and less string match.
17825@c JP
17826フィルタにより生成されたデータに適したアルゴリズムを使います。
17827このようなデータは小さな値とランダムな分散を持つことが多いため、
17828このアルゴリズムではハフマンエンコーディングをより優先し、
17829文字列一致の使用をやや抑えます。
17830@c COMMON
17831@end defvr
17832
17833@defvr {Constant} Z_HUFFMAN_ONLY
17834@c MOD rfc.zlib
17835@c EN
17836Force huffman encoding only (no string match).
17837@c JP
17838ハフマンエンコーディングのみを使います (文字列一致を使いません)。
17839@c COMMON
17840@end defvr
17841
17842@defvr {Constant} Z_RLE
17843@c MOD rfc.zlib
17844@c EN
17845Limit match distance to 1 (that is, to force run-length encoding).
17846It is as fast as @code{Z_HUFFMAN_ONLY} and gives better compression
17847for png image data.
17848@c JP
17849マッチ距離を1に制限します (ランレングスエンコーディングを強制することになります)。
17850@code{Z_HUFFMAN_ONLY}と同じくらい高速で、かつpngイメージデータに対して
17851良い圧縮率が得られます。
17852@c COMMON
17853@end defvr
17854
17855@defvr {Constant} Z_FIXED
17856@c MOD rfc.zlib
17857@c EN
17858Prohibits dynamic huffman encoding.  It allows a simple decoder
17859for special applications.
17860@c JP
17861動的ハフマンエンコーディングを禁止します。特殊なアプリケーションで、
17862単純なデコーダを使いたい場合に便利です。
17863@c COMMON
17864@end defvr
17865
17866@c EN
17867The choice of @var{strategy} only affects compression ratio and
17868speed.  Any choice produces correct and decompressable data.
17869@c JP
17870@var{strategy}の選択は圧縮率と速度にのみ影響を与えます。
17871どの値を選んでも圧縮されたデータは正しく展開できます。
17872@c COMMON
17873
17874@c EN
17875You can give an initial dictionary to the @var{dictionary}
17876argument to be used in compression.
17877The compressor and decompressor must use exactly the same dictionary.
17878See the zlib documentation for the details.
17879@c JP
17880@var{dictionary}には圧縮に使う辞書を文字列で与えます。辞書を与える場合、
17881圧縮と展開で全く同じものを使う必要があります。
17882辞書の詳細についてはzlibのドキュメントを参照してください。
17883@c COMMON
17884
17885@c EN
17886By default, a deflating port leaves @var{drain} open
17887after all conversion is done, i.e. the deflating port itself is
17888closed.  If you don't want to bother closing @var{drain},
17889give a true value to the @var{owner?} argument; then @var{drain}
17890is closed after the deflating port is closed and all data
17891is written out.
17892@c JP
17893デフォルトでは、deflating portはそれ自身がクローズされても
17894@var{drain}をクローズしません。@var{drain}の後始末を気にしたくない
17895場合は@var{owner?}引数に真の値を与えてください。
17896その場合、deflating portがクローズされすべてのデータが書き出されたのちに
17897@var{drain}は自動的にクローズされます。
17898@c COMMON
17899
17900@c EN
17901Note: You @emph{must} close a deflating port explicitly,
17902or the compressed data can be chopped prematurely.
17903When you leave a deflating port open to be GCed, the
17904finalizer will close it; however, the order in which
17905finalizers are called is undeterministic, and it is
17906possible that the @var{drain} port is closed before
17907the deflating port is closed.  In such cases,
17908the deflating port's attempt to flush the buffered data
17909and trailer will fail.
17910@c JP
17911注意: deflating portは必ず明示的にクローズしてください。
17912そうしなければ圧縮データの終わりの部分(バッファされているデータおよびトレイラ)が
17913@var{drain}に書き出されないかもしれません。
17914ポートを明示的にクローズせずにガベージ・コレクタに任せた場合、
17915出力ポートのクローズ手続きはファイナラザから呼び出されることになります。
17916複数のごみに対してファイナライザの呼ばれる順番は不定なので、
17917deflating portより先に@var{drain}のファイナライザが呼ばれて
17918そのポートがクローズされてしまうことがあります。
17919こうなると、圧縮データの終わりの部分の出力がエラーになってしまいます。
17920@c COMMON
17921@end defun
17922
17923@defun open-inflating-port source :key buffer-size window-bits dictionary owner?
17924@c MOD rfc.zlib
17925@c EN
17926Takes an input port @var{source} from which a compressed data
17927can be read, and creates and returns a new instance of
17928@code{<inflating-port>}, that is, a port that allows
17929decompressed data from it.
17930This procedure covers zlib's functionality of
17931@code{inflateInit2()} and @code{inflateSetDictionary()}.
17932@c JP
17933圧縮データを読み出せる入力ポート@var{source}を取り、
17934新たな@code{<inflating-port>}のインスタンス、すなわち
17935展開されたデータを読み出すことのできる入力ポートを作成し、そのポートを返します。
17936これはZlibの関数@code{inflateInit2()}、@code{inflateSetDictionary()}
17937を合わせた手続きです。
17938@c COMMON
17939
17940@c EN
17941The meaning of @var{buffer-size} and @var{owner} are
17942the same as @code{open-deflating-port}.
17943@c JP
17944@var{buffer-size}、@var{owner?}の意味は
17945@code{open-deflating-port}と同じです。
17946@c COMMON
17947
17948@c EN
17949The meaning of @var{window-bits} is almost the same,
17950except that if a value increased by 32 is given, the inflating port
17951automatically detects whether the source stream is
17952zlib or gzip by its header.
17953@c JP
17954@var{window-bits}の意味もほぼ同じですが、
1795532が足された値が与えられた場合にはZLIBとGZIPのヘッダ自動判定が有効になります。
17956@c COMMON
17957
17958@c EN
17959If the input data is compressed with specified dictionary,
17960the same dictionary must be given to the @var{dictionary} argument.
17961Otherwise, a compound condition of
17962@code{<io-read-error>} and @code{<zlib-need-dict-error>} will be raised.
17963@c JP
17964@var{dictionary}は圧縮時の辞書と同じものを指定しなければなりません。
17965辞書を使って圧縮されたデータを展開する際に、@var{dictionary}引数
17966を指定しなかったり、異なる辞書を与えた場合は
17967@code{<io-read-error>}と@code{<zlib-need-dict-error>}の
17968合成コンディションが投げられます。
17969@c COMMON
17970@end defun
17971
17972@subheading Operations on inflating/deflating ports
17973
17974@defun zstream-total-in xflating-port
17975@defunx zstream-total-out xflating-port
17976@defunx zstream-adler32 xflating-port
17977@defunx zstream-data-type xflating-port
17978@c MOD rfc.zlib
17979@c EN
17980The @var{xflating-port} argument must be either
17981inflating and deflating port, or an error is raised.
17982
17983Returns the value of @code{total_in}, @code{total_out},
17984@var{adler32}, and @code{data_type} fields of the @code{z_stream}
17985structure associated to the given inflating or deflating port,
17986respectively.
17987@c JP
17988@var{xflating-port}はinflating portかdeflating portでなければ
17989なりません。さもなくばエラーが通知されます。
17990
17991@code{z_stream}構造体の@code{total_in}、@code{total_out}、
17992@code{adlre32}および@code{data_type}フィールドの値を返します。
17993@c COMMON
17994
17995@c EN
17996The value of @code{data_type} can be one of the following
17997constants:
17998@c JP
17999@code{data_type}フィールドの値は以下の定数のうちのいずれかです。
18000@c COMMON
18001
18002@defvr {Constant} Z_BINARY
18003@defvrx {Constant} Z_TEXT
18004@defvrx {Constant} Z_ASCII
18005@defvrx {Constant} Z_UNKNOWN
18006@c MOD rfc.zlib
18007@end defvr
18008
18009@end defun
18010
18011@defun zstream-params-set! deflating-port :key compression-level strategy
18012@c MOD rfc.zlib
18013@c EN
18014Changes compression level and/or strategy during compressing.
18015@c JP
18016圧縮率とストラテジを動的に変更するための手続きです。
18017@c COMMON
18018@end defun
18019
18020@defun zstream-dictionary-adler32 deflating-port
18021@c MOD rfc.zlib
18022@c EN
18023When a dictionary is given to @code{open-deflating-port}, the
18024dictionary's adler32 checksum is calculated.  This
18025procedure returns the checksum.  If no dictionary has been given,
18026this procedure returns @code{#f}.
18027@c JP
18028deflating portの作成時に辞書を指定すると、辞書のAdler32チェックサム
18029が計算されます。この手続きはそのチェックサムを返します。
18030@code{open-deflating-port}に辞書を与えなかったなら、@code{#f}が返ります。
18031@c COMMON
18032@end defun
18033
18034@defun deflating-port-full-flush deflating-port
18035@c MOD rfc.zlib
18036@c EN
18037Flush the data buffered in the @var{deflating-port}, and
18038resets compression state.  The decompression routine can
18039skip the data to the full-flush point by @code{inflate-sync}.
18040@c JP
18041ポートのデータをフルフラッシュし、圧縮状態をリセットします。
18042展開ルーチンは@code{inflate-sync}手続きを使って
18043入力をこの地点までスキップすることができます。
18044@c COMMON
18045@end defun
18046
18047@defun inflate-sync inflating-port
18048@c MOD rfc.zlib
18049@c EN
18050Skip the (possibly corrupted) compressed data up to the
18051next full-flush point marked by @code{deflating-port-full-flush}.
18052You may want to use this procedure when you get
18053@code{<zlib-data-error>}.  Returns the number of bytes
18054skipped when the next full-flush point is found, or
18055@code{#f} when the input reaches EOF before finding the next point.
18056@c JP
18057圧縮データを、@code{deflating-port-full-flush}によって
18058フルフラッシュしたポイントまで読み飛ばします。
18059@code{<zlib-data-error>}が投げられたときに使用するとよいでしょう。
18060フルフラッシュポイントに達したときは読み飛ばしたバイトの数を、EOFまで達
18061したときは@code{#f}を返します。
18062@c COMMON
18063@end defun
18064
18065@subheading Miscellaneous API
18066
18067@defun zlib-version
18068@c MOD rfc.zlib
18069@c EN
18070Returns Zlib's version in string.
18071@c JP
18072Zlibのバージョンを文字列で返します。
18073@c COMMON
18074@end defun
18075
18076@defun deflate-string string options @dots{}
18077@c MOD rfc.zlib
18078@c EN
18079Compresses the given string and returns zlib-compressed data
18080in a string.  All optional arguments are passed to
18081@code{open-deflating-port} as they are.
18082@c JP
18083与えられた文字列を圧縮し、zlib圧縮されたデータを文字列で返します。
18084すべてのオプション引数はそのまま@code{open-deflating-port}に渡されます。
18085@c COMMON
18086@end defun
18087
18088@defun inflate-string string options @dots{}
18089@c MOD rfc.zlib
18090@c EN
18091Takes zlib-compressed data in string, and returns decompressed data
18092in a string.  All optional arguments are passed to
18093@code{open-inflating-port} as they are.
18094@c JP
18095Zlib圧縮されたデータを文字列で受け取り、展開されたデータを文字列で
18096返します。
18097すべてのオプション引数はそのまま@code{open-deflating-port}に渡されます。
18098@c COMMON
18099@end defun
18100
18101@defun gzip-encode-string string options @dots{}
18102@defunx gzip-decode-string string options @dots{}
18103@c MOD rfc.zlib
18104@c EN
18105Like @code{deflate-string} and @code{inflate-string}, but
18106uses the gzip format instead.  It is same as giving
18107more than 15 to the @var{window-bits} argument of @code{deflate-string}
18108and @code{inflate-string}.
18109@c JP
18110@code{deflate-string}および@code{inflate-string}と似ていますが、
18111GZIPフォーマットを使います。これは
18112@code{deflate-string}および@code{inflate-string}の
18113@var{window-bits}に15以上の値指定するのと同じです。
18114@c COMMON
18115@end defun
18116
18117@defun crc32 string :optional checksum
18118@c MOD rfc.zlib
18119@c EN
18120Returns CRC32 checksum of @var{string}.  If optional @var{checksum}
18121is given, the returned checksum is an update of @var{checksum} by
18122@var{string}.
18123@c JP
18124文字列@var{string}のCRC32チェックサムを計算して返します。@var{checksum}
18125引数が与えられた場合は、それを@var{string}によるチェックサムで更新した
18126値が返されます。
18127@c COMMON
18128@end defun
18129
18130@defun adler32 string :optional checksum
18131@c MOD rfc.zlib
18132@c EN
18133Returns Adler32 checksum of @var{string}.  If optional @var{checksum}
18134is given, the returned checksum is an update of @var{checksum} by
18135@var{string}.
18136
18137Calculating Adler32 is faster than CRC32, but it is known to produce
18138uneven distribution of hash values for small input.
18139See RFC3309 for the detailed description.  If it matters,
18140use CRC32 instead.
18141@c JP
18142文字列@var{string}のAdler32チェックサムを計算して返します。@var{checksum}
18143引数が与えられた場合は、それを@var{string}によるチェックサムで更新した
18144値が返されます。
18145
18146Adler32はCRC32と比較して高速に計算することが可能なアルゴリズムです
18147が、小さなデータのチェックサムの信頼性にいくらか問題があることがわ
18148かっています。詳しくはRFC3309を見てください。これが問題になる場合
18149はCRC32を使用してください。
18150@c COMMON
18151@end defun
18152
18153
18154
18155
18156
18157
18158@c ----------------------------------------------------------------------
18159@node SLIB, Functional XML parser, Zlib compression library, Library modules - Utilities
18160@section @code{slib} - SLIB interface
18161@c NODE SLIBインタフェース, @code{slib} - SLIBインタフェース
18162
18163@deftp {Module} slib
18164@mdindex slib
18165@c EN
18166This module is the interface to the Aubrey Jaffer's SLIB.
18167To use SLIB, say @code{(use slib)}.   SLIB itself is not included
18168in Gauche distribution.   If you don't have it on your system,
18169get it from @uref{http://www-swiss.ai.mit.edu/~jaffer/SLIB.html}.
18170@c JP
18171このモジュールはAubrey Jaffer氏のSLIBへのインタフェースです。
18172SLIBがインストールされている場合、@code{(use slib)} とすれば
18173SLIBの機能が使えるようになります。
18174SLIBそのものはGaucheのディストリビューションには含まれていません。
18175あなたのシステムにまだインストールされていない場合は
18176@uref{http://www-swiss.ai.mit.edu/~jaffer/SLIB.html}から入手することができます。
18177@c COMMON
18178
18179@c EN
18180By default, the SLIB installation is searched from the directory
18181specified at the Gauche configuration.  If SLIB isn't there, an error
18182is signaled.  In that case, you can set the environment
18183variable @code{SCHEME_LIBRARY_PATH} to point to the SLIB installation path.
18184@c JP
18185デフォルトでは、インストールされたSLIBはGaucheのconfiguration時に指定された
18186場所から探されます。SLIBがそこになければ、エラーが報告されます。
18187その場合、環境変数@code{SCHEME_LIBRARY_PATH}でSLIBがインストールされた
18188パスを指定してください。
18189@c COMMON
18190
18191@c EN
18192This module redefines @code{require}, shadowing the Gauche's original
18193@code{require}.  If it gets a symbol as an argument, it works as
18194SLIB's @code{require}, while if it gets a string, it works as
18195Gauche's @code{require}.   The same applies to @code{provide} and
18196@code{provided?}.
18197@c JP
18198このモジュールは@code{require}を再定義し、Gaucheオリジナルの@code{require}を
18199シャドウします。@code{require}にシンボルが渡された場合はSLIBの@code{require}
18200のように動作します。@code{require}に文字列が渡された場合はGaucheの@code{require}
18201のように動作します。@code{provide}と@code{provided?}についても同様です。
18202@c COMMON
18203
18204@c EN
18205All SLIB symbol bindings, loaded by @code{require}, stay in the
18206module @code{slib}.
18207@c JP
18208@code{require}でロードされる、SLIBで導入されるすべての定義は、
18209@code{slib}モジュール内で行われます。
18210@c COMMON
18211@end deftp
18212
18213@example
18214(use slib)         ; @r{load and set up slib}
18215(require 'getopt)  ; @r{load SLIB's getopt module}
18216(require "foo")    ; @r{load Gauche's foo module}
18217@end example
18218
18219@c ----------------------------------------------------------------------
18220@node Functional XML parser, SXML query language, SLIB, Library modules - Utilities
18221@section @code{sxml.ssax} - Functional XML parser
18222@c NODE 関数的なXMLパーザ, @code{sxml.ssax} - 関数的なXMLパーザ
18223
18224@deftp {Module} sxml.ssax
18225@mdindex sxml.ssax
18226@c EN
18227@code{sxml.*} modules are the adaptation of
18228Oleg Kiselyov's SXML framework (@uref{http://okmij.org/ftp/Scheme/xml.html}),
18229which is based on S-expression representation of XML structure.
18230@c JP
18231@code{sxml.*}モジュールは、XML構造のS式表現に基づく
18232Oleg KiselyovのSXMLフレームワーク(@uref{http://okmij.org/ftp/Scheme/xml.html})の適合です。
18233@c COMMON
18234
18235@c EN
18236SSAX is a parser part of SXML framework.
18237This is a quote from SSAX webpage:
18238@c JP
18239SSAXは、SXMLフレームワークのパーザ部分です。以下は、
18240SSAXのウェブページからの引用です。
18241@c COMMON
18242
18243@quotation
18244@c EN
18245A SSAX functional XML parsing framework consists of a DOM/SXML parser,
18246a SAX parser, and a supporting library of lexing and parsing procedures.
18247The procedures in the package can be used separately to tokenize or parse
18248various pieces of XML documents.
18249The framework supports XML Namespaces, character, internal
18250and external parsed entities, attribute value normalization,
18251processing instructions and CDATA sections. The package includes
18252a semi-validating SXML parser : a DOM-mode parser that is an
18253instantiation of a SAX parser (called SSAX).
18254@c JP
18255SSAXは関数的なXMLパージングフレームワークで、DOM/SXMLパーザ、SAXパーザ、
18256字句解析・構文解析手続きのサポートライブラリから構成されます。
18257パッケージ内の手続きは、XML文書の様々な部分をトークナイズ、あるいは
18258パーズするために独立して使うことができます。
18259このフレームワークは、XML名前空間、文字、内部および外部解析済み実体、
18260属性値の正規化、処理命令とCDATAセクションをサポートしています。
18261パッケージは、ある程度の妥当性検査を行うSXMLパーザ: SAXパーザの
18262インスタンスであるDOMモードのパーザ(SSAXと呼ばれます)を含んでいます。
18263@c COMMON
18264@end quotation
18265
18266@c EN
18267The current version is based on the SSAX CVS version newer than
18268the last 'official' release of SXML toolset (4.9), and
18269SXML-gauche-0.9 package which was based on SXML-4.9.
18270There is an important change from that release.
18271Now the API uses lowercase letter suffix @code{ssax:}
18272instead of uppercase @code{SSAX:}---the difference matters since
18273Gauche is case sensitive by default.
18274Alias names are defined for backward compatibility,
18275but the use of uppercase suffixed names are deprecated.
18276@c JP
18277現在のバージョンは、SXMLツールセットの最新の'公式な'リリース(4.9)よりも
18278新しい、SSAXのCVSバージョンをベースにしており、パッケージSXML-gauche-0.9は、
18279SXML-4.9をベースにしています。
18280SXMLのリリース4.9以降では、重要な変更があります。
18281現在のAPIでは、大文字の接頭辞@code{SSAX:}の代わりに小文字の@code{ssax:}を
18282使います。Gaucheはデフォルトで文字の大小を区別するために、この違いは
18283問題となります。
18284後方互換性のためにエイリアスされた名前が定義されていますが、
18285大文字の接頭辞付きの名前の使用は推奨されません。
18286@c COMMON
18287@end deftp
18288
18289@c EN
18290I derived the content of this part of the manual from SSAX
18291source code, just by converting its comments into texinfo format.
18292The original text is by Oleg Kiselyov.  Shiro Kawai
18293should be responsible for any typographical error or formatting error
18294introduced by conversion.
18295@c JP
18296マニュアルのこのパートの内容はSSAXのソースコードから抽出されたもので、
18297単にそのコメントをTexinfoのフォーマットに変換しただけです。
18298オリジナルのテキストは、Oleg Kiselyovによるものです。
18299変換により生じた誤字・誤植やフォーマットエラーの責任は、
18300Shiro Kawaiにあります。
18301@c COMMON
18302
18303@c EN
18304The manual entries are ordered in "bottom-up" way, beginning from
18305the lower-level constructs towards the high-level utilities.
18306If you just want to parse XML document and obtain SXML,
18307check out @code{ssax:xml->sxml} in @ref{SSAX Highest-level parsers - XML to SXML}.
18308@c JP
18309このマニュアルのエントリは、低レベルの構造から高レベルのユーティリティへと
18310``ボトムアップ''の方法で並べられています。
18311もし、あなたが単にXMLドキュメントをパーズしたりSXMLを得たいだけならば、
18312@ref{SSAX Highest-level parsers - XML to SXML}の@code{ssax:xml->sxml}を
18313チェックして下さい。
18314@c COMMON
18315
18316@c ----------------------------------------------------------------------
18317@menu
18318* SSAX data types::
18319* SSAX low-level parsing code::
18320* SSAX higher-level parsers and scanners::
18321* SSAX Highest-level parsers - XML to SXML::
18322@end menu
18323
18324@node SSAX data types, SSAX low-level parsing code, Functional XML parser, Functional XML parser
18325@subsection SSAX data types
18326@c NODE SSAXデータタイプ
18327
18328@table @emph
18329@item TAG-KIND
18330@c EN
18331a symbol '@code{START}, '@code{END}, '@code{PI}, '@code{DECL}, '@code{COMMENT}, '@code{CDSECT}
18332or '@code{ENTITY-REF} that identifies a markup token.
18333@c JP
18334シンボル'@code{START}、'@code{END}、'@code{PI}、'@code{DECL}、'@code{COMMENT}、
18335'@code{CDSECT}は、マークアップトークンを識別するものです。
18336@c COMMON
18337@item UNRES-NAME
18338@c EN
18339a name (called @code{GI} in the XML Recommendation) as given in an xml
18340document for a markup token: start-tag, @code{PI} target, attribute name.
18341If a @code{GI} is an @code{NCName}, @var{UNRES-NAME} is this @code{NCName} converted into
18342a Scheme symbol. If a @code{GI} is a @code{QName}, @var{UNRES-NAME} is a pair of
18343symbols: (@var{PREFIX} . @var{LOCALPART})
18344@c JP
18345XML文書で、マークアップトークン: 開始タグ、@code{PI}ターゲット、属性名に
18346与えられる名前(XML勧告では@code{GI}と呼ばれます)です。
18347@code{GI}が@code{NCName}である場合、@var{UNRES-NAME}はこの@code{NCName}が
18348Schemeのシンボルに変換されたものになります。
18349@code{GI}が@code{QName}ならば、@var{UNRES-NAME}は、シンボルのペア、
18350(@var{PREFIX} . @var{LOCALPART})となります。
18351@c COMMON
18352@item RES-NAME
18353@c EN
18354An expanded name, a resolved version of an @var{UNRES-NAME}.
18355For an element or an attribute name with a non-empty namespace URI,
18356@var{RES-NAME} is a pair of symbols, (@var{URI-SYMB} . @var{LOCALPART}).
18357Otherwise, it's a single symbol.
18358@c JP
18359展開された名前、つまり@var{UNRES-NAME}の解決されたバージョンです。
18360名前空間URIが空でない場合の要素や属性名では、@var{RES-NAME}はシンボルのペア、
18361(@var{URI-SYMB} . @var{LOCALPART})です。そうでない場合は、1つのシンボルです。
18362@c COMMON
18363@item ELEM-CONTENT-MODEL
18364@c EN
18365A symbol:
18366@c JP
18367以下のシンボルのうちの1つです。
18368@c COMMON
18369@c EN
18370@multitable @columnfractions .3 .7
18371@item @code{ANY}
18372@tab anything goes, expect an END tag.
18373@item @code{EMPTY-TAG}
18374@tab no content, and no END-tag is coming.
18375@item @code{EMPTY}
18376@tab no content, expect the END-tag as the next token.
18377@item @code{PCDATA}
18378@tab expect character data only, and no children elements.
18379@item @code{MIXED}
18380@tab
18381@item @code{ELEM-CONTENT}
18382@tab
18383@end multitable
18384@c JP
18385@multitable @columnfractions .3 .7
18386@item @code{ANY}
18387@tab 何でもよく、ENDタグがあるもの。
18388@item @code{EMPTY-TAG}
18389@tab 内容がなく、ENDタグのないもの。
18390@item @code{EMPTY}
18391@tab 内容がなく、次のトークンがENDタグであるもの。
18392@item @code{PCDATA}
18393@tab 文字データのみで、子要素がないもの。
18394@item @code{MIXED}
18395@tab
18396@item @code{ELEM-CONTENT}
18397@tab
18398@end multitable
18399@c COMMON
18400@item URI-SYMB
18401@c EN
18402A symbol representing a namespace URI -- or other symbol chosen
18403by the user to represent URI. In the former case,
18404@var{URI-SYMB} is created by @code{%}-quoting of bad URI characters and
18405converting the resulting string into a symbol.
18406@c JP
18407名前空間を表すシンボル、あるいはURIを表すためにユーザが選んだ他のシンボルです。
18408前者の場合、@var{URI-SYMB}は不正なURI文字が@code{%}でクォートされた
18409文字列をシンボルに変換したものです。
18410@c COMMON
18411@item NAMESPACES
18412@c EN
18413A list representing namespaces in effect. An element of the list
18414has one of the following forms:
18415@c JP
18416効力を持つ名前空間を表すリストです。リストの要素は、以下のフォームのうちの1つです。
18417@c COMMON
18418
18419@c EN
18420@table @code
18421@item (@var{prefix} @var{uri-symb} . @var{uri-symb})
18422or,
18423@item (@var{prefix} @var{user-prefix} . @var{uri-symb})
18424@var{user-prefix} is a symbol chosen by the user
18425to represent the URI.
18426@item (#f @var{user-prefix} . @var{uri-symb})
18427Specification of the user-chosen prefix and a @var{uri-symbol}.
18428@item (*DEFAULT* @var{user-prefix} . @var{uri-symb})
18429Declaration of the default namespace
18430@item (*DEFAULT* #f . #f)
18431Un-declaration of the default namespace. This notation
18432represents overriding of the previous declaration
18433@end table
18434@c JP
18435@table @code
18436@item (@var{prefix} @var{uri-symb} . @var{uri-symb})
18437あるいは、
18438@item (@var{prefix} @var{user-prefix} . @var{uri-symb})
18439@var{user-prefix}は、そのURIを表現するためにユーザにより選ばれたシンボル。
18440@item (#f @var{user-prefix} . @var{uri-symb})
18441ユーザが選んだプリフィックスと@var{uri-symbol}の指定。
18442@item (*DEFAULT* @var{user-prefix} . @var{uri-symb})
18443デフォルト名前空間の宣言。
18444@item (*DEFAULT* #f . #f)
18445デフォルト名前空間を宣言しない。この記法は、それ以前の宣言を上書き
18446することを表す。
18447@end table
18448@c COMMON
18449
18450@c EN
18451A @var{NAMESPACES} list may contain several elements for the same @var{PREFIX}.
18452The one closest to the beginning of the list takes effect.
18453@c JP
18454@var{NAMESPACES}のリストは、同じ@var{PREFIX}についていくつかの要素を含むかも
18455しれません。リストの先頭に近いものが効力を持ちます。
18456@c COMMON
18457
18458@item ATTLIST
18459@c EN
18460An ordered collection of (@var{NAME} . @var{VALUE}) pairs, where @var{NAME} is
18461a @var{RES-NAME} or an @var{UNRES-NAME}. The collection is an ADT.
18462@c JP
18463ペア(@var{NAME} . @var{VALUE})の順序付きのコレクションで、@var{NAME}は
18464@var{RES-NAME}か@var{UNRES-NAME}です。このコレクションはADTです。
18465@c COMMON
18466@item STR-HANDLER
18467@c EN
18468A procedure of three arguments:
18469@code{(@var{string1} @var{string2} @var{seed})}
18470returning a new @var{seed}.
18471The procedure is supposed to handle a chunk of character data
18472@var{string1} followed by a chunk of character data @var{string2}.
18473@var{string2} is a short string, often "\n" and even ""
18474@c JP
184753引数の手続き @code{(@var{string1} @var{string2} @var{seed})}で、
18476新しい@var{seed}を返します。
18477この手続きは、文字データ@var{string2}が後に続く、文字データ@var{string1}を
18478扱うものです。@var{string2}は、``\n''や``''のような短い文字列です。
18479@c COMMON
18480@item ENTITIES
18481@c EN
18482An assoc list of pairs:
18483@example
18484  (@var{named-entity-name} . @var{named-entity-body})
18485@end example
18486where @var{named-entity-name} is a symbol under which the entity was
18487declared, @var{named-entity-body} is either a string, or
18488(for an external entity) a thunk that will return an
18489input port (from which the entity can be read).
18490@var{named-entity-body} may also be @code{#f}. This is an indication that a
18491@var{named-entity-name} is currently being expanded. A reference to
18492this @var{named-entity-name} will be an error: violation of the
18493WFC nonrecursion.
18494@c JP
18495ペア (@var{named-entity-name} . @var{named-entity-body})の連想リストで、
18496@var{named-entity-name}はその実体が宣言されたシンボル、
18497@var{named-entity-body}は文字列か、(外部実体の場合は)
18498(そこから実体が読み込める)入力ポートを返す手続きです。
18499@var{named-entity-body}はまた、@code{#f}かも知れません。
18500これは、@var{named-entity-name}がその時点で展開されていることを
18501示します。
18502この@var{named-entity-name}への参照は、WFC非再帰違反としてエラーに
18503なります。
18504@c COMMON
18505@item XML-TOKEN
18506@c EN
18507A record with two slots, @var{kind} and @var{token}.
18508This record represents a markup, which is, according to the XML
18509Recommendation, "takes the form of start-tags, end-tags, empty-element tags,
18510entity references, character references, comments, CDATA section delimiters,
18511document type declarations, and processing instructions."
18512@c JP
18513@var{kind}と@var{token}という2つのスロットを持つレコードです。
18514このレコードは、XML勧告によれば、「開始タグ、終了タグ、空要素タグ、
18515実体参照、文字参照、コメント、CDATAセクションの区切り、
18516文書型宣言、処理命令の形を取る」マークアップを表します。
18517@c COMMON
18518@table @var
18519@item kind
18520@c EN
18521a @var{TAG-KIND}
18522@c JP
18523@var{TAG-KIND}。
18524@c COMMON
18525@item head
18526@c EN
18527an @var{UNRES-NAME}. For xml-tokens of kinds '@code{COMMENT} and
18528'@code{CDSECT}, the head is @code{#f}
18529@c JP
18530@var{UNRES-NAME}。'@code{COMMENT}と'@code{CDSECT}というkindのXMLトークンでは、
18531そのheadは@code{#f}になります。
18532@c COMMON
18533@end table
18534
18535@c EN
18536For example,
18537@c JP
18538例を示します。
18539@c COMMON
18540@example
18541<P>  => kind='START, head='P
18542</P> => kind='END, head='P
18543<BR/> => kind='EMPTY-EL, head='BR
18544<!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
18545<?xml version="1.0"?> => kind='PI, head='xml
18546&my-ent; => kind = 'ENTITY-REF, head='my-ent
18547@end example
18548@c EN
18549Character references are not represented by xml-tokens as these references
18550are transparently resolved into the corresponding characters.
18551@c JP
18552文字参照は、対応する文字へと透過的に解決されるので、XMLトークンとしては
18553表現されません。
18554@c COMMON
18555@item XML-DECL
18556@c EN
18557A record with three slots, @var{elems}, @var{entities}, and @var{notations}.
18558
18559The record represents a datatype of an XML document: the list of
18560declared elements and their attributes, declared notations, list of
18561replacement strings or loading procedures for parsed general
18562entities, etc. Normally an xml-decl record is created from a DTD or
18563an XML Schema, although it can be created and filled in in many other
18564ways (e.g., loaded from a file).
18565@c JP
18566@var{elems}、@var{entities}、@var{notations}という3つのスロットを持つレコードです。
18567
18568このレコードは、XML文書のデータタイプを表現します。それは、
18569宣言された要素とその属性のリスト、宣言された記法、
18570解析済み一般実体の置換文字列やロードされる手続きのリストなどです。
18571通常、xml-declレコードは、それを作るには他にたくさんの方法
18572(例えばファイルからロードするなど)があるにも関わらず、DTDかXML Schemaから
18573作られます。
18574@c COMMON
18575
18576@c EN
18577@var{elems}: an (assoc) list of decl-elem or @code{#f}. The latter instructs
18578the parser to do no validation of elements and attributes.
18579@c JP
18580@var{elems}: decl-elemか@code{#f}の(連想)リスト。後者は、パーザに、
18581要素と属性の妥当性検査を行わないように指示します。
18582@c COMMON
18583
18584@c EN
18585@var{decl-elem}: declaration of one element:
18586@code{(@var{elem-name} @var{elem-content} @var{decl-attrs})};
18587@var{elem-name} is an @var{UNRES-NAME} for the element.
18588@var{elem-content} is an @var{ELEM-CONTENT-MODEL}.
18589@var{decl-attrs} is an @var{ATTLIST},
18590of @code{(@var{attr-name} . @var{value})} associations.
18591This element can declare a user procedure to handle parsing of an
18592element (e.g., to do a custom validation, or to build a hash of
18593IDs as they're encountered).
18594@c JP
18595@var{decl-elem}: 1つの要素の宣言:
18596@code{(@var{elem-name} @var{elem-content} @var{decl-attrs})};
18597@var{elem-name}はその要素の@var{UNRES-NAME}。
18598@var{elem-content}は@var{ELEM-CONTENT-MODEL}。
18599@var{decl-attrs}は@var{ATTLIST}か、@code{(@var{attr-name} . @var{value})}の
18600連想リスト。
18601この要素は、要素のパージングを扱うユーザ手続きを宣言できます。
18602(例えば、カスタムな妥当性検査を行ったり、タグに出会うたびに
18603IDのハッシュを構築するなど。)
18604@c COMMON
18605
18606@c EN
18607@var{decl-attr}: an element of an @var{ATTLIST}, declaration of one attribute
18608@code{(@var{attr-name} @var{content-type} @var{use-type} @var{default-value})}:
18609@var{attr-name} is an @var{UNRES-NAME} for the declared attribute;
18610@var{content-type} is a symbol: @code{CDATA}, @var{NMTOKEN}, @var{NMTOKENS}, ...;
18611or a list of strings for the enumerated type.
18612@var{use-type} is a symbol: @code{REQUIRED}, @code{IMPLIED}, @code{FIXED}
18613default-value is a string for the default value, or @code{#f} if not given.
18614@c JP
18615@var{decl-attr}: @var{ATTLIST}の要素で、1つの属性
18616@code{(@var{attr-name} @var{content-type} @var{use-type} @var{default-value})}
18617の宣言:
18618@var{attr-name}はその宣言された属性の@var{UNRES-NAME}、
18619@var{content-type}はシンボル@code{CDATA}、@var{NMTOKEN}、@var{NMTOKENS}、
18620あるいは列挙されたタイプの文字列のリスト。
18621@var{use-type}はシンボル@code{REQUIRED}、@code{IMPLIED}、@code{FIXED}。
18622default-valueは、デフォルト値としての文字列か、与えられなければ@code{#f}。
18623@c COMMON
18624@end table
18625
18626@defun make-empty-attlist
18627@defunx attlist-add attlist name-value
18628@defunx attlist-null?
18629@defunx attlist-remove-top attlist
18630@defunx attlist->alist attlist
18631@defunx attlist-fold
18632@c MOD sxml.ssax
18633@c EN
18634Utility procedures to deal with attribute list, which
18635keeps name-value association.
18636@c JP
18637名前-値の属性リストを扱うユーティリティ手続きです。
18638@c COMMON
18639@end defun
18640
18641@defun make-xml-token kind head
18642@defunx xml-token? token
18643@c MOD sxml.ssax
18644@c EN
18645A constructor and a predicate for a @var{XML-TOKEN} record.
18646@c JP
18647@var{XML-TOKEN}レコードのコンストラクタと述語です。
18648@c COMMON
18649@end defun
18650
18651@defmac xml-token-kind token
18652@defmacx xml-token-head token
18653@c MOD sxml.ssax
18654@c EN
18655Accessor macros of a @var{XML-TOKEN} record.
18656@c JP
18657@var{XML-TOKEN}レコードのアクセッサマクロです。
18658@c COMMON
18659@end defmac
18660
18661@c ----------------------------------------------------------------------
18662@node SSAX low-level parsing code, SSAX higher-level parsers and scanners, SSAX data types, Functional XML parser
18663@subsection SSAX low-level parsing code
18664@c NODE SSAXの低レベルパージングコード
18665
18666@c EN
18667They deal with primitive lexical units (Names, whitespaces, tags)
18668and with pieces of more generic productions. Most of these parsers
18669must be called in appropriate context. For example, @code{ssax:complete-start-tag}
18670must be called only when the start-tag has been detected and its @code{GI}
18671has been read.
18672@c JP
18673これらは、プリミティブな字句解析ユニット(名前、空白、タグ)や、
18674より一般的な断片を扱います。
18675これらのパーザのほとんどは、適切なコンテキストで呼ばれなければなりません。
18676例えば、@code{ssax:complete-start-tag}は、開始タグが検知されその@code{GI}が
18677読み込まれたときにのみ呼ばれなければなりません。
18678@c COMMON
18679
18680@defun ssax:skip-S port
18681@c MOD sxml.ssax
18682@c EN
18683Skip the S (whitespace) production as defined by
18684@c JP
18685次のように定義されるS(空白)をスキップします。
18686@c COMMON
18687@example
18688 [3] S ::= (#x20 | #x9 | #xD | #xA)
18689@end example
18690@c EN
18691The procedure returns the first not-whitespace character it
18692encounters while scanning the @var{port}. This character is left
18693on the input stream.
18694@c JP
18695この手続きは、@var{port}のスキャン中に遭遇した最初の空白ではない文字を
18696返します。この文字は、入力ストリームに残されます。
18697@c COMMON
18698@end defun
18699
18700@defun ssax:ncname-starting-char? a-char
18701@c MOD sxml.ssax
18702@c EN
18703Check to see if a-char may start a @code{NCName}.
18704@c JP
18705@code{NCName}がa-charで始まるかどうかを検査します。
18706@c COMMON
18707@end defun
18708
18709@defun ssax:read-NCName port
18710@c MOD sxml.ssax
18711@c EN
18712Read a @code{NCName} starting from the current position in the @var{port} and
18713return it as a symbol.
18714@c JP
18715@var{port}で現在の位置から始まる@code{NCName}を読み込み、それをシンボルとして
18716返します。
18717@c COMMON
18718@end defun
18719
18720@defun ssax:read-QName port
18721@c MOD sxml.ssax
18722@c EN
18723Read a (namespace-) Qualified Name, @code{QName}, from the current
18724position in the @var{port}.
18725
18726From REC-xml-names:
18727@c JP
18728(名前空間)完全修飾名、@code{QName}を@var{port}の現在の位置から読み込みます。
18729
18730REC-xml-namesは、
18731@c COMMON
18732@example
18733 [6] QName ::= (Prefix ':')? LocalPart
18734 [7] Prefix ::= NCName
18735 [8] LocalPart ::= NCName
18736@end example
18737
18738@c EN
18739Return: an @var{UNRES-NAME}.
18740@c JP
18741戻り値は、@var{UNRES-NAME}です。
18742@c COMMON
18743@end defun
18744
18745@defvar ssax:Prefix-XML
18746@c MOD sxml.ssax
18747@c EN
18748The prefix of the pre-defined XML namespace, i.e. '@code{xml}.
18749@c JP
18750定義済みのXML名前空間の接頭辞、つまり、'@code{xml}です。
18751@c COMMON
18752@end defvar
18753
18754@defun ssax:read-markup-token port
18755@c MOD sxml.ssax
18756@c EN
18757This procedure starts parsing of a markup token. The current position
18758in the stream must be @code{#\<}. This procedure scans enough of the input stream
18759to figure out what kind of a markup token it is seeing. The procedure returns
18760an xml-token structure describing the token. Note, generally reading
18761of the current markup is not finished! In particular, no attributes of
18762the start-tag token are scanned.
18763
18764Here's a detailed break out of the return values and the position in the @var{port}
18765when that particular value is returned:
18766@c JP
18767この手続きは、マークアップトークンのパージングを開始します。
18768ストリームの現在の位置は、@code{#\<}でなければなりません。
18769この手続きは、見ているマークアップトークンがどの種類のものか見当を
18770つけるに十分な程度、入力ストリームをスキャンします。
18771この手続きは、そのトークンを表現するxml-token構造を返します。
18772通常、その時点のマークアップの読み込みは完了していないことに注意して下さい。
18773特に、開始タグトークンの属性はスキャンされていません。
18774
18775特定の値が返されたときの戻り値と@var{port}での位置を詳細に説明します。
18776@c COMMON
18777@table @code
18778@item PI-token
18779@c EN
18780only @code{PI}-target is read.
18781To finish the Processing Instruction and disregard it,
18782call @code{ssax:skip-pi}. @code{ssax:read-attributes} may be useful
18783as well (for @code{PI}s whose content is attribute-value
18784pairs)
18785@c JP
18786@code{PI}ターゲットのみが読み込まれました。
18787処理命令の読み込みを完了してそれを無視するためには、@code{ssax:skip-pi}を呼びます。
18788(@code{PI}の内容が、属性-値のペアの場合は、)@code{ssax:read-attributes}も
18789便利です。
18790@c COMMON
18791@item END-token
18792@c EN
18793The end tag is read completely; the current position
18794is right after the terminating @code{#\>} character.
18795@c JP
18796終了タグが完全に読み込まれました。
18797現在の位置は、終了の@code{#\>}文字の直後です。
18798@c COMMON
18799@item COMMENT
18800@c EN
18801is read and skipped completely. The current position
18802is right after "@code{-->}" that terminates the comment.
18803@c JP
18804コメントが完全に読み込まれスキップされました。
18805現在の位置は、コメントが終了する``@code{-->}''の直後です。
18806@c COMMON
18807@item CDSECT
18808@c EN
18809The current position is right after "@code{<!CDATA[}".
18810Use @code{ssax:read-cdata-body} to read the rest.
18811@c JP
18812現在の位置は、"@code{<!CDATA[}"の直後です。
18813残りを読むためには、@code{ssax:read-cdata-body}を使います。
18814@c COMMON
18815@item DECL
18816@c EN
18817We have read the keyword (the one that follows "@code{<!}")
18818identifying this declaration markup. The current
18819position is after the keyword (usually a
18820whitespace character)
18821@c JP
18822この宣言マークアップを識別するキーワード(``@code{<!}''に続くもの)を
18823読み込んだところです。現在の位置は、(通常は空白文字である)
18824そのキーワードの直後です。
18825@c COMMON
18826@item START-token
18827@c EN
18828We have read the keyword (@code{GI}) of this start tag.
18829No attributes are scanned yet. We don't know if this
18830tag has an empty content either.
18831Use @code{ssax:complete-start-tag} to finish parsing of
18832the token.
18833@c JP
18834この開始タグのキーワード(@code{GI})を読み込んだところです。
18835属性はまだスキャンされていません。
18836また、このタグが空の要素を持つかどうかも分かりません。
18837このトークンのパージングを終了するためには、
18838@code{ssax:complete-start-tag}を使います。
18839@c COMMON
18840@end table
18841@end defun
18842
18843@defun ssax:skip-pi port
18844@c MOD sxml.ssax
18845@c EN
18846The current position is inside a @code{PI}. Skip till the rest of the @code{PI}.
18847@c JP
18848現在の位置は、@code{PI}の内側です。
18849@code{PI}の残りをスキップします。
18850@c COMMON
18851@end defun
18852
18853@defun ssax:read-pi-body-as-string port
18854@c MOD sxml.ssax
18855@c EN
18856The current position is right after reading the @code{PITarget}. We read the
18857body of @code{PI} and return it as a string. The port will point to the
18858character right after '@code{?>}' combination that terminates @code{PI}.
18859@c JP
18860現在の位置は、@code{PITarget}を読み込んだ直後です。
18861@code{PI}のボディを読み込んで、それを文字列として返します。
18862ポートでは、@code{PI}を終了する'@code{?>}'の直後の文字を指します。
18863@c COMMON
18864@example
18865 [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
18866@end example
18867@end defun
18868
18869@defun ssax:skip-internal-dtd port
18870@c MOD sxml.ssax
18871@c EN
18872The current pos in the port is inside an internal DTD subset
18873(e.g., after reading @code{#\[ }that begins an internal DTD subset)
18874Skip until the "@code{]>}" combination that terminates this DTD
18875@c JP
18876ポートでの現在の位置は、内部DTDサブセットの内側です
18877(例えば、内部DTDサブセットの始まりである@code{#\[ }を読み込んだところ)。
18878このDTDを終了する、組み合わせとなる``@code{]>}''までをスキップします。
18879@c COMMON
18880@end defun
18881
18882@defun ssax:read-cdata-body port str-handler seed
18883@c MOD sxml.ssax
18884@c EN
18885This procedure must be called after we have read a string "@code{<![CDATA[}"
18886that begins a @code{CDATA} section. The current position must be the first
18887position of the @code{CDATA} body. This function reads @emph{lines} of the @code{CDATA}
18888body and passes them to a @var{STR-HANDLER}, a character data consumer.
18889@c JP
18890この手続きは、@code{CDATA}セクションを開始する文字列、"@code{<![CDATA[}"を
18891読み込んだ後に呼ばれなければなりません。
18892現在の位置は、@code{CDATA}のボディの最初の位置です。
18893この手続きは、@code{CDATA}のボディの@emph{データ}を読み込み、それらを
18894@var{STR-HANDLER}(文字データのコンシューマ)へ渡します。
18895@c COMMON
18896
18897@c EN
18898The str-handler is a @var{STR-HANDLER}, a procedure @code{string1} @var{string2} @var{seed}.
18899The first @var{string1} argument to @var{STR-HANDLER} never contains a newline.
18900The second @var{string2} argument often will. On the first invocation of
18901the @var{STR-HANDLER}, the seed is the one passed to @code{ssax:read-cdata-body}
18902as the third argument. The result of this first invocation will be
18903passed as the seed argument to the second invocation of the line
18904consumer, and so on. The result of the last invocation of the
18905@var{STR-HANDLER} is returned by the @code{ssax:read-cdata-body}.  Note a
18906similarity to the fundamental '@code{fold}' iterator.
18907@c JP
18908str-handlerは、@code{string1} @var{string2} @var{seed}を取る手続き
18909@var{STR-HANDLER}です。
18910@var{STR-HANDLER}の最初の引数@var{string1}は、改行を含みません。
189112番目の引数@var{string2}は、改行を含むことがよくあります。
18912@var{STR-HANDLER}の最初の呼び出しでは、seedは@code{ssax:read-cdata-body}の
18913第3引数として渡されるものです。
18914この最初の呼び出しの結果は、文字データのコンシューマの引数seedとして渡され、
18915以降同じように続きます。
18916@var{STR-HANDLER}の最後の呼び出しの結果は、@code{ssax:read-cdata-body}
18917から返されるものです。
18918基本的な'@code{fold}'イテレータに似ています。
18919@c COMMON
18920
18921@c EN
18922Within a @code{CDATA} section all characters are taken at their face value,
18923with only three exceptions:
18924@c JP
18925@code{CDATA}セクションでは、以下の3つだけの例外を除いて、全ての文字は
18926その表面上の値を持ちます。
18927@c COMMON
18928@itemize @bullet
18929@item
18930@c EN
18931@code{CR}, @code{LF}, and @code{CRLF} are treated as line delimiters, and passed
18932as a single @code{#\newline} to the @var{STR-HANDLER}.
18933@c JP
18934@code{CR}、@code{LF}、@code{CRLF}は行区切りとして扱われ、@var{STR-HANDLER}へは
189351つの@code{#\newline}として渡されます。
18936@c COMMON
18937@item
18938@c EN
18939"@code{]]>}" combination is the end of the @code{CDATA} section.
18940@c JP
18941組み合わせとなる``@code{]]>}''は、@code{CDATA}セクションの終わりであると
18942されます。
18943@c COMMON
18944@item
18945@c EN
18946@code{&gt;} is treated as an embedded @code{#\>} character.
18947Note, @code{&lt;} and @code{&amp;} are not specially recognized (and are not expanded)!
18948@c JP
18949@code{&gt;}は、@code{#\>}文字の埋め込みとして扱われます。
18950@code{&lt;}と@code{&amp;}は特別なものとして認識されない(よって展開されない)ことに
18951注意が必要です!
18952@c COMMON
18953@end itemize
18954@end defun
18955
18956@defun ssax:read-char-ref port
18957@c MOD sxml.ssax
18958@example
18959 [66]  CharRef ::=  '&#' [0-9]+ ';'
18960                  | '&#x' [0-9a-fA-F]+ ';'
18961@end example
18962@c EN
18963This procedure must be called after we we have read "@code{&#}"
18964that introduces a char reference.
18965The procedure reads this reference and returns the corresponding char.
18966The current position in @var{port} will be after "@code{;}" that terminates
18967the char reference.
18968Faults detected: @code{WFC: XML-Spec.html#wf-Legalchar}.
18969@c JP
18970この手続きは、文字参照を表す``@code{&#}''を読み込んだ後に呼ばれなければ
18971なりません。
18972この手続きは、この参照を読み込んで対応する文字を返します。
18973@var{port}での現在の位置は、文字参照の終わりとなる``@code{;}''の後と
18974なります。
18975@code{WFC: XML-Spec.html#wf-Legalchar}も参照のこと。
18976@c COMMON
18977
18978@c EN
18979According to Section "4.1 Character and Entity References"
18980of the XML Recommendation:
18981@c JP
18982XML勧告のセクション``4.1 文字と実体参照''によると、
18983@c COMMON
18984@quotation
18985@c EN
18986"[Definition: A character reference refers to a specific character
18987 in the ISO/IEC 10646 character set, for example one not directly
18988 accessible from available input devices.]"
18989@c JP
18990``[定義: 文字参照は、ISO/IEC 10646文字集合にある特定の文字を参照する。
18991例えば、利用できる入力デバイスからは直接アクセスできないものなど。]''
18992@c COMMON
18993@end quotation
18994@c EN
18995Therefore, we use a @code{ucscode->char} function to convert a character
18996code into the character -- @emph{regardless} of the current character
18997encoding of the input stream.
18998@c JP
18999したがって、入力ストリームの現在の文字エンコーディングに@emph{関係なく}、
19000文字コードを文字に変換するために関数@code{ucscode->char}を使います。
19001@c COMMON
19002@end defun
19003
19004@defun ssax:handle-parsed-entity port name entities content-handler str-handler seed
19005@c MOD sxml.ssax
19006@c EN
19007Expand and handle a parsed-entity reference
19008@c JP
19009解析済み実体参照を展開し処理します。
19010@c COMMON
19011@itemize @bullet
19012@item
19013@c EN
19014@var{port} - a PORT
19015@c JP
19016@var{port} - ポート
19017@c COMMON
19018@item
19019@c EN
19020@var{name} - the name of the parsed entity to expand, a symbol.
19021@c JP
19022@var{name} - 展開する解析済み実体の名前。シンボル。
19023@c COMMON
19024@item
19025@c EN
19026@var{entities} - see @var{ENTITIES}
19027@c JP
19028@var{entities} - @var{ENTITIES}を参照。
19029@c COMMON
19030@item
19031@c EN
19032@var{content-handler} - procedure @var{port} @var{entities} @var{seed}
19033that is supposed to return a @var{seed}.
19034@c JP
19035@var{content-handler} - @var{port} @var{entities} @var{seed}を取る手続きで、
19036@var{seed}を返す。
19037@c COMMON
19038@item
19039@c EN
19040@var{str-handler} - a @var{STR-HANDLER}. It is called if the entity in question
19041turns out to be a pre-declared entity
19042@c JP
19043@var{str-handler} - @var{STR-HANDLER}。対象となる実体が宣言済み実体となった
19044場合に呼ばれる。
19045@c COMMON
19046@end itemize
19047@c EN
19048The result is the one returned by @var{content-handler} or @var{str-handler}.
19049@c JP
19050戻り値は、@var{content-handler}か@var{str-handler}から返された値です。
19051@c COMMON
19052
19053@c EN
19054Faults detected:
19055@c JP
19056こちらも参照のこと。
19057@c COMMON
19058@example
19059  WFC: XML-Spec.html#wf-entdeclared
19060  WFC: XML-Spec.html#norecursion
19061@end example
19062@end defun
19063
19064@defun ssax:read-attributes port entities
19065@c MOD sxml.ssax
19066@c EN
19067This procedure reads and parses a production @code{Attribute*}
19068@c JP
19069この手続きは、@code{Attribute*}を読み込みパーズします。
19070@c COMMON
19071@example
19072 [41] Attribute ::= Name Eq AttValue
19073 [10] AttValue ::=  '"' ([^<&"] | Reference)* '"'
19074                 | "'" ([^<&'] | Reference)* "'"
19075 [25] Eq ::= S? '=' S?
19076@end example
19077@c EN
19078The procedure returns an @var{ATTLIST}, of @var{Name} (as @var{UNRES-NAME}),
19079@var{Value} (as string) pairs.
19080The current character on the @var{port} is a non-whitespace character
19081that is not an ncname-starting character.
19082@c JP
19083この手続きは、@var{Name}(@var{UNRES-NAME})と@var{Value}(文字列)のペアである
19084@var{ATTLIST}を返します。
19085@var{port}での現在の文字は、NCNameの開始文字ではなく、空白ではない文字です。
19086@c COMMON
19087
19088@c EN
19089Note the following rules to keep in mind when reading an 'AttValue'
19090"Before the value of an attribute is passed to the application
19091or checked for validity, the XML processor must normalize it as follows:
19092@c JP
19093'AttValue'を読み込むときには、以下のルールに留意して下さい。
19094``属性の値がアプリケーションに渡されるか妥当性が検査される前に、
19095XMLプロセッサはそれを以下のように正規化しなければならない:
19096@c COMMON
19097@itemize @bullet
19098@item
19099@c EN
19100a character reference is processed by appending the referenced
19101character to the attribute value
19102@c JP
19103文字参照は、属性値に参照された文字を追加することで処理される。
19104@c COMMON
19105@item
19106@c EN
19107an entity reference is processed by recursively processing the
19108replacement text of the entity [see @var{ENTITIES}]
19109[named entities amp lt gt quot apos are assumed pre-declared]
19110@c JP
19111実体参照は、その実体のテキストの置換を再帰的に行うことにより
19112処理される。[@var{ENTITIES}参照] [名前付きのエンティティ、amp lt gt
19113quot aposは定義済みと想定される]
19114@c COMMON
19115@item
19116@c EN
19117a whitespace character (@code{#x20}, @code{#xD}, @code{#xA}, @code{#x9}) is processed by appending @code{#x20}
19118to the normalized value, except that only a single @code{#x20} is appended for a
19119"@code{#xD#xA}" sequence that is part of an external parsed entity or the
19120literal entity value of an internal parsed entity
19121@c JP
19122空白文字(@code{#x20}、@code{#xD}、@code{#xA}、@code{#x9})は、
19123外部解析済み実体か内部解析済み実体のリテラルの実体の値の一部である
19124``@code{#xD#xA}''のシーケンスにただ1つの@code{#x20}が追加されることを
19125除いて、正規化された値に@code{#x20}を追加することで処理される。
19126@c COMMON
19127@item
19128@c EN
19129other characters are processed by appending them to the normalized value "
19130@c JP
19131他の文字は、正規化された値をそれらに追加することにより処理される''
19132@c COMMON
19133@end itemize
19134
19135@c EN
19136Faults detected:
19137@c JP
19138こちらも参照のこと。
19139@c COMMON
19140@example
19141 WFC: XML-Spec.html#CleanAttrVals
19142 WFC: XML-Spec.html#uniqattspec
19143@end example
19144@end defun
19145
19146@defun ssax:resolve-name port unres-name namespaces apply-default-ns?
19147@c MOD sxml.ssax
19148@c EN
19149Convert an @var{unres-name} to a @var{res-name} given the appropriate @var{namespaces}
19150declarations.
19151The last parameter @var{apply-default-ns?} determines if the default
19152namespace applies (for instance, it does not for attribute names)
19153
19154Per @code{REC-xml-names/#nsc-NSDeclared}, "xml" prefix is considered pre-declared
19155and bound to the namespace name "@url{http://www.w3.org/XML/1998/namespace}".
19156
19157This procedure tests for the namespace constraints:
19158@url{http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared}.
19159@c JP
19160与えられた適切な@var{namespaces}の宣言を用いて、@var{unres-name}を
19161@var{res-name}に変換する。
19162最後の引数@var{apply-default-ns?}は、デフォルト名前空間の適用を行うか
19163どうかを決めます(例えば、属性名には適用しないなど)。
19164
19165@code{REC-xml-names/#nsc-NSDeclared}によれば、接頭辞``xml''は
19166名前空間名``@url{http://www.w3.org/XML/1998/namespace}''に定義済みで束縛されていると
19167されます。
19168
19169この手続きは、名前空間の制約をテストします:
19170@url{http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared}。
19171@c COMMON
19172@end defun
19173
19174@defun ssax:uri-string->symbol uri-str
19175@c MOD sxml.ssax
19176@c EN
19177Convert a @var{uri-str} to an appropriate symbol.
19178@c JP
19179@var{uri-str}を適切なシンボルに変換します。
19180@c COMMON
19181@end defun
19182
19183@defun ssax:complete-start-tag tag port elems entities namespaces
19184@c MOD sxml.ssax
19185@c EN
19186This procedure is to complete parsing of a start-tag markup. The
19187procedure must be called after the start tag token has been
19188read. @var{Tag} is an @var{UNRES-NAME}.
19189@var{Elem
19190s} is an instance of @code{xml-decl::elems};
19191it can be @code{#f} to tell the function to do @emph{no} validation of elements
19192and their attributes.
19193@c JP
19194この手続きは、開始タグのマークアップのパージングを完了するためのものです。
19195この手続きは、開始タグトークンが読み込まれた後に呼ばれなければなりません。
19196@var{tag}は@var{UNRES-NAME}です。
19197@var{elems}は@code{xml-decl::elems}のインスタンスで、
19198手続きに、要素とそれらの属性の妥当性検査を@emph{行わない}ように
19199指示するために、@code{#f}を指定することができます。
19200@c COMMON
19201
19202@c EN
19203This procedure returns several values:
19204@c JP
19205この手続きはいくつかの値を返します。
19206@c COMMON
19207@table @var
19208@item elem-gi
19209@c EN
19210a @var{RES-NAME}.
19211@c JP
19212@var{RES-NAME}。
19213@c COMMON
19214@item attributes
19215@c EN
19216element's attributes, an @var{ATTLIST} of @code{(@var{res-name} . @var{string})}
19217pairs. The list does @emph{not} include @code{xmlns} attributes.
19218@c JP
19219要素の属性。@code{(@var{res-name} . @var{string})}というペアの@var{ATTLIST}。
19220このリストは、@code{xmlns}属性を@emph{含みません}。
19221@c COMMON
19222@item namespaces
19223@c EN
19224the input list of namespaces amended with namespace
19225(re-)declarations contained within the start-tag under parsing
19226@var{ELEM-CONTENT-MODEL}.
19227@c JP
19228パージング中の開始タグに含まれる名前空間(再)宣言により修正された後の
19229名前空間の入力リスト。
19230@c COMMON
19231@end table
19232
19233@c EN
19234On exit, the current position in @var{port} will be the first character after
19235@code{#\>} that terminates the start-tag markup.
19236@c JP
19237終了時の@var{port}での現在の位置は、開始タグのマークアップを終了する
19238@code{#\>}の後になります。
19239@c COMMON
19240
19241@c EN
19242Faults detected:
19243@c JP
19244こちらも参照のこと。
19245@c COMMON
19246@example
19247 VC: XML-Spec.html#enum
19248 VC: XML-Spec.html#RequiredAttr
19249 VC: XML-Spec.html#FixedAttr
19250 VC: XML-Spec.html#ValueType
19251 WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
19252 VC: XML-Spec.html#elementvalid
19253 WFC: REC-xml-names/#dt-NSName
19254@end example
19255
19256@c EN
19257Note, although XML Recommendation does not explicitly say it,
19258@var{xmlns} and @var{xmlns:} attributes don't have to be declared (although they
19259can be declared, to specify their default value).
19260@c JP
19261XML勧告では明示されていませんが、@var{xmlns}と@var{xmlns:}属性は、
19262(そのデフォルト値を指定するために宣言されることが出来ますが)
19263宣言される必要がないことに注意して下さい。
19264@c COMMON
19265@end defun
19266
19267@defun ssax:read-external-id port
19268@c MOD sxml.ssax
19269@c EN
19270This procedure parses an @code{ExternalID} production.
19271@c JP
19272この手続きは、@code{ExternalID}をパーズします。
19273@c COMMON
19274@example
19275 [75] ExternalID ::= 'SYSTEM' S SystemLiteral
19276                 | 'PUBLIC' S PubidLiteral S SystemLiteral
19277 [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
19278 [12] PubidLiteral ::=  '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
19279 [13] PubidChar ::=  #x20 | #xD | #xA | [a-zA-Z0-9]
19280                | [-'()+,./:=?;!*#@@$_%]
19281@end example
19282@c EN
19283This procedure is supposed to be called when an @code{ExternalID} is expected;
19284that is, the current character must be either @code{#\S} or @code{#\P} that start
19285correspondingly a @code{SYSTEM} or @code{PUBLIC} token. This procedure returns the
19286@code{SystemLiteral} as a string. A @code{PubidLiteral} is disregarded if present.
19287@c JP
19288この手続きは、@code{ExternalID}が期待されるところで呼ばれます。
19289つまり、現在の文字は、それぞれ@code{SYSTEM}か@code{PUBLIC}トークンを開始する
19290@code{#\S}か@code{#\P}でなければなりません。
19291この手続きは、@code{SystemLiteral}を文字列として返します。
19292@code{PubidLiteral}は、存在したとしても無視されます。
19293@c COMMON
19294@end defun
19295
19296@c ----------------------------------------------------------------------
19297@node SSAX higher-level parsers and scanners, SSAX Highest-level parsers - XML to SXML, SSAX low-level parsing code, Functional XML parser
19298@subsection SSAX higher-level parsers and scanners
19299@c NODE SSAXの高レベルのパーザとスキャナ
19300
19301@c EN
19302They parse productions corresponding to the whole (document) entity
19303or its higher-level pieces (prolog, root element, etc).
19304@c JP
19305これらは、全体的な実体(ドキュメント)あるいはその高レベルな断片
19306(プロローグ、ルート要素など)をパーズします。
19307@c COMMON
19308
19309@defun ssax:scan-Misc port
19310@c MOD sxml.ssax
19311@c EN
19312Scan the @code{Misc} production in the context:
19313@c JP
19314そのコンテキストでの@code{Misc}をスキャンします。
19315@c COMMON
19316@example
19317[1]  document ::=  prolog element Misc*
19318[22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
19319[27] Misc ::= Comment | PI |  S
19320@end example
19321@c EN
19322The following function should be called in the prolog or epilog contexts.
19323In these contexts, whitespaces are completely ignored.
19324The return value from @code{ssax:scan-Misc} is either a @code{PI}-token,
19325a @code{DECL}-token, a @code{START} token, or EOF.
19326Comments are ignored and not reported.
19327@c JP
19328以下の関数は、プロローグかエピローグのコンテキストで呼ばれます。
19329これらのコンテキストでは、空白文字は完全に無視されます。
19330@code{ssax:scan-Misc}からの戻り値は、@code{PI}トークンか@code{DECL}トークン、
19331@code{START}トークン、EOFのいずれかです。
19332コメントは無視され報告されません。
19333@c COMMON
19334@end defun
19335
19336@defun ssax:read-char-data port expect-eof? str-handler seed
19337@c MOD sxml.ssax
19338@c EN
19339This procedure is to read the character content of an XML document
19340or an XML element.
19341@c JP
19342この手続きは、XML文書かXML要素の文字内容を読むためのものです。
19343@c COMMON
19344@example
19345 [43] content ::=
19346        (element | CharData | Reference | CDSect | PI
19347         | Comment)*
19348@end example
19349@c EN
19350To be more precise, the procedure reads @code{CharData}, expands @code{CDSect}
19351and character entities, and skips comments. The procedure stops
19352at a named reference, EOF, at the beginning of a @code{PI} or a start/end tag.
19353@c JP
19354具体的には、この手続きは@code{CharData}を読み込み、@code{CDSect}と
19355文字実体を展開し、コメントをスキップします。
19356この手続きは、名前付き参照、EOF、@code{PI}あるいは開始/終了タグの開始地点で
19357停止します。
19358@c COMMON
19359
19360@table @var
19361@item port
19362@c EN
19363a port to read
19364@c JP
19365読み込むポート。
19366@c COMMON
19367@item expect-eof?
19368@c EN
19369a boolean indicating if EOF is normal, i.e., the character
19370data may be terminated by the EOF. EOF is normal
19371while processing a parsed entity.
19372@c JP
19373EOFがノーマルかどうか、つまり、文字データがEOFで終わるかどうかを
19374表す真偽値。解析済み実体を処理している間はEOFはノーマル。
19375@c COMMON
19376@item str-handler
19377@c EN
19378a @var{STR-HANDLER}.
19379@c JP
19380@var{STR-HANDLER}。
19381@c COMMON
19382@item seed
19383@c EN
19384an argument passed to the first invocation of @var{STR-HANDLER}.
19385@c JP
19386@var{STR-HANDLER}の最初の呼び出し時に渡される引数。
19387@c COMMON
19388@end table
19389
19390@c EN
19391The procedure returns two results: @var{seed} and @var{token}.
19392
19393The @var{seed} is the result of the last invocation of @var{str-handler}, or the
19394original seed if @var{str-handler} was never called.
19395@c JP
19396この手続きは2つの結果、@var{seed}と@var{token}を返します。
19397
19398@var{seed}は@var{str-handler}の最後の呼び出しの結果、あるいは
19399@var{str-handler}が一度も呼ばれなかった場合はオリジナルのseedです。
19400@c COMMON
19401
19402@c EN
19403@var{Token} can be either an eof-object (this can happen only if
19404@var{expect-eof?} was @code{#t}), or:
19405@c JP
19406@var{token}はEOFオブジェクト(これは@var{expect-eof?}が@code{#t}の場合のみ)か、
19407@c COMMON
19408@itemize @bullet
19409@item
19410@c EN
19411an xml-token describing a @var{START} tag or an @var{END}-tag;
19412For a start token, the caller has to finish reading it.
19413@c JP
19414@var{START}タグか@var{END}タグを表すxml-token。
19415開始トークンの場合は、呼び出し側が読み込みを完了する必要がある。
19416@c COMMON
19417@item
19418@c EN
19419an xml-token describing the beginning of a @code{PI}. It's up to an
19420application to read or skip through the rest of this @code{PI};
19421@c JP
19422@code{PI}の開始を表すxml-token。
19423この@code{PI}の残りを読み込むかスキップするかはアプリケーションに
19424任される。
19425@c COMMON
19426@item
19427@c EN
19428an xml-token describing a named entity reference.
19429@c JP
19430名前付き実体参照を表すxml-token。
19431@c COMMON
19432@end itemize
19433
19434@c EN
19435@code{CDATA} sections and character references are expanded inline and
19436never returned. Comments are silently disregarded.
19437
19438As the XML Recommendation requires, all whitespace in character data
19439must be preserved. However, a @code{CR} character (@code{#xD}) must be disregarded
19440if it appears before a @code{LF} character (@code{#xA}), or replaced by a @code{#xA} character
19441otherwise. See Secs. 2.10 and 2.11 of the XML Recommendation. See also
19442the canonical XML Recommendation.
19443@c JP
19444@code{CDATA}セクションと文字参照はインラインで展開され返されません。
19445コメントは無視されます。
19446
19447XML勧告が要求するように、文字データ中の全ての空白文字は保存されなければなりません。
19448しかし、@code{CR}文字(@code{#xD})は、@code{LF}文字(@code{#A})の前に現れるか
19449@code{#xA}文字で置き換えられた場合は、無視されなければなりません。
19450XML勧告のセクション2.10と2.11を参照して下さい。
19451また、正規のXML勧告も参照して下さい。
19452@c COMMON
19453@end defun
19454
19455@defun ssax:assert-token token kind gi error-cont
19456@c MOD sxml.ssax
19457@c EN
19458Make sure that @var{token} is of anticipated @var{kind} and has anticipated @var{gi}.
19459Note @var{gi} argument may actually be a pair of two symbols, Namespace
19460URI or the prefix, and of the localname.
19461If the assertion fails, @var{error-cont} is evaluated by passing it
19462three arguments: @var{token} @var{kind} @var{gi}.
19463The result of @var{error-cont} is returned.
19464@c JP
19465@var{token}が、予想された@var{kind}のもので、予想された@var{gi}を
19466持つことを確認します。@var{gi}引数は、実際には2つのシンボル、
19467名前空間URIかその接頭辞と、そのローカル名のペアでしょう。
19468アサーションが失敗したら、@var{error-cont}に3つの引数、@var{token} @var{kind} @var{gi}
19469を渡されて評価されます。
19470@var{error-cont}の結果が返されます。
19471@c COMMON
19472@end defun
19473
19474@c ----------------------------------------------------------------------
19475@node SSAX Highest-level parsers - XML to SXML,  , SSAX higher-level parsers and scanners, Functional XML parser
19476@subsection SSAX Highest-level parsers - XML to SXML
19477@c NODE SSAXの高レベルのパーザ - XMLからSXMLへ
19478
19479@c EN
19480These parsers are a set of syntactic forms to instantiate a SSAX parser.
19481A user can instantiate the parser to do the full validation, or
19482no validation, or any particular validation. The user specifies
19483which @code{PI} he wants to be notified about. The user tells what to do
19484with the parsed character and element data. The latter handlers
19485determine if the parsing follows a SAX or a DOM model.
19486@c JP
19487これらのパーザは、SSAXパーザをインスタンス化するための構文的フォームのセットです。
19488ユーザは、完全な妥当性検査、妥当性検査なし、特定の妥当性検査を行うために
19489このパーザをインスタンス化できます。
19490ユーザは、どの@code{PI}について通知されたいかを指定します。
19491ユーザは、解析済み文字と要素のデータで何をしたいかを知らせます。
19492後者のハンドラは、パージングがSAXやDOMモデルに従うかを決定します。
19493@c COMMON
19494
19495@defmac ssax:make-pi-parser my-pi-handlers
19496@c MOD sxml.ssax
19497@c EN
19498Create a parser to parse and process one Processing Element (@code{PI}).
19499@c JP
195001つの処理命令(@code{PI})をパーズして処理するパーザを作ります。
19501@c COMMON
19502
19503@c EN
19504@var{My-pi-handlers}:
19505An assoc list of pairs (@var{PI-TAG} . @var{PI-HANDLER})
19506where @var{PI-TAG} is an @var{NCName} symbol, the @code{PI} target, and
19507@var{PI-HANDLER} is a procedure @var{port} @var{pi-tag} @var{seed}
19508where @var{port} points to the first symbol after the @code{PI} target.
19509The handler should read the rest of the @code{PI} up to and including
19510the combination '@code{?>}' that terminates the @code{PI}. The handler should
19511return a new seed.
19512One of the @var{PI-TAG}s may be a symbol @code{*DEFAULT*}. The corresponding
19513handler will handle @code{PI}s that no other handler will. If the
19514@code{*DEFAULT*} @var{PI-TAG} is not specified,
19515@code{ssax:make-pi-parser} will make
19516one, which skips the body of the @code{PI}.
19517@c JP
19518@var{my-pi-handlers}:
19519(@var{PI-TAG} . @var{PI-HANDLER})のペアの連想リスト。
19520@var{PI-TAG}は@var{NCName}のシンボル、@code{PI}ターゲット。
19521@var{PI-HANDLER}は@var{port} @var{pi-tag} @var{seed}を引数とする手続きで、
19522@var{port}では@code{PI}ターゲットの後の最初のシンボルを指しています。
19523ハンドラは、@code{PI}を終了する組み合わせとなる'@code{?>}'を含む、
19524@code{PI}の残りを読み込みます。ハンドラは新しいseedを返します。
19525@var{PI-TAG}の1つは、シンボル@code{*DEFAULT*}でしょう。
19526これに対応するハンドラは、他のハンドラが扱わない@code{PI}を処理します。
19527@code{*DEFAULT*} @var{PI-TAG}が指定されていない場合は、
19528@code{ssax:make-pi-parser}は、@code{PI}のボディをスキップするパーザを
19529作ります。
19530@c COMMON
19531
19532@c EN
19533The output of the @code{ssax:make-pi-parser} is a procedure
19534@var{port} @var{pi-tag} @var{seed},
19535that will parse the current @code{PI} accoding to user-specified handlers.
19536@c JP
19537@code{ssax:make-pi-parser}が返すのは、@var{port} @var{pi-tag} @var{seed}を
19538取る手続きで、ユーザ指定のハンドラに従い現在の@code{PI}をパーズします。
19539@c COMMON
19540@end defmac
19541
19542@defmac ssax:make-elem-parser my-new-level-seed my-finish-element my-char-data-handler my-pi-handlers
19543@c MOD sxml.ssax
19544@c EN
19545Create a parser to parse and process one element, including its
19546character content or children elements. The parser is typically
19547applied to the root element of a document.
19548@c JP
19549その文字内容や子要素をも含む1つの要素をパーズし処理するパーザを作ります。
19550このパーザは通常、ドキュメントのルート要素の適用されます。
19551@c COMMON
19552
19553@table @var
19554@item my-new-level-seed
19555@c EN
19556procedure @var{elem-gi} @var{attributes} @var{namespaces} @var{expected-content} @var{seed} @*
19557where @var{elem-gi} is a @var{RES-NAME} of the element
19558about to be processed.
19559This procedure is to generate the seed to be passed
19560to handlers that process the content of the element.
19561@c JP
19562@var{elem-gi} @var{attributes} @var{namespaces} @var{expected-content} @var{seed} @*
19563を引数に取る手続きで、@var{elem-gi}は処理されようとしている要素の@var{RES-NAME}です。
19564この手続きは、要素の内容を処理するハンドラに渡されるseedを生成します。
19565@c COMMON
19566@c This is the function identified as 'fdown' in the denotational
19567@c semantics of the XML parser given in the title comments to this
19568@c file.
19569
19570@item my-finish-element
19571@c EN
19572procedure @var{elem-gi} @var{attributes} @var{namespaces} @var{parent-seed} @var{seed} @*
19573This procedure is called when parsing of @var{elem-gi} is finished.
19574The @var{seed} is the result from the last content parser (or
19575from @var{my-new-level-seed} if the element has the empty content).
19576@var{Parent-seed} is the same seed as was passed to @var{my-new-level-seed}.
19577The procedure is to generate a seed that will be the result
19578of the element parser.
19579@c JP
19580@var{elem-gi} @var{attributes} @var{namespaces} @var{parent-seed} @var{seed} @*
19581を引数に取る手続きです。この手続きは、@var{elem-gi}のパージングが完了した時に
19582呼ばれます。
19583@var{seed}は、最後に呼ばれたパーザからの(あるいは、
19584要素が空要素であった場合は、@var{my-new-level-seed}からの)結果です。
19585@var{parent-seed}は、@var{my-new-level-seed}へ渡されたのと同じseedです。
19586この手続きは、パーザの結果となるseedを生成するためのものです。
19587@c COMMON
19588@c This is the function identified as 'fup' in the denotational
19589@c semantics of the XML parser given in the title comments to this
19590@c file.
19591
19592@item my-char-data-handler
19593@c EN
19594A @var{STR-HANDLER}.
19595@c JP
19596@var{STR-HANDLER}。
19597@c COMMON
19598
19599@item my-pi-handlers
19600@c EN
19601See @code{ssax:make-pi-handler} above.
19602@c JP
19603@code{ssax:make-pi-handler}を参照して下さい。
19604@c COMMON
19605@end table
19606
19607@c EN
19608The generated parser is a:
19609procedure @var{start-tag-head} @var{port} @var{elems} @var{entities}
19610@var{namespaces} @var{preserve-ws?} @var{seed}. @*
19611The procedure must be called after the start tag token has been
19612read. @var{Start-tag-head} is an @var{UNRES-NAME} from the start-element tag.
19613@var{Elems} is an instance of @code{xml-decl::elems}.
19614See @code{ssax:complete-start-tag::preserve-ws?}
19615@c JP
19616生成されたパーザは:
19617@var{start-tag-head} @var{port} @var{elems} @var{entities} @var{namespaces}
19618@var{preserve-ws?} @var{seed} @*
19619を引数に取る手続きです。
19620この手続きは、開始タグのトークンが読み込まれた後に呼ばれなければなりません。
19621@var{start-tag-head}は要素の開始タグの@var{UNRES-NAME}です。
19622@var{elems}は@code{xml-decl::elems}のインスタンスです。
19623@code{ssax:complete-start-tag::preserve-ws?}も参照して下さい。
19624@c COMMON
19625
19626@c EN
19627Faults detected:
19628@c JP
19629こちらも参照のこと。
19630@c COMMON
19631@example
19632 VC: XML-Spec.html#elementvalid
19633 WFC: XML-Spec.html#GIMatch
19634@end example
19635@end defmac
19636
19637@defmac ssax:make-parser user-handler-tag user-handler-proc @dots{}
19638@c MOD sxml.ssax
19639@c EN
19640Create an XML parser, an instance of the XML parsing framework.
19641This will be a SAX, a DOM, or a specialized parser depending
19642on the supplied user-handlers.
19643
19644@var{user-handler-tag} is a symbol that identifies a procedural expression
19645that follows the tag. Given below are tags and signatures of the
19646corresponding procedures. Not all tags have to be specified. If some
19647are omitted, reasonable defaults will apply.
19648@c JP
19649XMLパージングフレームワークのインスタンスである、XMLパーザを作ります。
19650これは、提供されるユーザハンドラによって、SAX、DOM、あるいは特化された
19651パーザになります。
19652
19653@var{user-handler-tag}はシンボルで、タグに続く手続き的な式を識別します。
19654以下にタグと対応する手続きのシグネチャを示します。
19655全てのタグが指定される必要はありません。
19656いくつかが省略されると、合理的なデフォルトのものが適用されます。
19657@c COMMON
19658
19659@table @code
19660@item tag: @var{DOCTYPE}
19661@c EN
19662handler-procedure: @var{port} @var{docname} @var{systemid} @var{internal-subset?} @var{seed}
19663
19664If @var{internal-subset?} is @code{#t}, the current position in the port
19665is right after we have read @code{#\[} that begins the internal DTD subset.
19666We must finish reading of this subset before we return
19667(or must call skip-internal-subset if we aren't interested in reading it).
19668The port at exit must be at the first symbol after the whole
19669DOCTYPE declaration.
19670
19671The handler-procedure must generate four values: @*
19672@var{elems} @var{entities} @var{namespaces} @var{seed}@*
19673See @code{xml-decl::elems} for @var{elems}.
19674It may be @code{#f} to switch off the validation.
19675@var{namespaces} will typically contain @var{USER-PREFIX}es for selected @var{URI-SYMB}s.
19676The default handler-procedure skips the internal subset,
19677if any, and returns @code{(values #f '() '() seed)}.
19678@c JP
19679ハンドラ手続きの引数: @var{port} @var{docname} @var{systemid} @var{internal-subset?} @var{seed}
19680
19681@var{internal-subset?}が@code{#t}なら、ポートでの現在の位置は内部DTDサブセットの
19682開始となる@code{#\[}を読んだ直後です。
19683手続きから戻る前に、このサブセットの残りの読み込みを完了しなければなりません
19684(あるいは、それを読むことに興味がなければ、skip-internal-subsetを呼ばなければなりません)。
19685終了時のポートでの位置は、DOCTYPE宣言全体のあとの最初のシンボルでなければなりません。
19686
19687ハンドラ手続きは4つの値: @*
19688@var{elems} @var{entities} @var{namespaces} @var{seed} @*
19689を生成しなければなりません。
19690@var{elems}については、@code{xml-decl::elems}を参照して下さい。
19691妥当性検査をオフにするためには、@code{#f}になるでしょう。
19692@var{namespaces}は、通常、選択された@var{URI-SYMB}に対して@var{USER-PREFIX}を含む
19693でしょう。
19694デフォルトのハンドラ手続きは、内部サブセットがあってもそれをスキップし、
19695@code{(values #f '() '() seed)}を返します。
19696@c COMMON
19697
19698@item tag: @var{UNDECL-ROOT}
19699@c EN
19700handler-procedure: @var{elem-gi} @var{seed} @*
19701where @var{elem-gi} is an @var{UNRES-NAME} of the root element. This procedure
19702is called when an XML document under parsing contains @emph{no} @code{DOCTYPE}
19703declaration.
19704The handler-procedure, as a DOCTYPE handler procedure above,
19705must generate four values: @*
19706@var{elems} @var{entities} @var{namespaces} @var{seed}@*
19707The default handler-procedure returns @code{(values #f '() '() seed)}.
19708@c JP
19709ハンドラ手続きの引数: @var{elem-gi} @var{seed} @*
19710@var{elem-gi}はルート要素の@var{UNRES-NAME}です。
19711この手続きは、パージング中のXML文書が@code{DOCTYPE}宣言を@emph{含まない}時に
19712呼ばれます。
19713ハンドラ手続きは、上ではDOCTYPEハンドラですが、4つの値: @*
19714@var{elems} @var{entities} @var{namespaces} @var{seed}@*
19715を生成しなければなりません。
19716デフォルトのハンドラ手続きは、@code{(values #f '() '() seed)}を返します。
19717@c COMMON
19718
19719@item tag: @var{DECL-ROOT}
19720@c EN
19721handler-procedure: @var{elem-gi} @var{seed} @*
19722where @var{elem-gi} is an @var{UNRES-NAME} of the root element. This procedure
19723is called when an XML document under parsing does contains the @code{DOCTYPE}
19724declaration.
19725The handler-procedure must generate a new @code{seed} (and verify
19726that the name of the root element matches the doctype, if the handler
19727so wishes).
19728The default handler-procedure is the identity function.
19729@c JP
19730ハンドラ手続きの引数: @var{elem-gi} @var{seed} @*
19731@var{elem-gi}は、ルート要素の@var{UNRES-NAME}です。
19732この手続きは、パージング中のXML文書が@code{DOCTYPE}宣言を含む場合に呼ばれます。
19733このハンドラ手続きは、新しい@code{seed}を生成しなければなりません
19734(そして、ハンドラが望めば、ルート要素の名前がDOCTYPEにマッチするかを
19735検証します)。
19736デフォルトのハンドラ手続きは、それ自身を返す手続きです。
19737@c COMMON
19738
19739@item tag: @var{NEW-LEVEL-SEED}
19740@c EN
19741handler-procedure: see @code{ssax:make-elem-parser}, @var{my-new-level-seed}
19742@c JP
19743ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-new-level-seed}を参照して下さい。
19744@c COMMON
19745
19746@item tag: @var{FINISH-ELEMENT}
19747@c EN
19748handler-procedure: see @code{ssax:make-elem-parser}, @var{my-finish-element}
19749@c JP
19750ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-finish-element}を参照して下さい。
19751@c COMMON
19752
19753@item tag: @var{CHAR-DATA-HANDLER}
19754@c EN
19755handler-procedure: see @code{ssax:make-elem-parser}, @var{my-char-data-handler}
19756@c JP
19757ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-char-data-handler}を参照して下さい。
19758@c COMMON
19759
19760@item tag: @var{PI}
19761@c EN
19762handler-procedure: see @code{ssax:make-pi-parser}. @*
19763The default value is @code{'()}.
19764@c JP
19765ハンドラ手続きの引数: @code{ssax:make-pi-parser}を参照して下さい。@*
19766デフォルトの値は、@code{'()}です。
19767@c COMMON
19768@end table
19769
19770@c EN
19771The generated parser is a @*
19772procedure @var{PORT} @var{SEED}
19773
19774This procedure parses the document prolog and then exits to
19775an element parser (created by ssax:make-elem-parser) to handle
19776the rest.
19777@c JP
19778生成されるパーザは、@*
19779@var{PORT} @var{SEED}を取る手続き、@*
19780です。
19781
19782この手続きは、ドキュメントのプロローグをパーズして、
19783その残りを処理するために(ssax:make-elem-parserで作られた)パーザへ
19784引き継いで終了します。
19785@c COMMON
19786
19787@example
19788 [1]  document ::=  prolog element Misc*
19789 [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
19790 [27] Misc ::= Comment | PI |  S
19791
19792 [28] doctypedecl ::=  '<!DOCTYPE' S Name (S ExternalID)? S?
19793                        ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
19794 [29] markupdecl ::= elementdecl | AttlistDecl
19795                      | EntityDecl
19796                      | NotationDecl | PI
19797                      | Comment
19798@end example
19799@end defmac
19800
19801@c EN
19802A few utility procedures that turned out useful.
19803@c JP
19804いくつかの便利なユーティリティ手続きがあります。
19805@c COMMON
19806
19807@defun ssax:reverse-collect-str fragments
19808@c MOD sxml.ssax
19809@c EN
19810given the list of @var{fragments} (some of which are text strings)
19811reverse the list and concatenate adjacent text strings.
19812@c JP
19813@var{fragments}(そのいくつかはテキスト文字列)のリストを渡すと、
19814そのリストを逆順にして隣り合ったテキスト文字列を連結します。
19815@c COMMON
19816@end defun
19817
19818@defun ssax:reverse-collect-str-drop-ws fragments
19819@c MOD sxml.ssax
19820@c EN
19821given the list of fragments (some of which are text strings)
19822reverse the list and concatenate adjacent text strings.
19823We also drop "unsignificant" whitespace, that is, whitespace
19824in front, behind and between elements. The whitespace that
19825is included in character data is not affected.
19826We use this procedure to "intelligently" drop "insignificant"
19827whitespace in the parsed SXML. If the strict compliance with
19828the XML Recommendation regarding the whitespace is desired, please
19829use the @code{ssax:reverse-collect-str} procedure instead.
19830@c JP
19831fragments(そのいくつかはテキスト文字列)のリストを渡すと、
19832そのリストを逆順にして隣り合ったテキスト文字列を連結します。
19833``重要でない''空白文字、つまり、最初や最後、要素の間にある空白文字を
19834削除します。文字データに含まれる空白文字には影響を与えません。
19835この手続きは、パーズされたSXMLにある``重要でない''空白文字を
19836``知的に''削除するために使います。空白文字に関して、厳密に
19837XML勧告に準拠したい場合は、代わりに手続き
19838@code{ssax:reverse-collect-str}を使って下さい。
19839@c COMMON
19840@end defun
19841
19842@defun ssax:xml->sxml port namespace-prefix-assig
19843@c MOD sxml.ssax
19844@c EN
19845This is an instance of a SSAX parser above that returns an SXML
19846representation of the XML document to be read from @var{port}.
19847@var{Namespace-prefix-assig} is a list of
19848@code{(@var{USER-PREFIX} . @var{URI-STRING})}
19849that assigns @var{USER-PREFIX}es to certain namespaces identified by
19850particular @var{URI-STRING}s. It may be an empty list.
19851The procedure returns an SXML tree. The port points out to the
19852first character after the root element.
19853@c JP
19854これは、上のSSAXパーザのインスタンスで、@var{port}から読み込まれる
19855XMLドキュメントのSXML表現を返します。
19856@var{namespace-prefix-assig}は、@code{(@var{USER-PREFIX} . @var{URI-STRING})}
19857のリストで、特定の@var{URI-STRING}で識別されるある名前空間を
19858@var{USER-PREFIX}に割り当てます。これは空リストでも構いません。
19859この手続きは、SXMLツリーを返します。
19860ポートでの位置は、ルート要素の後の最初の文字を指します。
19861@c COMMON
19862@end defun
19863
19864@c ----------------------------------------------------------------------
19865@node SXML query language, Manipulating SXML structure, Functional XML parser, Library modules - Utilities
19866@section @code{sxml.sxpath} - SXML query language
19867@c NODE SXMLクエリ言語, @code{sxml.sxpath} - SXMLクエリ言語
19868
19869@deftp {Module} sxml.sxpath
19870@mdindex sxml.sxpath
19871@c EN
19872SXPath is a query language for SXML, an instance of XML Information
19873set (Infoset) in the form of s-expressions.
19874
19875It is originally written by Oleg Kiselyov, and
19876improved by Dmitry Lizorkin and Kirill Lisovsky.
19877This module also incorporates
19878various procedures written for SXPath by Dmitry Lizorkin and Kirill Lisovsky.
19879
19880Current version is based on sxpathlib.scm,v 3.915,
19881sxpath.scm,v 1.1, and sxpath-ext.scm,v 1.911.
19882@c JP
19883SXPathは、XML Information set (Infoset)のインスタンスのS式フォームである
19884SXMLのためのクエリ言語です。
19885
19886これは最初にOleg Kiselyovによって書かれ、Dmitry LizorkinとKirill Lisovsky
19887によって改良されました。
19888このモジュールにはまた、Dmitry LizorkinとKirill LisovskyによりSXPathのために
19889書かれたたくさんの手続きが盛り込まれています。
19890
19891現在のバージョンは、sxpathlib.scm v3.915、sxpath.scm v1.1、sxpath-ext.scm v1.911を
19892ベースにしています。
19893@c COMMON
19894@end deftp
19895
19896@c EN
19897This manual is mostly derived from the comments in the
19898original source files.
19899
19900The module consists of three layers.
19901@c JP
19902このマニュアルは、そのほとんどがオリジナルのソースファイルのコメントより
19903導出されています。
19904
19905このモジュールは3つのレイヤから構成されます。
19906@c COMMON
19907@enumerate
19908@item
19909@c EN
19910Basic converters and applicators, which provides the means to
19911access and translate SXML tree.
19912@c JP
19913SXMLツリーへのアクセスやその変換の手段を提供する基本的なコンバータや
19914アプリケータ(適用子)。
19915@c COMMON
19916@item
19917@c EN
19918High-level query language compiler,
19919which takes abbreviated SXPath and
19920returns a Scheme function that selects a nodeset
19921that satisfies the specified path from the given nodeset.
19922@c JP
19923省略形のSXPathを取り、与えられたノードセットから指定されたパスを満足する
19924ノードセットを選択するScheme関数を返す、高レベルなクエリ言語コンパイラ。
19925@c COMMON
19926@item
19927@c EN
19928Extension libraries, which implements
19929SXML counterparts to W3C XPath Core Functions Library.
19930@c JP
19931W3CのXPathコア関数ライブラリのSXML版を実装する拡張ライブラリ。
19932@c COMMON
19933@end enumerate
19934
19935@c ----------------------------------------------------------------------
19936@menu
19937* SXPath basic converters and applicators::
19938* SXPath query language::
19939* SXPath extension::
19940@end menu
19941
19942@node SXPath basic converters and applicators, SXPath query language, SXML query language, SXML query language
19943@subsection SXPath basic converters and applicators
19944@c NODE SXPathの基本的なコンバータとアプリケータ
19945
19946@c EN
19947A converter is a function
19948@c JP
19949コンバータは、以下を満たす関数です。
19950@c COMMON
19951@example
19952  type Converter = Node|Nodeset -> Nodeset
19953@end example
19954@c EN
19955A converter can also play a role of a predicate: in that case, if a
19956converter, applied to a node or a nodeset, yields a non-empty
19957nodeset, the converter-predicate is deemed satisfied. Throughout
19958this file a nil nodeset is equivalent to @code{#f} in denoting a failure.
19959@c JP
19960コンバータは、述語としての役割を担うこともあります。
19961その場合、コンバータが、ノードやノードセットに適用され、空ではないノードセットを
19962返す場合、述語としてのコンバータは満足したものとみなされます。
19963このファイルを通して、nilノードセットは失敗を表す@code{#f}と等価です。
19964@c COMMON
19965
19966@defun nodeset? x
19967@c MOD sxml.sxpath
19968@c EN
19969Returns @code{#t} if given object is a nodeset.
19970@c JP
19971与えられたオブジェクトがノードセットならば、@code{#t}を返します。
19972@c COMMON
19973@end defun
19974
19975@defun as-nodeset x
19976@c MOD sxml.sxpath
19977@c EN
19978If @var{x} is a nodeset - returns it as is, otherwise wrap it in a list.
19979@c JP
19980@var{x}がノードセットならば、それをそのまま返し、そうでなければそれを
19981リストでラップして返します。
19982@c COMMON
19983@end defun
19984
19985@defun sxml:element? obj
19986@c MOD sxml.sxpath
19987@c EN
19988Predicate which returns @code{#t}
19989if @var{obj} is SXML element, otherwise returns @code{#f}.
19990@c JP
19991@var{obj}がSXMLの要素であれば@code{#t}を返し、そうでなければ@code{#f}を
19992返す述語です。
19993@c COMMON
19994@end defun
19995
19996@defun ntype-names?? crit
19997@c MOD sxml.sxpath
19998@c EN
19999The function @code{ntype-names??} takes a list of acceptable node names as a
20000criterion and returns a function, which, when applied to a node,
20001will return @code{#t} if the node name is present in criterion list
20002and @code{#f} otherwise.
20003@c JP
20004関数@code{ntype-names??}は、判定基準として受け付け可能なノード名のリストを取り、
20005関数を返します。この関数は、ノードに適用された際、そのノード名が判定基準リストに
20006含まれていれば@code{#t}を、含まれていなければ@code{#f}を返す関数です。
20007@c COMMON
20008@example
20009 ntype-names?? :: ListOfNames -> Node -> Boolean
20010@end example
20011@end defun
20012
20013@defun ntype?? crit
20014@c MOD sxml.sxpath
20015@c EN
20016The function @code{ntype??} takes a type criterion and returns
20017a function, which, when applied to a node, will tell if the node satisfies
20018the test.
20019@c JP
20020関数@code{ntype??}は、型に関する判定基準を取り、関数を返します。
20021この関数は、ノードに適用された際、そのノードがそのテストを満足するかを
20022返します。
20023@c COMMON
20024@example
20025  ntype?? :: Crit -> Node -> Boolean
20026@end example
20027
20028@c EN
20029The criterion @var{crit} is
20030one of the following symbols:
20031@c JP
20032判定基準@var{crit}は、以下のシンボルのうちの1つです。
20033@c COMMON
20034@table @code
20035@item id
20036@c EN
20037tests if the Node has the right name (id)
20038@c JP
20039そのノードが正しい名前(id)を持っているかをテストします。
20040@c COMMON
20041@item @@
20042@c EN
20043tests if the Node is an @var{attributes-list}.
20044@c JP
20045そのノードが@var{attributes-list}であるかをテストします。
20046@c COMMON
20047@item *
20048@c EN
20049tests if the Node is an @var{Element}.
20050@c JP
20051そのノードが@var{Element}であるかをテストします。
20052@c COMMON
20053@item *text*
20054@c EN
20055tests if the Node is a text node.
20056@c JP
20057そのノードがテキストノードであるかをテストします。
20058@c COMMON
20059@item *data*
20060@c EN
20061tests if the Node is a data node
20062(text, number, boolean, etc., but not pair).
20063@c JP
20064そのノードがデータノード(テキスト、数値、真偽値などで、ペアではない)であるか
20065をテストします。
20066@c COMMON
20067@item *PI*
20068@c EN
20069tests if the Node is a @code{PI} node.
20070@c JP
20071そのノードが@code{PI}ノードであるかをテストします。
20072@c COMMON
20073@item *COMMENT*
20074@c EN
20075tests if the Node is a @code{COMMENT} node.
20076@c JP
20077そのノードが@code{COMMENT}ノードであるかをテストします。
20078@c COMMON
20079@item *ENTITY*
20080@c EN
20081tests if the Node is a @code{ENTITY} node.
20082@c JP
20083そのノードが@code{ENTITY}ノードであるかをテストします。
20084@c COMMON
20085@item *any*
20086@c EN
20087@code{#t} for any type of Node.
20088@c JP
20089どんなタイプのノードに対しても@code{#t}を返します。
20090@c COMMON
20091@end table
20092@end defun
20093
20094@defun ntype-namespace-id?? ns-id
20095@c MOD sxml.sxpath
20096@c EN
20097This function takes a namespace-id, and returns a predicate
20098@code{Node -> Boolean}, which is @code{#t}
20099for nodes with this very namespace-id.
20100@var{ns-id} is a string.
20101@code{(ntype-namespace-id?? #f)} will be @code{#t}
20102for nodes with non-qualified names.
20103@c JP
20104この関数は、名前空間IDを取り、述語@code{Node -> Boolean}を
20105返します。この述語はまさにその名前空間IDを持つノードに対しては
20106@code{#t}を返します。@var{ns-id}は文字列です。
20107@code{(ntype-namespace-id?? #f)}は、完全修飾されていない名前を
20108持つノードに対して@code{#t}を返します。
20109@c COMMON
20110@end defun
20111
20112@defun sxml:invert pred
20113@c MOD sxml.sxpath
20114@c EN
20115This function takes a predicate and returns it inverted .
20116That is if the given predicate yields @code{#f} or '@code{()} the inverted one
20117yields the given node (@code{#t}) and vice versa.
20118@c JP
20119この関数は、述語を取り、それを反対にして返します。
20120与えられた述語が@code{#f}や'@code{()}を返す場合、反対にされたものは
20121与えられたノード(@code{#t})を返します。
20122@c COMMON
20123@end defun
20124
20125@defun node-eq? other
20126@defunx node-equal? other
20127@c MOD sxml.sxpath
20128@c EN
20129Curried equivalence converter-predicates, i.e.
20130@c JP
20131等価な述語としてのコンパータにカリー化します。すなわち、
20132@c COMMON
20133@example
20134  ((node-eq? a) b)    @equiv{} (eq? a b)
20135  ((node-equal? a) b) @equiv{} (equal? a b)
20136@end example
20137@end defun
20138
20139@defun node-pos n
20140@c MOD sxml.sxpath
20141
20142@example
20143 node-pos:: N -> Nodeset -> Nodeset, or
20144 node-pos:: N -> Converter
20145@end example
20146
20147@c EN
20148Select the @var{N}'th element of a Nodeset and return as a singular Nodeset;
20149Return an empty nodeset if the Nth element does not exist.
20150@code{((node-pos 1) Nodeset)} selects the node at the head of the Nodeset,
20151if exists;
20152@code{((node-pos 2) Nodeset)} selects the Node after that, if
20153exists.
20154@var{N} can also be a negative number: in that case the node is picked from
20155the tail of the list.
20156@code{((node-pos -1) Nodeset)} selects the last node of a non-empty nodeset;
20157@code{((node-pos -2) Nodeset)} selects the last but one node, if exists.
20158@c JP
20159ノードセットの@var{N}番目の要素を選択し、1つの要素を持つノードセットを返します。
20160N番目の要素が存在しなければ、空のノードセットを返します。
20161@code{((node-pos 1) Nodeset)}は、ノードセットの先頭ノードがあればそれを選択します。
20162@code{((node-pos 2) Nodeset)}は、2番目のノードがあればそれを選択します。
20163@var{N}は負の数でも構いません。その場合、ノードはリストの末尾から数えられます。
20164@code{((node-pos -1) Nodeset)}は、空ではないノードセットの最後のノードを選択します。
20165@code{((node-pos -2) Nodeset)}は、最後から2番目のノードがあればそれを選択します。
20166@c COMMON
20167@end defun
20168
20169@defun sxml:filter pred?
20170@c MOD sxml.sxpath
20171
20172@example
20173 filter:: Converter -> Converter
20174@end example
20175
20176@c EN
20177A filter applicator, which introduces a filtering context. The argument
20178converter is considered a predicate, with either @code{#f}
20179or nil result meaning failure.
20180@c JP
20181フィルタリングを行う、フィルタアプリケータです。
20182引数のコンバータは、@code{#f}あるいはnilとなることが失敗を意味する述語と
20183みなされます。
20184@c COMMON
20185@end defun
20186
20187@defun take-until pred?
20188@c MOD sxml.sxpath
20189
20190@example
20191 take-until:: Converter -> Converter, or
20192 take-until:: Pred -> Node|Nodeset -> Nodeset
20193@end example
20194
20195@c EN
20196Given a converter-predicate and a nodeset, apply the predicate to
20197each element of the nodeset, until the predicate yields anything but
20198@code{#f} or nil. Return the elements of the input nodeset that have
20199been processed
20200till that moment (that is, which fail the predicate).
20201@code{take-until} is a variation of the filter above:
20202@code{take-until} passes
20203elements of an ordered input set till (but not including) the first
20204element that satisfies the predicate.
20205The nodeset returned by @code{((take-until (not pred)) nset)} is a subset --
20206to be more precise, a prefix -- of the nodeset returned by
20207@code{((filter pred) nset)}.
20208@c JP
20209述語としてのコンバータとノードセットが与えられると、
20210ノードセットの各要素に述語を適用し、
20211述語が@code{#f}あるいはnil以外を返すと、
20212(その述語が失敗した)その時点までに処理された要素を返します。
20213@code{take-until}は、上のフィルタのバリエーションの1つです。
20214@code{take-until}は、その述語を満足する最初の要素(それ自体は含まない)まで、
20215順序付けられた入力のセットの要素をパスします。
20216@code{((take-until (not pred)) nset)}により返されるノードセットは、
20217@code{((filter pred) nset)}により返されるノードセットのサブセット
20218-- 具体的には接頭辞 --になります。
20219@c COMMON
20220@end defun
20221
20222@defun take-after pred?
20223@c MOD sxml.sxpath
20224
20225@example
20226take-after:: Converter -> Converter, or
20227take-after:: Pred -> Node|Nodeset -> Nodeset
20228@end example
20229
20230@c EN
20231Given a converter-predicate and a nodeset, apply the predicate to
20232each element of the nodeset, until the predicate yields anything but
20233@code{#f} or
20234nil. Return the elements of the input nodeset that have not been processed:
20235that is, return the elements of the input nodeset that follow the first
20236element that satisfied the predicate.
20237@code{take-after} along with @code{take-until}
20238partition an input nodeset into three
20239parts: the first element that satisfies a predicate, all preceding
20240elements and all following elements.
20241@c JP
20242述語としてのコンバータとノードセットを与えると、
20243述語をノードセットの各要素に適用し、
20244述語が@code{#f}かnil以外を返すと、
20245まだ述語が適用されていない要素を返します。
20246つまり、述語を満足する最初の要素の後に続く要素を返します。
20247@code{take-after}と@code{take-until}を一緒に使うと、
20248入力のノードセットを3つのパート:
20249述語を満足する最初の要素、その要素の前の部分、その要素の後の部分に
20250分けます。
20251@c COMMON
20252@end defun
20253
20254@defun map-union proc lst
20255@c MOD sxml.sxpath
20256@c EN
20257Apply proc to each element of lst and return the list of results.
20258If proc returns a nodeset, splice it into the result.
20259
20260From another point of view,
20261@code{map-union} is a function Converter->Converter,
20262which places an argument-converter in a joining context.
20263@c JP
20264procをlstの各要素に適用し、結果のリストを返します。
20265procがノードセットを返す場合、それを結果につなぎ合わせます。
20266
20267別の観点から見ると、@code{map-union}はConverter->Converter関数で、
20268結合を行いたいコンテキストでの引数としてのコンバータに
20269位置します。
20270@c COMMON
20271@end defun
20272
20273@defun node-reverse node-or-nodeset
20274@c MOD sxml.sxpath
20275
20276@example
20277node-reverse :: Converter, or
20278node-reverse:: Node|Nodeset -> Nodeset
20279@end example
20280
20281@c EN
20282Reverses the order of nodes in the nodeset.
20283This basic converter is needed to implement a reverse document order
20284(see the XPath Recommendation).
20285@c JP
20286ノードセットでのノードの順番を逆順にします。
20287この基本的なコンバータは、逆順のドキュメントオーダーを実装するために
20288必要です。(XPath勧告を参照して下さい。)
20289@c COMMON
20290@end defun
20291
20292@defun node-trace title
20293@c MOD sxml.sxpath
20294
20295@example
20296 node-trace:: String -> Converter
20297@end example
20298
20299@c EN
20300@code{(node-trace title)} is an identity converter. In addition it prints out
20301a node or nodeset it is applied to, prefixed with the 'title'.
20302This converter is very useful for debugging.
20303@c JP
20304@code{(node-trace title)}は、それ自身を返すコンバータです。
20305また、自身が適用されるノードやノードセットを、'title'という
20306プリフィックスを付けてプリントします。
20307このコンバータは、デバッグの際にとても便利です。
20308@c COMMON
20309@end defun
20310
20311@c EN
20312What follow are Converter combinators,
20313higher-order functions that transmogrify a converter
20314or glue a sequence of converters into a single, non-trivial
20315converter. The goal is to arrive at converters that correspond to
20316XPath location paths.
20317
20318From a different point of view, a combinator is a fixed, named
20319@emph{pattern} of applying converters. Given below is a complete set of
20320such patterns that together implement XPath location path
20321specification. As it turns out, all these combinators can be built
20322from a small number of basic blocks: regular functional composition,
20323map-union and filter applicators, and the nodeset union.
20324@c JP
20325コンバータの組み合わせに続くものは、コンバータを一変させる、
20326あるいはコンバータのシーケンスを1つの強力なコンバータにつなぎ合わせる
20327高階関数です。そのゴールは、XPathのロケーションパスに対応する
20328コンバータとなることです。
20329
20330別の観点から見ると、コンバータは、コンバータ群の適用の固定され
20331名前の付いた@emph{パターン}とみなせます。
20332以下に挙げるのは、XPathのロケーションパスの仕様を実装する
20333そのようなパターンの完全なセットです。
20334結局のところ、これら全てのコンビネータはいくつかの基本的なブロック、
20335通常の関数的なコンポジション、map-unionとfilterアプリケータ、
20336ノードセットユニオンなどから構築することができます
20337@c COMMON
20338
20339@defun select-kids test-pred?
20340@c MOD sxml.sxpath
20341
20342@example
20343select-kids:: Pred -> Node -> Nodeset
20344@end example
20345@c EN
20346Given a Node, return an (ordered) subset its children that satisfy
20347the Pred (a converter, actually).
20348@c JP
20349ノードを与えると、述語(実際はコンバータ)を満足するその子要素の
20350(順序付けられた)サブセットを返します。
20351@c COMMON
20352
20353@example
20354select-kids:: Pred -> Nodeset -> Nodeset
20355@end example
20356@c EN
20357The same as above, but select among children of all the nodes in
20358the Nodeset.
20359@c JP
20360上と同じですが、ノードセットの全てのノードの子要素から選択します。
20361@c COMMON
20362@end defun
20363
20364@defun node-self pred
20365@c MOD sxml.sxpath
20366
20367@example
20368 node-self:: Pred -> Node -> Nodeset, or
20369 node-self:: Converter -> Converter
20370@end example
20371
20372@c EN
20373Similar to select-kids but apply to the Node itself rather
20374than to its children. The resulting Nodeset will contain either one
20375component, or will be empty (if the Node failed the Pred).
20376@c JP
20377select-kidsに似ていますが、自身をその子要素に適用するのでは
20378なく、ノードそれ自身に適用します。
20379結果のノードセットは、1つのコンポーネントを含むか、
20380空(ノードが述語を満足しない場合)になります。
20381@c COMMON
20382@end defun
20383
20384@defun node-join . selectors
20385@c MOD sxml.sxpath
20386
20387@example
20388 node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or
20389 node-join:: [Converter] -> Converter
20390@end example
20391
20392@c EN
20393join the sequence of location steps or paths as described
20394in the title comments above.
20395@c JP
20396上のタイトルコメントで説明されるようなロケーションステップ
20397あるいはロケーションパスのシーケンスをつなぎ合わせます。
20398@c COMMON
20399@end defun
20400
20401@defun node-reduce . converters
20402@c MOD sxml.sxpath
20403
20404@example
20405 node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or
20406 node-reduce:: [Converter] -> Converter
20407@end example
20408
20409@c EN
20410A regular functional composition of converters.
20411From a different point of view,
20412@code{((apply node-reduce converters) nodeset)}
20413is equivalent to
20414@code{(foldl apply nodeset converters)}
20415i.e., folding, or reducing, a list of converters with the nodeset
20416as a seed.
20417@c JP
20418コンバータの通常の関数的なコンポジションです。
20419見方を変えると、@code{((apply node-reduce converters) nodeset)}は
20420@code{(foldl apply nodeset converters)}と等価です。
20421すなわち、コンバータのリストをノードセットをseedとして畳み込みや分解
20422を行うようなものです。
20423@c COMMON
20424@end defun
20425
20426@defun node-or . converters
20427@c MOD sxml.sxpath
20428
20429@example
20430 node-or:: [Converter] -> Converter
20431@end example
20432
20433@c EN
20434This combinator applies all converters to a given node and
20435produces the union of their results.
20436This combinator corresponds to a union, '@code{|}' operation for XPath
20437location paths.
20438@c JP
20439このコンビネータは、全てのコンバータを与えられたノードに適用し、
20440それらの結果のユニオンを作ります。
20441このコンビネータは、XPathのロケーションパスでの'@code{|}'オペレーション
20442であるユニオンに対応します。
20443@c COMMON
20444@end defun
20445
20446@defun node-closure test-pred?
20447@c MOD sxml.sxpath
20448
20449@example
20450 node-closure:: Converter -> Converter
20451@end example
20452
20453@c EN
20454Select all @emph{descendants} of a node that satisfy a converter-predicate.
20455This combinator is similar to @code{select-kids} but applies to
20456grand... children as well.
20457This combinator implements the "@code{descendant::}" XPath axis.
20458Conceptually, this combinator can be expressed as
20459@c JP
20460述語としてのコンバータを満足するノードの全ての@emph{子孫}を選択します。
20461このコンビネータは@code{select-kids}に似ていますが、孫要素やその
20462子要素達にも適用を行います。
20463このコンビネータは、XPathの軸である``@code{descendant::}''を実装します。
20464概念的には、このコンビネータは以下のように表現することができます。
20465@c COMMON
20466@example
20467 (define (node-closure f)
20468      (node-or
20469        (select-kids f)
20470	 (node-reduce (select-kids (ntype?? '*)) (node-closure f))))
20471@end example
20472
20473@c EN
20474This definition, as written, looks somewhat like a fixpoint, and it
20475will run forever.  It is obvious however that sooner or later
20476@code{(select-kids (ntype?? '*))} will return an empty nodeset. At
20477this point further iterations will no longer affect the result and
20478can be stopped.
20479@c JP
20480この定義は、字面の通り、フィックスポイントのような何かで、
20481永久に実行し続けます。しかし、いつかは@code{(select-kids (ntype?? '*))}
20482が空のノードセットを返すことは明白です。その時点では、以降の
20483イテレーションはその結果に影響を及ぼさず停止されることができます。
20484@c COMMON
20485@end defun
20486
20487@c ----------------------------------------------------------------------
20488@node SXPath query language, SXPath extension, SXPath basic converters and applicators, SXML query language
20489@subsection SXPath query language
20490@c NODE SXPathクエリ言語
20491
20492@defun sxpath abbrpath . ns-binding
20493@c MOD sxml.sxpath
20494Evaluates an abbreviated SXPath. Returns a procedure that when applied
20495on a node or nodeset will return a nodeset matching the given path.
20496
20497@example
20498 sxpath:: AbbrPath -> Converter, or
20499 sxpath:: AbbrPath -> Node|Nodeset -> Nodeset
20500@end example
20501
20502@c COMMON
20503@var{AbbrPath} is a list or a string. If it is a list, it is
20504translated to the full SXPath according to the following rewriting
20505rules. More informal explanation follows shortly. If it is a string,
20506it is an XPath query.
20507
20508Note that these are abstract rules to show how it works, and not the
20509running code examples. The nonterminals @i{sxpath1} and @i{sxpathr}
20510don't exist as APIs. The term @i{txpath} is an internal function that
20511interprets XPath query given as a string.
20512
20513@c COMMON
20514@example
20515 (sxpath '()) -> (node-join)
20516 (sxpath '(path-component ...)) ->
20517                (node-join (@i{sxpath1} path-component) (sxpath '(...)))
20518 (@i{sxpath1} '//) -> (node-or
20519                     (node-self (ntype?? '*any*))
20520                     (node-closure (ntype?? '*any*)))
20521 (@i{sxpath1} '(equal? x)) -> (select-kids (node-equal? x))
20522 (@i{sxpath1} '(eq? x))    -> (select-kids (node-eq? x))
20523 (@i{sxpath1} '(or@@ ...))  -> (select-kids (ntype-names??
20524                                          (cdr '(or@@ ...))))
20525 (@i{sxpath1} '(not@@ ...)) -> (select-kids (sxml:invert
20526                                         (ntype-names??
20527                                          (cdr '(not@@ ...)))))
20528 (@i{sxpath1} '(ns-id:* x)) -> (select-kids
20529                                      (ntype-namespace-id?? x))
20530 (@i{sxpath1} ?symbol)     -> (select-kids (ntype?? ?symbol))
20531 (@i{sxpath1} ?string)     -> (@i{txpath} ?string)
20532 (@i{sxpath1} procedure)   -> procedure
20533 (@i{sxpath1} '(?symbol ...)) -> (@i{sxpath1} '((?symbol) ...))
20534 (@i{sxpath1} '(path reducer ...)) ->
20535                (node-reduce (sxpath path) (@i{sxpathr} reducer) ...)
20536 (@i{sxpathr} number)      -> (node-pos number)
20537 (@i{sxpathr} path-filter) -> (filter (sxpath path-filter))
20538@end example
20539
20540@c COMMON
20541
20542SXPath in its simplest form is a list of path components. The result
20543procedure will follow the same path and return the matching node
20544list. For example @code{(one two three)} will find element @code{one}
20545then @code{two} inside it and @code{three} inside element
20546@code{two}. The equivalent XPath would be @code{one/two/three}.
20547
20548There are a few special path components (see @code{ntype??} for the
20549complete list):
20550
20551@table @code
20552@item *
20553matches an element node.
20554@item //
20555matches any one or many consecutive path components.
20556@item *text*
20557matches a text node (@code{text()} in XPath).
20558@item *data*
20559matches any data node (e.g. text, number, boolean, etc.,
20560but not pair).
20561@item @@
20562selects the attribute list node.
20563@end table
20564
20565A path component could be a list in one of these forms:
20566
20567@table @code
20568@item (equal? x)
20569matches if the node under examination matches @var{x} using
20570@code{node-equal?}
20571@item (eq? x)
20572matches if the node under examination matches @var{x} using
20573@code{node-eq?}
20574@item (or@@ ...)
20575matches if the element name is one of the specified symbols.
20576@item (not@@ ...)
20577matches if the element name is not one of the specified symbols.
20578@item (ns-id:* x)
20579matches the node if it's with namespace @var{x}
20580@item (<path> n)
20581matches the @var{n}-th node matching same path component. @var{n}
20582starts from 1. Negative numbers start from the end of the node list
20583backward. This is @code{path[n]} syntax in XPath.
20584@item (<path> (<predicate>...))
20585matches a path component @var{path} and @code{(sxpath (<predicate>...))}
20586on those nodes are not empty. This is @code{path[predicate...]} syntax
20587in XPath.
20588@end table
20589
20590If the path component is a string, it is interpreted as an XPath query
20591string.
20592
20593If the path component is a procedure, the procedure takes three
20594arguments: the nodeset being examined, the root node and the variable
20595bindings.
20596
20597The root node is usually the entire sxml being applied. However if you
20598apply the result sxpath procedure with two arguments, root-node will
20599be the second argument.
20600
20601When applied with three arguments, the variable bindings are the third
20602one. This lets you pass arguments to the procedure.
20603
20604@c COMMON
20605
20606@smalllisp
20607;; select all <book> elements whose style attribute value is equal to
20608;; the <bookstore> element's specialty attribute value.
20609(sxpath "//book[/bookstore/@@specialty=@@style]")
20610;; a similar query but this time make sure specialty of _all_
20611;; bookstores is matched
20612(let ([match-specialty
20613       (lambda (node root var-binding)
20614         (let ([style (car ((sxpath '(@@ style *text*)) node))]
20615               [all-specialty ((sxpath '(bookstore @@ specialty *text*)) node)])
20616           (fold (lambda (specialty last-result)
20617                   (and last-result (string=? style specialty)))
20618                        #t
20619                        all-specialty)))])
20620  (sxpath `(// (book (,match-specialty)))))
20621
20622;; select all <bookstore> elements that are inside top-level <book>
20623;; element
20624(sxpath '(book bookstore))
20625;; select all <bookstore> elements from anywhere
20626(sxpath '(// bookstore))
20627;; select attribute "name" in the top-level <book> element
20628(sxpath '(book @@ name))
20629;; select all <bookstore> and <bookshop> elements that are inside
20630;; top-level <book> element
20631(sxpath '(book (or@@ bookstore bookshop)))
20632;; select all elements except <movie> that are inside top-level <book>
20633;; element
20634(sxpath '(book (not@@ movie @@)))
20635;; select the attribute "name" of the second <bookstore> element
20636(sxpath '(book (bookstore 2) @@ name))
20637;; select the attribute "name" of all <bookstore> elements that has
20638;; attribute "recommended"
20639(sxpath '(book (bookstore (@@ recommended)) @@ name))
20640;; select the attribute "name" of all <bookstore> elements whose
20641;; "rating" attribute is 3
20642(sxpath '(book (bookstore (@@ rating (eq? 3))) @@ name))
20643;; select the attribute "rating" whose value is greater than 3 from
20644;; all <bookstore> elements
20645(let ([greater (lambda (nodeset root-node var-binding)
20646                 (filter (lambda (node)
20647                           (> (string->number (sxml:string-value node))
20648                              3))
20649                         nodeset))])
20650  (sxpath `(book bookstore @@ rating ,greater)))
20651@end smalllisp
20652@end defun
20653
20654@c EN
20655Some wrapper functions around @code{sxpath}:
20656@c JP
20657@code{sxpath}には、いくつかのラッパ関数があります。
20658@c COMMON
20659
20660@defun if-sxpath path
20661@c MOD sxml.sxpath
20662@c EN
20663@code{sxpath} always returns a list, which is @code{#t} in Scheme.
20664@code{if-sxpath} returns @code{#f} instead of empty list.
20665@c JP
20666@code{sxpath}は、常にリストを返し、それはSchemeでは@code{#t}となります。
20667@code{if-sxpath}は、空リストの代わりに@code{#f}を返します。
20668@c COMMON
20669@end defun
20670
20671@defun if-car-sxpath path
20672@c MOD sxml.sxpath
20673@c EN
20674Returns first node found, if any.
20675Otherwise returns @code{#f}.
20676@c JP
20677もし存在すれば、最初に見つかったノードを返します。
20678そうでなければ、@code{#f}を返します。
20679@c COMMON
20680@end defun
20681
20682@defun car-sxpath path
20683@c MOD sxml.sxpath
20684@c EN
20685Returns first node found, if any.
20686Otherwise returns empty list.
20687@c JP
20688もし存在すれば、最初に見つかったノードを返します。
20689そうでなければ、空リストを返します。
20690@c COMMON
20691@end defun
20692
20693@defun sxml:id-alist node . lpaths
20694@c MOD sxml.sxpath
20695@c EN
20696Built an index as a list of
20697@code{(@var{ID_value} . @var{element})} pairs for given
20698node.  @var{lpaths} are location paths for attributes of type ID.
20699@c JP
20700与えられたノードについて、@code{(@var{ID_value} . @var{element})}の
20701ペアのリストをインデックスとして構築します。
20702@var{lpaths}は、タイプIDの属性のロケーションパスです。
20703@c COMMON
20704@end defun
20705
20706@c ----------------------------------------------------------------------
20707@node SXPath extension,  , SXPath query language, SXML query language
20708@subsection SXPath extension
20709@c NODE SXPathの拡張
20710
20711@c EN
20712SXML counterparts to W3C XPath Core Functions Library.
20713@c JP
20714W3CのXPathコア関数ライブラリのSXML版です。
20715@c COMMON
20716
20717@defun sxml:string object
20718@c MOD sxml.sxpath
20719@c EN
20720The counterpart to XPath @code{string} function (section 4.2 XPath Rec.)
20721Converts a given object to a string.
20722NOTE:
20723@c JP
20724XPathの@code{string}関数(XPath勧告のセクション4.2)に対応するものです。
20725与えられたオブジェクトを文字列に変換します。
20726注意:
20727@c COMMON
20728@enumerate
20729@item
20730@c EN
20731When converting a nodeset - a document order is not preserved
20732@c JP
20733ノードセットを変換する時は、ドキュメントオーダーは保持されません。
20734@c COMMON
20735@item
20736@c EN
20737@var{number->string} function returns the result in a form which is slightly
20738different from XPath Rec. specification
20739@c JP
20740@var{number->string}関数は、その結果をXPath勧告の仕様とは少し違った
20741フォームで返します。
20742@c COMMON
20743@end enumerate
20744@end defun
20745
20746@defun sxml:boolean object
20747@c MOD sxml.sxpath
20748@c EN
20749The counterpart to XPath @code{boolean} function (section 4.3 XPath Rec.)
20750Converts its argument to a boolean.
20751@c JP
20752XPathの@code{boolean}関数(XPath勧告のセクション4.3)に対応するものです。
20753引数を真偽値に変換します。
20754@c COMMON
20755@end defun
20756
20757@defun sxml:number obj
20758@c MOD sxml.sxpath
20759@c EN
20760The counterpart to XPath @code{number} function (section 4.4 XPath Rec.)
20761Converts its argument to a number
20762NOTE:
20763@c JP
20764XPathの@code{number}関数(XPath勧告のセクション4.4)に対応するものです。
20765引数を数値に変換します。
20766注意:
20767@c COMMON
20768@enumerate
20769@item
20770@c EN
20771The argument is not optional (yet?).
20772@c JP
20773引数は(まだ?)オプションではありません。
20774@c COMMON
20775@item
20776@c EN
20777@code{string->number} conversion is not IEEE 754 round-to-nearest.
20778@c JP
20779@code{string->number}の変換は、IEEE 754の四捨五入ではありません。
20780@c COMMON
20781@item
20782@c EN
20783NaN is represented as 0.
20784@c JP
20785NaNは、0として表現されます。
20786@c COMMON
20787@end enumerate
20788@end defun
20789
20790@defun sxml:string-value node
20791@c MOD sxml.sxpath
20792@c EN
20793Returns a string value for a given node in accordance to
20794XPath Rec. 5.1 - 5.7
20795@c JP
20796XPath勧告のセクション5.1 - 5.7にしたがって、与えられたノードの
20797文字列値を返します。
20798@c COMMON
20799@end defun
20800
20801
20802@defun sxml:node? node
20803@c MOD sxml.sxpath
20804@c EN
20805According to XPath specification 2.3, this test is true for any
20806XPath node.
20807For SXML auxiliary lists and lists of attributes has to be excluded.
20808@c JP
20809XPathの仕様2.3にしたがい、このテストはいかなるXPathノードに
20810対しても真を返します。
20811SXMLの補助的なリストや属性のリストは除外されます。
20812@c COMMON
20813@end defun
20814
20815@defun sxml:attr-list obj
20816@c MOD sxml.sxpath
20817@c EN
20818Returns the list of attributes for a given SXML node.
20819Empty list is returned if the given node is not an element,
20820or if it has no list of attributes
20821@c JP
20822与えられたSXMLノードの属性のリストを返します。
20823与えられたノードが要素ではないか、属性のリストを持っていない場合は、
20824空リストが返されます。
20825@c COMMON
20826@end defun
20827
20828@defun sxml:id id-index
20829@c MOD sxml.sxpath
20830@c EN
20831Select SXML element by its unique IDs.  (XPath Rec. 4.1)
20832Returns a converter that takes @var{object},
20833which is a nodeset or a datatype which can be converted to a string by means
20834of a '@code{string}' function.
20835
20836@var{id-index} is @code{( (id-value . element) (id-value . element) ... )}.
20837
20838This index is used for selection of an element by its unique ID.
20839@c JP
20840SXML要素を、そのユニークなIDによって選択します(XPath勧告 4.1)。
20841@var{object}を引数に取るコンバータを返します。
20842この@var{object}は、ノードセットか、'@code{string}'関数により
20843文字列に変換できるデータタイプです。
20844
20845@var{id-index}は、@code{( (id-value . element) (id-value . element) ... )}です。
20846
20847このインデックスは、要素をそのユニークなIDによって選択するために使われます。
20848@c COMMON
20849@end defun
20850
20851@c EN
20852Comparators for XPath objects:
20853@c JP
20854XPathオブジェクトの比較子:
20855@c COMMON
20856
20857@defun sxml:equality-cmp bool-op number-op string-op
20858@c MOD sxml.sxpath
20859@c EN
20860A helper for XPath equality operations: @code{=} , @code{!=}
20861@var{bool-op}, @var{number-op} and
20862@var{'string-op} are comparison operations for
20863a pair of booleans,  numbers and strings respectively.
20864@c JP
20865XPathの等値比較: @code{=}、@code{!=}のためのヘルパです。
20866@var{bool-op}、@var{number-op}、@var{'string-op}はそれぞれ、
20867真偽値、数値、文字列のペアのための比較子です。
20868@c COMMON
20869@end defun
20870
20871@defun sxml:equal? a b
20872@defunx sxml:not-equal? a b
20873@c MOD sxml.sxpath
20874@c EN
20875Counterparts of XPath equality operations: @code{=} , @code{!=},
20876using default equality tests.
20877@c JP
20878XPathの等値比較: @code{=}、@code{!=}に対応するもので、
20879デフォルトの等値テストを使います。
20880@c COMMON
20881@end defun
20882
20883@defun sxml:relational-cmp op
20884@c MOD sxml.sxpath
20885@c EN
20886Creates a relational operation ( @code{<} , @code{>} , @code{<=} , @code{>=} )
20887for two XPath objects.
20888@code{op} is comparison procedure: @code{<} , @code{>} , @code{<=} or @code{>=}.
20889@c JP
208902つのXPathオブジェクトの関係比較( @code{<}、@code{>}、@code{<=}、@code{>=} )
20891を作ります。
20892@code{op}は、比較を行う手続き: @code{<}、@code{>}、@code{<=}、@code{>=}です。
20893@c COMMON
20894@end defun
20895
20896@c EN
20897XPath axises.
20898An order in resulting nodeset is preserved.
20899@c JP
20900XPathの軸。
20901結果のノードセットにおける順序は維持されます。
20902@c COMMON
20903
20904@defun sxml:attribute test-pred?
20905@c MOD sxml.sxpath
20906@c EN
20907Attribute axis.
20908@c JP
20909属性の軸です。
20910@c COMMON
20911@end defun
20912
20913@defun sxml:child test-pred?
20914@c MOD sxml.sxpath
20915@c EN
20916Child axis.
20917This function is similar to '@code{select-kids}', but it returns an empty
20918child-list for PI, Comment and Entity nodes.
20919@c JP
20920子要素の軸です。
20921この関数は、'@code{select-kids}'に似ていますが、処理命令やコメント、
20922実体ノードについては、空の子リストを返します。
20923@c COMMON
20924@end defun
20925
20926@defun sxml:parent test-pred?
20927@c MOD sxml.sxpath
20928@c EN
20929Parent axis.
20930
20931Given a predicate, it returns a function
20932@code{RootNode -> Converter}
20933which yields a
20934@code{ node -> parent }
20935converter then applied to a rootnode.
20936
20937Thus, such a converter may be constructed using
20938@code{ ((sxml:parent test-pred) rootnode) }
20939and returns a parent of a node it is applied to.
20940If applied to a nodeset, it returns the
20941list of parents of nodes in the nodeset. The rootnode does not have
20942to be the root node of the whole SXML tree -- it may be a root node
20943of a branch of interest.
20944The @code{parent::} axis can be used with any SXML node.
20945@c JP
20946親の軸です。
20947
20948述語を与えると、@code{RootNode -> Converter}関数を返します。
20949この関数は、rootnodeに適用されると、@code{node -> parent}と
20950なります。
20951
20952このようなコンバータは、@code{ ((sxml:parent test-pred) rootnode) }
20953を使って構築され、それが適用されたノードの親を帰します。
20954ノードセットに適用された場合、そのノードセットにあるノードの
20955親のリストを返します。
20956rootnodeはSXMLツリー全体のルートノードである必要はありません。
20957興味の対象となるブランチ(枝)のルートノードでも構いません。
20958@code{parent::}軸は、どんなSXMLノードにも使えます。
20959@c COMMON
20960@end defun
20961
20962@defun sxml:ancestor test-pred?
20963@c MOD sxml.sxpath
20964@c EN
20965Ancestor axis
20966@c JP
20967祖先の軸です。
20968@c COMMON
20969@end defun
20970
20971@defun sxml:ancestor-or-self test-pred?
20972@c MOD sxml.sxpath
20973@c EN
20974Ancestor-or-self axis
20975@c JP
20976祖先と自分の軸です。
20977@c COMMON
20978@end defun
20979
20980@defun sxml:descendant test-pred?
20981@c MOD sxml.sxpath
20982@c EN
20983Descendant axis
20984@c JP
20985子孫の軸です。
20986@c COMMON
20987@end defun
20988
20989@defun sxml:descendant-or-self test-pred?
20990@c MOD sxml.sxpath
20991@c EN
20992Descendant-or-self axis
20993@c JP
20994子孫と自分の軸です。
20995@c COMMON
20996@end defun
20997
20998@defun sxml:following test-pred?
20999@c MOD sxml.sxpath
21000@c EN
21001Following axis
21002@c JP
21003後続するものの軸です。
21004@c COMMON
21005@end defun
21006
21007@defun sxml:following-sibling test-pred?
21008@c MOD sxml.sxpath
21009@c EN
21010Following-sibling axis
21011@c JP
21012後続する兄弟の軸です。
21013@c COMMON
21014@end defun
21015
21016@defun sxml:namespace test-pred?
21017@c MOD sxml.sxpath
21018@c EN
21019Namespace axis
21020@c JP
21021名前空間の軸です。
21022@c COMMON
21023@end defun
21024
21025@defun sxml:preceding test-pred?
21026@c MOD sxml.sxpath
21027@c EN
21028Preceding axis
21029@c JP
21030先行するものの軸です。
21031@c COMMON
21032@end defun
21033
21034@defun sxml:preceding-sibling test-pred?
21035@c MOD sxml.sxpath
21036@c EN
21037Preceding-sibling axis
21038@c JP
21039先行する兄弟の軸です。
21040@c COMMON
21041@end defun
21042
21043@c EN
21044Popular shortcuts:
21045@c JP
21046ポピュラーなショートカット:
21047@c COMMON
21048
21049@defun sxml:child-nodes nodeset
21050@c MOD sxml.sxpath
21051@example
21052((sxml:child sxml:node?) nodeset)
21053@end example
21054@end defun
21055
21056@defun sxml:child-elements nodeset
21057@c MOD sxml.sxpath
21058@example
21059((select-kids sxml:element?) nodeset)
21060@end example
21061@end defun
21062
21063
21064@c ----------------------------------------------------------------------
21065@node Manipulating SXML structure, Serializing XML and HTML from SXML, SXML query language, Library modules - Utilities
21066@section @code{sxml.tools} - Manipulating SXML structure
21067@c NODE SXML構造を操作する, @code{sxml.tools} - SXML構造を操作する
21068
21069@deftp {Module} sxml.tools
21070@mdindex sxml.tools
21071
21072@c EN
21073This module is a port of Kirill Lisofsky's sxml-tools,
21074a collection of convenient procedures that work on
21075SXML structure.
21076The current version is derived from sxml-tools CVS revision 3.13.
21077
21078The manual entry is mainly derived from the comments in the original
21079source code.
21080@c JP
21081現在のバージョンは、sxml-toolsのCVSのリビジョン3.13から導出されています。
21082
21083マニュアルのエントリは主に、オリジナルのソースコードから導出されています。
21084@c COMMON
21085@end deftp
21086
21087@c ----------------------------------------------------------------------
21088@menu
21089* SXML predicates::
21090* SXML accessors::
21091* SXML modifiers::
21092* SXPath auxiliary utilities::
21093* SXML to markup conversion::
21094@end menu
21095
21096@c ----------------------------------------------------------------------
21097@node SXML predicates, SXML accessors, Manipulating SXML structure, Manipulating SXML structure
21098@subsection SXML predicates
21099@c NODE SXMLの述語
21100
21101@defun sxml:empty-element? obj
21102@c MOD sxml.tools
21103@c EN
21104A predicate which returns @code{#t} if given element @var{obj} is empty.
21105Empty element has no nested elements, text nodes, @code{PI}s,
21106Comments or entities
21107but it may contain attributes or namespace-id.
21108It is a SXML counterpart of XML @code{empty-element}.
21109@c JP
21110与えられた要素@var{obj}が空なら@code{#t}を返す述語です。
21111空要素は、ネストした要素、テキストノード、@code{PI}、コメントや実体を
21112持ちませんが、属性や名前空間IDは持つかもしれません。
21113それは、XMLの@code{empty-element}のSXML版です。
21114@c COMMON
21115@end defun
21116
21117@defun sxml:shallow-normalized? obj
21118@c MOD sxml.tools
21119@c EN
21120Returns @code{#t} if the given @var{obj} is shallow-normalized SXML element.
21121The element itself has to be normalized but its nested elements are not tested.
21122@c JP
21123与えられた@var{obj}が浅く正規化されたSXML要素であれば@code{#t}を返します。
21124要素それ自体は正規化されていなければなりませんが、ネストした要素は
21125テストされません。
21126@c COMMON
21127@end defun
21128
21129@defun sxml:normalized? obj
21130@c MOD sxml.tools
21131@c EN
21132Returns @code{#t} if the given @var{obj} is normalized SXML element.
21133The element itself and all its nested elements have to be normalised.
21134@c JP
21135与えられた@var{obj}が正規化されたSXML要素であれば@code{#t}を返します。
21136要素それ自体とその全てのネストした要素が正規化されていなければなりません。
21137@c COMMON
21138@end defun
21139
21140@defun sxml:shallow-minimized? obj
21141@c MOD sxml.tools
21142@c EN
21143Returns @code{#t} if the given @var{obj} is shallow-minimized SXML element.
21144The element itself has to be minimised but its nested elements are not tested.
21145@c JP
21146与えられた@var{obj}が浅く最小化されたSXML要素であれば@code{#t}を返します。
21147要素それ自体は最小化されていなければなりませんが、そのネストした要素は
21148テストされません。
21149@c COMMON
21150@end defun
21151
21152@defun sxml:minimized? obj
21153@c MOD sxml.tools
21154@c EN
21155Returns @code{#t} if the given @var{obj} is minimized SXML element.
21156The element itself and all its nested elements have to be minimised.
21157@c JP
21158与えられた@var{obj}が最小化されたSXML要素であれば@code{#t}が返されます。
21159要素それ自体とその全てのネストした要素が最小化されていなければなりません。
21160@c COMMON
21161@end defun
21162
21163@c ----------------------------------------------------------------------
21164@node SXML accessors, SXML modifiers, SXML predicates, Manipulating SXML structure
21165@subsection SXML accessors
21166@c NODE SXMLへのアクセッサ
21167
21168@defun sxml:name obj
21169@c MOD sxml.tools
21170@c EN
21171Returns a name of a given SXML node.
21172It's just an alias of @code{car}, but introduced for the sake of encapsulation.
21173@c JP
21174与えられたSXMLノードの名前を返します。
21175これは単に@code{car}のエイリアスに過ぎませんが、カプセル化のために導入されています。
21176@c COMMON
21177@end defun
21178
21179@defun sxml:element-name obj
21180@c MOD sxml.tools
21181@c EN
21182A version of @code{sxml:name}, which returns @code{#f}
21183if the given @var{obj} is not a SXML element.
21184Otherwise returns its name.
21185@c JP
21186@code{sxml:name}の、与えられた@var{obj}がSXML要素ではない場合は@code{#f}を返す
21187バージョンです。@var{obj}がSXML要素であれば、その名前を返します。
21188@c COMMON
21189@end defun
21190
21191@defun sxml:node-name obj
21192@c MOD sxml.tools
21193@c EN
21194Safe version of @code{sxml:name}, which returns @code{#f}
21195if the given @var{obj} is not a SXML node.
21196Otherwise returns its name.
21197@c JP
21198@code{sxml:name}の、与えられた@var{obj}がSXMLノードでない場合は@code{#f}を返す、
21199安全なバージョンです。@var{obj}がSXMLノードであれば、その名前を返します。
21200@c COMMON
21201@end defun
21202
21203@defun sxml:ncname obj
21204@c MOD sxml.tools
21205@c EN
21206Returns Local Part of Qualified Name (Namespaces in XML production [6])
21207for given obj, which is "@code{:}"-separated suffix of its Qualified Name.
21208If a name of a node given is @code{NCName} (Namespaces in XML production [4]),
21209then it is returned as is.
21210Please note that while SXML name is a symbol this function returns a string.
21211@c JP
21212与えられたobjの完全修飾名(Namespaces in XML production [6])のローカルパート、
21213つまりその完全修飾名を``@code{:}''で分割した後ろの部分を返します。
21214与えられたノードの名前が@code{NCName}(Namespaces in XML production [4])であれば、
21215それをそのまま返します。
21216SXMLの名前はシンボルですが、この関数は文字列を返すことに注意して下さい。
21217@c COMMON
21218@end defun
21219
21220@defun sxml:name->ns-id sxml-name
21221@c MOD sxml.tools
21222@c EN
21223Returns namespace-id part of given name, or @code{#f} if it's LocalName
21224@c JP
21225与えられた名前の名前空間ID部分を返します。与えられた名前がLocalNameの
21226場合は@code{#f}を返します。
21227@c COMMON
21228@end defun
21229
21230@defun sxml:content obj
21231@c MOD sxml.tools
21232@c EN
21233Returns the content of given SXML element or nodeset (just text and element
21234nodes) representing it as a list of strings and nested elements in document
21235order.  This list is empty if @var{obj} is empty element or empty list.
21236@c JP
21237与えられたSXML要素かノードセット(テキストノードと要素ノードのみ)の内容を、
21238ドキュメントオーダーにしたがった文字列のリストとネストした要素として
21239返します。このリストは、@var{obj}が空要素や空リストの場合は空です。
21240@c COMMON
21241@end defun
21242
21243@defun sxml:content-raw obj
21244@c MOD sxml.tools
21245@c EN
21246Returns all the content of normalized SXML element except
21247@var{attr-list} and @var{aux-list}.
21248Thus it includes @code{PI}, @code{COMMENT} and @code{ENTITY}
21249nodes as well as @code{TEXT} and @code{ELEMENT} nodes
21250returned by @code{sxml:content}.
21251Returns  a list of nodes in document order or empty list if @var{obj} is empty
21252element or empty list.
21253This function is faster than @code{sxml:content}.
21254@c JP
21255正規化されたSXML要素の全ての内容を、@var{attr-list}と@var{aux-list}を除いて
21256返します。
21257したがってそれは、@code{PI}、@code{COMMENT}、@code{ENTITY}
21258ノードとともに、@code{sxml:content}によって返される@code{TEXT}や@code{ELEMENT}も含みます。
21259戻り値は、ドキュメントオーダーにしたがったノードのリストか、
21260@var{obj}が空要素や空リストの場合は空リストになります。
21261この関数は、@code{sxml:content}よりも高速です。
21262@c COMMON
21263@end defun
21264
21265@c EN
21266In SXML normal form, an element is represented by a list as this:
21267@c JP
21268SXMLの通常のフォームでは、1つの要素は次のようなリストで表現されます。
21269@c COMMON
21270@example
21271  (@var{name} @var{attr-list} @var{aux-list} @var{content} @dots{})
21272@end example
21273@c EN
21274where @var{attr-list} is a list beginning with @code{@@},
21275and @var{aux-list} is a list beginning with @code{@@@@}.
21276
21277In the minimized form,
21278@var{Aux-list} can be omitted when it is empty.
21279@var{Attr-list} can be omitted when it is empty @emph{and}
21280@var{aux-list} is absent.
21281
21282The following procedures extract @var{attr-list} and @var{aux-list}.
21283@c JP
21284@var{attr-list}は@code{@@}で始まるリストで、@var{aux-list}は@code{@@@@}で
21285始まるリストです。
21286
21287最小化されたフォームでは、@var{aux-list}は空であれば省略できます。
21288@var{attr-list}は、それが空で@emph{かつ}@var{aux-list}がなければ省略できます。
21289
21290以下の手続きは、@var{attr-list}と@var{aux-list}を抽出するものです。
21291@c COMMON
21292
21293@defun sxml:attr-list-node obj
21294@c MOD sxml.tools
21295@c EN
21296Returns @var{attr-list} for a given @var{obj},
21297or @code{#f} if it is absent
21298@c JP
21299与えられた@var{obj}の@var{attr-list}を返します。
21300@var{attr-list}が存在しなければ@code{#f}を返します。
21301@c COMMON
21302@end defun
21303
21304@defun sxml:attr-as-list obj
21305@c MOD sxml.tools
21306@c EN
21307Returns @var{attr-list} wrapped in list,
21308or '@code{((@@))} if it is absent and @var{aux-list} is present,
21309or '@code{()} if both lists are absent.
21310@c JP
21311@var{attr-list}をリストにラップして返します。
21312@var{attr-list}が存在せず@var{aun-list}がある場合は'@code{((@@))}を返します。
21313両方とも存在しない場合には'@code{()}を返します。
21314@c COMMON
21315@end defun
21316
21317@defun sxml:aux-list-node obj
21318@c MOD sxml.tools
21319@c EN
21320Returns @var{aux-list} for a given @var{obj},
21321or @code{#f} if it is absent.
21322@c JP
21323与えられた@var{obj}の@var{aux-list}を返します。
21324@var{attr-list}が存在しなければ@code{#f}を返します。
21325@c COMMON
21326@end defun
21327
21328@defun sxml:aux-as-list obj
21329@c MOD sxml.tools
21330@c EN
21331Returns @var{aux-list} wrapped in list,
21332or '@code{()} if it is absent.
21333@c JP
21334@var{aux-list}をリストにラップして返します。
21335@var{aux-list}が存在しなければ'@code{()}を返します。
21336@c COMMON
21337@end defun
21338
21339@defun sxml:attr-list-u obj
21340@c MOD sxml.tools
21341@c EN
21342Returns the list of attributes for given element or nodeset.
21343Analog of @code{((sxpath '(@@ *)) @var{obj})}.
21344Empty list is returned if there is no list of attributes.
21345
21346The @code{-u} suffix indicates it can be used for non-normalized
21347SXML node.  ('u' stands for 'universal').
21348@c JP
21349与えられた要素かノードセットの属性のリストを返します。
21350@code{((sxpath '(@@ *)) @var{obj})}と類似です。
21351属性のリストがない場合は空リストが返されます。
21352@c COMMON
21353@end defun
21354
21355@defun sxml:aux-list obj
21356@c MOD sxml.tools
21357@c EN
21358Returns the list of auxiliary nodes for given element or nodeset.
21359Analog of @code{((sxpath '(@@@@ *)) @var{obj})}.
21360Empty list is returned if a list of auxiliary nodes is absent.
21361@c JP
21362与えられた要素かノードセットの補助ノードのリストを返します。
21363@code{((sxpath '(@@@@ *)) @var{obj})}と類似です。
21364補助ノードのリストがない場合は空リストが返されます。
21365@c COMMON
21366@end defun
21367
21368@defun sxml:aux-list-u obj
21369@c MOD sxml.tools
21370@c EN
21371Returns the list of auxiliary nodes for given element or nodeset.
21372Analog of @code{((sxpath '(@@@@ *)) @var{obj})}.
21373Empty list is returned if a list of auxiliary nodes is absent.
21374
21375The @code{-u} suffix indicates it can be used for non-normalized
21376SXML node.  ('u' stands for 'universal').
21377@c JP
21378与えられた要素かノードセットの補助ノードのリストを返します。
21379@code{((sxpath '(@@@@ *)) @var{obj})}と類似です。
21380補助ノードのリストがない場合は空リストが返されます。
21381
21382@code{-u}が付くものは、正規化されていないSXMLノードに対しても
21383使えるということを示しています。('u'は'universal'の意味です。)
21384@c COMMON
21385@end defun
21386
21387@defun sxml:aux-node obj aux-name
21388@c MOD sxml.tools
21389@c EN
21390Return the first aux-node with @var{aux-name}
21391given in SXML element @var{obj}
21392or @code{#f} is such a node is absent.
21393Note: it returns just the @emph{first} node found even if multiple nodes are
21394present, so it's mostly intended for nodes with unique names .
21395@c JP
21396与えられたSXML要素@var{obj}で@var{aux-name}という名前の付いている最初の
21397補助ノードを返します。そのようなノードがない場合は@code{#f}を返します。
21398注意: 複数のノードがあっても@emph{最初に}見つかったノードのみを
21399返します。したがって、ユニークな名前を持っているノード群に対して
21400使われることを意図しています。
21401@c COMMON
21402@end defun
21403
21404@defun sxml:aux-nodes obj aux-name
21405@c MOD sxml.tools
21406@c EN
21407Return a list of aux-node with @var{aux-name}
21408given in SXML element @var{obj}
21409or '@code{()} if such a node is absent.
21410@c JP
21411与えられたSXML要素@var{obj}で@var{aux-name}とうい名前の付いている補助ノードの
21412リストを返します。そのようなノードがなければ'@code{()}を返します。
21413@c COMMON
21414@end defun
21415
21416@defun sxml:attr obj attr-name
21417@c MOD sxml.tools
21418@c EN
21419Accessor for an attribute @var{attr-name} of
21420given SXML element @var{obj}.
21421It returns:
21422the value of the attribute if the attribute is present, or
21423@code{#f} if there is no such an attribute in the given element.
21424@c JP
21425与えられたSXML要素@var{obj}の@var{attr-name}という属性へのアクセッサです。
21426戻り値は、その属性が存在すればその属性の値、与えられた要素に
21427そのような属性がなければ@code{#f}です。
21428@c COMMON
21429@end defun
21430
21431@defun sxml:num-attr obj attr-name
21432@c MOD sxml.tools
21433@c EN
21434Accessor for a numerical attribute @var{attr-name}
21435of given SXML element @var{obj}.
21436It returns:
21437a value of the attribute as the attribute as a number if the attribute
21438is present and its value may be converted to number using @code{string->number},
21439or @code{#f} if there is no such an attribute in the given element or
21440its value can't be converted to a number.
21441@c JP
21442与えられたSXML要素@var{obj}の@var{attr-name}という数値の属性への
21443アクセッサです。
21444戻り値は、その属性が存在してその値が@code{string->number}により数値へ
21445変換できる場合はその属性を数値としてその属性の値、
21446与えられた要素にそのような属性がないかその値が数値へ変換できない場合は
21447@code{#f}です。
21448@c COMMON
21449@end defun
21450
21451@defun sxml:attr-u obj attr-name
21452@c MOD sxml.tools
21453@c EN
21454Accessor for an attribute @var{attr-name}
21455of given SXML element @var{obj} which
21456may also be an attributes-list or nodeset (usually content of SXML element).
21457
21458It returns:
21459the value of the attribute if the attribute is present,
21460or @code{#f} if there is no such an attribute in the given element.
21461
21462The @code{-u} suffix indicates it can be used for non-normalized
21463SXML node.  ('u' stands for 'universal').
21464@c JP
21465与えられたSXML要素@var{obj}の@var{attr-name}という名前の属性への
21466アクセッサです。@var{obj}は、(通常はSXML要素の内容である)
21467属性リストやノードセットでも構いません。
21468
21469戻り値は、その属性が存在すればその属性の値、与えられた要素に
21470そのような属性がない場合は@code{#f}です。
21471
21472@code{-u}が付くものは、正規化されていないSXMLノードに対しても
21473使えるということを示しています。('u'は'universal'の意味です。)
21474@c COMMON
21475@end defun
21476
21477@defun sxml:ns-list obj
21478@c MOD sxml.tools
21479@c EN
21480Returns the list of namespaces for given element.
21481Analog of @code{((sxpath '(@@@@ *NAMESPACES* *)) @var{obj})}
21482Empty list is returned if there is no list of namespaces.
21483@c JP
21484与えられた要素の名前空間のリストを返します。
21485@code{((sxpath '(@@@@ *NAMESPACES* *)) @var{obj})}と類似です。
21486名前空間のリストがない場合は空リストが返されます。
21487@c COMMON
21488@end defun
21489
21490@defun sxml:ns-id->nodes obj namespace-id
21491@c MOD sxml.tools
21492@c EN
21493Returns the list of namespace-assoc's for given @var{namespace-id} in
21494SXML element @var{obj}.
21495Analog of @code{((sxpath '(@@@@ *NAMESPACES* namespace-id)) @var{obj})}.
21496Empty list is returned if there is no namespace-assoc with
21497@var{namespace-id} given.
21498@c JP
21499SXML要素@var{obj}で、与えられた@var{namespace-id}に対応する名前空間の
21500連想リストのリストを返します。
21501@code{((sxpath '(@@@@ *NAMESPACES* namespace-id)) @var{obj})}と類似です。
21502与えられた@var{namespace-id}に対応する名前空間の連想リストがない場合は
21503空リストが返されます。
21504@c COMMON
21505@end defun
21506
21507@defun sxml:ns-id->uri obj namespace-id
21508@c MOD sxml.tools
21509@c EN
21510Returns a URI for @var{namespace-id} given, or
21511@code{#f} if there is no namespace-assoc with @var{namespace-id} given.
21512@c JP
21513与えられた@var{namespace-id}に対応するURIを返します。
21514与えられた@var{namespace-id}に対応する名前空間の連想リストがない場合は
21515@code{#f}を返します。
21516@c COMMON
21517@end defun
21518
21519@defun sxml:ns-uri->id obj uri
21520@c MOD sxml.tools
21521@c EN
21522Returns a namespace-id for namespace URI given.
21523@c JP
21524与えられた名前空間URIに対応する名前空間IDを返します。
21525@c COMMON
21526@end defun
21527
21528@defun sxml:ns-id ns-assoc
21529@c MOD sxml.tools
21530@c EN
21531Returns namespace-id for given namespace-assoc list.
21532@c JP
21533与えられた名前空間連想リストに対応する名前空間IDを返します。
21534@c COMMON
21535@end defun
21536
21537@defun sxml:ns-uri ns-assoc
21538@c MOD sxml.tools
21539@c EN
21540Returns URI for given namespace-assoc list.
21541@c JP
21542与えられた名前空間連想リストに対応するURIを返します。
21543@c COMMON
21544@end defun
21545
21546@defun sxml:ns-prefix ns-assoc
21547@c MOD sxml.tools
21548@c EN
21549It returns namespace prefix for given namespace-assoc list.
21550Original (as in XML document) prefix for namespace-id given
21551has to be strored as the third element in namespace-assoc list
21552if it is different from namespace-id.
21553If original prefix is omitted in namespace-assoc then
21554namespace-id is used instead.
21555@c JP
21556与えられた名前空間連想リストに対応する名前空間接頭辞を返します。
21557与えられた名前空間IDの(XML文書における)オリジナルの接頭辞は、
21558それが名前空間IDと異なる場合は、名前空間連想リストの3番目の要素として
21559格納されなければなりません。
21560名前空間連想リストでオリジナルの接頭辞が省略されている場合は、
21561代わりに名前空間IDが使われます。
21562@c COMMON
21563@end defun
21564
21565@c ----------------------------------------------------------------------
21566@node SXML modifiers, SXPath auxiliary utilities, SXML accessors, Manipulating SXML structure
21567@subsection SXML modifiers
21568@c NODE SXMLのモディファイヤ
21569
21570@c EN
21571Constructors and mutators for normalized SXML data.
21572These functions are optimized for normalized SXML data.
21573They are not applicable to arbitrary non-normalized SXML data.
21574
21575Most of the functions are provided in two variants:
21576@c JP
21577正規化されたSXMLデータのコンストラクタやミューテータです。
21578これらの関数は、正規化されたSXMLデータに最適化されています。
21579任意の正規化されていないSXMLデータには適用できません。
21580
21581ほとんどの関数には2つのバージョンがあります。
21582@c COMMON
21583@enumerate
21584@item
21585@c EN
21586side-effect intended functions for linear update of given elements.
21587Their names are ended with exclamation mark.
21588Note that the returned value of this variant is unspecified,
21589unless explicitly noted.
21590An example: @code{sxml:change-content!}.
21591@c JP
21592与えられた要素のその場での更新のために副作用が意図された関数。
21593これらの名前はエクスクラメーションマークで終わっています。
21594このバージョンの戻り値は、特に断りのない限り未定義です。
21595例としては、@code{sxml:change-content!}が挙げられます。
21596@c COMMON
21597@item
21598@c EN
21599pure functions without side-effects which return modified elements.
21600An example: @code{sxml:change-content}.
21601@c JP
21602変更された要素を返す、副作用のない純粋な関数。
21603例としては、@code{sxml:change-content}が挙げられます。
21604@c COMMON
21605@end enumerate
21606
21607@defun sxml:change-content obj new-content
21608@defunx sxml:change-content! obj new-content
21609@c MOD sxml.tools
21610@c EN
21611Change the content of given SXML element to @var{new-content}.
21612If @var{new-content} is an empty list then the @var{obj} is transformed
21613to an empty element.
21614The resulting SXML element is normalized.
21615@c JP
21616与えられたSXML要素の内容を、@var{new-content}に変更します。
21617@var{new-content}が空リストの場合は、@var{obj}は空要素に変更されます。
21618結果のSXML要素は正規化されています。
21619@c COMMON
21620@end defun
21621
21622@defun sxml:change-attrlist obj new-attrlist
21623@defunx sxml:change-attrlist! obj new-attrlist
21624@c MOD sxml.tools
21625@c EN
21626The resulting SXML element is normalized.
21627If @var{new-attrlist} is empty,
21628the cadr of @var{obj} is @code{(@@)}.
21629@c JP
21630結果のSXML要素は正規化されています。
21631@var{new-attrlist}が空の場合は、@var{obj}のcadrは@code{(@@)}になります。
21632@c COMMON
21633@end defun
21634
21635@defun sxml:change-name obj new-name
21636@defunx sxml:change-name! obj new-name
21637@c MOD sxml.tools
21638@c EN
21639Change a name of SXML element destructively.
21640@c JP
21641SXML要素の名前を破壊的に変更します。
21642@c COMMON
21643@end defun
21644
21645@defun sxml:add-attr obj attr
21646@c MOD sxml.tools
21647@c EN
21648Returns SXML element @var{obj} with attribute @var{attr} added,
21649or @code{#f} if the attribute with given name already exists.
21650@var{attr} is @code{(@var{attr-name} @var{attr-value})}.
21651Pure functional counterpart to @code{sxml:add-attr!}.
21652@c JP
21653属性@var{attr}が追加されたSXML要素@var{obj}を返します。
21654与えられた名前の属性がすでに存在する場合は@code{#f}を返します。
21655@var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
21656@code{sxml:add-attr!}に対応する純粋関数的な関数です。
21657@c COMMON
21658@end defun
21659
21660@defun sxml:add-attr! obj attr
21661@c MOD sxml.tools
21662@c EN
21663Add an attribute @var{attr} for an element @var{obj}.
21664Returns @code{#f} if the attribute with given name already exists.
21665The resulting SXML node is normalized.
21666Linear update counterpart to @code{sxml:add-attr}.
21667@c JP
21668要素@var{obj}に属性@var{attr}を追加します。
21669与えられた名前の属性がすでに存在する場合は@code{#f}を返します。
21670結果のSXMLノードは正規化されています。
21671@code{sxml:add-attr}に対応するその場で更新する関数です。
21672@c COMMON
21673@end defun
21674
21675@defun sxml:change-attr obj attr
21676@c MOD sxml.tools
21677@c EN
21678Returns SXML element @var{obj} with changed value of
21679attribute @var{attr}, or @code{#f}
21680if where is no attribute with given name.
21681@var{attr} is @code{(@var{attr-name} @var{attr-value})}.
21682@c JP
21683属性@var{attr}の値が変更されたSXML要素@var{obj}を返します。
21684与えられた名前の属性がない場合は@code{#f}を返します。
21685@var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
21686@c COMMON
21687@end defun
21688
21689@defun sxml:change-attr! obj attr
21690@c MOD sxml.tools
21691@c EN
21692Change value of the attribute for element @var{obj}.
21693@var{attr} is @code{(@var{attr-name} @var{attr-value})}.
21694Returns @code{#f} if where is no such attribute.
21695@c JP
21696要素@var{obj}の属性の値を変更します。
21697@var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
21698そのような属性がない場合は@code{#f}を返します。
21699@c COMMON
21700@end defun
21701
21702@defun sxml:set-attr obj attr
21703@defunx sxml:set-attr! obj attr
21704@c MOD sxml.tools
21705@c EN
21706Set attribute @var{attr} of element @var{obj}.
21707If there is no such attribute the new one is added.
21708@c JP
21709要素@var{obj}の属性@var{attr}をセットします。
21710そのような属性がない場合は新しい属性として追加されます。
21711@c COMMON
21712@end defun
21713
21714@defun sxml:add-aux obj aux-node
21715@c MOD sxml.tools
21716@c EN
21717Returns SXML element @var{obj}
21718with an auxiliary node @var{aux-node} added.
21719@c JP
21720補助ノード@var{aux-node}が追加されたSXML要素@var{obj}を返します。
21721@c COMMON
21722@end defun
21723
21724@defun sxml:add-aux! obj aux-node
21725@c MOD sxml.tools
21726@c EN
21727Add an auxiliary node @var{aux-node} for an element @var{obj}.
21728@c JP
21729要素@var{obj}に補助ノード@var{aux-node}を追加します。
21730@c COMMON
21731@end defun
21732
21733@defun sxml:squeeze obj
21734@defunx sxml:squeeze! obj
21735@c MOD sxml.tools
21736@c EN
21737Eliminates empty lists of attributes and aux-lists for given SXML element
21738@var{obj} and its descendants ("minimize" it).
21739Returns a minimized and normalized SXML element.
21740@c JP
21741与えられたSXML要素@var{obj}とその子孫について、空のリストである属性
21742および補助リストを排除します(最小化)。
21743最小化され、正規化されたSXML要素が返されます。
21744@c COMMON
21745@end defun
21746
21747@defun sxml:clean obj
21748@c MOD sxml.tools
21749@c EN
21750Eliminates empty lists of attributes and all aux-lists for given SXML element
21751@var{obj} and its descendants.
21752Returns a minimized and normalized SXML element.
21753@c JP
21754与えられたSXML要素@var{obj}とその子孫について、空リストである属性と、
21755全ての補助リストを削除します。
21756最小化され、正規化されたSXML要素が返されます。
21757@c COMMON
21758@end defun
21759
21760@c ----------------------------------------------------------------------
21761@node SXPath auxiliary utilities, SXML to markup conversion, SXML modifiers, Manipulating SXML structure
21762@subsection SXPath auxiliary utilities
21763@c NODE SXPathの補助的ユーティリティ
21764
21765@c EN
21766These are convenience utilities to extend SXPath functionalities.
21767@c JP
21768これらは、SXPathの機能を拡張する便利なユーティリティです。
21769@c COMMON
21770
21771@defun sxml:add-parents obj . top-ptr
21772@c MOD sxml.tools
21773@c EN
21774Returns an SXML nodeset with a 'parent pointer' added.
21775A parent pointer is an aux node of the form @code{(*PARENT* @var{thunk})},
21776where @var{thunk} returns the parent element.
21777@c JP
21778SXMLノードセットに'親へのポインタ'を追加したものを返します。
21779親へのポインタは、@code{(*PARENT* @var{thunk})}というフォームを持つ
21780補助ノードです。@var{thunk}は親要素を返します。
21781@c COMMON
21782@end defun
21783
21784@defun sxml:node-parent rootnode
21785@c MOD sxml.tools
21786@c EN
21787Returns a fast 'node-parent' function, i.e.
21788a function of one argument - SXML element - which returns its parent
21789node using @code{*PARENT*} pointer in aux-list.
21790'@code{*TOP-PTR*} may be used as a pointer to root node.
21791It return an empty list when applied to root node.
21792@c JP
21793高速な'node-parent'関数を返します。
21794すなわち、SXML要素を1引数として取り、補助リストで
21795@code{*PARENT*}ポインタを使ってその親ノードを返す関数を返します。
21796'@code{*TOP-PTR*}はルートノードへのポインタとして使われます。
21797ルートノードに対して適用されると空リストを返します。
21798@c COMMON
21799@end defun
21800
21801@defun sxml:lookup id index
21802@c MOD sxml.tools
21803@c EN
21804Lookup an element using its ID.
21805@c JP
21806要素をそのIDを使って探します。
21807@c COMMON
21808@end defun
21809
21810@c ----------------------------------------------------------------------
21811@node SXML to markup conversion,  , SXPath auxiliary utilities, Manipulating SXML structure
21812@subsection SXML to markup conversion
21813@c NODE SXMLからマークアップへの変換
21814
21815@c EN
21816Procedures to generate XML or HTML marked up text from SXML.
21817For more advanced conversion, see the SXML serializer
21818(@ref{Serializing XML and HTML from SXML}).
21819
21820@c JP
21821SXMLからXMLやHTMLなどのマークアップされたテキストを生成する手続き。
21822もっと高尚な変換器を得たいだけならば、
21823@ref{Serializing XML and HTML from SXML}をチェックして下さい。
21824@c COMMON
21825
21826@defun sxml:clean-feed . fragments
21827@c MOD sxml.tools
21828@c EN
21829Filter the 'fragments'.
21830The fragments are a list of strings, characters,
21831numbers, thunks, @code{#f} -- and other fragments.
21832The function traverses the tree depth-first, and returns a list
21833of strings, characters and executed thunks,
21834and ignores @code{#f} and '@code{()}.
21835
21836If all the meaningful fragments are strings, then
21837@code{(apply string-append ... )}
21838to a result of this function will return its string-value.
21839
21840It may be considered as a variant of Oleg Kiselyov's
21841@code{SRV:send-reply}:
21842While @code{SRV:send-reply} displays fragments, this function returns the list
21843of meaningful fragments and filter out the garbage.
21844@c JP
21845'fragments'をフィルタします。
21846fragmentsは、文字列、文字、数値、手続き、@code{#f}、他のフラグメントの
21847リストです。
21848この関数はツリーを深さ優先でトラバースし、
21849文字列、文字、実行された手続きのリストを返し、
21850@code{#f}と'@code{()}を無視します。
21851
21852全ての意味のあるフラグメントは文字列で、
21853この関数の結果に@code{(apply string-append ... )}を
21854適用すると、そのstring-valueを返します。
21855
21856これは、Oleg Kiselyovの@code{SRV:send-reply}の変種であるとみなすことが
21857できるでしょう。
21858@code{SRV:send-reply}はフラグメントを印字(display)しますが、
21859この関数は意味のあるフラグメントのリストを返し、ごみをふるい落とします。
21860@c COMMON
21861@end defun
21862
21863@defun sxml:attr->xml attr
21864@c MOD sxml.tools
21865@c EN
21866Creates the XML markup for attributes.
21867@c JP
21868属性のXMLマークアップを作ります。
21869@c COMMON
21870@end defun
21871
21872@defun sxml:string->xml string
21873@c MOD sxml.tools
21874@c EN
21875Return a string or a list of strings where all the occurrences of
21876characters @code{<}, @code{>},
21877@code{&}, @code{"}, or @code{'} in a given string are
21878replaced by corresponding
21879character entity references. See also @code{sxml:string->html}.
21880@c JP
21881与えられた文字列中の全ての@code{<}、@code{>}、@code{&}、@code{``}、
21882@code{'}を対応する文字実体参照に置き換えた、文字列あるいは
21883文字列のリストを返します。
21884@code{sxml:string->html}も参照して下さい。
21885@c COMMON
21886@end defun
21887
21888@defun sxml:sxml->xml tree
21889@c MOD sxml.tools
21890@c EN
21891A version of dispatch-node specialized and optimized for SXML->XML
21892transformation.
21893@c JP
21894SXML->XML変換に特化され最適化されたバージョンのノードディスパッチです。
21895@c COMMON
21896@end defun
21897
21898@defun sxml:attr->html attr
21899@c MOD sxml.tools
21900@c EN
21901Creates the HTML markup for attributes.
21902@c JP
21903属性のHTMLマークアップを作ります。
21904@c COMMON
21905@end defun
21906
21907@defun sxml:string->html string
21908@c MOD sxml.tools
21909@c EN
21910Given a string, check to make sure it does not contain characters
21911@var{<}, @var{>}, @var{&},
21912@var{"} that require encoding.
21913See also @code{html-escape-string}
21914in @ref{Simple HTML document construction}.
21915@c JP
21916与えられた文字列で、それがエンコーディングを必要とする文字、
21917@var{<}、@var{>}、@var{&}、@var{``}を含まないことをチェックします。
21918@ref{Simple HTML document construction}の
21919@code{html-escape-string}も参照して下さい。
21920@c COMMON
21921@end defun
21922
21923@defun sxml:non-terminated-html-tag? tag
21924@c MOD sxml.tools
21925@c EN
21926This predicate yields @code{#t} for "non-terminated" HTML 4.0 tags.
21927@c JP
21928この述語は、``終了タグのない''HTML 4.0のタグに対して@code{#t}を
21929返します。
21930@c COMMON
21931@end defun
21932
21933@defun sxml:sxml->html tree
21934@c MOD sxml.tools
21935@c EN
21936A version of dispatch-node specialized and optimized for SXML->HTML
21937transformation.
21938@c JP
21939SXML->HTML変換に対して特化され最適化されたバージョンのノードディスパッチ
21940です。
21941@c COMMON
21942@end defun
21943
21944@c ----------------------------------------------------------------------
21945@node Serializing XML and HTML from SXML, Text terminal control, Manipulating SXML structure, Library modules - Utilities
21946@section @code{sxml.serializer} -  Serializing XML and HTML from SXML
21947@c NODE SXMLからXMLとXHTMLのシリアライゼーション, @code{sxml.serializer} - SXMLからXMLとXHTMLのシリアライゼーション
21948
21949@deftp {Module} sxml.serializer
21950@mdindex sxml.serializer
21951@c EN
21952This module contains a full-featured serializer from SXML into XML and
21953HTML, partially conforming to XSLT 2.0 and XQuery 1.0 Serialization
21954(@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/}).
21955It's more powerful than sxml:sxml->xml and sxml:sxml->html from
21956sxml.tools.
21957
21958The manual entry is mainly derived from the comments in the original
21959source code.
21960@c JP
21961このモジュールはSXMLからXMLとHTMLへの変換を行う、様々な機能を持つ
21962シリアライザを提供します。XSLT2.0とXQuery1.0に部分的に適合しています。
21963(@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/})。
21964sxml.toolsのsxml:sxml->xmlとsxml:sxml->htmlよりも強力です。
21965
21966マニュアルのエントリは主に、オリジナルのソースコードから取られてています。
21967@c COMMON
21968@end deftp
21969
21970@c ----------------------------------------------------------------------
21971@menu
21972* Simple SXML serializing::
21973* Custom SXML serializing::
21974@end menu
21975
21976@c ----------------------------------------------------------------------
21977@node Simple SXML serializing, Custom SXML serializing, Serializing XML and HTML from SXML, Serializing XML and HTML from SXML
21978@subsection Simple SXML serializing
21979@c NODE 簡単なSXML変換
21980
21981@c EN
21982The SXML serializer provides some convenient high-level converters which
21983should be enough for most tasks.
21984@c JP
21985高レベルの、簡単に使えるシリアライザです。大抵の目的にはこれで十分使えるでしょう。
21986@c COMMON
21987
21988@defun srl:sxml->xml sxml-obj :optional port-or-filename
21989@c MOD sxml.serializer
21990@c EN
21991Serializes the @var{sxml-obj} into XML, with indentation to facilitate
21992readability by a human.
21993
21994If @var{port-or-filename} is not supplied, the functions return a
21995string that contains the serialized representation of the
21996@var{sxml-obj}.
21997
21998If @var{port-or-filename} is supplied and is a port, the functions
21999write the serialized representation of @var{sxml-obj} to this port and
22000return an unspecified result.
22001
22002If @var{port-or-filename} is supplied and is a string, this string is
22003treated as an output filename, the serialized representation of
22004@var{sxml-obj} is written to that filename and an unspecified result
22005is returned. If a file with the given name already exists, the effect
22006is unspecified.
22007@c JP
22008@var{sxml-obj}をXMLへと変換します。出力は人間が読みやすいように
22009インデントされます。
22010
22011@var{port-or-filename}が与えられなければ、
22012戻り値は@var{sxml-obj}の変換結果の文字列になります。
22013
22014@var{port-or-filename}がポートならば、そのポートにXMLを書き出します。
22015戻り値は不定です。
22016
22017@var{port-or-filename}が文字列ならば、その名のファイルにXMLを書き出し
22018ます。戻り値は不定です。そのようなファイルが既に存在する場合、
22019結果は不定です。
22020@c COMMON
22021@end defun
22022
22023@defun srl:sxml->xml-noindent sxml-obj :optional port-or-filename
22024@c MOD sxml.serializer
22025@c EN
22026Serializes the @var{sxml-obj} into XML, without indentation.
22027
22028Argument @var{port-or-filename} works like described in
22029@code{srl:sxml->xml}.
22030@c JP
22031@code{srl:sxml->xml}と同じように動作しますが、インデントを行いません。
22032
22033引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
22034@c COMMON
22035@end defun
22036
22037@defun srl:sxml->html sxml-obj :optional port-or-filename
22038@c MOD sxml.serializer
22039@c EN
22040Serializes the @var{sxml-obj} into HTML, with indentation to
22041facilitate readability by a human.
22042
22043Argument @var{port-or-filename} works like described in @code{srl:sxml->xml}.
22044@c JP
22045@var{sxml-obj}をHTMLへと変換します。出力は人間が読みやすいように
22046インデントされます。
22047
22048引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
22049@c COMMON
22050@end defun
22051
22052@defun srl:sxml->html-noindent sxml-obj :optional port-or-filename
22053@c MOD sxml.serializer
22054@c EN
22055Serializes the @var{sxml-obj} into HTML, without indentation.
22056
22057Argument @var{port-or-filename} works like described in @code{srl:sxml->xml}.
22058@c JP
22059@code{srl:sxml->html}と同じように動作しますが、インデントを行いません。
22060
22061引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
22062@c COMMON
22063@end defun
22064
22065@c ----------------------------------------------------------------------
22066@node Custom SXML serializing,  , Simple SXML serializing, Serializing XML and HTML from SXML
22067@subsection Custom SXML serializing
22068@c NODE カスタムSXML変換
22069
22070@c EN
22071These functions provide full access to all configuration parameters of
22072the XML serializer.
22073@c JP
22074以下の手続きはXMLシリアライザの全ての設定パラメータへのアクセスを提供
22075します。
22076@c COMMON
22077
22078@defun srl:parameterizable sxml-obj :optional port-or-filename params*
22079@c MOD sxml.serializer
22080@c EN
22081Generalized serialization procedure, parameterizable with all the
22082serialization parameters supported by this implementation.
22083@c JP
22084汎用シリアライズ手続、この実装でサポートするすべてのシリアライズパラメー
22085タのパラメータ化。
22086@c COMMON
22087
22088@c EN
22089@var{sxml-obj} - an SXML object to serialize
22090@c JP
22091@var{sxml-obj} - シリアライズするSXMLオブジェクト。
22092@c COMMON
22093
22094@c EN
22095@var{port-or-filename} - either @code{#f}, a port or a string; works
22096like in srl:sxml->xml (@ref{Simple SXML serializing}).
22097@c JP
22098@var{port-or-filename} - @code{#f}あるいはポートあるいは文字列のどれか。
22099srl:sxml->xmlのものと同じ働きをします(@ref{Simple SXML serializing})。
22100@c COMMON
22101
22102@c EN
22103@var{params} - each parameter is a cons of param-name (a symbol) and
22104param-value.  The available parameter names and their values are
22105described below:
22106@c JP
22107@var{params} - 各パラメータはパラメータ名(シンボル)とパラメータ値との
22108コンス対。利用可能なパラメータ名とその値については後述。
22109@c COMMON
22110
22111@c EN
22112@code{method} - Either the symbol @code{xml} or @code{html}.  For a
22113detailed explanation of the difference between XML and HTML methods,
22114see XSLT 2.0 and XQuery 1.0 Serialization (@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/}).
22115@c JP
22116@code{method} - シンボル@code{xml}か@code{html}のどちらか。XMLメソッド
22117とHTMLメソッドの相違についての詳しい説明は、XSLT 2.0 と XQuery
22118Serialization
22119(@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/})
22120を参照してください。
22121@c COMMON
22122
22123@c EN
22124@code{indent} - Whether the output XML should include whitespace for
22125human readability (@code{#t} or @code{#f}).  You can also supply a
22126string, which will be used as the indentation unit.
22127@c JP
22128@code{indent} - 出力の XML が読みやすさのために空白を含むかどうか
22129(@code{#t}あるいは@code{#f})。文字列を設定することもでき、その場合
22130インデント単位に使われます。
22131@c COMMON
22132
22133@c EN
22134@code{omit-xml-declaration?} - Whether the XML declaration should be
22135omitted.  Default: @code{#t}.
22136@c JP
22137@code{omit-xml-declaration?} - XML宣言を省略するかどうか。デフォルトは
22138@code{#t}。
22139@c COMMON
22140
22141@c EN
22142@code{standalone} - Whether to define the XML document as standalone in
22143the XML declaration.  Should be one of the symbols @code{yes},
22144@code{no} or @code{omit}, the later causing standalone declaration to
22145be suppressed.  Default: @code{omit}.
22146@c JP
22147@code{standalone} - XML ドキュメントを XML 宣言でスタンドアローンとし
22148て定義するかどうか。@code{yes}、@code{no}、@code{omit}のうちいずれかの
22149シンボルでなければならない。デフォルトは @code{omit}
22150@c COMMON
22151
22152@c EN
22153@code{version} - The XML version used in the declaration.  A string or
22154a number.  Default: @code{"1.0"}.
22155@c JP
22156@code{version} - XML宣言中のXMLバージョン。文字列または数。デフォルト
22157は@code{"1.0"}。
22158@c COMMON
22159
22160@c EN
22161@code{cdata-section-elements} - A list of SXML element names (as
22162symbols).  The contents of those elements will be escaped as CDATA
22163sections.
22164@c JP
22165@code{cdata-section-elements} - SXML要素の名前(シンボル)のリスト。これ
22166らの要素の中身はCDATAセクションと同様にエスケープされる。
22167@c COMMON
22168
22169@c EN
22170@code{ns-prefix-assig} - A list of @code{(cons prefix namespace-uri)},
22171where each @code{prefix} is a symbol and each @code{namespace-uri} a
22172string.  Will serialize the given namespaces with the corresponding
22173prefixes.
22174@c JP
22175@code{ns-prefix-assig} - @code{(cons prefix namespace-uri)}のリスト。
22176各@code{prefix}はシンボルで、@code{namespace-uri}は文字列。
22177対応する接頭辞をつけて与えられた名前空間をシリアライズする。
22178@c COMMON
22179
22180@c EN
22181ATTENTION: If a parameter name is unexpected or a parameter value is
22182ill-formed, the parameter is silently ignored!
22183@c JP
22184注意: パラメータ名が期待された名前ではない場合、あるいはパラメータ値
22185が不正な形式である場合にはそのようなパラメータは警告なしで無視されます。
22186@c COMMON
22187
22188@c EN
22189Example usage:
22190
22191@lisp
22192(srl:parameterizable
22193  '(tag (@@ (attr "value")) (nested "text node") (empty))
22194  (current-output-port)
22195  '(method . xml)  ; XML output method is used by default
22196  '(indent . "\t")  ; use a single tabulation to indent
22197  '(omit-xml-declaration . #f)  ; add XML declaration
22198  '(standalone . yes)  ; denote a standalone XML document
22199  '(version . "1.0"))  ; XML version
22200@end lisp
22201@c JP
22202使用実例:
22203@lisp
22204(srl:parameterizable
22205  '(tag (@@ (attr "value")) (nested "text node") (empty))
22206  (current-output-port)
22207  '(method . xml)  ; XML出力をデフォールト
22208  '(indent . "\t")  ; インデントは一つのタブ
22209  '(omit-xml-declaration . #f)  ; XML宣言をつける
22210  '(standalone . yes)  ; 「standalone」宣言もつける
22211  '(version . "1.0"))  ; XMLのバージョン
22212@end lisp
22213@c COMMON
22214
22215@lisp
22216param ::= (cons param-name param-value)
22217param-name ::= symbol
22218
22219cdata-section-elements
22220value ::= (listof sxml-elem-name)
22221sxml-elem-name ::= symbol
22222
22223indent
22224value ::= 'yes | #t | 'no | #f | whitespace-string
22225
22226method
22227value ::= 'xml | 'html
22228
22229ns-prefix-assig
22230value ::= (listof (cons prefix namespace-uri))
22231prefix ::= symbol
22232namespace-uri ::= string
22233
22234omit-xml-declaration?
22235value ::= 'yes | #t | 'no | #f
22236
22237standalone
22238value ::= 'yes | #t | 'no | #f | 'omit
22239
22240version
22241value ::= string | number
22242@end lisp
22243@end defun
22244
22245@defun srl:sxml->string sxml-obj cdata-section-elements indent method ns-prefix-assig omit-xml-declaration? standalone version
22246@c MOD sxml.serializer
22247@c EN
22248Same as @code{srl:parameterizable} returning a string and without the
22249overhead of parsing parameters.  This function interface may change in
22250future versions of the library.
22251@c JP
22252@code{srl:parameterizable}と同様ですが、文字列を返し、パラメータ解析のオーバヘッ
22253ドはありません。この関数のインタフェースはこのライブラリの将来のバージョ
22254ンでは変更されるかもしれません。
22255@c COMMON
22256@end defun
22257
22258@defun srl:display-sxml sxml->obj port-or-filename cdata-section-elements indent method ns-prefix-assig omit-xml-declaration? standalone version
22259@c MOD sxml.serializer
22260@c EN
22261Same as @code{srl:parameterizable} writing output to
22262@var{port-or-filename} and without the overhead of parsing parameters.
22263This function interface may change in
22264future versions of the library.
22265@c JP
22266@code{srl:parameterizable}と同様ですが、結果を
22267@var{port-or-filename}に書き出します。パラメータ解析のオーバーヘッドはありません。
22268この関数のインタフェースはこの
22269ライブラリの将来のバージョンでは変更されるかもしれません。
22270@c COMMON
22271@end defun
22272
22273@c ----------------------------------------------------------------------
22274@node Text terminal control, CSV tables, Serializing XML and HTML from SXML, Library modules - Utilities
22275@section @code{text.console} - Text terminal control
22276@c NODE テキスト端末制御, @code{text.console} - テキスト端末制御
22277
22278@deftp {Module} text.console
22279@mdindex text.console
22280@c EN
22281This module provides a simple interface for character terminal control.
22282Currently we support vt100 compatible terminals and Windows
22283console.
22284
22285This module doesn't depend on external library such as @code{curses}
22286and works with Gauche alone, but
22287what it can do is limited; for example, you can't get an event
22288when shift key alone is pressed.  For finer controls, you need
22289some extension libraries.
22290
22291For an example of the features in this module, see
22292@file{snake.scm} in the examples directory of Gauche source distribution.
22293@c JP
22294このモジュールは文字端末を制御する簡単なインタフェースを提供します。
22295今のところ、vt100互換端末とWindowsコンソールがサポートされています。
22296
22297@code{curses}等の外部ライブラリには依存しておらず、Gaucheだけで使うことができますが、
22298出来ることは限られています。
22299例えばシフトキーだけが押されたタイミングでイベントを受け取ることはできません。
22300より細かい制御には、何らかの外部拡張ライブラリが必要になるでしょう。
22301
22302このモジュールの機能の例としては、
22303Gaucheソースのexamplesディレクトリにある@file{snake.scm}を見てください。
22304@c COMMON
22305@end deftp
22306
22307@c EN
22308@subheading Console objects
22309@c JP
22310@subheading コンソールオブジェクト
22311@c COMMON
22312
22313@deftp {Class} <vt100>
22314@clindex vt100
22315@c MOD text.console
22316@c EN
22317Represents a vt100-compatible terminal.   An instance of this class
22318can be passed to the ``console'' argument of the following generic
22319functions.
22320@c JP
22321vt100互換端末を表します。このクラスのインスタンスは
22322以降のジェネリックファンクションの ``console'' 引数に渡せます。
22323@c COMMON
22324
22325@defivar {<vt100>} iport
22326@c EN
22327Input port connected to the terminal.  The default value is
22328the standard input port.
22329@c JP
22330端末に接続されている入力ポートです。デフォルトは標準入力です。
22331@c COMMON
22332@end defivar
22333
22334@defivar {<vt100>} oport
22335@c EN
22336Output port connected to the terminal.  The default value is
22337the standard output port.
22338@c JP
22339端末に接続されている出力ポートです。デフォルトは標準出力です。
22340@c COMMON
22341@end defivar
22342
22343@defivar {<vt100>} input-delay
22344@c EN
22345The terminal send back special keys encoded in an input escape sequence.
22346In order to distinguish such keys from the actual ESC key, we time the
22347input---if the subsequent input doesn't come within @code{input-delay}
22348microseconds, we interpret the input as individual keystroke, rather
22349than a part of an escape sequence.  The default value is @code{1000} (1ms).
22350@c JP
22351端末は、特殊キーが押された場合、ESCから始まるエスケープシーケンスを送って来ます。
22352実際にESCキーが押された場合と区別するために、入力の間隔を測っています。
22353後続の入力が@code{input-delay}μs以内に来なかった場合はそこでシーケンスが終了したと
22354みなし、受け取っているシーケンスが有効なエスケープシーケンスを構成しなければ
22355個別にキー入力されたとみなします。デフォルトは@code{1000}、すなわち1msです。
22356@c COMMON
22357@end defivar
22358@end deftp
22359
22360@deftp {Class} <windows-console>
22361@clindex windows-console
22362@c EN
22363Represents Windows console.  This class is defined on all platforms,
22364but its useful methods are only available on Windows-native runtime.
22365
22366It doesn't have public slots.
22367@c JP
22368Windowsコンソールを表します。このクラス自体は全てのプラットフォームで
22369定義されていますが、有用なメソッドはWindowsネイティブのランタイムでしか提供されません。
22370
22371パブリックなスロットはありません。
22372@c COMMON
22373@end deftp
22374
22375@c EN
22376The application has to check the runtime to see what kind of console
22377is available.  A suggested flow is as follows.
22378@c JP
22379アプリケーションは実行時にどの種類のコンソールが利用可能かを見極めなければなりません。
22380推奨される手順は次のとおりです。
22381@c COMMON
22382@itemize
22383@item
22384@c EN
22385If @code{has-windows-console?} returns true, create @code{<windows-console>}
22386instance.
22387You don't need @code{cond-expand}; @code{has-windows-console?} returns
22388@code{#f} on non-Windows platforms.
22389@c JP
22390@code{has-windows-console?}が真の値を返したなら、@code{<windows-console>}の
22391インスタンスを作ります。
22392@code{has-windows-console?}はWindowsプラットフォーム以外では常に@code{#f}を
22393返すので、@code{cond-expand}は不要です。
22394@c COMMON
22395@item
22396@c EN
22397Check the environment variable @code{TERM}.  If it is set and
22398satisfies @code{vt100-compatible?}, you can create
22399@code{<vt100>} instance.
22400(Note: It is possible that you end up using @code{<vt100>} console
22401on Windows; e.g. @code{gosh} running on MSYS shell.)
22402@c JP
22403環境変数@code{TERM}を調べます。それが定義されていて、@code{vt100-compatible?}を
22404満たすなら、@code{<vt100>}のインスタンスを作ります。
22405(Windows上でも@code{<vt100>}端末を使うことになる可能性もあります。
22406例えば@code{gosh}がMSYSシェルから使われている場合です。)
22407@c COMMON
22408@item
22409@c EN
22410Otherwise, console isn't available.
22411@c JP
22412いずれでもなければ、端末は使えません。
22413@c COMMON
22414@end itemize
22415
22416@c EN
22417The following procedure packages this flow.
22418@c JP
22419次の手続きは上の手順を実装しています。
22420@c COMMON
22421
22422@defun make-default-console :key if-not-available
22423@c MOD text.console
22424@c EN
22425Determines a suitable console class of the running process and
22426returns its instance.
22427
22428If no suitable console is available, the behavior depends on the
22429@var{if-not-available} keyword argument.  If it is @code{:error},
22430which is default, an error is signalled.  If it is @code{#f},
22431the procedure returns @code{#f}.
22432@c JP
22433実行中のプロセスで使える端末のインスタンスを作成して返します。
22434
22435適切な端末クラスが無い場合、振る舞いは@var{if-not-available}キーワード引数に
22436依存します。デフォルトである@code{:error}の場合はエラーが報告されます。
22437@code{#f}の場合はこの手続きが@code{#f}を返します。
22438@c COMMON
22439@end defun
22440
22441@defun vt100-compatible? string
22442@c MOD text.console
22443@c EN
22444Given the string value of the environment variable @code{TERM},
22445returns @code{#t} if the terminal can be handled by @code{<vt100>} console,
22446@code{#f} otherwise.
22447@c JP
22448環境変数@code{TERM}の値を文字列で受け取り、それが@code{<vt100>}端末として
22449扱えるなら@code{#t}を、そうでなければ@code{#f}を返します。
22450@c COMMON
22451@end defun
22452
22453
22454@subheading Console control
22455
22456@deffn {Generic function} call-with-console console proc :key mode
22457@c MOD text.console
22458Takes over the control of the console, and calls @var{proc} with
22459@var{console} as the only argument.   The console is set to
22460the @var{mode}, which must be a symbol @code{with-terminal-mode}
22461accepts: @code{raw}, @code{rare} or @code{cooked}.  By default
22462the console is set to @code{rare} mode, which turn off the echoing
22463and passes most of keystrokes to the program, but it intercepts
22464terminal controls (like @code{Ctrl-C} for interrupt and
22465@code{Ctrl-Z} for suspend; the actual key depends on terminal
22466settings, though.)
22467
22468If @var{proc} raises an unhandled error, this generic function
22469resets the terminal mode before returning.  It does not clear
22470the screen.
22471@end deffn
22472
22473@deffn {Generic function} putch console char
22474@c MOD text.console
22475Display a character at the current cursor position, and
22476move the current cursor position.
22477@end deffn
22478
22479@deffn {Generic function} putstr console string
22480@c MOD text.console
22481Display a string from the current cursor position, and
22482move the current cursor position.
22483@end deffn
22484
22485@deffn {Generic function} beep console
22486@c MOD text.console
22487Ring the beep, or flash the screen (visible bell) if possible.
22488@end deffn
22489
22490@deffn {Generic function} getch console
22491@c MOD text.console
22492Fetch a keypress from the console.  This blocks until
22493any key is pressed.
22494
22495The return value may be one of the following values:
22496
22497@table @asis
22498@item A character
22499A key for the character is pressed.  It may be a control code
22500if the control key is pressed with the key; that is, if the user
22501presses Ctrl-A, @code{#\x01} will be returned.
22502@item A symbol
22503Indicates a special key; the following keys are supported:
22504@code{KEY_UP}, @code{KEY_DOWN}, @code{KEY_LEFT}, @code{KEY_RIGHT},
22505@code{KEY_HOME}, @code{KEY_END}, @code{KEY_INS}, @code{KEY_DEL},
22506@code{KEY_PGDN}, @code{KEY_PGUP}, @code{KEY_F1}, @code{KEY_F2},
22507@code{KEY_F3}, @code{KEY_F4}, @code{KEY_F5}, @code{KEY_F6},
22508@code{KEY_F7}, @code{KEY_F8}, @code{KEY_F9}, @code{KEY_F10},
22509@code{KEY_F11}, @code{KEY_F12}.
22510(Note: DELETE key is usually mapped to @code{#\x7f}, but it depends on
22511the terminal).
22512@item A list of symbol @code{ALT} and a character.
22513Indicates the character key is pressed with Alt key.  For example,
22514if the user presses Alt-a, @code{(ALT #\a)} is returned (assuming
22515CAPSLOCK is off).
22516@item EOF
22517Indicates the input is closed somehow.
22518@end table
22519
22520Modifier keys except @code{ALT} are not treated separately but
22521included in the returned keycode.  Assuming CAPSLOCK is off,
22522if the user press @code{a}, @code{Shift}+@code{a}, and @code{Ctrl}+@code{a},
22523the returned value is @code{#\a}, @code{#\A} and @code{#\x01}, respectively.
22524@code{Ctrl}+@code{Shift}+@code{a} can't be distinguished from
22525@code{Ctrl}+@code{a}.  @code{ALT}+@code{a}, @code{ALT}+@code{Shift}+@code{a},
22526and @code{ALT}+@code{Ctrl}+@code{a} will be @code{(ALT #\a)},
22527@code{(ALT #\A)} and @code{(ALT #\x01)}, respectively.
22528@end deffn
22529
22530@deffn {Generic function} chready? console
22531@c MOD text.console
22532Returns true if there's a key sequence to be read in the console's
22533input.
22534@end deffn
22535
22536@deffn {Generic function} query-cursor-position console
22537@c MOD text.console
22538Returns two values, the current cursor's x and y position.
22539The top-left corner is (0,0).
22540@end deffn
22541
22542@deffn {Generic function} move-cursor-to console row column
22543@c MOD text.console
22544Move cursor to the specified position.  The top-left corner is (0,0).
22545@end deffn
22546
22547@deffn {Generic function} reset-terminal console
22548@c MOD text.console
22549Reset terminal.  Usually this sets the
22550character attributes to the default,
22551clears the screen, and moves the cursor to (0, 0).
22552@end deffn
22553
22554@deffn {Generic function} clear-screen console
22555@c MOD text.console
22556Clear entire screen.
22557@end deffn
22558
22559@deffn {Generic function} clear-to-eol console
22560@c MOD text.console
22561Clear characters from the current cursor position to the
22562end of the line.
22563@end deffn
22564
22565@deffn {Generic function} clear-to-eos console
22566@c MOD text.console
22567Clear characters from the current cursor position to the
22568end of the screen.
22569@end deffn
22570
22571@deffn {Generic function} hide-cursor console
22572@deffnx {Generic function} show-cursor console
22573@c MOD text.console
22574Hide/show the cursor.
22575@end deffn
22576
22577@deffn {Generic function} cursor-down/scroll-up console
22578@c MOD text.console
22579If the cursor is at the bottom line of the screen,
22580scroll up the contents and clear the bottom line; the cursor stays
22581the same position.  If the cursor is not at the bottom line of
22582the screen, move the cursor down.
22583@end deffn
22584
22585@deffn {Generic function} cursor-up/scroll-down console
22586@c MOD text.console
22587If the cursor is at the top line of the screen,
22588scroll down the contents and clear the top line; the cursor stays
22589the same position.  If the cursor is not at the top line of
22590the screen, move the cursor up.
22591@end deffn
22592
22593@deffn {Generic function} query-screen-size console
22594@c MOD text.console
22595Returns two values, the width and height of the screen.
22596
22597Note: This may affect what's shown in the console.
22598It is recommended that you only call this before redrawing
22599the entire screen and save the result.
22600@end deffn
22601
22602@deffn {Generic function} set-character-attribute console spec
22603@c MOD text.console
22604Set the console so that the subsequent characters will be written
22605with attributes specified by @var{spec}.
22606
22607The character attributes spec is a list in the following format:
22608
22609@example
22610(<fgcolor> [<bgcolor> . <option> ...])
22611@end example
22612
22613where:
22614
22615@example
22616<fgcolor> : <color> | #f     ; #f means default
22617<bgcolor> : <color> | #f
22618<color>  : black | red | green | yellow | blue | magenta | cyan | white
22619<option> : bright | reverse | underscore
22620@end example
22621
22622For example, you can set characters to be written in red with
22623black background and underscore, you can call:
22624
22625@example
22626(set-character-attribute con '(red black underscore))
22627@end example
22628
22629That the options may seem rather limited in the age of
22630full-color bitmap displays.  That's what it used to be, young lads.
22631@end deffn
22632
22633@deffn {Generic function} reset-character-attribute console
22634@c MOD text.console
22635Reset character attributes to the default.
22636@end deffn
22637
22638@deffn {Generic function} with-character-attribute console attrs thunk
22639@c MOD text.console
22640Sets the console's attributes to @var{attrs} and calls @var{thunk},
22641then restores the attributes.  Even if @var{thunk} throws an error,
22642attributes are restored.
22643
22644Note: You should be able to nest this, but currently nesting
22645isn't working.
22646@end deffn
22647
22648
22649@c ----------------------------------------------------------------------
22650@node CSV tables, Calculate difference of text streams, Text terminal control, Library modules - Utilities
22651@section @code{text.csv} - CSV tables
22652@c NODE CSVテーブル, @code{text.csv} - CSVテーブル
22653
22654@deftp {Module} text.csv
22655@mdindex text.csv
22656@c EN
22657Provides a function to parse/generate CSV (comma separated value) tables,
22658including the format defined in RFC4180.  You can customize the
22659separator and quoter character to deal with variations of CSV formats.
22660
22661CSV table is consisted by a series of @var{records}, separated by
22662a newline.  Each record contains number of @var{fields}, separated
22663by a separator character (by default, a comma).  A field can contain
22664comma or newline if quoted, i.e. surrounded by double-quote characters.
22665To include double-quote character in a quoted field, use two
22666consecutive double-quote character.   Usually, the whitespaces around
22667the field are ignored.
22668@c JP
22669RFC4180に定義されたフォーマットを含む、
22670CSV (カンマ区切りの値) の表をパーズ/生成するための手続きを提供します。
22671区切り文字やクオート文字をカスタマイズすることで、CSVに似たフォーマットを
22672広くカバーすることができます。
22673
22674CSV の表は、改行で区切られた @var{record} の連続で構成されます。
22675それぞれのレコードは、区切り文字(デフォルトではカンマ)で区切られた
22676複数の @var{field} を含みます。フィールドは、クォートされている
22677(二重引用符で囲まれている)場合は、カンマや改行を含むことができます。
22678クォートされたフィールドに二重引用符を含めるには、2つの連続する
22679二重引用符を使います。通常、フィールドの前後の空白は無視されます。
22680@c COMMON
22681
22682@c EN
22683Since use cases of CSV-like files vary, we provide layered API
22684to be combined flexibly.
22685@c JP
22686CSV様のファイルの使われ方は多様なので、このモジュールでは柔軟に組み合わせることが出来る
22687多層的なAPIを提供します。
22688@c COMMON
22689@end deftp
22690
22691@c EN
22692@subheading Low-level API
22693@c JP
22694@subheading 低レベルAPI
22695@c COMMON
22696
22697@c EN
22698The bottom layer of API is to convert text into list of lists and vice versa.
22699@c JP
22700一番下の層のAPIは、テキストとリストのリストとを相互変換するものです。
22701@c COMMON
22702
22703@defun make-csv-reader separator :optional (quote-char #\")
22704@c MOD text.csv
22705@c EN
22706Returns a procedure with one optional argument, an input port.
22707When the procedure is called, it reads one record from the port
22708(or, if omitted, from the current input port)
22709and returns a list of fields.
22710If input reaches EOF, it returns EOF.
22711@c JP
22712入力ポートを省略可能引数として取る手続きを返します。
22713手続きが呼ばれると、ポート(省略された場合は現在の入力ポート)からレコードを1つ読み込み、
22714フィールドのリストを返します。入力ポートが EOF に達すると、EOF を返します。
22715@c COMMON
22716@end defun
22717
22718@defun make-csv-writer separator :optional newline (quote-char #\") special-char-set
22719@c MOD text.csv
22720@c EN
22721Returns a procedure with two arguments, output port and
22722a list of fields.  When the procedure is called, it
22723outputs a @var{separator}-separated fields with proper escapes,
22724to the output port.   Each field value must be a string.
22725The separator argument can be a character or a string.
22726@c JP
22727出力ポートとフィールドのリストの2つの引数を取る手続きを返します。
22728手続きが呼ばれると、@var{separator} で区切られたフィールドを
22729正しくエスケープして出力ポートに出力します。各フィールドの値は文字列でなければなりません。
22730@var{separator}は文字または文字列です。
22731@c COMMON
22732
22733@c EN
22734You can also specify the record delimiter
22735string by @var{newline}; for example, you can pass @code{"\r\n"}
22736to prepare a file to be read by Windows programs.
22737@c JP
22738レコードの区切り文字列を@var{newline} で指定することもできます。例えば、ファイルが Windows の
22739プログラムでも読めるように、@code{"\r\n"} を渡すことができます。
22740@c COMMON
22741
22742@c EN
22743The output of field is quoted when it contains special characters---
22744which automatically includes characters
22745in @var{separator}, @var{quote-char} and @var{newline} argument,
22746plus the characters in the char-set given to @var{special-char-set};
22747its default is @code{#[;\s]}.
22748@c JP
22749フィールドの出力は、その中に特殊文字が含まれていた場合にクオートされます。
22750@var{separator}, @var{quote-char}, @var{newline}に含まれる文字は
22751自動的に特殊文字と認識されます。さらに
22752@var{special-char-set}に文字集合を渡すと、それも特殊文字として扱われます。
22753省略時は@code{#[;\s]}が使われます。
22754@c COMMON
22755@end defun
22756
22757@c EN
22758@subheading Middle-level API
22759@c JP
22760@subheading 中レベルAPI
22761@c COMMON
22762
22763@c EN
22764Occasionally, CSV files generated from spreadsheet contains
22765superfluous rows/columns and we need to make sense of them.
22766Here are some utilities to help them.
22767@c JP
22768スプレッドシート等で作成されたCSVファイルはしばしば、
22769不要な行や列を含んでいたり、
22770行や列の内容から有効なデータの場所を探したりする必要があります。
22771そのために役に立つユーティリティが用意してあります。
22772@c COMMON
22773
22774@c EN
22775A typical format of such spreadsheet-generated CSV file has
22776the following properties:
22777@c JP
22778スプレッドシート等によって生成される典型的なCSVには以下の特徴があります。
22779@c COMMON
22780
22781@enumerate
22782@item
22783@c EN
22784There's a ``header row'' near the top; not necessarily the very
22785first row, but certainly it comes before any real data.  It signifies
22786the meaning of each column of the data.
22787There may be superfluous columns inserted just for cosmetics,
22788and sometimes the order of columns are changed when the original spreadsheet
22789is edited.  So we need some
22790flexibility to interpret the input data.
22791@c JP
22792最初の方に、「ヘッダ行」があります。一番最初の行とは限りませんが、
22793データの実体より前に現れ、データの各列の意味を決めます。
22794しばしば、見た目のためだけに余分な列が挿入されたり、
22795編集によって列が入れ替わったりすることもあるので、
22796ヘッダ行を見てどの列に何があるか判断する必要があります。
22797@c COMMON
22798
22799@item
22800@c EN
22801``Record rows'' follow the header row.  It contains actual data.
22802There may be superfluous rows inserted just for cosmetics.
22803Also, it's often the case that the end of data isn't marked clearly
22804(you find large number of rows of empty strings, for example).
22805@c JP
22806ヘッダ行の後に続く「レコード行」。ここにデータの実体があります。
22807見た目のためだけに余分な行が挿入されていることもあります。
22808また、データの終わりがきちんと示されていないことも多いです (例えば、
22809CSVの末尾に全ての列が空文字列である行がぞろぞろとくっついている、等。)
22810@c COMMON
22811@end enumerate
22812
22813@c EN
22814The main purpose of middle-level CSV parser is to take the output
22815of low-level parser, which is a list of lists of strings, and
22816find the header row, and then convert the subsequent record rows
22817into tuples according to the header row.  A tuple is just a list of
22818strings, but ordered in the same way as the specified header spec.
22819@c JP
22820中レベルCSVパーザの主目的は、低レベルパーザの出力である文字列のリストのリストを
22821受け取って、ヘッダ行を探し出し、続くレコード行をヘッダ行の内容に沿って
22822タプルに変換することにあります。ここで、タプルは単なる文字列のリストですが、
22823指定されたヘッダ仕様に沿った順序で並べてあるものとします。
22824@c COMMON
22825
22826@defun csv-rows->tuples rows header-specs :key required-slots allow-gap?
22827@c MOD text.csv
22828@c EN
22829Convert input rows (a list of lists of strings)
22830to a list of tuples.
22831A tuple is a list of slot values.
22832
22833First, it looks for a header row that
22834matches the given @var{header-spec}.  Once the header row is found,
22835parse the subsequent rows as record row according to the header
22836and convert them to tuples.
22837If no header is found, @code{#f} is returned.
22838@c JP
22839入力行(文字列のリスト)のリストを、タプルのリストに変換します。
22840タプルはスロットの値のリストです。
22841
22842まず@var{header-spec}にマッチするヘッダ行が探されます。ヘッダ行が見つかったら、
22843それにしたがって後続の行をレコード行として解釈し、各行をタプルへと変換します。
22844ヘッダ行が見つからなければ、@code{#f}が返されます。
22845@c COMMON
22846
22847@c EN
22848@var{Header-specs} is a list of header spec, each of which can be either
22849a string, a regexp, or a predicate on a string.  If it's a string,
22850a column that exactly matches the string is picked.  If it's a regexp,
22851a column that matches the regexp is picked.  And if it's a predicate,
22852as you might have already guessed, a column that satisfies the predicate
22853is picked.
22854
22855The order fo @var{header-specs} determines the order of columns of
22856output tuples.
22857@c JP
22858@var{header-specs}はヘッダ仕様のリストです。各要素は文字列、正規表現、
22859あるいは文字列を取る述語手続きのいずれかです。文字列の場合、その文字列と正確に
22860一致する内容を持つ列が選ばれます。正規表現なら内容がそれと一致する列、
22861述語手続きなら、内容がその述語を満たすような列がそれぞれ選ばれます。
22862
22863@var{header-specs}に現れる順番が、出力タプルの列の順番を決めます。
22864@c COMMON
22865
22866@c EN
22867@var{Required-slots} determines if the input row is a valid record row
22868or not.  The structure of @var{required-slots} is as follows:
22869@c JP
22870@var{required-slots}は、入力行が有効なレコード行かそうでないかを決めます。
22871@var{required-slots}の構造は以下のとおりです。
22872@c COMMON
22873
22874@example
22875   <required-slots> : (<spec> ...)
22876   <spec> : <header-spec> | (<header-spec> <predicate>)
22877@end example
22878
22879@c EN
22880The @code{<header-spec>} compared to the elements of @var{header-slot}
22881(by @code{equal?}) to figure out which columns to check.  A single
22882@code{<header-spec>} in @code{<spec>} means that the column shouldn't be
22883empty for a valid record row.  If @var{<spec>} is a list of
22884@code{<header-spec>} and @code{<predicate>}, then the value of the
22885column corresponds to the @var{<header-spec>} is passed to @var{<predicate>}
22886to determine if it's a valid record row.
22887
22888If @var{required-slots} is omitted or an empty list, any row with
22889at least one non-empty column to be included in the tuple.
22890@c JP
22891@code{<header-spec>}はどの列の要素をチェックすべきかを指定します。
22892@var{header-slot}に現れる要素のいずれかと@code{equal?}でなければなりません。
22893@code{<header-spec>}だけが@code{<spec>}として与えられていた場合は、
22894その列が空であってはいけない、ということを意味します。
22895@code{<header-spec>}と@code{<predicate>}が与えられた場合は、
22896レコード行の該当列の値(文字列)が述語手続き@code{<predicate>}に与えられ、
22897それが偽を返したらその行は有効でないということになります。
22898@c COMMON
22899
22900@c EN
22901If @var{allow-gap?} is @code{#t}, it keeps reading rows until the end,
22902skipping invalid rows.  If @var{allow-gap?} is @code{#f} (default),
22903it stops reading once it sees an invalid row after headers.
22904@c JP
22905@var{allow-gap?}が@code{#t}であった場合、無効な行を飛ばしながら、
22906入力データは最後まで処理されます。@var{allow-gap?}が@code{#f}であった場合(デフォルト)は、
22907無効な行が出てきた時点で処理を打ちきります。
22908@c COMMON
22909
22910@c EN
22911Let's see an example.  Suppose we have the following CSV file as
22912@file{data.csv}.  It has extra rows and columns, as is often seen
22913in spreadsheet-exported files.
22914@c JP
22915例を見てみましょう。次のデータが@file{data.csv}というファイルに書かれているとします。
22916スプレッドシートからエクスポートされるデータによくあるように、不要な行や列が混ざっています。
22917@c COMMON
22918
22919@smallexample
22920,,,,,,,,
22921"Exported data",,,,,,,,
22922,,,,,,,,
22923,,Year,Country,,Population,GDP,,Note
22924,,1958,"Land of Lisp",,39994,"551,435,453",,
22925,,1957,"United States of Formula Translators",,115333,"4,343,225,434",,Estimated
22926,,1959,"People's Republic of COBOL",,82524,"3,357,551,143",,
22927,,1970,"Kingdom of Pascal",,3785,,,"GDP missing"
22928,,,,,,,,
22929,,1962,"APL Republic",,1545,"342,335,151",,
22930@end smallexample
22931
22932@c EN
22933You can extract tuples of Country, Year, GDP and Population,
22934as follows:
22935@c JP
22936ここから、Country, Year, GDP, Populationの値からなるタプルのリストを
22937次のとおり取り出せます。
22938@c COMMON
22939
22940@smallexample
22941(use text.csv)
22942(use gauche.generator)
22943
22944(call-with-input-file "data.csv"
22945  (^p (csv-rows->tuples
22946       (generator->list (cute (make-csv-reader #\,) p))
22947       '("Country" "Year" "GDP" "Population"))))
22948 @result{}
22949  (("Land of Lisp" "1958" "551,435,453" "39994")
22950   ("United States of Formula Translators" "1957" "4,343,225,434" "115333")
22951   ("People's Republic of COBOL" "1959" "3,357,551,143" "82524")
22952   ("Kingdom of Pascal" "1970" "" "3785"))
22953@end smallexample
22954
22955@c EN
22956Note that irrelevant rows are skipped, and columns in the results
22957are ordered as specified in the @var{header-specs}.
22958@c JP
22959無関係な行は無視されており、また結果の列は@var{header-specs}に渡した順序に
22960整列されていることに注目してください。
22961@c COMMON
22962
22963@c EN
22964Since there's a gap (empty row) after the ``Kingdom of Pascal'' entry,
22965@code{csv-rows->tuples} stops processing there by default.  If you want
22966to include ``APL Republic'', you have to pass @code{:allow-gap? #t}
22967to @code{csv-rows->tuples}.
22968@c JP
22969``Kingdom of Pascal''の列の後にギャップ(空の列)があるため、
22970@code{csv-rows->tuples}はそこで処理を打ち切っています。
22971ギャップの後の``APL Republic''まで含めたければ、@code{csv-rows->tuples}に
22972@code{:allow-gap? #t}を渡してください。
22973@c COMMON
22974
22975@c EN
22976The next example gives @code{:required-slots} option to eliminate
22977rows with missing some of Year, Country or GDP---thus ``Kingdom of Pascal''
22978is omitted from the result, while ``APL Republic'' is included
22979because of @code{:allow-gap?} argument.
22980(It also checks Year has exactly 4 digits.)
22981@c JP
22982次の例では、@code{:required-slots}引数を与えて、
22983Year、Country、GDPのデータの一つ以上が欠けている行を除外しています。
22984したがって``Kingdom of Pascal''は結果から除かれます。一方、
22985@code{:allow-gap?}引数のために``APL Republic''が含まれます。
22986(この例ではYearが4桁ぴったりの数値であるかどうかもチェックしています。)
22987@c COMMON
22988
22989@smallexample
22990(call-with-input-file "data.csv"
22991  (^p (csv-rows->tuples
22992       (generator->list (cute (make-csv-reader #\,) p))
22993       '("Country" "Year" "GDP" "Population")
22994        :required-slots '(("Year" #/^\d@{4@}$/) "Country" "GDP")
22995        :allow-gap? #t)))
22996 @result{}
22997 (("Land of Lisp" "1958" "551,435,453" "39994")
22998  ("United States of Formula Translators" "1957" "4,343,225,434" "115333")
22999  ("People's Republic of COBOL" "1959" "3,357,551,143" "82524")
23000  ("APL Republic" "1962" "342,335,151" "1545"))
23001@end smallexample
23002@end defun
23003
23004@c EN
23005The following two procedures are ingredients of
23006@code{csv-rows->tuples}:
23007@c JP
23008以下の二つの手続きは@code{csv-rows->tuples}の材料です。
23009@c COMMON
23010
23011
23012@defun make-csv-header-parser header-specs
23013@c MOD text.csv
23014@c EN
23015Create a procedure that takes a row (a list of strings) and checks if
23016if it matches the criteria specified by @var{header-specs}.
23017(See @code{csv-rows->tuples} above about @var{header-specs}.)
23018If the input satisfies the spec, it returns a permuter vector that maps
23019the tuple positions to the input column numbers.
23020Otherwise, it returns @code{#f}.
23021@c JP
23022行(文字列のリスト)を受け取り、それが@var{header-specs}で指定される条件に
23023一致するかどうかを調べます。
23024(@var{header-specs}については上の@code{csv-rows->tuples}を見てください。)
23025もし引数が条件を満たしたなら、置換ベクタを返します。
23026置換ベクタはタプルの位置を入力行の列番号へとマップするもので。
23027一致しなかった場合は@code{#f}を返します。
23028@c COMMON
23029
23030@c EN
23031The permuter vector is a vector of integers,
23032where K-th element being I means the K-th item of the tuple should be
23033taken from I-th column.
23034@c JP
23035置換ベクタは整数のベクタです。K番目の要素がIであることは、
23036タプルのK番目の要素が入力のI番目の列から取られることを示します。
23037@c COMMON
23038
23039@c EN
23040Let's see the example.  Suppose we know that the input contains
23041the following row as the header row:
23042@c JP
23043例を見てみましょう。入力に、以下の形の行がヘッダ行として含まれていることが
23044わかっているとします。
23045@c COMMON
23046
23047@example
23048(define *input-row*
23049  '("" "" "Year" "Country" "" "Population" "GDP" "Notes"))
23050@end example
23051
23052@c EN
23053We want to detect that row, but we only needs
23054Country, Year, GDP and Population columns, in that order.  So we create
23055a header parser as follows:
23056@c JP
23057こういう形の行を見つけたいわけですが、取り出すデータとしては、
23058@code{Country}、@code{Year}、@code{GDP}、@code{Population}だけが
23059この順で必要であるとします。この場合、ヘッダパーザを
23060次のとおり構成できます。
23061@c COMMON
23062
23063@example
23064(define header-parser
23065  (make-csv-header-parser '("Country" "Year" "GDP" "Population")))
23066@end example
23067
23068@c EN
23069Applying this header parser to the input data returns the permuter vector:
23070@c JP
23071このヘッダパーザを想定される入力行に適用すれば、置換ベクタが返ってきます:
23072@c COMMON
23073
23074@example
23075(header-parser *input-row*)
23076 @result{} #(3 2 6 5)
23077@end example
23078
23079@c EN
23080It means, the first item of tuple (Country) is in the 3rd column of the input,
23081the second item of tuple (Year) is in the 2nd column of the input,
23082and so on.  This permuter vector can be used to parse record rows to
23083get tuples.
23084@c JP
23085返り値の意味は、タプルの第0要素(@code{Country})は入力の第3列にあり、
23086タプルの第1要素(@code{Year})は入力の第2列にある、といった具合です。
23087置換ベクタはレコード行をパーズしてタプルを生成するのに使えます。
23088@c COMMON
23089@end defun
23090
23091@defun make-csv-record-parser header-slots permuter :optional required-slots
23092@c MOD text.csv
23093@c EN
23094Create a procedure that converts one input row into a tuple.
23095
23096@var{Permuter} is the vector returned by @code{make-csv-header-parser}.
23097
23098See @code{cvs-rows->tuples} above for @var{header-slots} and
23099@var{required-slots} arguments.
23100@c JP
23101入力の1行をタプルへと変換する手続きを作って返します。
23102
23103@var{permuter}は@code{make-csv-header-parser}が返す置換ベクタです。
23104
23105@var{header-slots}及び@var{required-slots}引数については
23106上の@code{cvs-rows->tuples}を見てください。
23107@c COMMON
23108@end defun
23109
23110
23111@c ----------------------------------------------------------------------
23112@node Calculate difference of text streams, EDN parsing and construction, CSV tables, Library modules - Utilities
23113@section @code{text.diff} - Calculate difference of text streams
23114@c NODE テキストストリームの相違点を計算する, @code{text.diff} - テキストストリームの相違点を計算する
23115
23116@deftp {Module} text.diff
23117@mdindex text.diff
23118@c EN
23119This module calculates the difference of two text streams or strings,
23120using @code{util.lcs} (@pxref{The longest common subsequence}).
23121@c JP
23122このモジュールでは、@code{util.lcs} (@ref{The longest common subsequence}参照)を
23123使って、2つのテキストストリーム、あるいは2つの文字列の相違点を計算します。
23124@c COMMON
23125@end deftp
23126
23127@defun diff src-a src-b :key reader eq-fn
23128@c MOD text.diff
23129@c EN
23130Generates an "edit list" from text sources @var{src-a} and @var{src-b}.
23131
23132Each of text sources, @var{src-a} and @var{src-b}, can be either an input
23133port or a string.  If it is a string, it is converted to a string input
23134port internally.  Then, the text streams from both sources are converted
23135to sequences by calling @var{reader} repeatedly on them; the default
23136of @var{reader} is @code{read-line}, and those sequences are
23137passed to @code{lcs-edit-list} to calculate the edit list.
23138The equality function @var{eq-fn} is also passed to @code{lcs-edit-list}.
23139
23140An edit list is a set of commands that turn the text sequence
23141from @code{src-a} to the one from @code{src-b}.
23142See the description of @code{lcs-edit-list} for
23143the detailed explanation of the edit list.
23144@c JP
23145テキストソース@var{src-a}と@var{src-b}から``編集リスト''を生成します。
23146
23147それぞれのテキストソース、@var{src-a}と@var{src-b}は入力ポートか文字列です。
23148もし文字列であれば、それは内部的に文字列ポートに変換されます。
23149そして、2つのソースからのテキストストリームは、それらに対して@var{reader}を繰り返し
23150呼ぶことによってシーケンスに変換されます。デフォルトの@var{reader}は@var{read-line}で、
231512つのシーケンスは編集リストを計算するために@code{lcs-edit-list}に渡されます。
23152@code{lcs-edit-list}には、等値を検査する関数@var{eq-fn}も渡されます。
23153
23154編集リストとは、@code{src-a}から@code{src-b}へテキストシーケンスを
23155変更するためのコマンドのセットです。編集リストの詳細な説明は、
23156@code{lcs-edit-list}を参照してください。
23157@c COMMON
23158
23159@example
23160(diff "a\nb\nc\nd\n" "b\ne\nd\nf\n")
23161@result{}
23162  (((- 0 "a"))
23163   ((- 2 "c") (+ 1 "e"))
23164   ((+ 3 "f")))
23165@end example
23166@end defun
23167
23168@defun diff-report src-a src-b :key reader eq-fn writer
23169@c MOD text.diff
23170@c EN
23171A convenience procedure to take the diff of two text sources
23172and display the result nicely.  This procedure calls @code{lcs-fold}
23173to calculate the difference of two text sources.  The meanings of
23174@var{src-a}, @var{src-b}, @var{reader} and @var{eq-fn} are the
23175same as @code{diff}'s.
23176@c JP
231772つのテキストソースのdiffをとって、その結果をきれいに表示するための
23178簡易手続きです。この手続きは、2つのテキストソースの相違点を計算する
23179ために@code{lcs-fold}を呼び出します。@var{src-a}、@var{src-b}、
23180@var{reader}、@var{eq-fn}の意味は、@code{diff}の場合と同じです。
23181@c COMMON
23182
23183@c EN
23184@var{Writer} is a procedure that takes two arguments, the text element
23185and a type, which is either a symbol @code{+},
23186a symbol @code{-}, or @code{#f}.   If the text element is only
23187in @var{src-a}, @var{writer} is called with the element and
23188@code{-}.  If the text element is only in @var{src-b},
23189it is called with the element and @code{+}.  If the text element
23190is in both sources, it is called with the element and
23191@code{#f}.   The default procedure of @var{writer} prints
23192the passed text element to the current output port
23193in unified-diff-like format:
23194@c JP
23195@var{writer}は2つの引数、テキスト要素とタイプ(シンボル@code{+}、
23196シンボル@code{-}、あるいは@code{#f}のいずれか)を取る手続きです。
23197テキスト要素が@var{src-a}にしかない場合は、@var{writer}がそのテキスト要素と
23198@code{-}とともに呼ばれます。テキスト要素が@var{src-b}にしかない場合は、
23199@var{writer}はそのテキスト要素と@code{+}とともに呼ばれます。
23200テキスト要素が両方のソースにある場合は、@var{writer}はそのテキスト要素と
23201@code{#f}とともに呼ばれます。@var{writer}のデフォルトの手続きは、
23202渡されたテキスト要素を現在の出力ポートにユニファイドdiffのようなフォーマットで
23203出力します。
23204@c COMMON
23205@example
23206(diff-report "a\nb\nc\nd\n" "b\ne\nd\nf\n")
23207@end example
23208displays:
23209@example
23210- a
23211  b
23212- c
23213+ e
23214  d
23215+ f
23216@end example
23217@end defun
23218
23219@c ----------------------------------------------------------------------
23220@node EDN parsing and construction, Running external editor, Calculate difference of text streams, Library modules - Utilities
23221@section @code{text.edn} - EDN parsing and construction
23222@c NODE EDNのパーズと構築, @code{text.edn} - EDNのパーズと構築
23223
23224@deftp {Module} text.edn
23225@mdindex text.edn
23226@c EN
23227EDN (Extensible Data Notation) is a subset of Clojure literals
23228for data exchange.  This module provides utilities to read and write EDN
23229format.  See @url{https://github.com/edn-format/edn} for the details of EDN.
23230@c JP
23231EDN (Extensible Data Notation)はデータ交換用に定められた、
23232Clojureのリテラル構文のサブセットです。このモジュールはEDNの読み書きをする
23233ユーティリティを提供します。EDNの詳細については
23234@url{https://github.com/edn-format/edn}を参照してください。
23235@c COMMON
23236
23237@multitable @columnfractions .2 .2 .6
23238@item EDN @tab Gauche @tab Note
23239@item @code{true} @tab @code{#t} @tab
23240@item @code{false} @tab @code{#f} @tab
23241@item @code{nil} @tab @code{nil}
23242@c EN
23243@tab Clojure's nil is not a symbol but a special value; since Clojure
23244can't have a symbol named nil, we can map it to Gauche's symbol @code{nil}.
23245@c JP
23246@tab Clojureのnilはシンボルではなく特殊な値ですが、
23247Clojureにはnilというシンボルは存在できないので、
23248Gaucheのシンボル@code{nil}に対応させています。
23249@c COMMON
23250@item number @tab @code{<real>}
23251@c EN
23252@tab Integers and floating point numbers.
23253The @code{N} and @code{M} suffixes in Clojure are ignored.
23254@c JP
23255@tab 整数と浮動小数点数。
23256Clojureの@code{N}と@code{M}サフィックスは無視されます。
23257@c COMMON
23258@item symbol @tab @code{<symbol>}
23259@c EN
23260@tab Clojure's symbol name has some restrictions, so not all Gauche symbols
23261map to EDN symbols.
23262Clojure's namespace-prefixed symbol, e.g. @code{foo/bar} simply maps to
23263Gauche's symbol @code{foo/bar}; we provide utility procedure to extract
23264namespace and basename parts.
23265@c JP
23266@tab Clojureのシンボル名には制約があるので、
23267全てのGaucheのシンボルがEDNシンボルとして使えるわけではありません。
23268Clojureの名前空間つきシンボル(例: @code{foo/bar}) はGauche側では
23269単に@code{foo/bar}という名前を持つシンボルの扱いになります。
23270この名前から名前空間とシンボル名を取り出すユーティリティが提供されます。
23271@c COMMON
23272@item keyword @tab @code{<keyword>}
23273@c EN
23274@tab Clojure has keywords distinct from symbols.  They are mapped to Gauche's
23275keywords (which is a subtype of symbols).
23276Gauche's keywords can also be symbols, but
23277no Clojure symbols begin with @code{:} so there won't be a conflict.
23278@c JP
23279@tab Clojureはキーワードとシンボルを別の型にしています。
23280ClojureキーワードはGaucheキーワード(シンボルのサブタイプ)に対応します。
23281Clojureのシンボルは@code{:}で始まることはないので、混同が起きることはありません。
23282@c COMMON
23283@item list @tab @code{<list>}
23284@c EN
23285@tab Clojure lists are Gauche lists.  Note that Clojure doesn't allow
23286improper lists.
23287@c JP
23288@tab ClojureのリストはGaucheのリストになります。
23289Clojureにはドットリスト(improper list)が無いことに注意してください。
23290@c COMMON
23291@item vector @tab @code{<vector>}
23292@c EN
23293@tab Clojure vectors are Gauche vectors.
23294@c JP
23295@tab ClojureのベクタはGaucheのベクタになります。
23296@c COMMON
23297@item map @tab @code{<hash-table>}
23298@c EN
23299@tab Clojure's map becomes Gauche's hashtable with @code{edn-comparator}
23300for hashing and comparison.
23301@c JP
23302@tab Clojureのマップは、Gaucheでは@code{edn-comparator}をハッシュ関数と比較に
23303使うハッシュテーブルになります。
23304@c COMMON
23305@item set @tab @code{<set>}
23306@c EN
23307@tab Clojure's set becomes Gauche's set with @code{edn-comparator}
23308for comparison.  @xref{R7RS sets} for interface of sets.
23309@c JP
23310@tab Clojureのセットは、Gaucheでは@code{edn-comparator}を比較に使う
23311@code{<set>}オブジェクトになります。@code{<set>}については@xref{R7RS sets}参照。
23312@c COMMON
23313@item tagged object @tab @code{<edn-object>}
23314@c EN
23315@tab Tagged objects are mapped to @code{<edn-object>} by default.
23316You can customize the parser/writer to map tagged objects with a
23317specific tag to a specific Gauche objects.
23318@c JP
23319@tab タグつきオブジェクトはデフォルトで@code{<edn-object>}のインスタンスになります。
23320タグつくオブジェクトの解釈をカスタマイズして、特定のGaucheオブジェクトに結びつけることも
23321できます。
23322@c COMMON
23323@end multitable
23324@end deftp
23325
23326@c EN
23327@subheading Parsing
23328@c JP
23329@subheading パーザ
23330@c COMMON
23331
23332@deftp {Condition Type} <edn-parse-error>
23333@c EN
23334When the parser encounters an error, this condition is thrown.
23335Inherits @code{<error>}.
23336@c JP
23337パーザのエラーはこのコンディションで通知されます。@code{<error>}を継承しています。
23338@c COMMON
23339@end deftp
23340
23341@defun parse-edn :optional iport
23342@c MOD text.edn
23343@c EN
23344Read one EDN representation from the given input port, and returns
23345Gauche object created from it.  If @var{iport} is omitted,
23346current input port is assumed.
23347
23348When the parser encounters unparsable sequence,
23349it raises @code{<edn-parse-error>}.
23350
23351Note that @var{iport} may be read ahead for characters. Suppose
23352the input consists of @code{abc@{:a b@}}, i.e. a symbol immediately
23353followed by a map.  The parser need to read @code{@{} to know the
23354end of the symbol. The read-ahead brace isn't pushed back
23355to the @var{iport}.  So it would be a problem if you keep reading
23356more EDN subsequently.   Use @code{parse-edn*} if you want to read
23357multiple objects.
23358@c JP
23359EDN表現を与えられた入力ポートから読み込み、パーズ結果をGaucheオブジェクトとして
23360返します。@var{iport}が省略された場合は現在の入力ポートが使われます。
23361
23362パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
23363
23364@var{iport}から文字が先読みされる可能性があることに注意してください。
23365例えば入力が@code{abc@{:a b@}}、つまりシンボルの直後にマップが来ていたとします。
23366パーザは@code{@{}まで読んでシンボルの終了を知り、シンボル@code{abc}を返しますが、
23367その時点で読まれていた@code{@{}はポートに戻されないので、
23368続けて@var{iport}からEDNを読む場合に問題となります。
23369複数のEDNオブジェクトを読み込む場合は@code{parse-edn*}を使ってください。
23370@c COMMON
23371@end defun
23372
23373@defun parse-edn* :optional iport
23374@c MOD text.edn
23375@c EN
23376Read EDN representations repeatedly from the given input port
23377and returns a list of them.  If @var{iport} is omitted,
23378current input port is assumed.
23379
23380When the parser encounters unparsable sequence,
23381it raises @code{<edn-parse-error>}.
23382@c JP
23383与えられた入力ポートから、EOFに達するまでEDN表現を読み込み、結果のGaucheオブジェクトの
23384リストを返します。@var{iport}が省略された場合は現在の入力ポートが使われます。
23385
23386パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
23387@c COMMON
23388@end defun
23389
23390@defun parse-edn-string str
23391@c MOD text.edn
23392@c EN
23393A convenience procedure to parse EDN representation in a string @var{str},
23394and returns the read object.
23395
23396When the parser encounters unparsable sequence,
23397it raises @code{<edn-parse-error>}.
23398@c JP
23399EDN表現を文字列から読み込む便利手続きです。
23400
23401パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
23402@c COMMON
23403
23404@example
23405(parse-edn-string "[1 2 (3 4) @{:a 5@}]")
23406 @result{} #(1 2 (3 4) #<hash-table general 0x1f05780>)
23407@end example
23408@end defun
23409
23410@c EN
23411@subheading Constructing
23412@c JP
23413@subheading 構築
23414@c COMMON
23415
23416@defun construct-edn obj :optional oport
23417@c MOD text.edn
23418@c EN
23419Write out an EDN representation of object @var{obj}
23420to the output port @var{oport}.  If @var{oport} is omitted,
23421current output port is assumed.
23422
23423If @var{obj} contains an object that doesn't have a defined
23424EDN representation, a generic function @var{edn-write} is called
23425on it.  See Customization heading below.  If no method is defined for
23426the object, an error is signaled.
23427@c JP
23428オブジェクト@var{obj}のEDN表現を出力ポート@var{oport}に書き出します。
23429@var{oport}が省略された場合は現在の出力ポートが使われます。
23430
23431@var{obj}中にEDNで表現できないオブジェクトがあった場合、
23432ジェネリック関数@var{edn-write}が呼ばれます。下のカスタマイズの項を参照してください。
23433適切なメソッドが定義されていなけばエラーが投げられます。
23434@c COMMON
23435@end defun
23436
23437@defun construct-edn-string obj
23438@c MOD text.edn
23439@c EN
23440Returns an EDN representation of @var{obj} in a string.
23441
23442If @var{obj} contains an object that doesn't have a defined
23443EDN representation, a generic function @var{edn-write} is called
23444on it.  See Customization heading below.  If no method is defined for
23445the object, an error is signaled.
23446@c JP
23447@var{obj}のEDN表現を文字列で返します。
23448
23449@var{obj}中にEDNで表現できないオブジェクトがあった場合、
23450ジェネリック関数@var{edn-write}が呼ばれます。下のカスタマイズの項を参照してください。
23451適切なメソッドが定義されていなけばエラーが投げられます。
23452@c COMMON
23453
23454@example
23455@end example
23456(construct-edn-string '#(1 2 "abc"))
23457 @result{} "[1 2 \"abc\"]"
23458@end defun
23459
23460@c EN
23461@subheading Utilities
23462@c JP
23463@subheading ユーティリティ
23464@c COMMON
23465
23466@defun edn-equal? a b
23467@c MOD text.edn
23468@c EN
23469Test equality of two objects that are read from EDN representation.
23470@c JP
23471EDN表現から読まれた二つのオブジェクトが、EDNのセマンティクスで等しいかどうかを調べます。
23472@c COMMON
23473@end defun
23474
23475@defvar edn-comparator
23476@c MOD text.edn
23477@c EN
23478A comparator that uses @code{edn-equal?} for the equality predicate.
23479Corresponding has function is also included.
23480EDN maps and sets become Gauche hash-tables and sets with this comparator.
23481@c JP
23482@code{edn-equal?}で等価性を判定する比較器です。ハッシュ関数も含まれます。
23483EDNのマップとセットは、この比較器を使うGaucheのハッシュテーブルとセットになります。
23484@c COMMON
23485@end defvar
23486
23487@defun edn-map key value @dots{}
23488@defunx edn-set item @dots{}
23489@c MOD text.edn
23490@c EN
23491Convenience procedures to create hash-tables and sets compatible
23492for EDN.
23493@c JP
23494EDNに使えるハッシュテーブルとセットを構築する便利手続きです。
23495@c COMMON
23496@end defun
23497
23498@deftp {Class} <edn-object>
23499@clindex edn-object
23500@c MOD text.edn
23501@c EN
23502EDN tagged object becomes an instance of this class by default.
23503The instance has the following slots, both are immutable:
23504@c JP
23505EDNのタグつきオブジェクトは、デフォルトではこの暮らすのインスタンスになります。
23506以下のスロットがあります。どちらも変更不可です。
23507@c COMMON
23508
23509@defivar <edn-object> tag
23510@c EN
23511Object's tag.  A symbol.
23512@c JP
23513シンボル。オブジェクトのタグです。
23514@c COMMON
23515@end defivar
23516
23517@defivar <edn-object> payload
23518@c EN
23519Object's payload.  Can be any object that can be representable in EDN.
23520@c JP
23521オブジェクトの内容です。EDNで表現可能なオブジェクト。
23522@c COMMON
23523@end defivar
23524
23525@c EN
23526For example, when you read @code{#myobject @{:a 1 :b 2@}},
23527the tag is @code{myobject} and the payload is a hashtable
23528containing mapping @code{@{:a 1 :b 2@}}.
23529@c JP
23530例えば、@code{#myobject @{:a 1 :b 2@}}を読んだ場合、
23531タグは@code{myobject}、内容は@code{@{:a 1 :b 2@}}を読んだ結果のハッシュテーブルに
23532なります。
23533@c COMMON
23534@end deftp
23535
23536@defun make-edn-object tag payload
23537@c MOD text.edn
23538@c EN
23539Returns a new @code{<edn-object>} instance.
23540Note: Arguments are not checked.  It's caller's responsibility to
23541pass valid arguments to guarantee it's serializable as EDN.
23542@c JP
23543新たな@code{<edn-object>}のインスタンスを作って返します。
23544引数がEDN表現可能かどうかのチェックはされません。
23545呼び出し側が有効な引数を渡す必要があります。
23546@c COMMON
23547@end defun
23548
23549@defun edn-object? obj
23550@c MOD text.edn
23551@c EN
23552Returns @code{#t} iff @var{obj} is an instance of @code{<edn-object>}.
23553@c JP
23554@var{obj}が@code{<edn-object>}のインスタンスなら@code{#t}を、そうでなければ
23555@code{#f}を返します。
23556@c COMMON
23557@end defun
23558
23559@defun edn-object-tag edn-object
23560@defunx edn-object-payload edn-object
23561@c MOD text.edn
23562@c EN
23563Returns the tag and the payload of @var{edn-object}, respectively.
23564@c JP
23565@var{edn-object}のタグと内容をそれぞれ返します。
23566@c COMMON
23567@end defun
23568
23569@defun edn-symbol-prefix symbol
23570@defunx edn-symbol-basename symbol
23571@c MOD text.edn
23572@c EN
23573Return prefix and basename part of the symbol, respectively.
23574@c JP
23575シンボルの、プリフィクスとベース名をそれぞれ返します。
23576@c COMMON
23577
23578@example
23579(edn-symbol-prefix 'foo/bar) @result{} foo
23580(edn-symbol-basename 'foo/bar) @result{} bar
23581
23582(edn-symbol-prefix 'bar) @result{} #f
23583(edn-symbol-basename 'bar) @result{} bar
23584@end example
23585@end defun
23586
23587@defun edn-valid-symbol-name? str
23588@c MOD text.edn
23589@c EN
23590Returns @code{#t} iff a string @var{str} can be a valid Clojure symbol name.
23591It may have namespace prefix.
23592@c JP
23593文字列@var{str}がClojureのシンボル名として有効なら@code{#t}を、そうでなければ
23594@code{#f}を返します。@var{str}には名前空間を含めることもできます。
23595@c COMMON
23596@end defun
23597
23598@c EN
23599@subheading Customization
23600@c JP
23601@subheading カスタマイズ
23602@c COMMON
23603
23604@c EN
23605You can map EDN tagged objects to other Gauche objects.
23606@c JP
23607EDNのタグつきオブジェクトを、他のGaucheオブジェクトへとマップすることが出来ます。
23608@c COMMON
23609
23610@defun register-edn-object-handler! tag handler
23611@c MOD text.edn
23612@c EN
23613@var{Tag} is a symbol, and @var{handler} is @code{#f} or a procedure
23614that takes a tag symbol and a payload object.
23615
23616@var{Tag} must have a name valid as Clojure symbol, or an error
23617is signaled.
23618
23619After the parser reads a tagged object with a symbol @var{tag}
23620and payload, it calls @var{handler}, and the returned object
23621becomes the result of the parser, instead of @code{<edn-object>}.
23622Registering @code{#f} removes the previously registered handler.
23623
23624This procedure is thread-safe.
23625
23626The following example makes EDN @code{#u8vector[1 2 3 4]} to be read
23627as @code{#u8(1 2 3 4)}:
23628@c JP
23629@var{tag}はシンボル、@var{handler}は@code{#f}もしくは
23630タグと内容を引数に取る手続きです。
23631
23632@var{tag}はClojureのシンボルとして有効な名前でなければなりません。
23633さもなくばエラーが投げられます。
23634
23635パーザが@var{tag}をタグに持つタグつきオブジェクトを読んだら、
23636そのタグと内容を引数にして@var{handler}を呼び出し、返り値を
23637パーズ結果とします。@var{handler}に@code{#f}を渡した場合は
23638既に登録されたハンドラを(もしあれば)削除します。
23639
23640この手続きはスレッドセーフです。
23641
23642以下の例はEDNの@code{#u8vector[1 2 3 4]}を
23643@code{#u8(1 2 3 4)}として読み込みます。
23644@c COMMON
23645
23646@example
23647(register-edn-object-handler! 'u8vector
23648                              (^[tag vec] (vector->u8vector vec)))
23649@end example
23650@end defun
23651
23652@defun edn-object-handler tag
23653@c MOD text.edn
23654@c EN
23655Returns a handler registered with a symbol @var{tag}.  If a handler
23656is not registered for @var{tag}, @code{#f} is returned.
23657This procedure is thread-safe.
23658@c JP
23659@var{tag}に登録されたハンドラを返します。ハンドラが登録されていなければ@code{#f}を返します。
23660この手続きはスレッドセーフです。
23661@c COMMON
23662@end defun
23663
23664@deffn {Generic Function} edn-write obj
23665@c MOD text.edn
23666@c EN
23667Write EDN representation of @var{obj} to the current output port.
23668The @code{construct-edn} procedure calls this internally.
23669
23670To write out a Gauche object as EDN tagged object, define a method to
23671this generic function.   In the method you can call @code{edn-write}
23672recursively to write out components of the object.
23673
23674The following example writes @code{#u8(1 2 3 4)} as
23675EDN @code{#u8vector[1 2 3 4]}:
23676@c JP
23677@var{obj}のEDN表現を現在の出力ポートに書き出します。
23678@code{construct-edn}は内部的にこれを呼んでいます。
23679
23680GaucheオブジェクトをEDNタグつきオブジェクトとして書き出したい場合に、
23681このジェネリック関数にメソッドを定義します。メソッド中で、オブジェクトの要素を
23682再帰的に書き出す場合はそれぞれに@code{edn-write}を呼び出してください。
23683
23684以下の例は、@code{#u8(1 2 3 4)}をEDNの@code{#u8vector[1 2 3 4]}として
23685書き出します。
23686@c COMMON
23687
23688@example
23689(define-method edn-write ((x <u8vector>))
23690  (display "#u8vector")
23691  (edn-write (u8vector->vector x)))
23692@end example
23693@end deffn
23694
23695@c ----------------------------------------------------------------------
23696@node Running external editor, Gap buffer, EDN parsing and construction, Library modules - Utilities
23697@section @code{text.external-editor} - Running external editor
23698@c NODE 外部エディタの起動, @code{text.external-editor} - 外部エディタの起動
23699
23700@deftp {Module} text.external-editor
23701@mdindex text.external-editor
23702A convenience module to invoke external editor program.
23703This is mainly to be used from REPL, but can be useful for
23704other purposes.
23705@end deftp
23706
23707@defun ed path-or-proc :key editor load-after
23708@c MOD text.external-editor
23709Starts an external editor.  The editor program path is determined
23710in the following order:
23711
23712@itemize @bullet
23713@item
23714The @var{editor} keyword argument, if it's a string.
23715@item
23716The value of @code{*editor*} in the user module, if defined.
23717@item
23718The value of the environment variable @code{GAUCHE_EDITOR}.
23719@item
23720The value of the environment variable @code{EDITOR}.
23721@item
23722If none works, the behavior depends on the value of :editor keyword
23723argument:
23724@table @code
23725@item #f
23726Just returns @code{#f}.
23727@item error
23728Throws an error.
23729@item ask
23730Asks the user.
23731@item message
23732Prints message and returns @code{#f}.
23733@end table
23734@end itemize
23735
23736Returns @code{#t} for normal termination.
23737
23738The editor program may be called in one of the following way:
23739
23740@example
23741EDITOR filename
23742EDITOR +lineno filename
23743@end example
23744
23745The latter expects to locate the cursor on the specified line number
23746in the filename.
23747
23748The file to open is determined by a generic function @code{ed-pick-file}.
23749It should return @code{(@var{filename} @var{lineno})},
23750or @code{#f} to indicate that it couldn't determine the file to edit.
23751
23752The @var{load-after} argument controls whether the file is loaded
23753into the process after the file is modified.  It must be one of
23754the following values:
23755@table @code
23756@item #t
23757Load the file once editor exits and the file is modified.
23758@item #f
23759Do not load the file.
23760@item ask
23761Ask the user if the file should be loaded or not.
23762@end table
23763
23764NB: Common Lisp's @code{ed} can be invoked without argument.  For our usage,
23765though, that feature doesn't seem too useful---it's more likely that
23766repl IS inside an editor so we only need to open a specific file in
23767a buffer.  Emacsclient requires filename, so it further complicates things.
23768For now we just require one argument.
23769@end defun
23770
23771@defun ed-string string :key editor
23772@c MOD text.external-editor
23773Invoke an external editor (as described in @code{ed}) with @var{string}
23774being the initial content.  Once editor exits,
23775returns the edited content as a string.
23776@end defun
23777
23778@deffn {Generic Function} ed-pick-file obj
23779@c MOD text.external-editor
23780Determine what to edit.  It must return a list of
23781filename and line number, or @code{#f} if it can't find appropriate file to
23782edit.
23783
23784Methos for strings, procedures and @code{<top>} are already defined.
23785If @var{obj} is a string, it is taken as a filename.
23786If @var{obj} is a procedure and its source location is available,
23787the source file and the location is returned.
23788Otherwise, @code{#f} is returned.
23789@end deffn
23790
23791@c ----------------------------------------------------------------------
23792@node Gap buffer, Localized messages, Running external editor, Library modules - Utilities
23793@section @code{text.gap-buffer} - Gap buffer
23794@c NODE ギャップバッファ, @code{text.gap-buffer} - ギャップバッファ
23795
23796@deftp {Module} text.gap-buffer
23797@mdindex text.gap-buffer
23798This module provides a gap buffer, a data structure useful for
23799editable text.
23800
23801A gap buffer is a vector of characters with a ``cursor'', where
23802you can insert or delete a character in O(1) time.  Most of
23803the editing API operate on the current cursor position.
23804@end deftp
23805
23806@defun make-gap-buffer :key initial-capacity
23807@c MOD text.gap-buffer
23808Creates a fresh gap buffer and returns it.  The initial content
23809is emtpy.
23810
23811The keyword argument
23812@var{initial-capacity} must be a positive exact integer if given,
23813and specifies the initial capacity of the buffer.  The buffer is
23814automatically extended if necessary, so the argument is only a
23815hint; if you know you'll insert a long string, for example,
23816you can create a buffer that's large enough to hold it to avoid
23817reallocation overhead.
23818@end defun
23819
23820@defun string->gap-buffer string :optional pos whence start end
23821@c MOD text.gap-buffer
23822Creates a gap buffer large enough to contain the given @var{string},
23823and returns it.
23824
23825The initial cursor position is set at the end of the string by default.
23826The @var{pos} and @var{whence} argument can set the initial
23827cursor position.  The @var{whence} argument must be either a symbol
23828@code{beginning} or a symbol @code{end}, and @var{pos} must be an exact
23829integer offset from the whence.  For example, @var{pos} = 10 and
23830@var{whence} = @code{beginning} sets the cursor at the 10th character
23831of the string from the beginning, and @var{pos} = -1 and @var{whence} =
23832@code{end} sets the cursor position at one character before the end
23833of the string.  If the combination of @var{pos} and @var{whence}
23834points the outside of the string, an error is signaled.
23835
23836The optional @var{start} and @var{end} trims the input string before
23837creating the gap buffer.
23838@end defun
23839
23840@defun gap-buffer? obj
23841@c MOD text.gap-buffer
23842Returns @code{#t} iff @var{obj} is a gap buffer.
23843@end defun
23844
23845@defun gap-buffer-copy gbuf
23846@c MOD text.gap-buffer
23847Returns a fresh copy of a gap buffer @var{gbuf}, with the same content
23848and cursor position.
23849@end defun
23850
23851@defun gap-buffer->string gbuf :optional start end
23852@defunx gap-buffer->generator gbuf :optional start end
23853@c MOD text.gap-buffer
23854Retrieve the content of a gap buffer @var{gbuf} as a string or
23855a generator of characters, respectively.  The optional @var{start} and
23856@var{end} arguments are nonnegative exact integers of character index
23857in the content of the buffer, and limits the output within the specified
23858range.
23859
23860If you modify the content of gap buffer before the returned generator
23861is exhausted, consistent behavior isn't guaranteed.
23862@end defun
23863
23864@defun gap-buffer-pos gbuf
23865@c MOD text.gap-buffer
23866Returns the current cursor position of @var{gbuf}, in a nonnegative
23867exact integer.
23868@end defun
23869
23870@defun gap-buffer-capacity gbuf
23871@c MOD text.gap-buffer
23872Returns the currently allocated storage size of @var{gbuf}.
23873If you insert more characters into @var{gbuf}, the storage is automatically
23874expanded.
23875@end defun
23876
23877@defun gap-buffer-content-length gbuf
23878@c MOD text.gap-buffer
23879Returns the length of current content of @var{gbuf},
23880in the number of characters.
23881@end defun
23882
23883@defun gap-buffer-gap-at? gbuf whence
23884@c MOD text.gap-buffer
23885The @var{whence} argument must be either a symbol @code{beginning}
23886or a symbol @code{end}.  Returns @code{#t} iff the current cursor position
23887of @var{gbuf} is at the beginning or at the end, respectively.
23888@end defun
23889
23890@defun gap-buffer-ref gbuf index :optional fallback
23891@c MOD text.gap-buffer
23892Returns @var{index}-th character of @var{gbuf}.  If @var{index} is
23893out of range, @var{fallback} is returned if given, or an error
23894is raised.
23895@end defun
23896
23897@defun gap-buffer-set! gbuf index char
23898@c MOD text.gap-buffer
23899Replaces @var{index}-th character of @var{gbuf} with @var{char}.
23900If @var{index} is out of range, an error is signaled.
23901@end defun
23902
23903@defun gap-buffer-move! gbuf pos :optional whence
23904@c MOD text.gap-buffer
23905Moves the cursor position of @var{gbuf} to a position @var{pos}, which
23906must be an exact integer.  The position @var{pos} is relative to
23907@var{whence}, which must be either one of the symbols @code{beginning},
23908@var{current} or @code{end}.
23909@end defun
23910
23911@defun gap-buffer-insert! gbuf content
23912@c MOD text.gap-buffer
23913Inserts @var{content}, which must be a character or a string,
23914at the current cursor position of @var{gbuf}.
23915The current cursor position is moved to the end of the inserted content.
23916@end defun
23917
23918@defun gap-buffer-delete! gbuf size
23919@c MOD text.gap-buffer
23920Delets @var{size} characters from the current cursor position
23921of @var{gbuf}.  It is an error if @var{size} overruns.
23922@end defun
23923
23924@defun gap-buffer-clear! gbuf
23925@c MOD text.gap-buffer
23926Makes @var{gbuf} empty.
23927@end defun
23928
23929@defun gap-buffer-replace! gbuf size content
23930@c MOD text.gap-buffer
23931This is a combination of @code{(gap-buffer-delete! gbuf size)} and
23932@code{(gap-buffer-insert! gbuf content)}.
23933The @var{size} argument must be a nonnegative exact integer,
23934and the @var{content} argument must be either a string or a character.
23935@end defun
23936
23937@defun gap-buffer-edit! gbuf edit-command
23938@c MOD text.gap-buffer
23939This is a convenience procedure to ``replay'' editing of the gap buffer
23940@var{gbuf}.  The @var{edit-command} argument must be either one of the
23941following:
23942
23943@table @code
23944@item (i @var{pos} @var{string})
23945Insert @var{string} at a position @var{pos}.
23946@item (d @var{pos} @var{length})
23947Delete @var{length} characters from a position @var{pos}.
23948@item (c @var{pos} @var{length} @var{string})
23949Change: Delets @var{length} characters from a position @var{pos},
23950then insert @var{string}.
23951@end table
23952
23953Here, @var{pos} must be a nonnegative exact integer specifying the
23954position in the gap buffer.
23955
23956One of the appliations of this procedure is to handle undo/redo list.
23957@end defun
23958
23959
23960@c ----------------------------------------------------------------------
23961@node Localized messages, Simple HTML document construction, Gap buffer, Library modules - Utilities
23962@section @code{text.gettext} - Localized messages
23963@c NODE 地域化メッセージ, @code{text.gettext} - 地域化メッセージ
23964
23965@deftp {Module} text.gettext
23966@mdindex text.gettext
23967@c EN
23968This module provides utilities to deal with localized messages.
23969The API is compatible to GNU's gettext, and the messages
23970are read from @file{*.po} and @file{*.mo} files,
23971so that you can use the GNU gettext
23972toolchain to prepare localized messages.
23973However, the code is written from scratch by Alex Shinn and
23974doesn't depend on GNU's gettext library.
23975@c JP
23976このモジュールは地域化メッセージを扱うユーティリティを提供します。
23977API は GNU の gettext と互換性があり、メッセージは @file{*.po} および
23978@file{*.mo} ファイルから読み込まれます。それゆえ、GNU の gettext toolchain
23979をつかって地域化メッセージを準備することができます。しかし、このコードは
23980Alex Shinn によってスクラッチから書き起こされたものであり、GNU の
23981gettext ライブラリには依存していません。
23982@c COMMON
23983
23984@c EN
23985This implementation extends GNU's gettext API in the following ways:
23986@itemize @bullet
23987@item
23988It can read from multiple message files in cascaded way,
23989allowing applications to share a part of message files.
23990@item
23991It supports multiple locale/domain simultaneously.
23992@end itemize
23993@c JP
23994この実装は GNU の gettext API を以下のように拡張したものです。
23995@itemize @bullet
23996@item
23997複数のメッセージファイルから、カスケードされた方法で読み込むことができます。
23998これにより、アプリケーションはメッセージファイルの部分を共有できます。
23999@item
24000複数のロケール/ドメインを同時に扱えます。
24001@end itemize
24002@c COMMON
24003
24004@c EN
24005SRFI-29 (@pxref{Localization}) provides another means of message
24006localization.  A portable program may wish to use srfi-29, but
24007generally @code{text.gettext} is recommended in Gauche scripts
24008because of its flexibility and compatibility to existing message files.
24009@c JP
24010SRFI-29 (@ref{Localization}参照) はこれとは別のメッセージの地域化
24011機構を提供しています。ポータブルなプログラムでは、SRFI-29 の方がよいこと
24012もありますが、一般には、Gauche スクリプトでは、@code{text.gettext} の
24013方を推奨します。それは、既存のメッセージファイルとの互換性と柔軟性の
24014ためです。
24015@c COMMON
24016@end deftp
24017
24018@c EN
24019@subheading Gettext-compatible API
24020@c JP
24021@subheading gettext-互換の API
24022@c COMMON
24023
24024@defun textdomain domain-name :optional locale dirs cdir cached? lookup-cached?
24025@c MOD text.gettext
24026@c EN
24027Sets up the default domain and other parameters for
24028the application.  The setting affects to the following @code{gettext}
24029call.
24030
24031@var{Domain} is a string or list of strings specifying the domain
24032(name of @file{.mo} or @file{.po} files) as in C gettext.
24033You can pass @code{#f} as @var{domain-name} just to get the default
24034domain accessor procedure.
24035You can alo pass multiple domains to @var{domain-name}.
24036@c JP
24037アプリケーション用に、デフォルトのドメインとそのほかのパラメータを
24038設定します。この設定は、以降の @code{gettext} の呼出しに影響を与えます。
24039
24040@var{domain} は文字列または文字列のリストで、ドメイン(@file{.mo} あるいは
24041@file{.po} ファイル名)を C の gettext と同じように指定します。
24042@code{#f} を @var{domain-name} として渡すと、デフォルトのドメインアクセサ
24043手続きが得られます。また、複数のドメインを @var{domain-name}にあたえる
24044ことができます。
24045@c COMMON
24046@example
24047(textdomain '("myapp" "gimp"))  ; search 1st myapp, then gimp
24048(gettext "/File/Close")         ; "Close" from gimp unless overridden
24049@end example
24050
24051@c EN
24052@var{Locale} is a string or list of strings in the standard Unix format of
24053@code{LANG[_REGION][.ENCODING]}.  You can also pass a list of locales
24054to specify fallbacks.
24055@c JP
24056@var{locale} は文字列または文字列のリストで、標準的なUnixのフォーマット
24057@code{LANG[_REGION][.ENCODING]} です。フォールバックを指定するロケール
24058のリストを渡すこともできます。
24059@c COMMON
24060
24061@example
24062(textdomain "myapp" '("ru" "uk"))  ; search 1st Russian then Ukranian,
24063(gettext "Hello, World!")          ; which are somewhat similar
24064@end example
24065
24066@c EN
24067@var{Dirs} is the search path of directories which should hold the
24068@file{LOCALE/CDIR/} directories which contain the actual message catalogs.
24069This is always appended with the system default, e.g.
24070@file{"/usr/share/locale"}, and may also inherit from the
24071@code{GETTEXT_PATH} colon-delimited environment variable.
24072
24073@var{Cdir} is the category directory, defaulting to either the
24074@code{LC_CATEGORY}
24075environment variable or the appropriate system default
24076(e.g. @code{LC_MESSAGES}).  You generally won't need this.
24077
24078@var{Cached?}
24079means to cache individual messages, and defaults to @code{#t}.
24080
24081@var{Lookup-cached?}
24082means to cache the lookup dispatch generated by these
24083parameters, and defaults to @code{#t}.
24084
24085@code{Textdomain} just passes these parameters to the internal
24086@code{make-gettext},
24087and binds the result to the global dispatch used by @code{gettext}.
24088You may build these closures manually for convenience in using multiple
24089separate domains or locales at once (useful for server environments).
24090See the description of @code{make-gettext} below.
24091
24092@code{Textdomain} returns an @emph{accessor procedure} which
24093packages information of the domain.  See @code{make-gettext} below
24094for the details.
24095@c JP
24096@var{dirs} は実際のメッセージカタログを含む @file{LOCALE/CDIR/}
24097ディレクトリのサーチパスです。これは常にシステムのデフォルト(たとえば、
24098@file{"/usr/share/locale"})に追加されます。そして、コロンで区切られた
24099@code{GETTEXT_PATH} 環境変数を継承します。
24100
24101@var{cdir} はカテゴリーディレクトリで、既定値を @code{LC_CATEGORY}
24102環境変数または、適当なシステム既定値(たとえば @code{LC_MESSAGES})に
24103設定します。一般にはこれを指定する必要はありません。
24104
24105@var{cached?} は個別のメッセージをキャッシュするかを意味し、デフォルトは
24106@code{#t} です。
24107
24108@var{lookup-cached?}
24109は、これらのパラメータで生成されるディスパッチをキャッシュするかどうか
24110を意味し、デフォルトは @code{#t} です。
24111
24112@code{textdomain} はこれらのパラメータを内部の @code{make-gettext} に
24113渡し、その結果を、@code{gettext} で使われるグローバルなディスパッチに
24114束縛します。これらのクロージャを複数の別々のドメインやロケールを一度に
24115扱うのに便利なように、手で構築することができます。(これらは
24116サーバ環境で便利です。) 後述の @code{make-gettext} を参照してください。
24117
24118@code{textdomain} はそのドメインの情報をもつ @emph{アクセサ手続き}を
24119返します。詳細については、後述の @code{make-gettext} を参照してください。
24120@c COMMON
24121@end defun
24122
24123@defun gettext msg-id
24124@c MOD text.gettext
24125@c EN
24126Returns a translated message of @var{msg-id}.  If there's no
24127translated message, @var{msg-id} itself is returned.
24128@c JP
24129@var{msg-id} の翻訳されたメッセージを返します。もし、翻訳された
24130メッセージがなければ、@var{msg-id} それ自身を返します。
24131@c COMMON
24132@end defun
24133
24134@defun ngettext msg-id :optional msg-id2 num
24135@c MOD text.gettext
24136@c EN
24137Similar to @var{gettext}, but it can be used to handle
24138plural forms.
24139Pass a singular form to @var{msg-id}, and plural form to
24140@code{msg-id2}.  The @var{num} argument is used to determine
24141the plural form.  If no message catalog is found, @var{msg-id}
24142is returned when @var{num} is 1, and @var{msg-id2} otherwise.
24143@c JP
24144@var{gettext}と似ていますが、複数形を処理するのに使うことが
24145できます。単数形のメッセージを @var{msg-id} へ、複数形のメッセージを
24146@code{msg-id2} に渡します。@var{num} 引数は、複数形を決定
24147するのに使われます。もし、メッセージカタログが見つからなければ、
24148@var{num} が 1 のときは、@var{msg-id} が返り、そうでなければ、
24149@var{msg-id2} が返ります。
24150@c COMMON
24151@end defun
24152
24153@defun bindtextdomain domain dirs
24154@c MOD text.gettext
24155@c EN
24156Sets the search path of domain @var{domain} to @var{dirs}, which
24157may be just a single directory name or a list of directory names.
24158@c JP
24159ドメイン @var{domain} のサーチパスを @var{dirs} に設定します。
24160単一のディレクトリ名であったり、ディレクトリのリストであったりします。
24161@c COMMON
24162@end defun
24163
24164@defun dgettext domain msg-id
24165@defunx dcgettext domain msg-id locale
24166@c MOD text.gettext
24167@c EN
24168Returns a translated message of @var{msg-id} in @var{domain}.
24169@code{Dcgettext} takes @var{locale} as well.
24170@c JP
24171@var{domain} 中の @var{msg-id} の翻訳されたメッセージを返します。
24172@code{dcgettext} は @var{locale} も引数としてとります。
24173@c COMMON
24174@end defun
24175
24176@c EN
24177@subheading Low-level flexible API
24178@c JP
24179@subheading 低水準の柔軟な API
24180@c COMMON
24181
24182@c EN
24183The following procedure is more flexible interface, on top of which
24184the gettext-compatible APIs are written.
24185@c JP
24186以下の手続きはより柔軟性のあるインタフェースで、この上で、gettext-互換の
24187API が書かれています。
24188@c COMMON
24189
24190@defun make-gettext :optional domain locale dirs gettext-cached? lookup-cached?
24191@c MOD text.gettext
24192@c EN
24193Creates and returns an @emph{accessor procedure}, which encapsulates
24194methods to retrieve localized messages.
24195
24196The meaning of arguments are the same as @code{textdomain} above.
24197Indeed, @code{textdomain} just calls @code{make-gettext}, and later
24198it binds the result to the global parameter.   If you wish to have
24199multiple independent domains within a single program, you can
24200call @code{make-gettext} directly and manage the created
24201accessor procedure by yourself.
24202@c JP
24203@emph{アクセサ手続き} を生成して返します。返された手続きは、
24204地域化されたメッセージを検索するメソッドをカプセル化しています。
24205
24206引数の意味は上述の @code{textdomain} と同じです。
24207実際は、@code{textdomain} は @code{make-gettext} を呼び、その後、
24208それは、結果をこのグローバルパラメータに束縛します。@code{make-gettext}
24209を直接呼んで、自分自身で、アクセサ手続きを管理することもできます。
24210@c COMMON
24211
24212@example
24213(define my-gettext (make-gettext "myapp"))
24214(define _ (my-gettext 'getter))
24215(_ "Hello, World!")
24216@end example
24217@end defun
24218
24219@c ----------------------------------------------------------------------
24220@node Simple HTML document construction, Display with pager, Localized messages, Library modules - Utilities
24221@section @code{text.html-lite} - Simple HTML document construction
24222@c NODE シンプルなHTMLドキュメントの構築, @code{text.html-lite} - シンプルなHTMLドキュメントの構築
24223
24224@deftp {Module} text.html-lite
24225@mdindex text.html-lite
24226@c EN
24227Provides procedures to construct an HTML document easily.
24228For example, you can construct an HTML table by the following code:
24229@c JP
24230HTML ドキュメントを簡単に構築するための手続きを提供します。
24231例えば、以下のコードは HTML のテーブルを構築します。
24232@c COMMON
24233@example
24234(html:table
24235  (html:tr (html:th "Item No") (html:th "Quantity"))
24236  (html:tr (html:td 1) (html:td 120))
24237  (html:tr (html:td 2) (html:td 30))
24238  (html:tr (html:td 3) (html:td 215)))
24239@end example
24240@c EN
24241See the description of @code{html:@var{element}} below for details.
24242
24243This module does little check for the constructed html documents,
24244such as whether the attributes are valid, and whether the content
24245of the element matches DTD.  It does not provide a feature to parse
24246the html document neither.  Hence the name `lite'.
24247@c JP
24248詳細については、以下の @code{html:@var{element}} の説明を見てください。
24249
24250このモジュールでは生成されたHTMLドキュメントに関して、
24251例えばアトリビュートに有効な値が入っているか、要素の内容はDTDを満たしているか、
24252等のチェックをほとんど行いません。また、HTMLをパーズする関数も提供されません。
24253それが「lite」の名の由来です。
24254@c COMMON
24255@end deftp
24256
24257@defun html-escape
24258@defunx html-escape-string string
24259@c MOD text.html-lite
24260@c EN
24261Escapes the ``unsafe'' characters in HTML.  @code{html-escape}
24262reads input string from the current input port and writes the result
24263to the current output port.   @code{html-escape-string} takes the
24264input from @var{string} and returns the result in a string.
24265@c JP
24266HTML に含まれる"安全でない"文字をエスケープします。
24267@code{html-escape} は、現在の入力ポートから文字列を読み込み、
24268結果を現在の出力ポートへ書き出します。@code{html-escape-string} は
24269@var{string} を入力とし、文字列を返します。
24270@c COMMON
24271@end defun
24272
24273@defun html-doctype :key type
24274@c MOD text.html-lite
24275@c EN
24276Returns a doctype declaration for an HTML document.
24277@var{type} can be either one of the followings (default is
24278@code{:html-4.01-strict}).
24279@c JP
24280HTML ドキュメントの文書型宣言を返します。
24281@var{type} は、以下のいずれかを指定します (デフォルトは@code{:html-4.01-strict}
24282です)。
24283@c COMMON
24284@table @code
24285@item :html-4.01-strict, :html-4.01, :strict
24286HTML 4.01 Strict DTD
24287@item :html-4.01-transitional, :transitional
24288HTML 4.01 Transitional DTD
24289@item :html-4.01-frameset, :frameset
24290HTML 4.01 Frameset DTD
24291@item :xhtml-1.0-strict, :xhtml-1.0
24292XHTML 1.0 Strict DTD
24293@item :xhtml-1.0-transitional
24294XHTML 1.0 Transitional DTD
24295@item :xhtml-1.0-frameset
24296XHTML 1.0 Frameset DTD
24297@item :xhtml-1.1
24298XHTML 1.1 DTD
24299@end table
24300@end defun
24301
24302@deftp {Function} html:@var{element} @var{args} @dots{}
24303@findex html:a
24304@findex html:abbr
24305@findex html:acronym
24306@findex html:address
24307@findex html:area
24308@findex html:b
24309@findex html:base
24310@findex html:bdo
24311@findex html:big
24312@findex html:blockquote
24313@findex html:body
24314@findex html:br
24315@findex html:button
24316@findex html:caption
24317@findex html:cite
24318@findex html:code
24319@findex html:col
24320@findex html:colgroup
24321@findex html:dd
24322@findex html:del
24323@findex html:dfn
24324@findex html:div
24325@findex html:dl
24326@findex html:dt
24327@findex html:em
24328@findex html:fieldset
24329@findex html:form
24330@findex html:frame
24331@findex html:frameset
24332@findex html:h1
24333@findex html:h2
24334@findex html:h3
24335@findex html:h4
24336@findex html:h5
24337@findex html:h6
24338@findex html:head
24339@findex html:hr
24340@findex html:html
24341@findex html:i
24342@findex html:iframe
24343@findex html:img
24344@findex html:input
24345@findex html:ins
24346@findex html:kbd
24347@findex html:label
24348@findex html:legend
24349@findex html:li
24350@findex html:link
24351@findex html:map
24352@findex html:meta
24353@findex html:noframes
24354@findex html:noscript
24355@findex html:object
24356@findex html:ol
24357@findex html:optgroup
24358@findex html:option
24359@findex html:p
24360@findex html:param
24361@findex html:pre
24362@findex html:q
24363@findex html:samp
24364@findex html:script
24365@findex html:select
24366@findex html:small
24367@findex html:span
24368@findex html:strong
24369@findex html:style
24370@findex html:sub
24371@findex html:sup
24372@findex html:table
24373@findex html:tbody
24374@findex html:td
24375@findex html:textarea
24376@findex html:tfoot
24377@findex html:th
24378@findex html:thead
24379@findex html:title
24380@findex html:tr
24381@findex html:tt
24382@findex html:ul
24383@findex html:var
24384@c MOD text.html-lite
24385@c EN
24386Construct an HTML element @var{element}.  Right now,
24387the following elements are provided.
24388(The elements defined in HTML 4.01 DTD,
24389@uref{http://www.w3.org/TR/html4/sgml/dtd.html}).
24390@c JP
24391@var{element} の HTML 要素を構築します。現時点では以下の要素が
24392サポートされています。
24393(HTML 4.01 DTD @uref{http://www.w3.org/TR/html4/sgml/dtd.html}
24394に定義されている要素です)。
24395@c COMMON
24396@example
24397a        abbr       acronym    address     area      b
24398base     bdo        big        blockquote  body      br
24399button   caption    cite       code        col       colgroup
24400dd       del        dfn        div         dl        dt
24401em       fieldset   form       frame       frameset
24402h1       h2         h3         h4          h5        h6
24403head     hr         html       i           iframe    img
24404input    ins        kbd        label       legend    li
24405link     map        meta       noframes    noscript  object
24406ol       optgroup   option     p           param     pre
24407q        samp       script     select      small     span
24408strong   style      sub        sup         table     tbody
24409td       textarea   tfoot      th          thead     title
24410tr       tt         ul         var
24411@end example
24412
24413@c EN
24414The result of these functions is a tree of text segments,
24415which can be written out to a port by @code{write-tree} or
24416can be converted to a string by @code{tree->string}
24417(@pxref{Lazy text construction}).
24418
24419You can specify attributes of the element by using a keyword-value
24420notation before the actual content.
24421@c JP
24422これらの手続きは、テキスト・セグメントのツリーを返すので、
24423@code{write-tree} でポートに書き出したり、@code{tree->string} で
24424文字列に変換したりできます
24425(@ref{Lazy text construction}参照)。
24426
24427要素のアトリビュートは要素の内容に先立つキーワード-値の表記で指定することができます。
24428@c COMMON
24429@example
24430(tree->string (html:a :href "http://foo/bar" "foobar"))
24431  @result{}
24432  "<a href=\"http://foo/bar\">foobar</a\n>"
24433
24434(tree->string
24435  (html:table :width "100%" :cellpadding 0 "content here"))
24436  @result{}
24437  "<table width=\"100%\" cellpadding=\"0\">content here</table\n>"
24438@end example
24439
24440@c EN
24441The boolean value given to the attribute has a special meaning.
24442If @code{#t} is given, the attribute is rendered without a value.
24443If @code{#f} is given, the attribute is not rendered.
24444@c JP
24445属性に与える真偽値は特別な意味を持ちます。
24446@code{#t} が与えられると、属性は値なしでレンダリングされます。
24447@code{#f} が与えられると、属性それ自体がレンダリングされません。
24448@c COMMON
24449@example
24450(tree->string (html:table :border #t))
24451  @result{} "<table border></table\n>"
24452
24453(tree->string (html:table :border #f))
24454  @result{} "<table></table\n>"
24455@end example
24456
24457@c EN
24458Special characters in attribute values are escaped by the function,
24459but the ones in the content are not.  It is caller's responsibility
24460to escape them.
24461
24462The functions signal an error if a content is given to the
24463HTML element that doesn't take a content.   They do not
24464check if the given attribute is valid, neither
24465if the given content is valid for the element.
24466@c JP
24467属性の値における特別な文字は、手続きによってエスケープされますが、
24468要素の内容にある特別な文字はエスケープされません。それをエスケープ
24469するのは呼び出し側の責任です。
24470
24471内容を持たない HTML 要素に内容を与えると手続きはエラーを通知します。
24472手続きは、与えられた属性が妥当であるか、与えられた内容がその要素に
24473とって妥当であるかのチェックはしません。
24474@c COMMON
24475
24476@c EN
24477@emph{Note:}
24478You might have noticed that these procedures insert a newline
24479before @code{>} of the closing tag.  That is, the rendered
24480HTML would look like this:
24481@c JP
24482@emph{注意:}
24483これらの手続は改行を終了タグの@code{>}の前に挿入することに注意してくだ
24484さい。つまり、HTMLをレンダリングすると以下のようになります。
24485@c COMMON
24486
24487@example
24488<table><tr><td>foo</td
24489><td>bar</td
24490></tr
24491></table
24492>
24493@end example
24494
24495@c EN
24496We intentionally avoid inserting newlines after the closing
24497tag, since @emph{it depends on the surrounding context whether
24498the newline is significant or not}.  We may be able to insert newlines
24499after the elements directly below a @code{<head>} element,
24500for example, but we cannot in a @code{<p>} element, without
24501affecting the content.
24502@c JP
24503終了ダグの後に改行をいれないのは意図的なものです。@emph{改行が意味をも
24504つかどうかは外側の文脈に依存するからです}。たとえば、@code{<head>}要素
24505の直下にある要素の後に改行を入れてもテキストの内容には影響を与えませんが、
24506@code{<p>}要素中で改行を入れるとそれは内容の一部となってしまいます。
24507@c COMMON
24508
24509@c EN
24510There are three possible solutions: (1) not to insert newlines
24511at all, (2) to insert newlines within tags, and (3) to insert
24512newlines only at the safe position.  The first one creates one
24513long line of HTML, and although it is still valid HTML, it is
24514inconvenient to handle it with line-oriented tools.
24515The third one requires the
24516rendering routine to be aware of DTD.  So we took the second
24517approach.
24518@c JP
245193つ可能性があって、(1) 改行は全く入れない、(2) タグの中だけで改行を入
24520れる。(3) 安全な場所にのみ改行をいれる。最初の場合はHTMLは一行になり、
24521正当なHTMLではあるものの、行指向のツールで処理するには不便です。3番目
24522の場合はレンダリングするのにDTDをちゃんと見るツールが必要になります。
24523というわけで、ここでは2番目のアプローチを取っています。
24524@c COMMON
24525@end deftp
24526
24527@c ----------------------------------------------------------------------
24528@node Display with pager, Parsing input stream, Simple HTML document construction, Library modules - Utilities
24529@section @code{text.pager} - Display with pager
24530@c NODE ページャーを用いた出力, @code{text.pager} - ページャーを用いた出力
24531
24532@deftp {Module} text.pager
24533@mdindex text.pager
24534A convenience module to present long text nicely to the user.
24535@end deftp
24536
24537@deffn {Parameter} pager-program
24538@c MOD text.pager
24539A parameter containing a list of pager program and its arguments
24540(e.g. @code{("/usr/bin/less" "-M")}).
24541
24542The program must take input from the standard input.
24543
24544The default value is taken from the environment variable @code{PAGER}
24545if set, or either @code{less} or @code{more} if those programs are
24546available on the system.
24547@end deffn
24548
24549@defun display/pager string
24550@c MOD text.pager
24551Display @var{string} by a pager subprocess specified by the parameter
24552@code{pager-program}.  The procedure returns when the subprocess exits.
24553
24554If the terminal is not suitable for control
24555(e.g. @code{TERM} is @code{dumb} or @code{emacs}), @var{string} is
24556simply @code{display}ed without a pager.
24557
24558If you're running MinGW version of @code{gosh} on mintty,
24559calling subprocess pager doesn't work well, so the procedure
24560emulate the pager behavior (@code{pager-program} is ignored).
24561@end defun
24562
24563@defun with-output-to-pager thunk
24564@c MOD text.pager
24565Call @var{thunk} with its current output port to a string buffer,
24566then show the buffered output using @code{display/pager}.
24567
24568Note that the output begins after @var{thunk} returns.
24569@end defun
24570
24571
24572@c ----------------------------------------------------------------------
24573@node Parsing input stream, Showing progress on text terminals, Display with pager, Library modules - Utilities
24574@section @code{text.parse} - Parsing input stream
24575@c NODE 入力ストリームのパージング, @code{text.parse} - 入力ストリームのパージング
24576
24577@deftp {Module} text.parse
24578@mdindex text.parse
24579@c EN
24580A collection of utilities that does simple parsing from
24581the input port.   The API is inspired, and compatible with
24582Oleg Kiselyov's input parsing library (@uref{http://okmij.org/ftp/Scheme/parsing.html}).
24583His library is used in lots of other libraries, notably,
24584a full-Scheme XML parser/generator SSAX (@uref{http://okmij.org/ftp/Scheme/xml.html}).
24585
24586You can use this module in place of his
24587@code{input-parse.scm} and @code{look-for-str.scm}.
24588
24589I reimplemented the functions to be efficient on Gauche.
24590Especially, usage of @code{string-set!} is totally avoided.
24591I extended the interface a bit so that they can deal with character sets
24592and predicates, as well as a list of characters.
24593
24594These functions work sequentially on the given input port,
24595that is, they read from the port as much as they need, without
24596buffering extra characters.
24597@c JP
24598入力ポートに対して単純な解析を行うユーティリティのコレクションです。
24599API は Oleg Kiselyov 氏の入力解析ライブラリ (@uref{http://okmij.org/ftp/Scheme/parsing.html}) に
24600触発され、互換性を持つものです。氏のライブラリは、他のたくさんの
24601ライブラリで使われています。特に、Scheme のみで書かれたパーサ/ジェネレータ
24602である SSAX (@uref{http://okmij.org/ftp/Scheme/xml.html}) が挙げられます。
24603
24604このモジュールは、氏の @code{input-parse.scm} や @code{look-for-str.scm}
24605の代わりに使うことができます。
24606
24607Gauche で効果的になるように手続きを再実装しました。特に、@code{string-set!}
24608の使用は完全に取り除きました。インターフェースを少し拡張したので、
24609文字集合や述語、文字のリストにも使うことができます。
24610
24611これらの手続きは、与えられた入力ポートに対してシーケンシャルに動作します。
24612それは、ポートから必要なだけ読み、余分な文字をバッファリングしないということです。
24613@c COMMON
24614@end deftp
24615
24616@defun find-string-from-port? str in-port :optional max-no-chars
24617@c MOD text.parse
24618@c EN
24619Looks for a string @var{str} from the input port @var{in-port}.
24620The optional argument @var{max-no-chars} limits the maximum number of
24621characters to be read from the port; if omitted, the search span is
24622until EOF.
24623
24624If @var{str} is found, this function returns the number of characters
24625it has read.   The next read from @var{in-port} returns the next char
24626of @var{str}.  If @var{str} is not found, it returns @code{#f}.
24627
24628Note: Although this procedure has `@code{?}' in its name,
24629it may return non-boolean value, contrary to the Scheme convention.
24630@c JP
24631入力ポート @var{in-port} から、文字列 @var{str} を探します。
24632オプショナル引数 @var{max-no-chars} は、ポートから読み込まれる最大文字数を
24633制限します。省略されると、検索する範囲は EOF までとなります。
24634
24635@var{str} が見つかると、手続きはすでに読み込んだ文字の数を返します。
24636@var{in-port} の次回の読み込みは、@var{str} の次の文字を返します。
24637@var{str} が見つからない場合、@code{#f} が返ります。
24638
24639注意: この手続きはその名前に「@code{?}」がつきますが、Scheme の慣習に反し、
24640真偽値ではない値を返すことがあります。
24641@c COMMON
24642@end defun
24643
24644@defun peek-next-char :optional port
24645@c MOD text.parse
24646@c EN
24647Discards the current character and peeks the next character from @var{port}.
24648Useful to look ahead one character.
24649If @var{port} is omitted, the current input port is used.
24650@c JP
24651現在の文字を破棄し、@var{port} から次の文字を読みます。一文字先読みするのに
24652便利です。@var{port} が省略されると、現在の入力ポートが使われます。
24653@c COMMON
24654@end defun
24655
24656@c EN
24657In the following functions, @var{char-list} refers to one of the
24658followings:
24659@itemize @bullet
24660@item
24661A character set.
24662@item
24663A list of characters, character sets and/or symbol @code{*eof*}.
24664@end itemize
24665That denotes a set of characters.  If a symbol @code{*eof*} is
24666included, the EOF condition is also included.  Without @code{*eof*},
24667the EOF condition is regarded as an error.
24668@c JP
24669以下の手続きでは、@var{char-list} は次のどれかを意味します。
24670@itemize @bullet
24671@item
24672文字集合。
24673@item
24674文字、文字集合、シンボル @code{*eof*} の任意の組み合わせのリスト。
24675@end itemize
24676これらにより文字の集合が表現されます。シンボル @code{*eof*} が含まれる場合、
24677EOF の条件もまた含まれます。@code{*eof*} が含まれない場合、EOF の条件は
24678エラーとして扱われます。
24679@c COMMON
24680
24681@defun assert-curr-char char-list string :optional port
24682@c MOD text.parse
24683@c EN
24684Reads a character from @var{port}.  If it is included in @var{char-list},
24685returns the character.  Otherwise, signals an error with a message
24686containing @var{string}.
24687If @var{port} is omitted, the current input port is used.
24688@c JP
24689@var{port} から文字を読みます。その文字が @var{char-list} に含まれている場合は
24690その文字を返します。そうでなければ、@var{string} を含むメッセージとともに
24691エラーを通知します。
24692@c COMMON
24693@end defun
24694
24695@defun skip-until char-list/number :optional port
24696@c MOD text.parse
24697@c EN
24698@var{char-list/number} is either a char-list or a number.
24699If it is a number; it reads that many characters and returns @code{#f}.
24700If the input is not long enough, an error is signaled.
24701If @var{char-list/number} is a char-list, it reads from @var{port}
24702until it sees a character that belongs to the char-list.
24703Then the character is returned.
24704If @var{port} is omitted, the current input port is used.
24705@c JP
24706@var{char-list/number} は、文字のリストか数です。
24707数の場合、たくさんの文字を読んで、@code{#f} を返します。
24708入力が十分に長くない場合は、エラーが通知されます。
24709@var{char-list/number} が文字のリストの場合、その文字リストに属する文字に
24710出会うまで @var{port} を読み込み、その文字を返します。
24711@var{port} が省略された場合、現在の入力ポートが使われます。
24712@c COMMON
24713@end defun
24714
24715@defun skip-while char-list :optional port
24716@c MOD text.parse
24717@c EN
24718Reads from @var{port} until it sees a character that does not
24719belong to @var{char-list}.  The character remains in the stream.
24720If it reaches EOF, an EOF is returned.
24721If @var{port} is omitted, the current input port is used.
24722
24723This example skips whitespaces from input.  Next read from
24724port returns the first non-whitespace character.
24725@c JP
24726@var{char-list} に属しない文字に出会うまで、@var{port} を読み込みます。
24727文字はストリームに残されます。EOF に達したら EOF が返されます。
24728@var{port} が省略された場合、現在の入力ポートが使われます。
24729
24730この例では、入力から空白スペースをスキップしています。ポートからの次の
24731読み込みは、最初の空白スペースでない文字を返します。
24732@c COMMON
24733@example
24734(skip-while #[\s] port)
24735@end example
24736@end defun
24737
24738@defun next-token prefix-char-list break-char-list :optional comment port
24739@c MOD text.parse
24740@c EN
24741Skips any number of characters in @var{prefix-char-list},
24742then collects the characters until it sees @var{break-char-list}.
24743The collected characters are returned as a string.
24744The break character remains in the @var{port}.
24745
24746If the function encounters EOF and @code{*eof*} is not included in
24747@var{break-char-list}, an error is signaled with @var{comment} is
24748included in the message.
24749@c JP
24750@var{prefix-char-list} に含まれる文字はいくつでもスキップします。
24751そして、@var{break-char-list} に含まれる文字に出会うまで、文字を
24752蓄積します。蓄積された文字群は文字列として返されます。
24753中断文字は @var{port} に残されます。
24754
24755手続きが EOF に達し、@code{*eof*} が @var{break-char-list} に含まれていない
24756場合、@var{comment} が含まれたメッセージとともにエラーが通知されます。
24757@c COMMON
24758@end defun
24759
24760@defun next-token-of char-list/pred :optional port
24761@c MOD text.parse
24762@c EN
24763Reads and collects the characters as far as
24764it belongs to @var{char-list/pred}, then returns them as a string.
24765The first character that doesn't belong to @var{char-list/pred} remains
24766on the port.
24767
24768@var{char-list/pred} may be a char-list or a predicate that takes
24769a character.   If it is a predicate, each character is passed to it,
24770and the character is regarded to ``belong to'' @var{char-list/pred}
24771when it returns a true value.
24772@c JP
24773読み込んだ文字が @var{char-list/pred} にある限り蓄積し、文字列として
24774返します。@var{char-list/pred} に含まれない最初の文字はポートに残されます。
24775
24776@var{char-list/pred} は文字のリストか文字を取る述語です。述語の場合、
24777それぞれの文字がその述語に渡され、真の値が返る場合はその文字は
24778@var{char-list/pred} に属するとみなされます。
24779@c COMMON
24780@end defun
24781
24782@defun read-string n :optional port
24783@c MOD text.parse
24784@c EN
24785This is like built-in @code{read-string} (@pxref{Reading data}),
24786except that this returns @code{""} when the input already reached EOF.
24787
24788Provided for the compatibility for the code that depends Oleg's library.
24789@c JP
24790組み込みの@code{read-string} (@ref{Reading data}参照) とほぼ同じですが、
24791入力が既にEOFに達していた場合は@code{""}を返します。
24792
24793Olegのライブラリに依存しているコードの互換性のために用意されています。
24794@c COMMON
24795@end defun
24796
24797@c ----------------------------------------------------------------------
24798@node Showing progress on text terminals, SQL parsing and construction, Parsing input stream, Library modules - Utilities
24799@section @code{text.progress} - Showing progress on text terminals
24800@c NODE テキスト端末上で進捗を表示する, @code{text.progress} - テキスト端末上で進捗を表示する
24801
24802@deftp {Module} text.progress
24803@mdindex text.progress
24804@c EN
24805This module provides a utility to report a progress of processing
24806on a text terminal, using characters to display bar chart.
24807@c JP
24808このモジュールはバーチャートを文字を用いて表示し、テキスト端末上に処理
24809の進行状況を出すためのユーティリティです。
24810@c COMMON
24811
24812@c EN
24813The generic format of a progress bar consists of a single line
24814of text, which is splitted into several parts; a header, which
24815displays the title; followed by a bar, a numeric part, and a time part,
24816as shown in the following example (only the line beginning with ``foo''
24817is actually displayed).
24818@c JP
24819進捗を示すプログレスバーの汎用的なフォーマットは1行のテキストで構成されます。
24820この1行はいくつかの部分に分解できます。タイトルを表示するヘッダ部、その後に
24821プログレスバーがあって、数値部、時間部と続きます。以下がその例です(foo
24822からはじまる1行だけが実際に表示されます。
24823@c COMMON
24824@example
24825<-header-> <-------bar---------> <-num-><-time->      <---info---->
24826foo       |#############        |123/211   01:21 ETA  compiling...
24827          ^
24828          separator
24829@end example
24830
24831@c EN
24832Various things like the character used in the bar chart or
24833the format of the numeric progress can be configured.
24834@c JP
24835バーチャートに使う文字などのいろいろなバリエーションや、数値で表わす
24836進捗のフォーマットなども設定可能です。
24837@c COMMON
24838
24839@c EN
24840Internally a progress bar maintains two numbers, the maximum (goal)
24841value and the current value.  The bar shows the proportion of
24842the current value relative to the maximum value.  The numeric progress
24843shows the current value over the maximum value by default, but you
24844can configure it to show only the current value or percentage, for example.
24845@c JP
24846内部的にはプログレスバーは2つの数値、最大値(ゴール)と現在の値を保持し
24847ています。バーは最大値に対する現在の値の比を示すものです。数値で表わす
24848進捗はデフォルトでは最大値の上に現在の値を表示します。しかし、たとえば、
24849現在の値だけを表示するとか、100分率で表示するなどの設定が可能です。
24850@c COMMON
24851
24852@c EN
24853A progress bar also has two states, ``in progress'' and ``finished''.
24854When it is in progress, every time the text is displayed it is
24855followed by @code{#\return}, so that the next display overwrites
24856the bar, and the time part shows ETA (estimated time of arrival).
24857Once it becomes finished, the last line of text is displayed
24858with @code{#\newline}, and the time part shows the actual time
24859it took to finish.
24860@c JP
24861プログレスバーは2つの状態「進捗中」および「終了」のどちらかの状態を保
24862持しています。「進捗中」なら、どの時点でも表示されるテキストには
24863@code{#\return}が続きます。これにより次の表示が前の表示を上書きするこ
24864とになります。時間部はETA(残り時間)を表示します。終了してしまえば、最
24865後の行の後に@code{#\newline}が続きます。時間部には終了までにかかった時
24866間が表示されます。
24867@c COMMON
24868@end deftp
24869
24870@c EN
24871This module provides only one procedure, @code{make-text-progress-bar},
24872which packages the progress bar feature in a closure and returns it.
24873@c JP
24874このモジュールは@code{make-text-progress-bar}という手続きを1つだけ提供
24875します。この手続きはプログレスバーの機能をクロージャに包んでそれを返し
24876ます。
24877@c COMMON
24878
24879@defun make-text-progress-bar :key header header-width bar-char bar-width num-width num-format time-width info info-width separator-char max-value port
24880@c MOD text.progress
24881@c EN
24882Returns a procedure that packages operations on the progress bar.
24883The procedure can be called with a symbol indicating an operation,
24884and an optional numeric argument.
24885@c JP
24886プログレスバー上の操作を包んだ手続きを返します。返された手続きに操作を
24887示すシンボルとオプションで数値を引数として渡して使います。
24888@c COMMON
24889
24890@table @code
24891@item @var{proc} 'show
24892@c EN
24893Redisplays the progress bar.  All other operations implies redisplay,
24894so you don't need to use this unless you have a specific reason to
24895redisplay the current state.
24896@c JP
24897プログレスバーを再表示する。他のどの操作も状態の再表示を行います。
24898したがって、現在のステータスを再表示しなければない特別な理由がないかぎ
24899りこれを使う必要はありません。
24900@c COMMON
24901
24902@item @var{proc} 'set @var{value}
24903@c EN
24904Sets the current value to @var{value}, then redisplays the progress bar.
24905If @var{value} exceeds the max value, it is clipped by the max value.
24906@c JP
24907現在の値を@var{value}にセットし、プログレスバーを再表示します。
24908@var{value}が最大値を超えていたら、超過分を切り捨て最大値にします。
24909@c COMMON
24910
24911@item @var{proc} 'inc @var{value}
24912@c EN
24913Increments the current value by @var{value}, then redisplays the progress bar.
24914If the current value exceeds the max value, it is clipped by the max value.
24915@c JP
24916@var{value}分だけ現在の値を増し、プログレスバーを再表示します。現在の
24917値が最大値を超えたら、超過分を切り捨て最大値にします。
24918@c COMMON
24919
24920@item @var{proc} 'finish
24921@c EN
24922Puts the progress bar to the ``finished'' state, then redisplays it.
24923The time part shows the total elapsed time, and the line is terminated
24924by @code{#\newline} so that it won't be clobbered.   Once a progress
24925bar becomes ``finished'', there's no way to put it back ``in progress''.
24926@c JP
24927プログレスバーを「終了」状態にし、再表示します。時間部はトータルの経過
24928時間を表示します。また、表示行末は@code{#\newline}とし、上書きされない
24929ようにします。プログレスバーはいったん「終了」状態になれば、「進捗中」
24930状態に戻す方法はありません。
24931@c COMMON
24932
24933@item @var{proc} 'set-info @var{text}
24934@c EN
24935Changes the text displayed in the ``info'' part.  To use the info part,
24936you have to give a positive value to @var{info-width} keyword argument
24937of @code{make-text-progress-bar}.
24938@c JP
24939``info''部に表示されるテキストを変更します。
24940info部を使うには、@code{make-text-progress-bar}の@var{info-width}キーワード
24941引数に正の値が指定されている必要があります。
24942@c COMMON
24943
24944
24945@item @var{proc} 'set-header @var{text}
24946@c EN
24947Changes the text displayed in the ``header' area.
24948@c JP
24949``header''部に表示されるテキストを変更します。
24950@c COMMON
24951@end table
24952
24953@c EN
24954The keyword arguments are used to customize the display:
24955@c JP
24956キーワード引数を使って表示をカスタマイズできます。
24957@c COMMON
24958@table @var
24959@item header
24960@c EN
24961The text to be displayed in the header part.
24962This can be changed later, by sending @code{set-header} message
24963to the created progress bar.
24964@c JP
24965ヘッダ部に表示するテキスト。このテキストは、作られたプログレスバーに
24966@code{set-header}メッセージを送ることで後で変更可能です。
24967@c COMMON
24968
24969@item header-width
24970@c EN
24971The width of the header part, in number of characters.
24972The header text is displayed left-aligned in the part.
24973If the header text is longer than the width, the excess characters
24974are omitted.  The default is 14.
24975@c JP
24976ヘッダ部の幅、文字数で指定します。ヘッダ部のテキストは左詰めです。ヘッ
24977ダ部に置くテキストが幅よりも長い場合には超過分の文字は切り捨てられます。
24978デフォルトは14文字です。
24979@c COMMON
24980
24981@item bar-char
24982@c EN
24983A character used to draw a bar chart.  The default is @code{#\#}.
24984@c JP
24985バーチャートを描くのに使う文字。デフォルトは@code{#\#}です。
24986@c COMMON
24987
24988@item bar-width
24989@c EN
24990The width of the bar chart part, in number of characters.
24991The default is 40.
24992@c JP
24993バーチャート部の幅で、文字数で指定します。デフォルトでは40文字です。
24994@c COMMON
24995
24996@item num-width
24997@c EN
24998The width of the numeric part, in number of characters.
24999The default is 9.  Setting this to 0 hides the numeric part.
25000@c JP
25001数値部の幅で、文字数で指定します。デフォルトでは9で、これを0に設定する
25002と数値部を隠せます。
25003@c COMMON
25004
25005@item num-format
25006@c EN
25007A procedure to format the numeric part.  Two arguments are
25008passed; the current value and the maximum value.  It must return
25009a string.  The default is the following procedure.
25010@c JP
25011数値部を整形する手続き。引数が2つ渡されます。ひとつは現在の値、もうひ
25012とつは最大値です。この手続きは文字列を返さなければなりません。デフォル
25013トでは以下の手続きです。
25014@c COMMON
25015@example
25016(lambda (cur max)
25017  (format "~d/~d" cur max))
25018@end example
25019
25020@item time-width
25021@c EN
25022The width of the time part, in number of characters.
25023The default is 7.  Settings this to 0 hides the time part.
25024@c JP
25025時間部の幅で、文字数で指定します。デフォルトでは7文字で、これを0に設定
25026すると時間部を隠せます。
25027@c COMMON
25028
25029@item info
25030@c EN
25031The text to be displayed in the info part.  This text can be
25032changed later by sending @code{set-info} message to the created
25033progress bar.  Note that you have to give a positive number
25034to @var{info-width} keyword argument to enable the info part.
25035@c JP
25036info部に表示されるテキストです。このテキストは、作られたプログレスバーに
25037@code{set-info}メッセージを送ることで後から変更できます。
25038info部を表示するには、@var{info-width}キーワード引数に正の値を
25039与えておく必要があります。
25040@c COMMON
25041
25042@item info-width
25043@c EN
25044The width of the info part.  The default value is zero,
25045which means the info part is not displayed.
25046@c JP
25047info部の表示幅です。デフォルトは0で、info部は表示されません。
25048@c COMMON
25049
25050@item separator-char
25051@c EN
25052A character put around the bar part.  Default is @code{#\|}.
25053You can pass @code{#f} not to display the separators.
25054@c JP
25055バー部分の前後に置く文字です。デフォルトでは@code{#\|}です。
25056セパレータを表示したくなければ、@code{#f}を渡します。
25057@c COMMON
25058
25059@item max-value
25060@c EN
25061The maximum value of the progress bar.  Must be a positive real number.
25062Default is 100.
25063@c JP
25064プログレスバーの最大値です。正の実数でなければなりません。デフォルトでは100です。
25065@c COMMON
25066
25067@item port
25068@c EN
25069An output port to which the progress bar is displayed.  The default value
25070is the current output port when @code{make-text-progress-bar} is called.
25071@c JP
25072プログレスバーを表示する出力ポートです。デフォルト値は
25073@code{make-text-progress-bar}が呼ばれた時点での現在の出力ポートです。
25074@c COMMON
25075@end table
25076@end defun
25077
25078@c EN
25079Here's a simple example, using customized numeric part:
25080@c JP
25081以下は簡単なカスタマイズをした例です。
25082@c COMMON
25083
25084@example
25085(use text.progress)
25086
25087(define (main args)
25088  (define (num-format cur max)
25089    (format "~d/~d(~3d%)" cur max
25090            (round->exact (/. (* cur 100) max))))
25091
25092  (let ((p (make-text-progress-bar :header "Example"
25093                                   :header-width 10
25094                                   :bar-char #\o
25095                                   :num-format num-format
25096                                   :num-width 13
25097                                   :max-value 256)))
25098    (do ((i 0 (+ i 1)))
25099        ((= i 256) (p 'finish))
25100      (p 'inc 1)
25101      (sys-select #f #f #f 50000))))
25102@end example
25103
25104@c ----------------------------------------------------------------------
25105@node SQL parsing and construction, Simple template expander, Showing progress on text terminals, Library modules - Utilities
25106@section @code{text.sql} - SQL parsing and construction
25107@c NODE SQLのパーズと構築, @code{text.sql} - SQLのパーズと構築
25108
25109@deftp {Module} text.sql
25110@mdindex text.sql
25111@c EN
25112This module provides a utility to parse and construct SQL statement.
25113@c JP
25114このモジュールはSQL文のパーズと構築のためのユーティリティを提供します。
25115@c COMMON
25116
25117@c EN
25118It is currently under development, and we only have a tokenization routine.
25119The plan is to define S-expression syntax of SQL and provides a routine
25120to translate one form to the other.
25121@c JP
25122このモジュールは現在まだ開発途上にあります。まだトークン列を生成するルー
25123チンしかありません。SQLのS式構文を定義して、SQLとその構文との間の変換
25124ルーチンを提供する計画です。
25125@c COMMON
25126
25127@c EN
25128Note: If you're looking for a routine to escape strings to be
25129safe in SQL, see @code{dbi-escape-sql} in @ref{DBI user API}.
25130@c JP
25131註: SQLに安全に渡せるように文字列をエスケープするルーチンをお探しなら、
25132@ref{DBI user API}の@code{dbi-escape-sql}を見てください。
25133@c COMMON
25134@end deftp
25135
25136@defun sql-tokenize sql-string
25137@c MOD text.sql
25138@c EN
25139Tokenize a SQL statement @var{sql-string}.  The return value is
25140a list of tokens, where each token is
25141represented by one of the following forms.
25142@c JP
25143SQL文@var{sql-string}をトークン列に分解します。返り値はトークンのリス
25144トで、各トークンは以下の形式のひとつで表現されます。
25145@c COMMON
25146
25147@c EN
25148@example
25149<symbol>              Special delimiter.  One of the followings:
25150                      + - * / < = > <> <= >= ||
25151<character>           Special delimiter.  One of the followings:
25152                      #\, #\. #\( #\) #\;
25153<string>              Regular identifier
25154(delimited <string>)  Delimited identifier
25155(parameter <num>)     Positional parameter (?)
25156(parameter <string>)  Named parameter (:foo)
25157(string    <string>)  Character string literal
25158(number    <string>)  Numeric literal
25159(bitstring <string>)  Binary string.  <string> is like "01101"
25160(hexstring <string>)  Binary string.  <string> is like "3AD20"
25161@end example
25162@c JP
25163@example
25164<symbol>              特殊区切り子、以下のどれか
25165                      + - * / < = > <> <= >= ||
25166<character>           特殊区切り子、以下のどれか
25167                      #\, #\. #\( #\) #\;
25168<string>              通常の識別子
25169(delimited <string>)  区切られた識別子
25170(parameter <num>)     位置パラメータ (?)
25171(parameter <string>)  名前つきパラメータ (:foo)
25172(string    <string>)  文字列リテラル
25173(number    <string>)  数値リテラル
25174(bitstring <string>)  バイナリ文字列  <string> は "01101" な感じ
25175(hexstring <string>)  Binary string.  <string> は "3AD20" な感じ
25176@end example
25177@c COMMON
25178
25179@c EN
25180If it encounters an untokenizable string, it raises an
25181@code{<sql-parse-error>} condition.
25182@c JP
25183トークンに分解できない文字列がくると@code{<sql-parse-error>}コンディショ
25184ンがあがります。
25185@c COMMON
25186@end defun
25187
25188@deftp {Condition Type} <sql-parse-error>
25189@c MOD text.sql
25190@c EN
25191A condition to indicate an SQL parse error.  Inherits @code{<error>}.
25192@c JP
25193SQLパーズエラーを示すコンディション。@code{<error>}を継承。
25194@c COMMON
25195@defivar <sql-parse-error> sql-string
25196@c EN
25197Holds the source SQL string.
25198@c JP
25199元のSQL文字列を保持。
25200@c COMMON
25201@end defivar
25202@end deftp
25203
25204@c ----------------------------------------------------------------------
25205@node Simple template expander, Transliterate characters, SQL parsing and construction, Library modules - Utilities
25206@section @code{text.template} - Simple template expander
25207@c NODE 簡単なテンプレート拡張, @code{text.template} - 簡単なテンプレート拡張
25208
25209@deftp {Module} text.template
25210@mdindex text.template
25211@c EN
25212This module lifts Gauche's built-in string interpolation feature
25213to be more general template engine.
25214@c JP
25215このモジュールは、Gauche組み込みの文字列補間機能をより一般的なテンプレートエンジンとして
25216使えるようにするものです。
25217@c COMMON
25218
25219@c EN
25220Gauche's string interpolation syntax is expanded at read time and then
25221handled by macro expanders, and
25222becomes a simple Scheme code fragment.
25223For example, if you have this:
25224@c JP
25225Gaucheの文字列補間構文はソース読み込み時にマクロ呼び出しへと展開され、
25226さらにマクロ展開器により展開されて単純なSchemeコード片となります。
25227例えば、次のソースコードがある場合:
25228@c COMMON
25229@example
25230(let ([x 10])
25231  #"The square of x is ~(* x x).")
25232@end example
25233
25234@c EN
25235It is eventually converted to this after macro expansion:
25236@c JP
25237マクロ展開後の最終形は次のコードになります:
25238@c COMMON
25239@example
25240(let ([x 10])
25241  (string-append '"The square of x is " (x->string (* x.0 x.0)) '"."))
25242@end example
25243
25244@c EN
25245It is a kind of template expansion, but you have to have the template string
25246as a literal, so it's restricted.  With this module, you can feed template
25247string and the bindings of the value at the runtime:
25248@c JP
25249これも一種のテンプレート展開と言えるのですが、文字列補間ではテンプレート文字列が
25250文字列リテラルとしてソースコード上に現れていなければならないという制限があります。
25251このモジュールでは、文字列と束縛を実行時に与えることができます:
25252@c COMMON
25253
25254@example
25255(define *template* "The square of x is ~(* x x).")
25256
25257(expand-template-string *template*
25258  (make-template-environment :bindings '(x 10)))
25259  @result{} "The square of x is 100."
25260@end example
25261
25262@c EN
25263The syntax of template strings is the same as string interpolation
25264(@pxref{String interpolation}); that is, tokens following @code{~}
25265is read as a Scheme expression.  In case if the token is a symbol
25266and you need to delimit it from subsequent characters, you can use
25267symbol escape by @code{|}.
25268@c JP
25269テンプレート文字列の構文は文字列補間のそれと同じです(@ref{String interpolation}参照)。
25270すなわち、@code{~}に続くトークンがScheme式として呼ばれます。もしトークンがシンボルで、
25271その後の続く文字から区切る必要がある場合は、@code{|}によるシンボルエスケープが使えます。
25272@c COMMON
25273
25274@c EN
25275You also need to provide a @emph{template environment}, where the
25276expressions in the template is evaluated.  Note that,
25277unlike string interpolation,
25278those expressions can't refer to the local bindings.
25279@c JP
25280また、テンプレート展開時には、テンプレート中の式を評価するための
25281@emph{テンプレート環境}を与える必要があります。
25282文字列補間と違って、テンプレート中の式がローカル束縛を参照することはできません。
25283@c COMMON
25284@end deftp
25285
25286@defun expand-template-string template env
25287@c EN
25288Expands a template string @var{template} with a template environment
25289@var{env}, and returns the result string.
25290@c JP
25291テンプレート文字列@var{template}を、テンプレート環境@var{env}のもとで展開し、
25292結果の文字列を返します。
25293@c COMMON
25294@end defun
25295
25296@defun expand-template-file filename env :optional paths
25297@c EN
25298Reads a template string from a file named by @var{filename}, expands
25299it with a template environment @var{env}, and returns the result string.
25300
25301If @var{filename} is not an absolute path, it is looked in the directories
25302listed in @var{paths}.
25303@c JP
25304テンプレート文字列を@var{filename}で指定されるファイルから読み込み、
25305テンプレート環境@var{env}のもとでそれを展開し、結果の文字列を返します。
25306
25307@var{filename}が絶対パスでない場合は、@var{paths}中のディレクトリからの相対パスで
25308探されます。
25309@c COMMON
25310@end defun
25311
25312@defun make-template-environment :key extends imports bindings
25313@c EN
25314Creates and returns a template environment.   A template environment
25315is like a module (@pxref{Modules}): It maps symbols to values, and
25316it can import bindings from other modules, or extend other modules.
25317@c JP
25318テンプレート環境を作成して返します。テンプレート環境はモジュールのようなものです
25319(@ref{Modules}参照)。それはシンボルを値にマップし、
25320また他のモジュールから束縛をインポートしたり、他のモジュールをextendしたりできます。
25321@c COMMON
25322
25323@c EN
25324The keyword arguments @var{extends} and @var{imports} must be a list
25325of symbols; they specify names of modules to inherit from or to import from.
25326@c JP
25327キーワード引数@var{extends}と@var{imports}はシンボルのリストを取り、
25328それぞれ継承元のモジュール、あるいはインポート元のモジュールを指定します。
25329@c COMMON
25330
25331@c EN
25332The keyword arguments @var{bindings} must either be a dictionary
25333(anything that inherits @code{<dictionary>}), or a key-value list.
25334The mappings represented by it are incorporated to the environment.
25335@c JP
25336キーワード引数@var{bindings}はディクショナリ(@code{<dictionary>}のサブクラスの
25337インスタンス)か、key-valueリストでなければなりません。
25338それにより表される束縛が環境に取り込まれます。
25339@c COMMON
25340@end defun
25341
25342@c ----------------------------------------------------------------------
25343@node Transliterate characters, Lazy text construction, Simple template expander, Library modules - Utilities
25344@section @code{text.tr} - Transliterate characters
25345@c NODE 文字変換, @code{text.tr} - 文字変換
25346
25347@deftp {Module} text.tr
25348@mdindex text.tr
25349@c EN
25350This module implements a transliterate function,
25351that substitutes characters of the input string.
25352This functionality is realized in Unix @code{tr(1)} command,
25353and incorporated in various programs such as @code{sed(1)}
25354and @code{perl}.
25355
25356Gauche's @code{tr} is aware of multibyte characters.
25357@c JP
25358このモジュールは、入力ストリームから指定の文字を置き換えて出力する、
25359文字変換(transliterate)機能を提供します。
25360Unixの@code{tr(1)}コマンドで実装され、@code{sed}や@code{perl}にも
25361採り入れられている機能です。
25362
25363Gaucheの@code{tr}はマルチバイト文字/文字列を正しく扱います。
25364@c COMMON
25365@end deftp
25366
25367@defun tr from-list to-list :key :complement :delete :squeeze :table-size :input :output
25368@c MOD text.tr
25369@c EN
25370Reads from @var{input} and writes to @var{output},
25371with transliterating characters in @var{from-list} to the
25372corresponding ones in @var{to-list}.  Characters that doesn't
25373appear in @var{from-list} are passed through.
25374@c JP
25375@var{input}から文字を読み込み、その文字が@var{from-list}内にあれば
25376対応する@var{to-list}内の文字に置き換えて、@var{output}へと書き出します。
25377@var{from-list}に無い文字はそのまま@var{output}へと渡されます。
25378@c COMMON
25379
25380@c EN
25381The default values of @var{input} and @var{output} are
25382current input port and current output port, respectively.
25383@c JP
25384@var{input}と@var{output}の既定値はそれぞれ現在の入力ポートと
25385出力ポートです。
25386@c COMMON
25387
25388@c EN
25389Both @var{from-list} and @var{to-list} must be strings.
25390They may contain the following special syntax.
25391Other characters that doesn't fits in the syntax are taken as they are.
25392@c JP
25393@var{from-list}と@var{to-list}は文字列でなければなりません。
25394その中には次のような表記を使うことができます。それ以外の文字はそのまま使われます。
25395@c COMMON
25396
25397@table @code
25398@item @b{x-y}
25399@c EN
25400Expanded to the increasing sequence of characters from @code{x} to @code{y},
25401inclusive.  The order is determined by the internal character
25402encoding system; generally it is safer to limit use of this within
25403the range of the same character class.   The character @code{x}
25404must be before @code{y}.
25405@c JP
25406文字@code{x}から文字@code{y}までの文字の昇順の並びと解釈されます。
25407@code{x}と@code{y}は含まれます。文字の並びはGaucheの内部文字エンコーディングに
25408よって決定されるので、一般には@code{x}と@code{y}は同じキャラクタクラスの中に
25409止めておいた方が安全でしょう。@code{x}は@code{y}より小さくなければなりません。
25410@c COMMON
25411
25412@item @b{x*n}
25413@c EN
25414Repeat @code{x} for @code{n} times.  @code{n} is a decimal number notation.
25415Meaningful only in
25416@var{to-list}; it is an error to use this form in @var{from-list}.
25417If @code{n} is omitted or zero, @code{x} is repeated until @var{to-list}
25418matches the length of @var{from-list} (any character after it is ignored).
25419@c JP
25420文字@code{x}の@code{n}個の並び。@code{n}は10進数で表記された数値です。
25421これは@var{to-list}でのみ有効で、@var{from-list}で使うとエラーになります。
25422@code{n}が省略されるか0の場合、@code{x}は@var{to-list}の長さが@var{from-list}
25423の長さに達するまで繰り返されます(その場合、@var{to-list}の残りは無視されます)。
25424@c COMMON
25425
25426@item @b{@code{\}x}
25427@c EN
25428Represents @code{x} itself.  Use this escape to avoid a special
25429character to be interpreted as itself.   Note that if you place
25430a backslash in a string, you must write @code{\\}, for the Scheme
25431reader also interprets backslash as a special character.
25432
25433There's no special sequence to represent non-graphical characters,
25434for you can put such characters by the string syntax.
25435@c JP
25436文字@code{x}それ自身。特殊文字そのものを埋め込みたい場合に使います。
25437文字列のリーダも@code{\}を解釈するので、@code{\\}と書かねばならないことに注意
25438して下さい。
25439
25440グラフィカルでない文字のための構文はありません。文字列リーダの構文を使って
25441そのような文字を文字列に含めることができます。
25442@c COMMON
25443@end table
25444
25445@c EN
25446Here's some basic examples.
25447@example
25448;; @r{swaps case of input}
25449(tr "A-Za-z" "a-zA-Z")
25450
25451;; @r{replaces 7-bit non-graphical characters to `?'}
25452(tr "\x00-\x19\x7f" "?*")
25453@end example
25454@c JP
25455いくつか例を挙げます。
25456@example
25457;; @r{大文字と小文字を交換します}
25458(tr "A-Za-z" "a-zA-Z")
25459
25460;; @r{ひらがなとかたかなを交換します}
25461(tr "ぁ-んァ-ン" "ァ-ンぁ-ん")
25462
25463;; @r{7ビットのノングラフィカルな文字を`?'に変換します}
25464(tr "\x00-\x19\x7f" "?*")
25465@end example
25466@c COMMON
25467
25468@c EN
25469If @var{to-list} is shorter than @var{from-list}, the behavior
25470depends on the keyword argument @var{delete}.  If a true value is
25471given,  characters that appear in @var{from-list} but not
25472in @var{to-list} are deleted.   Otherwise,
25473the extra characters in @var{from-list} are just passed through.
25474@c JP
25475@var{to-list}が@var{from-list}より短い場合、動作はキーワード引数@var{delete}に
25476依存します。もし真の値が@var{delete}に与えられれば、@var{from-list}に現われて
25477@var{to-list}に対応するものがない文字は入力から取り除かれます。そうでなければ
25478そのような文字はそのまま出力されます。
25479@c COMMON
25480
25481@c EN
25482When a true value is specified to @var{complement},
25483the character set in @var{from-list} is complemented.
25484Note that it implies @emph{huge} set of characters,
25485so it is not very useful unless either output character
25486set is a single character (using `*') or used with
25487@code{delete} keyword.
25488@c JP
25489真の値が@var{complement}に与えられた場合、@var{from-list}の文字の
25490補集合が@var{from-list}として使われます。この文字集合は極めて大きくなる
25491可能性があることに注意してください。従って、一般にこのオプションは
25492@var{to-list}に`*'を使ってそれらの文字を一文字にマッピングするか、
25493@code{delete}オプションと併用するかしないとあまり意味がありません。
25494@c COMMON
25495
25496@c EN
25497When a true value is specified to @var{squeeze},
25498the sequence of the same replaced characters is squeezed to one.
25499If @var{to-list} is empty, the sequence of the same characters
25500in @var{from-list} is squeezed.
25501@c JP
25502真の値が@var{squeeze}に与えられた場合、同じ文字への置換が2つ以上並ぶ場合に
255032つめ以降の文字が削除されます。@var{to-list}が空の場合は、@var{from-list}
25504に含まれる文字で同一文字が並んだ場合に2つめ以降の文字が削除されます。
25505@c COMMON
25506
25507@c EN
25508Internally, @code{tr} builds a table to map the characters for
25509efficiency.  Since Gauche can deal with potentially huge set
25510of characters, it limits the use of the table for only smaller
25511characters (<256 by default).  If you want to transliterate
25512multibyte characters on the large text, however, you might want
25513to use larger table, trading off the memory usage.  You can specify
25514the internal table size by @var{table-size} keyword argument.
25515For example, if you transliterate lots of EUC-JP hiragana text
25516to katakana, you may want to set table size greater than 42483
25517(the character code of the last katakana).
25518@c JP
25519内部的に、@code{tr}はキャラクタのマッピングのためにテーブルを使用します。
25520但し、Gaucheでは極めて大きな文字集合を扱うため、テーブルはキャラクタコードの
25521小さい文字のみに対して使われます(デフォルトではコード255以下の文字)。
25522もし、より大きな文字を頻繁に変換することが分かっていて、メモリを余分に使っても
25523速度を上げたい場合は、このテーブルの大きさを@var{table-size}キーワード引数で
25524指定することができます。例えばEUC-JPコードで大量の平仮名と片仮名を変換する場合は、
25525@var{table-size}を42483以上にすると、全ての変換がテーブルルックアップで
25526行われます。
25527@c COMMON
25528
25529@c EN
25530Note that the pre-calculation to build the transliterate table
25531needs some overhead.  If you want to call @code{tr} many times
25532inside loop, consider to use @code{build-transliterator} described below.
25533@c JP
25534@code{tr}が変換テーブルを計算するのにいくらかオーバーヘッドがあることに
25535注意して下さい。内側のループで@code{tr}を繰り返し呼ぶような場合は
25536下に示す@code{build-transliterator}を使った方が良いでしょう。
25537@c COMMON
25538@end defun
25539
25540@defun string-tr string from-list to-list :key :complement :delete :squeeze :table-size
25541@c MOD text.tr
25542@c EN
25543Works like @code{tr}, except that input is taken from a string @var{string}.
25544@c JP
25545入力を@var{string}から取って変換結果を文字列で返す以外は@code{tr}と同じです。
25546@c COMMON
25547@end defun
25548
25549@defun build-transliterator from-list to-list :key :complement :delete :squeeze :table-size :input :output
25550@c MOD text.tr
25551@c EN
25552Returns a procedure that does the actual transliteration.  This effectively
25553``pre-compiles'' the internal data structure.   If you want to run
25554@code{tr} with the same sets repeatedly, you may build the procedure
25555once and apply it repeatedly, saving the overhead of initialization.
25556@c JP
25557実際の変換動作をする手続きを作成して返します。内部データのセットアップを済ませるため、
25558同じ文字変換セットに対して@code{tr}を繰り返し呼ぶような場合は、この手続きを用いることで
25559初期化のオーバヘッドを軽減することができます。
25560@c COMMON
25561
25562@c EN
25563A note for an edge case:
25564When @var{input} and/or @var{output} keyword arguments are omitted,
25565the created transliterator is set up to use current-input-port and/or
25566current-output-port at the time transliterator is called.
25567@c JP
25568註記:@var{input}や@var{output}キーワード引数が省略された場合、
25569作成される変換手続きは、それが使用された時点でのカレント入出力ポート
25570を参照します。
25571@c COMMON
25572
25573@example
25574(with-input-from-file "huge-file.txt"
25575  (lambda ()
25576    (let loop ((line (read-line)))
25577      (unless (eof-object? line) (tr "A-Za-z" "a-zA-Z")))))
25578
25579@c EN
25580;; @r{runs more efficiently...}
25581@c JP
25582;; @r{以下の方が効率良く動作します...}
25583@c COMMON
25584
25585(with-input-from-file "huge-file.txt"
25586  (lambda ()
25587    (let ((ptr (build-transliterator "A-Za-z" "a-zA-Z")))
25588      (let loop ((line (read-line)))
25589        (unless (eof-object? line) (ptr))))))
25590@end example
25591
25592@end defun
25593
25594@c ----------------------------------------------------------------------
25595@node Lazy text construction, Combination library, Transliterate characters, Library modules - Utilities
25596@section @code{text.tree} - Lazy text construction
25597@c NODE 怠惰なテキスト構築, @code{text.tree} - 怠惰なテキスト構築
25598
25599@deftp {Module} text.tree
25600@mdindex text.tree
25601@c EN
25602Defines simple but commonly used functions for a text construction.
25603
25604When you generate a text by a program,
25605It is a very common operation to concatenate text segments.
25606However, using string-append repeatedly causes unnecessary
25607copying of intermediate strings, and sometimes such intermediate
25608strings are discarded due to the error situation (for example,
25609think about constructing an HTML document in the CGI script).
25610
25611The efficient technique is to delay concatenation of those
25612text segments until it is needed.  In Scheme it is done very
25613easily by just consing the text segments together, thus forming
25614a tree of text, and then traverse the tree to construct a text.
25615You can even directly writes out the text during traversal,
25616avoiding intermediate string buffer.
25617(Hans Boehm's ``cord'' library, which comes with his garbage
25618collector library, uses this technique and proves it is very
25619efficient for editor-type application).
25620
25621Although the traversal of the tree can be written in a
25622few lines of Scheme, I provide this module in the spirits
25623of OnceAndOnlyOnce.   Also it's easier if we have a common interface.
25624@c JP
25625テキストを生成する場合によく使われるシンプルな手続きを定義します。
25626
25627プログラムでテキストを生成する場合、テキストの断片をつなぎ合わせて行く操作が
25628非常に多く現われます。しかし単純に@code{string-append}を繰り返し
25629呼んでしまうと、中間結果の文字列を保持するためだけにメモリアロケーションが多発しますし、
25630途中でエラーが発生した場合にその中間結果は結局捨てられてしまうかもしれません
25631(例えば、CGIスクリプト中でHTMLドキュメントを構築してゆくような場合を考えてみて下さい)。
25632
25633よく知られた効率の良い方法は、テキストの断片をつなぎ合わせるのを本当に必要に
25634なるまで遅らせることです。Schemeではそれは非常に簡単です。単に断片をコンス
25635していって木構造を作り、最後にそれをトラバースしてテキストを作成するのです。
25636場合によっては、トラバースしながらテキストを出力すれば事足りてしまうので、
25637中間結果のバッファを持つ必要さえありません。
25638(Hans Boehmのガベージコレクションライブラリに附属している ``cord'' ライブラリ
25639はこのテクニックを実装したもので、エディタ等のアプリケーションで非常に効率良く
25640動作することが知られています)。
25641
25642木構造をトラバースする手続きなどほんの2〜3行で書けてしまいますが、
25643「一度、そして一度だけ」の精神の下に、このモジュールを提供します。
25644インタフェースが統一されてたほうが便利ですしね。
25645@c COMMON
25646@end deftp
25647
25648@deffn {Generic Function} write-tree tree :optional out
25649@c MOD text.tree
25650@c EN
25651Writes out an @var{tree} as a tree of text, to the output port @var{out}.
25652If @var{out} is omitted, the current output port is used.
25653
25654Two methods are defined for this generic function, as shown below.
25655If you have more complex behavior, you can define more methods
25656to customize the behavior.
25657@c JP
25658@var{tree}をテキストの木構造とみなして、出力ポート@var{out}に出力します。
25659@var{out}が省略された場合は現在の出力ポートが使われます。
25660
25661下に示す2つのメソッドが定義されています。より複雑な動作をさせたい場合は、
25662単純なリストの替わりにノードとなるクラスを定義して、それにメソッドを定義するようにすれば
25663動作をカスタマイズできます。
25664@c COMMON
25665@end deffn
25666
25667@deffn {Method} write-tree ((tree <list>) out)
25668@deffnx {Method} write-tree ((tree <top>) out)
25669@c MOD text.tree
25670@c EN
25671Default methods.  For a list, @code{write-tree} is recursively
25672called for each element.  Any objects other than list is written out
25673using @code{display}.
25674@c JP
25675@code{write-tree}の既定の動作です。@var{tree}がリストなら、その要素それぞれに
25676ついて@code{write-tree}を呼び出します。それ以外のオブジェクトに関しては
25677@code{display}を呼んで出力します。
25678@c COMMON
25679@end deffn
25680
25681@defun tree->string tree
25682@c MOD text.tree
25683@c EN
25684Just calls the @code{write-tree} method for @var{tree} using
25685an output string port, and returns the result string.
25686@c JP
25687出力文字列ポートを作成して@code{write-tree}を呼び、生成された文字列を返します。
25688@c COMMON
25689@end defun
25690
25691
25692@c ----------------------------------------------------------------------
25693@node Combination library, Message digester framework, Lazy text construction, Library modules - Utilities
25694@section @code{util.combinations} - Combination library
25695@c NODE 組み合わせ, @code{util.combinations} - 組み合わせ
25696
25697@deftp {Module} util.combinations
25698@mdindex util.combinations
25699@c EN
25700This module implements several useful procedures of
25701combinations, permutations and related operations.
25702
25703Most procedures in the module have two variants: a procedure without
25704star (e.g. @code{permutations}) treats all elements in the given
25705set distinct, while a procedure with star (e.g. @code{permutations*})
25706considers duplication.  The procedures with star take optional @var{eq}
25707argument that is used to test equality, which defaults to @code{eqv?}.
25708@c JP
25709このモジュールは、いくつかの便利なコンビネーションや順列とそれに関連する
25710操作の手続きを実装しています。
25711
25712このモジュールのほとんどの手続きは2つのバージョンを持っています。
257131つはアスタリスクの付かない手続き(例えば、@code{permutations})で、
25714与えられたセットにある全ての要素を区別して扱います。もう1つは、
25715アスタリスクの付く手続き(例えば、@code{permutations*})で、重複を
25716考慮します。アスタリスクの付く手続きは、オプショナルな@var{eq}引数を取り
25717ます。それは等値性のテストに使われ、デフォルトは@code{eqv?}です。
25718@c COMMON
25719@end deftp
25720
25721@defun permutations set
25722@defunx permutations* set :optional eq
25723@c MOD util.combinations
25724@c EN
25725Returns a list of all permutations of a list @var{set}.
25726@c JP
25727リスト@var{set}の全ての順列のリストを返します。
25728@c COMMON
25729
25730@example
25731(permutations '(a b c))
25732  @result{} ((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))
25733
25734(permutations '(a a b))
25735  @result{} ((a a b) (a b a) (a a b) (a b a) (b a a) (b a a))
25736
25737(permutations* '(a a b))
25738  @result{} ((a a b) (a b a) (b a a))
25739@end example
25740
25741@c EN
25742The number of possible permutations explodes if @var{set} has
25743more than several elements.  Use with care.  If you want to process
25744each permutation at a time, consider @code{permutations-for-each} below.
25745@c JP
25746@var{set}がある程度の要素を持っている場合、可能性のある順列の数は
25747爆発的に大きくなります。注意して使って下さい。
25748一度にそれぞれの順列を処理したい場合は、下記の@code{permutations-for-each}の
25749使用を考慮して下さい。
25750@c COMMON
25751@end defun
25752
25753@defun permutations-for-each proc set
25754@defunx permutations*-for-each proc set :optional eq
25755@c MOD util.combinations
25756@c EN
25757For each permutation of a list @var{set}, calls @var{proc}.
25758Returns an undefined value.
25759@c JP
25760リスト@var{set}のそれぞれの順列に対して、@var{proc}を呼び出します。
25761戻り値は未定義値です。
25762@c COMMON
25763@end defun
25764
25765@defun combinations set n
25766@defunx combinations* set n :optional eq
25767@c MOD util.combinations
25768@c EN
25769Returns a list of all possible combinations of @var{n} elements out
25770of a list @var{set}.
25771@c JP
25772リスト@var{set}の@var{n}個の要素の可能性のある全ての順列のリストを
25773返します。
25774@c COMMON
25775
25776@example
25777(combinations '(a b c) 2)
25778  @result{} ((a b) (a c) (b c))
25779
25780(combinations '(a a b) 2)
25781  @result{} ((a a) (a b) (a b))
25782
25783(combinations* '(a a b) 2)
25784  @result{} ((a a) (a b))
25785@end example
25786
25787@c EN
25788Watch out the explosion of combinations when @var{set} is large.
25789@c JP
25790@var{set}が大きいときは、組み合わせの爆発について注意して下さい。
25791@c COMMON
25792@end defun
25793
25794@defun combinations-for-each proc set n
25795@defunx combinations*-for-each proc set n :optional eq
25796@c MOD util.combinations
25797@c EN
25798Calls @var{proc} for each combination of @var{n} elements out of @var{set}.
25799Returns an undefined value.
25800@c JP
25801@var{set}の@var{n}個の要素のそれぞれの組み合わせについて@var{proc}を
25802呼び出します。戻り値は未定義値です。
25803@c COMMON
25804@end defun
25805
25806@defun power-set set
25807@defunx power-set* set :optional eq
25808@c MOD util.combinations
25809@c EN
25810Returns power set (all subsets) of a list @var{set}.
25811@c JP
25812リスト@var{set}の累乗集合(全てのサブセット)を返します。
25813@c COMMON
25814
25815@example
25816(power-set '(a b c))
25817  @result{} (() (a) (b) (c) (a b) (a c) (b c) (a b c))
25818
25819(power-set* '(a a b)
25820  @result{} (() (a) (b) (a a) (a b) (a a b))
25821@end example
25822@end defun
25823
25824@defun power-set-for-each proc set
25825@defunx power-set*-for-each proc set :optional eq
25826@c MOD util.combinations
25827@c EN
25828Calls @var{proc} for each subset of @var{set}.
25829@c JP
25830@var{set}のそれぞれのサブセットについて@var{proc}を呼び出す。
25831@c COMMON
25832@end defun
25833
25834@defun power-set-binary set
25835@c MOD util.combinations
25836@c EN
25837Returns power set of @var{set}, like @code{power-set}, but in different order.
25838@code{Power-set-binary} traverses subset space in depth-first order,
25839while @code{power-set} in breadth-first order.
25840@c JP
25841@code{power-set}のように、@var{set}の累乗集合を返しますが、順番が異なります。
25842@code{power-set-binary}はサブセットの空間を深さ優先でトラバースしますが、
25843@code{power-set}は横型探索を行います。
25844@c COMMON
25845
25846@example
25847(power-set-binary '(a b c))
25848  @result{} (() (c) (b) (b c) (a) (a c) (a b) (a b c))
25849@end example
25850@end defun
25851
25852@defun cartesian-product list-of-sets
25853@defunx cartesian-product-right list-of-sets
25854@c MOD util.combinations
25855@c EN
25856Returns a cartesian product of sets in @var{list-of-sets}.
25857@code{Cartesian-product} construct the result in left fixed order
25858(the rightmost element varies first), while
25859@code{cartesian-product-right} in right fixed order
25860(the leftmost element varies first).
25861@c JP
25862@var{list-of-sets}にあるセットのデカルト積を返します。
25863@code{cartesian-product}は左固定順で結果を構築しますが
25864(一番右の要素がまず異なる)、
25865@code{cartesian-product-right}は右固定順で行います
25866(一番左の要素がまず異なる)。
25867@c COMMON
25868
25869@example
25870(cartesian-product '((a b c) (0 1)))
25871  @result{} ((a 0) (a 1) (b 0) (b 1) (c 0) (c 1))
25872
25873(cartesian-product-right '((a b c) (0 1)))
25874  @result{} ((a 0) (b 0) (c 0) (a 1) (b 1) (c 1))
25875@end example
25876@end defun
25877
25878@c ----------------------------------------------------------------------
25879@node Message digester framework, Calculate dominator tree, Combination library, Library modules - Utilities
25880@section @code{util.digest} - Message digester framework
25881@c NODE メッセージダイジェストフレームワーク, @code{util.digest} - メッセージダイジェストフレームワーク
25882
25883@deftp {Module} util.digest
25884@mdindex util.digest
25885@c EN
25886This module provides a base class and common interface for
25887message digest algorithms, such as MD5 (@pxref{MD5 message digest})
25888and SHA (@pxref{SHA message digest}).
25889@c JP
25890このモジュールは、MD5 (@ref{MD5 message digest}参照)や
25891SHA (@ref{SHA message digest}参照)などの、メッセージ
25892ダイジェストアルゴリズムのためのベースクラスと一般的なインターフェースを
25893提供します。
25894@c COMMON
25895@end deftp
25896
25897@deftp {Class} <message-digest-algorithm-meta>
25898@clindex message-digest-algorithm-meta
25899@c MOD util.digest
25900@c EN
25901A metaclass of message digest algorithm implementation.
25902@c JP
25903メッセージダイジェストアルゴリズムの実装のメタクラスです。
25904@c COMMON
25905
25906@defivar {<message-digest-algorithm-meta>} hmac-block-size
25907@c EN
25908Specifies the block size (in bytes), which is specific to each algorithm.
25909(This is a slot for each @emph{class} object that implements the algorithm,
25910not for instance of such classes.  Only the author of such digest classes
25911needs to care.  See @file{ext/digest/sha.scm} in the source tree
25912for more details.)
25913@c JP
25914各アルゴリズムに固有のブロックサイズをバイト数で指定します。
25915(これはアルゴリズムを実装する各クラスオブジェクトのスロットで、
25916それらのクラスのインスタンスのスロットではありません。通常、新たなダイジェストアルゴリズム
25917クラスを実装する人のみが気にすれば良いスロットです。具体例は
25918ソースツリーの@file{ext/digest/sha.scm}を見てください。)
25919@c COMMON
25920@end defivar
25921@end deftp
25922
25923@deftp {Class} <message-digest-algorithm>
25924@clindex message-digest-algorithm
25925@c MOD util.digest
25926@c EN
25927A base class of message digest algorithm implementation.
25928@c JP
25929メッセージダイジェストアルゴリズムの実装のベースクラスです。
25930@c COMMON
25931@end deftp
25932
25933@c EN
25934The concrete subclass of message digest algorithm has to
25935implement the following methods.
25936@c JP
25937メッセージダイジェストアルゴリズムの具体サブクラスは、以下のメソッドを
25938実装しなければなりません。
25939@c COMMON
25940
25941@deffn {Generic function} digest-update! algorithm data
25942@c MOD util.digest
25943@c EN
25944Takes the instance of massage-digest algorithm, and updates it
25945with the data @var{data}, which can be either a u8vector
25946or a (possibly incomplete) string.
25947@c JP
25948メッセージダイジェストアルゴリズムのインスタンスを取り、
25949それをu8vectorか(不完全な可能性のある)文字列のデータ@var{data}で
25950更新します。
25951@c COMMON
25952@end deffn
25953
25954@deffn {Generic function} digest-final! algorithm
25955@c MOD util.digest
25956@c EN
25957Finalizes the instance of message-digest algorithm, and
25958returns the digest result in an incomplete string.
25959@c JP
25960メッセージダイジェストアルゴリズムのインスタンスを終了させ、
25961そのダイジェストの結果を不完全文字列で返します。
25962@c COMMON
25963@end deffn
25964
25965@deffn {Generic function} digest class
25966@c MOD util.digest
25967@c EN
25968A wrapper of digest routines.  Given message-digest algorithm @var{class},
25969this function reads the input data from current input port until EOF,
25970and returns the digest result in an incomplete string.
25971@c JP
25972ダイジェストルーチンのラッパです。メッセージダイジェストアルゴリズム
25973@var{class}を与え、現在の入力ポートから入力データをEOFまで読み込み、
25974そのダイジェストの結果を不完全文字列で返します。
25975@c COMMON
25976@end deffn
25977
25978@deffn {Generic function} digest-string class string
25979@c MOD util.digest
25980@c EN
25981A wrapper of digest routines.  Given message-digest algorithm @var{class},
25982this function reads the input data from @var{string},
25983and returns the digest result in an incomplete string.
25984@c JP
25985ダイジェストルーチンのラッパです。メッセージダイジェストアルゴリズム
25986@var{class}を与え、入力データを@var{string}から読み込み、
25987そのダイジェストの結果を不完全文字列で返します。
25988@c COMMON
25989@end deffn
25990
25991@defun digest-hexify digest-result
25992@c MOD util.digest
25993@c EN
25994An utility procedure.  Given the result of digest, @var{digest-result},
25995which can be an u8vector or a (possibly incomplete) string,
25996converts it to a hexified string.
25997@c JP
25998ユーティリティ手続きです。ダイジェストの結果、@var{digest-result}
25999(u8vectorか(不完全かもしれない)文字列)
26000与えると、それを16進文字列に変換します。
26001@c COMMON
26002@end defun
26003
26004@c ----------------------------------------------------------------------
26005@node Calculate dominator tree, Determine isomorphism, Message digester framework, Library modules - Utilities
26006@section @code{util.dominator} - Calculate dominator tree
26007@c NODE 支配木, @code{util.dominator} - 支配木
26008
26009@deftp {Module} util.dominator
26010@mdindex util.dominator
26011@c EN
26012Dominator tree is an auxiliary structure for control flow graphs.
26013It is frequently used in the flow analysis of compilers, but
26014also useful for handling general directed graphs.
26015@c JP
26016支配木(dominator tree)は制御フローグラフで補助的に使われる構造です。
26017コンパイラのフロー解析によく使われることが多いですが、一般の有向グラフでも有用です。
26018@c COMMON
26019@end deftp
26020
26021@defun calculate-dominators start upstreams downstreams node-comparator
26022@c MOD util.dominator
26023@c EN
26024The four arguments represent a directed, possibly cyclic, graph.
26025Here, we use @code{Node} to denote an abstract type of a node
26026of the graph.  It can be anything---the algorithm is oblivious on
26027the actual type of nodes.
26028@c JP
260294つの引数で有向グラフが表現されます。循環があっても構いません。
26030以下ではグラフのノードが@code{Node}という型を持つとして説明します。
26031実際にはノードの型は何であっても構いません。
26032アルゴリズムはノードの実際の型とは無関係に動作します。
26033@c COMMON
26034
26035@table @asis
26036@item @var{start} @code{:: Node}
26037@c EN
26038The start node, or the enter node, of the graph.
26039@c JP
26040フローの起点となるノード。startノードとかenterノードとも呼ばれます。
26041@c COMMON
26042@item @var{upstreams} @code{:: Node -> (Node @dots{})}
26043@c EN
26044A procedure that takes a node, and returns its upstream
26045(immediate ancestor) nodes.
26046@c JP
26047ノードを取り、その直接の上流ノードのリストを返す関数。
26048@c COMMON
26049@item @var{downstreams} @code{:: Node -> (Node @dots{})}
26050@c EN
26051A procedure that takes a node, and returns its downstream
26052(immediate descendant) nodes.
26053@c JP
26054ノードを取り、その直接の下流ノードのリストを返す関数。
26055@c COMMON
26056@item @var{node-comparator}
26057@c EN
26058A comparator that is used to determine if two nodes are equal to each other.
26059It doesn't need to have comparison procedure (we don't need to see
26060which is smaller than the other), but it has to have hash function,
26061for we use hashtables internally.  (@xref{Basic comparators}, for the details
26062of comparators.)
26063@c JP
26064二つのノードが等しいかどうかを決定する比較器。大小比較関数を持っている必要はありませんが、
26065アルゴリズム内部でハッシュテーブルを使うので、ハッシュ関数は持っている必要があります。
26066比較器について詳しくは@ref{Basic comparators}を参照してください。
26067@c COMMON
26068@end table
26069
26070@c EN
26071The procedure returns a list of @code{(node1 node2)}, where
26072@code{node2} is the immediate dominator of @code{node1}.
26073@c JP
26074返り値は@code{(node1 node2)}を要素に持つリストです。ここで、
26075@code{node2}は@code{node1}の直接支配ノード(immediate dominator)です。
26076@c COMMON
26077
26078@c EN
26079If there are node in the given graph that are unreachable
26080from @var{start}, such nodes are ignored and not included
26081in the result.
26082@c JP
26083与えられたグラフの中に@var{start}から到達不可能なノードがあった場合、
26084それは単に無視され、結果に含まれません。
26085@c COMMON
26086
26087@c EN
26088(A bit of explanation: Suppose you want to go to node X from @var{start}.
26089There may be multiple routes, but if you have to pass node Y no matter
26090which route you take, then Y is a dominator of X.  There may be
26091many dominators of X.  Among them, there's
26092always one dominator such that all other X's dominators are also
26093its dominators---in other words, the closest dominator of X---which
26094is called the immediate dominator of X.)
26095@c JP
26096(ちょっとした説明: @var{start}からノードXに行きたいとします。
26097複数の経路がありえますが、どの経路を取っても必ずノードYを通らないと
26098Xに行けない場合、YをXの支配ノード(dominator)と呼びます。
26099支配ノードは複数ありえますが、その中で一つだけ、他のXの支配ノード全てが
26100そのノードの支配ノードでもあるようなノードがあります(言い換えれば、
26101Xに一番「近い」支配ノードです)。それをXの直接支配ノードと呼びます。)
26102@c COMMON
26103
26104@c EN
26105Let's see an example.  You have this directed graph:
26106@c JP
26107例を見てみましょう。こんな有向グラフがあるとします。
26108@c COMMON
26109
26110@example
26111          A (start)
26112          |
26113          v
26114          B <-------+
26115          |         |
26116    ------+-----    |
26117    |          |    |
26118    v          v    |
26119    C -------> D ---+
26120    |          |
26121    v          v
26122    E <------- F
26123@end example
26124
26125@c EN
26126Let's represent the graph by a list of @code{(x y z ...)} where @code{x}
26127can directly go to either @code{y z ...}.
26128@c JP
26129このグラフをリストのリストで表現してみましょう。
26130ここで、内側のリスト@code{(x y z ...)}は、@code{x}からは@code{y}や@code{z}に
26131直接行ける、ということを表します。
26132@c COMMON
26133
26134@example
26135(define *graph* '((A B)
26136                  (B C D)
26137                  (C D E)
26138                  (D F B)
26139                  (F E)))
26140@end example
26141
26142@c EN
26143Then you can calculate the immediate dominator of each node as follows:
26144@c JP
26145すると、各ノードの直接支配ノードが次の通り計算できます。
26146@c COMMON
26147
26148@example
26149(calculate-dominators 'A
26150  (^n (filter-map (^g (and (memq n (cdr g)) (car g))) *graph*))
26151  (^n (assoc-ref *graph* n '()))
26152  eq-comparator)
26153  @result{} ((E B) (F D) (D B) (C B) (B A))
26154@end example
26155
26156@c EN
26157That is, @code{E}'s immediate dominator is @code{B},
26158@code{F}'s is @code{D}, and so on.
26159@c JP
26160つまり、@code{E}の直接支配ノードは@code{B}であり、
26161@code{F}のは@code{D}である、という具合です。
26162@c COMMON
26163
26164@c EN
26165The result itself can be viewed as a tree.  It is called a dominator tree.
26166@c JP
26167この結果自体を木と解釈することができます。これを支配木(dominator tree)と呼びます。
26168@c COMMON
26169
26170@example
26171              F
26172              |
26173              v
26174        E     D     C
26175        |     |     |
26176        |     v     |
26177        +---> B <---+
26178              |
26179              v
26180              A
26181@end example
26182@end defun
26183
26184
26185@c ----------------------------------------------------------------------
26186@node Determine isomorphism, The longest common subsequence, Calculate dominator tree, Library modules - Utilities
26187@section @code{util.isomorph} - Determine isomorphism
26188@c NODE 同型判定, @code{util.isomorph} - 同型判定
26189
26190@deftp {Module} util.isomorph
26191@mdindex util.isomorph
26192@c EN
26193Provides a procedure that determines whether two structures are
26194isomorphic.
26195@c JP
26196二つの構造が同型かどうかを判定する手続きを提供するモジュールです。
26197@c COMMON
26198@end deftp
26199
26200@defun isomorphic? obj1 obj2 :optional context
26201@c MOD util.isomorph
26202@c EN
26203Returns @code{#t} if @var{obj1} and @var{obj2} are isomorphic.
26204
26205@var{context} is used if you want to call @code{isomorphic?}
26206recursively inside @code{object-isomorphic?} described below.
26207@c JP
26208@var{obj1}と@var{obj2}が同型であれば@code{#t}を返します。
26209
26210省略可能な引数@var{context}は、下で説明する@code{object-isomorphic?}
26211の中から@code{isomorphic?}を再帰的に呼び出す場合に使います。
26212@c COMMON
26213
26214@example
26215(isomorphic? '(a b) '(a b)) @result{} #t
26216
26217(define x (cons 0 0))
26218(define y (cons 0 0))
26219(isomorphic? (cons x x)
26220             (cons x y))
26221 @result{} #f
26222(isomorphic? (cons x x)
26223             (cons y y))
26224 @result{} #t
26225@end example
26226@end defun
26227
26228@deffn {Generic Function} object-isomorphic? obj1 obj2 context
26229@c MOD util.isomorph
26230@c EN
26231With this method, you can customize how to determine isomorphism of
26232two objects.  Basically, you will call @code{isomorphic?} recursively
26233for each slots of object you want to traverse; the method should return
26234@code{#t} if all of the test succeeds, or return @code{#f} otherwise.
26235@var{context} is an opaque structure
26236that keeps the traversal context, and you should pass it to
26237@code{isomorphic?} as is.
26238
26239The default method returns @code{#t} if @var{obj1} and @var{obj2} are
26240equal (in the sense of @code{equal?}).
26241@c JP
26242このメソッドで、二つのオブジェクトの同型判定処理をカスタマイズできます。
26243基本的には、オブジェクトのトラバースしたいスロットに対して@code{isomorphic?}を順に適用し、
26244全てが成功すれば@code{#t}を、一つでも失敗すれば@code{#f}を返すようにします。
26245@var{context}はトラバースのコンテクストを保持しているオブジェクトです。そのまま
26246@code{isomorphic?}に渡して下さい。
26247
26248デフォルトメソッドは、@var{obj1}と@var{obj2}が@code{equal?}の意味で等しければ
26249@code{#t}を返します。
26250@c COMMON
26251@end deffn
26252
26253@c ----------------------------------------------------------------------
26254@node The longest common subsequence, Levenshtein edit distance, Determine isomorphism, Library modules - Utilities
26255@section @code{util.lcs} - The longest common subsequence
26256@c NODE 最長共通サブシーケンス, @code{util.lcs} - 最長共通サブシーケンス
26257
26258@deftp {Module} util.lcs
26259@mdindex util.lcs
26260@c EN
26261This module implements the algorithm to find the longest common subsequence
26262of two given sequences.  The implemented algorithm is based on
26263Eugene Myers' O(ND) algorithm
26264(Eugene Myers, An O(ND) Difference Algorithm and Its Variations,
26265@i{Algorithmica} Vol. 1 No. 2, pp. 251-266, 1986.).
26266
26267One of the applications of this algorithm is to calculate
26268the difference of two text streams;
26269see @ref{Calculate difference of text streams}.
26270@c JP
26271このモジュールは、与えられた2つのシーケンスの最長共通サブシーケンスを見つける
26272アルゴリズムを実装しています。アルゴリズムは、Eugene Myersの
26273O(ND)アルゴリズムに基づいています
26274(Eugene Myers, An O(ND) Difference Algorithm and Its Variations,
26275@i{Algorithmica} Vol. 1 No. 2, pp. 251-266, 1986.)。
26276
26277このアルゴリズムを使うアプリケーションの1つは、2つのテキストストリームの
26278相違点を計算する@ref{Calculate difference of text streams}です。
26279@c COMMON
26280@end deftp
26281
26282@defun lcs seq-a seq-b :optional eq-fn
26283@c MOD util.lcs
26284@c EN
26285Calculates and returns the longest common sequence of
26286two lists, @var{seq-a} and @var{seq-b}.
26287Optional @var{eq-fn} specifies
26288the comparison predicate; if omitted, @code{equal?} is used.
26289@c JP
262902つのリスト、@var{seq-a}と@var{seq-b}の最長共通シーケンスを計算して
26291返します。オプションの@var{eq-fn}では、比較を行う述語を指定します。
26292省略されると、@code{equal?}が使われます。
26293@c COMMON
26294
26295@example
26296(lcs '(x a b y) '(p a q b))
26297 @result{} (a b)
26298@end example
26299@end defun
26300
26301@defun lcs-with-positions seq-a seq-b :optional eq-fn
26302@c MOD util.lcs
26303@c EN
26304This is the detailed version of @code{lcs}.
26305The arguments are the same.
26306
26307Returns a list of the following structure:
26308@c JP
26309@code{lcs}の詳細バージョンです。引数は同じです。
26310
26311以下の構造のリストを返します。
26312@c COMMON
26313
26314@example
26315(@var{length} ((@var{elt} @var{a-pos} @var{b-pos}) @dots{}))
26316@end example
26317
26318@c EN
26319@var{Length} is an integer showing the length of the found LCS.
26320What follows is a list of elements of LCS; each sublist
26321consists of the element, the integer position of the element
26322in @var{seq-a}, then the integer position of the element in @var{seq-b}.
26323@c JP
26324@var{length}は、見つかったLCS(最長共通サブシーケンス)の長さを表す整数です。
26325それに続くのは、LCSの要素のリストで、その要素を構成するそれぞれのサブリスト、
26326@var{seq-a}の中での要素の位置(整数)、@var{seq-b}の中での要素の位置(整数)
26327となります。
26328@c COMMON
26329
26330@example
26331(lcs-with-positions '(a) '(a))
26332 @result{} (1 ((a 0 0)))
26333
26334(lcs-with-positions '(x a b y) '(p q a b))
26335 @result{} (2 ((a 1 2) (b 2 3)))
26336
26337(lcs-with-positions '(x a b y) '(p a q b))
26338 @result{} (2 ((a 1 1) (b 2 3)))
26339
26340(lcs-with-positions '(x y) '(p q))
26341 @result{} (0 ())
26342@end example
26343@end defun
26344
26345@defun lcs-fold a-proc b-proc both-proc seed a b :optional eq-fn
26346@c MOD util.lcs
26347@c EN
26348A fundamental iterator over the "edit list" derived from
26349two lists @var{a} and @var{b}.
26350
26351@var{A-proc}, @var{b-proc}, @var{both-proc} are all procedures
26352that take two arguments.   The second argument is a intermediate
26353state value of the calculation.  The first value is an element
26354only in @var{a} for @var{a-proc}, or an element only in @var{b}
26355for @var{b-proc}, or an element in both @var{a} and @var{b}
26356for @var{both-proc}.  The return value of each procedure is used
26357as the state value of the next call of either one of the procedures.
26358@var{Seed} is used as the initial value of the state value.
26359The last state value is returned from @code{lcs-fold}.
26360
26361The three procedures are called in the following order: Suppose the sequence
26362@var{a} consists of @var{a'}@var{c}@var{a''}, and @var{b} consists of
26363@var{b'}@var{c}@var{b''}, where @var{a'}, @var{b'}, @var{a''}, and @var{b''}
26364are subsequences, and @var{c} is the head of the
26365LCS of @var{a} and @var{b}.   Then @var{a-proc} is called first on
26366each element in @var{a'}, @var{b-proc} is called second on
26367each element in @var{b'}, then @var{both-proc} is called on @var{c}.
26368Afterwards, the process is repeated using @var{a''} and @var{b''}.
26369@c JP
263702つのリスト@var{a}と@var{b}から引き出された``編集リスト''に対する
26371基本的なイテレータです。
26372
26373@var{a-proc}、@var{b-proc}、@var{both-proc}は全て2引数を取る手続きです。
263742番目の引数は、計算の中間の値です。最初の値は、@var{a-proc}では@var{a}にしかない要素、
26375@var{b-proc}では@var{b}にしかない要素、@var{both-proc}では@var{a}と@var{b}の両方に
26376ある要素となります。それぞれの手続きが返す値は、次に呼び出される手続きのうちの1つの
26377状態を表す値として使われます。@var{seed}は、状態を表す値の初期値として使われます。
26378@code{lcs-fold}が返す値は、最後の状態を表す値です。
26379
26380これらの3つの手続きは、以下の順番で呼ばれます。ここでは、シーケンス@var{a}は
26381@var{a'}@var{c}@var{a''}、@var{b}は@var{b'}@var{c}@var{b''}となっているとすると、
26382ここでは@var{a'}、@var{b'}、@var{a''}、@var{b''}はサブシーケンスで、
26383@var{c}は@var{a}と@var{b}のLCSの先頭になります。そして、@var{a-proc}はまず
26384@var{a'}のそれぞれの要素に対して呼ばれ、@var{b-proc}が@var{b'}のそれぞれの
26385要素に対して呼ばれ、@var{both-proc}が@var{c}に対して呼ばれます。
26386その後、このプロセスは@var{a''}と@var{b''}を使って繰り返されます。
26387@c COMMON
26388@end defun
26389
26390@defun lcs-edit-list a b :optional eq-fn
26391@c MOD util.lcs
26392@c EN
26393Calculates 'edit-list' from two lists @var{a} and @var{b}, which is
26394the smallest set of commands (additions and deletions) that changes
26395@var{a} into @var{b}.
26396This procedure is built on top of @code{lcs-fold} above.
26397
26398Returns a list of @emph{hunk}s, which is a contiguous section of
26399additions and deletions.  Each hunk consists of a list of
26400directives, which is a form of:
26401@c JP
264022つのリスト@var{a}と@var{b}から``編集リスト''を計算します。それは、
26403@var{a}を@var{b}に変更するためのコマンド(追加と削除)の最小セットです。
26404この手続きは、上の@code{lcs-fold}の上に構築されています。
26405@c COMMON
26406@example
26407(@var{+}|@var{-} @var{position} @var{element})
26408@end example
26409
26410@c EN
26411Here's an example.  Suppose @var{a} and @var{b} are the following
26412lists, respectively.
26413@c JP
26414例を挙げます。@var{a}と@var{b}がそれぞれ以下のようなリストだとします。
26415@c COMMON
26416
26417@example
26418@var{a} @equiv{} ("A" "B" "C" "E" "H" "J" "L" "M" "N" "P")
26419@var{b} @equiv{} ("B" "C" "D" "E" "F" "J" "K" "L" "M" "R" "S" "T")
26420@end example
26421
26422@c EN
26423Then, @code{(lcs-edit-list a b equal?)} returns the following list.
26424@c JP
26425すると、@code{(lcs-edit-list a b equal?)}は以下のリストを返します。
26426@c COMMON
26427@example
26428(((- 0 "A"))
26429 ((+ 2 "D"))
26430 ((- 4 "H") (+ 4 "F"))
26431 ((+ 6 "K"))
26432 ((- 8 "N") (- 9 "P") (+ 9 "R") (+ 10 "S") (+ 11 "T"))
26433)
26434@end example
26435@c EN
26436The result consists of five hunks.  The first hunk consists of
26437one directive, @code{(- 0 "A")}, which means the element @code{"A"}
26438at the position 0 of list @var{a} has to be deleted.
26439The second hunk also consists of one directive, @code{(+ 2 "D")},
26440meaning the element @code{"D"} at the position 2 of list @var{b}
26441has to be added.  The third hunk means @code{"H"} at the position
264424 of list @var{a} should be removed and @code{"F"} at the position
264434 of list @var{b} should be added, and so on.
26444
26445If you are familiar with Perl's Algorithm::Diff module, you may
26446notice that this is the same structure that its @code{diff} procedure
26447returns.
26448@c JP
26449結果は5つの片からなります。最初のものは1つのディレクティブ、@code{(- 0 ``A'')}から
26450なり、これはリスト@var{a}の位置0にある要素@code{``A''}が削除されることを意味します。
264512番目のものはまた1つのディレクティブ、@code{(+ 2 ``D'')}からなり、これは
26452リスト@var{b}の位置2にある要素@code{``D''}が追加されることを意味します。
264533番目のものは、リスト@var{a}の位置4にある@code{``H''}は削除され、リスト@var{b}の
26454位置4にある@code{``F''}が追加される、などとなります。
26455
26456もしあなたがPerlのAlgorithm::Diffモジュールを良く知っていれば、
26457その@code{diff}手続きが返すものと同じ構造だということが分かるでしょう。
26458@c COMMON
26459@end defun
26460
26461@c ----------------------------------------------------------------------
26462@node Levenshtein edit distance, Pattern matching, The longest common subsequence, Library modules - Utilities
26463@section @code{util.levenshtein} - Levenshtein edit distance
26464@c NODE Levenshtein編集距離, @code{util.levenshtein} - Levenshtein編集距離
26465
26466@deftp {Module} util.levenshtein
26467@mdindex util.levenshtein
26468@c EN
26469This module provides procedures to calculate edit distance between
26470two sequences.  Edit distance is the minimum number of edit operations
26471required to match one sequence to another.
26472Three algorithms are implemented:
26473@c JP
26474このモジュールは二つのシーケンスの間の編集距離を計算する手続きを提供します。
26475編集距離とは、ひとつのシーケンスからもうひとつのシーケンスへと変更する
26476編集操作の数です。3つのアルゴリズムが実装されています。
26477@c COMMON
26478
26479@table @asis
26480@item Levenshtein distance
26481@c EN
26482Count deletion of one element, insertion of one element,
26483and substitution of one element.
26484@c JP
264851要素の削除、1要素の追加、1要素の置き換えそれぞれを1操作と数えます。
26486@c COMMON
26487@item Damerau-Levenshtein distance
26488@c EN
26489Besides deletion, insertion and substitution, we allow transposition
26490of adjacent elements.
26491@c JP
26492削除、追加、置き換えに加え、隣合った要素の入れ替えも1操作と数えます。
26493@c COMMON
26494@item Restricted edit distance
26495@c EN
26496Also called optimal string alignment distance.  Like Damerau-Levenshtein,
26497but once transposition is applied, no further editing on those elements
26498are allowed.
26499@c JP
26500Optimal string alignmentとも呼ばれます。Damerau-Levenshteinと似ていますが、
26501隣合った要素の入れ替えを行った場合、それらの要素は以降の編集を受けません。
26502@c COMMON
26503@end table
26504
26505@c EN
26506These algorithms are often used to compare strings, but the procedures
26507in this module can handle any type of sequence (@pxref{Sequence framework}).
26508@c JP
26509これらのアルゴリズムは文字列に対して使われることが多いですが、
26510このモジュールの手続きはシーケンスになら何でも使えます
26511(@ref{Sequence framework}参照)。
26512@c COMMON
26513@end deftp
26514
26515@defun l-distance seq-A seq-B :key elt= cutoff
26516@defunx l-distances seq-A seq-Bs :key elt= cutoff
26517@defunx re-distance seq-A seq-B :key elt= cutoff
26518@defunx re-distances seq-A seq-Bs :key elt= cutoff
26519@defunx dl-distance seq-A seq-B :key elt= cutoff
26520@defunx dl-distances seq-A seq-Bs :key elt= cutoff
26521@c MOD util.levenshtein
26522@c EN
26523Calculates Levenshtein distance (@code{l-*}), restricted edit
26524distance (@code{re-*}) and Damerau-Levenshtein distance (@code{dl-*})
26525between sequences, respectively.  Each algorithm comes in two
26526flavors: The singular form @code{*-distance} takes two sequences,
26527@var{seq-A} and @var{seq-B}, and calculates distance between them.
26528The plural form @code{*-distances} takes a sequence @var{seq-A}
26529and a list of sequences @var{seq-Bs}, and calculates distances
26530between @var{seq-A} and each in @var{seq-Bs}.
26531@c JP
26532それぞれ、与えられたシーケンス間のLevenshtein距離(@code{l-*})、
26533Restricted edit距離(@code{re-*})およびDamerau-Levenshtein距離(@code{dl-*})を
26534計算します。アルゴリズム毎にふたつのAPIが提供されます。
26535単数形の@code{*-distance}は、二つのシーケンス@var{seq-A}と@var{seq-B}を取り、
26536両者の間の距離を計算します。
26537複数形の@code{*-distances}は、一つのシーケンス@var{seq-A}と
26538シーケンスのリスト@var{seq-Bs}をとり、@var{seq-Bs}の各シーケンスと
26539@var{seq-A}との距離を計算します。
26540@c COMMON
26541
26542@c EN
26543If you need to calculate distances from a single sequence to many
26544sequences, using the plural version is much faster than repeatedly
26545calling the singular version, for the plural version can reuse internal
26546data structures and save allocation and setup time.
26547@c JP
26548あるシーケンスと、多数のシーケンスとの間の距離を計算したいなら、
26549単数形のAPIを繰り返し呼ぶより複数形のAPIを使う方が効率的です。
26550複数形のAPIでは内部で使うデータ構造を再利用するので、
26551重複するアロケーションと初期化の時間を節約できます。
26552@c COMMON
26553
26554@c EN
26555Sequences can be any object that satisfy the @code{<sequence>} protocol
26556(@pxref{Sequence framework}).
26557@c JP
26558シーケンスは、@code{<sequence>}プロトコルを満足するオブジェクトであれば
26559何でも構いません (@ref{Sequence framework}参照)。
26560@c COMMON
26561
26562@c EN
26563The keyword argument @var{elt=} is used to compare elements in
26564the sequences.  Its default is @code{eqv?}.
26565@c JP
26566キーワード引数@var{elt=}はシーケンスの要素同士を比較するのに使われます。
26567デフォルトは@code{eqv?}です。
26568@c COMMON
26569
26570@c EN
26571The keyword argument @var{cutoff} must be, if given, a nonnegative
26572exact integer.  Once the possible minimum distance between two sequences
26573becomes greater than this number, the algorithm stops and gives @code{#f}
26574as the result, and moves on to the next calculation.
26575This is useful when you run the algorithm on large set of sequences
26576and you only need to look for the pairs closer than the certain limit.
26577@c JP
26578キーワード引数@var{cutoff}は非負の正確な整数でなければなりません。与えられた場合、
26579二つのシーケンスの距離を比較していて、それが@var{cutoff}以上になることがわかったら、
26580それ以上の計算を打ち切り@code{#f}を結果とします。
26581これは、特にたくさんのシーケンスから、ごく限られた限度以下の距離を持つものを探す
26582場合に便利です。
26583@c COMMON
26584
26585@c EN
26586In our implementation, Levenshtein is the fastest, Damerau-Levenshtein
26587is the slowest and Restricted edit is somewhere inbetween.  If you don't
26588need to take into account of transpositions, use Levenshtein; it counts
265892 for @code{cat} -> @code{act}, while other algorithms yield 1 for it.
26590If you need to consider transpositions, choose either
26591@code{re-} or @code{dl-}.  The catch in @code{re-} is that it does not
26592satisfy triangular inequality, i.e. for given three sequences X, Y and Z,
26593(Damerau-)Levenshtein distance L always satisfy
26594L(X;Z) <= L(X;Y) + L(Y;Z), but restricted edit distance doesn't
26595guarantee that.
26596@c JP
26597現在の実装ではだいたい、Levenshteinが最も速く、Damerau-Levenshteinが最も遅く、
26598Restricted editがその中間です。置換を1操作と考える必要がなければ、
26599Levenshteinを使うのが良いでしょう。@code{cat}から@code{act}は
26600Levenshtein距離では2ですが他の距離では1です。
26601置換を1操作とする必要があれば、@code{re-}か@code{dl-}を
26602使うことになります。@code{re-}の落とし穴は、それが三角不等式を満たさないことです。
26603つまり、3つのシーケンスX, Y, Zがある時、
26604(Damerau-)Levenshtein距離Lは常に
26605L(X;Z) <= L(X;Y) + L(Y;Z) を満たしますが、Restricted edit距離には
26606その保証がありません。
26607@c COMMON
26608
26609@example
26610(l-distance "cat" "act")  @result{} 2
26611(l-distances "cat" '("Cathy" "scathe" "stack")
26612  :elt= char-ci=?)
26613  @result{} (2 3 4)
26614
26615(re-distance "cat" "act") @result{} 1
26616
26617(re-distances "pepper"
26618  '("peter" "piper" "picked" "peck" "pickled" "peppers")
26619  :cutoff 4)
26620  @result{} (2 2 4 4 #f 1)
26621
26622(dl-distance '(a b c d e) '(c d a b e)) @result{} 4
26623@end example
26624
26625@c EN
26626Note: If you pass a list of sequences to the second argument
26627of the singular version by accident, you might not get an error immediately
26628because a list is also a sequence.
26629@c JP
26630註: 単数形のAPIの第2引数にうっかりシーケンスのリストを渡してしまった場合でも、
26631直ちにエラーになるとは限らないことに注意。リスト自体もシーケンスだからです。
26632@c COMMON
26633@end defun
26634
26635@c ----------------------------------------------------------------------
26636@node Pattern matching, SLIB-compatible record type, Levenshtein edit distance, Library modules - Utilities
26637@section @code{util.match} - Pattern matching
26638@c NODE パターンマッチング, @code{util.match} - パターンマッチング
26639
26640@deftp {Module} util.match
26641@mdindex util.match
26642@c EN
26643This module is a port of Andrew Wright's pattern matching macro library.
26644It is widely used in the Scheme world, and ported to various Scheme
26645implementations, including Chez Scheme, PLT Scheme, Scheme48, Chicken,
26646and SLIB.
26647It is similar to, but more powerful than
26648Common Lisp's @code{destructuring-bind}.
26649@c JP
26650このモジュールは Andrew Wright のパターンマッチングマクロライブラリを
26651ポートしたものです。このライブラリは Scheme 界では広くつかわれており、
26652Chez Scheme、PLT Scheme、Scheme48、Chicken および SLIB を含む、様々な
26653Scheme の実装にポートされています。この機能は Common Lisp の
26654@code{destructuring-bind} に似ていますがより強力です。
26655@c COMMON
26656
26657@c EN
26658This version retains compatibility of the original Wright's macro,
26659except (1) @var{box} is not supported since Gauche doesn't have one,
26660and (2) structure matching is integrated to Gauche's object system.
26661@c JP
26662この版では、オリジナルの Wright's macro のマクロとの互換性が保たれて
26663います。ただし、例外がふたつあって、それは、(1) @var{box} はサポートされて
26664いません。Gauche にそれがないからです。(2) 構造のマッチングは Gauche の
26665オブジェクトシステムに統合されています。
26666@c COMMON
26667@end deftp
26668
26669@c EN
26670We show a list of APIs first, then the table of complete syntax of
26671patterns, followed by examples.
26672@c JP
26673まず API のリストを示し、それからパターンの完全な構文のテーブルを示し、
26674そして例を示します。
26675@c COMMON
26676
26677@c EN
26678@subheading Pattern matching API
26679@c JP
26680@subheading パターンマッチング API
26681@c COMMON
26682
26683@defmac match expr clause @dots{}
26684@c MOD util.match
26685@c EN
26686Each @var{clause} is either one of the followings:
26687@c JP
26688それぞれの @var{clause} は以下のうちどちらかです。
26689@c COMMON
26690@example
26691(@var{pat} @var{body} @dots{})
26692(@var{pat} (=> @var{identifier}) @var{body} @dots{})
26693@end example
26694
26695@c EN
26696First, the @var{expr} is matched against @var{pat} of each clauses.
26697The detailed syntax of the pattern is explained below.
26698@c JP
26699まず、@var{expr} を各節の @var{pat} に照合します。パターンの詳しい
26700構文については後述します。
26701@c COMMON
26702
26703@c EN
26704If a matching @var{pat} is found, the @emph{pattern variables} in
26705@var{pat} are bound to the corresponding elements in @var{expr}, then
26706@var{body} @dots{} are evaluated.  Then @code{match} returns the value(s)
26707of the last expression of @var{body} @dots{}.
26708@c JP
26709@var{pat} にマッチする部分が見つかれば、@var{pat} 中の @emph{パターン変数}
26710は、@var{expr} 中の対応する要素に束縛され、その後、@var{body} @dots{}
26711が評価されます。@code{match}は@var{body} @dots{}の最後の式の値を返します。
26712@c COMMON
26713
26714@c EN
26715If the clause is the second form, @var{identifier} is also bound
26716to the failure continuation of the @var{clause}.  It is a
26717procedure with no arguments, and when called, it jumps back to
26718the matcher as if the matching of @var{pat} is failed, and
26719@code{match} continues to try the rest of clauses.
26720So you can perform extra tests
26721within @var{body} @dots{} and if you're not satisfied you can reject
26722the match by calling @code{(@var{identifier})}.  See the examples
26723below for more details.
26724@c JP
26725節が 2つ目の形式である場合、@var{identifier} は @var{clause} の失敗継続
26726に束縛されます。これは引数をもたない手続きで、呼ばれると、あたかも、
26727@var{pat} の照合に失敗したかの如くマッチャーに戻り、@code{match} が
26728残りの節について試行を続けます。それゆえ、@var{body} @dots{} 内部で
26729追加のテストを実行することが可能で、もし、満足いくものでなければ、
26730@code{(@var{identifier})} を呼ぶことで、照合結果を拒絶することができます。
26731より詳しくは、後述の例を見てください。
26732@c COMMON
26733
26734@c EN
26735If no @var{pat} matches, @code{match} reports an error.
26736@c JP
26737どの @var{pat} もマッチしなければ、@code{match} はエラーを報告します。
26738@c COMMON
26739@end defmac
26740
26741@defmac match-lambda clause @dots{}
26742@c MOD util.match
26743@c EN
26744Creates a function that takes one argument and performs @code{match} on it,
26745using @var{clause} @dots{}.  It's functionally equivalent to the following
26746expression:
26747@c JP
26748ひとつの引数をとり、それに対して @var{clause} @dots{} を用いて、
26749@code{match} を実行する関数を生成します。機能としては以下の式と同等です。
26750@c COMMON
26751@example
26752(lambda (expr) (match expr @var{clause} @dots{}))
26753@end example
26754
26755@c EN
26756Example:
26757@c JP
26758例:
26759@c COMMON
26760
26761@example
26762(map (match-lambda
26763       ((item price-per-lb (quantity 'lbs))
26764        (cons item (* price-per-lb quantity)))
26765       ((item price-per-lb (quantity 'kg))
26766        (cons item (* price-per-lb quantity 2.204))))
26767     '((apple      1.23 (1.1 lbs))
26768       (orange     0.68 (1.4 lbs))
26769       (cantaloupe 0.53 (2.1 kg))))
26770 @result{} ((apple . 1.353) (orange . 0.952)
26771            (cantaloupe . 2.4530520000000005))
26772@end example
26773@end defmac
26774
26775@defmac match-lambda* clause @dots{}
26776@c MOD util.match
26777@c EN
26778Like @code{match-lambda}, but performs @code{match} on the list of
26779whole arguments.
26780It's functionally equivalent to the following expression:
26781@c JP
26782@code{match-lambda} と同じですが、@code{match} をすべての引数のリスト
26783に対して実行します。機能としては以下の式と同等です。
26784@c COMMON
26785@example
26786(lambda expr (match expr @var{clause} @dots{}))
26787@end example
26788@end defmac
26789
26790@defmac match-let ((pat expr) @dots{}) body-expr @dots{}
26791@defmacx match-let name ((pat expr) @dots{}) body-expr @dots{}
26792@defmacx match-let* ((pat expr) @dots{}) body-expr @dots{}
26793@defmacx match-letrec ((pat expr) @dots{}) body-expr @dots{}
26794@c MOD util.match
26795@c EN
26796Generalize @code{let}, @code{let*}, and @code{letrec} to allow
26797patterns in the binding position rather than just variables.
26798Each @var{expr} is evaluated, and then matched to @var{pat},
26799and the bound pattern variables are visible in
26800@var{body-expr} @dots{}.
26801@c JP
26802束縛部分が単なる変数ではなく、パターンを許す、一般化された @code{let}、
26803@code{let*} および @code{letrec} です。
26804各 @var{expr} が評価され、その後、@var{pat} と照合され、束縛された
26805パターン変数が @var{body-expr} @dots{} から見えるようになります。
26806@c COMMON
26807
26808@example
26809(match-let (
26810             (((ca . cd) ...)   '((a . 0) (b . 1) (c . 2)))
26811           )
26812  (list ca cd))
26813 @result{} ((a b c) (0 1 2))
26814@end example
26815
26816@c EN
26817If you're sick of parenthesis, try @code{match-let1} below.
26818@c JP
26819括弧はうんざりという向きには、以下の @code{match-let1} をおためしあれ。
26820@c COMMON
26821@end defmac
26822
26823@defmac match-let1 pat expr body-expr @dots{}
26824@c MOD util.match
26825@c EN
26826This is a Gauche extension and isn't found in the original Wright's code.
26827This one is equivalent to the following code:
26828@c JP
26829これは Gauche での拡張で、オリジナルの Wright のコードにはありません。
26830これは以下のコードと同等です。
26831@c COMMON
26832@example
26833(match-let ((@var{pat} @var{expr})) @var{body-expr} @dots{})
26834@end example
26835
26836@c EN
26837Syntactically, @code{match-let1} is very close to the Common Lisp's
26838@code{destructuring-bind}.
26839@c JP
26840構文としては @code{match-let1} は Common Lisp の @code{destructuring-bind}
26841に非常によく似ています。
26842@c COMMON
26843
26844@example
26845(match-let1 ('let ((var val) ...) body ...)
26846            '(let ((a b) (c d)) foo bar baz)
26847  (list var val body))
26848 @result{} ((a c) (b d) (foo bar baz))
26849@end example
26850@end defmac
26851
26852@defmac match-define pat expr
26853@c MOD util.match
26854@c EN
26855Like toplevel @code{define}, but allows a pattern instead of variables.
26856@c JP
26857トップレベルの @code{define} と同様ですが、変数の代りにパターンが許されます。
26858@c COMMON
26859
26860@example
26861(match-define (x . xs) (list 1 2 3))
26862
26863x  @result{} 1
26864xs @result{} (2 3)
26865@end example
26866
26867@end defmac
26868
26869@c EN
26870@subheading Pattern syntax
26871@c JP
26872@subheading パターンの構文
26873@c COMMON
26874
26875@c EN
26876Here's a summary of pattern syntax. The asterisk @code{(*)}
26877after explanation means Gauche's extension which does not present
26878in the original Wright's code.
26879@c JP
26880ここにあるのはパターンの構文の要約です。説明の後にあるアスタリスク
26881@code{(*)} はオリジナルの Wright のコードにはない、Gauche の拡張で
26882あることを意味します。
26883@c COMMON
26884
26885@c EN
26886@example
26887pat : @var{patvar}                       ;; anything, and binds pattern var
26888    | @b{_}                            ;; anything
26889    | ()                           ;; the empty list
26890    | #t                           ;; #t
26891    | #f                           ;; #f
26892    | @var{string}                       ;; a string
26893    | @var{number}                       ;; a number
26894    | @var{character}                    ;; a character
26895    | '@var{sexp}                        ;; an s-expression
26896    | '@var{symbol}                      ;; a symbol (special case of s-expr)
26897    | (@var{pat1} ... @var{patN})              ;; list of n elements
26898    | (@var{pat1} ... @var{patN} . @var{patN+1})     ;; list of n or more
26899    | (@var{pat1} ... @var{patN} @var{patN+1} ooo)   ;; list of n or more, each element
26900                                   ;;   of remainder must match @var{patN+1}
26901    | #(@var{pat1} ... @var{patN})             ;; vector of n elements
26902    | #(@var{pat1} ... @var{patN} @var{patN+1} ooo)  ;; vector of n or more, each element
26903                                   ;;   of remainder must match @var{patN+1}
26904    | (@b{$} @var{class} @var{pat1} ... @var{patN})      ;; an object (@var{patK} matches in slot order)
26905    | (@b{struct} @var{class} @var{pat1} ... @var{patN}) ;; ditto (*)
26906    | (@b{@@} @var{class} (@var{slot1} @var{pat1}) ...)   ;; an object (using slot names) (*)
26907    | (@b{object} @var{class} (@var{slot1} @var{pat1}) ...) ;; ditto (*)
26908    | (@b{=} @var{proc} @var{pat})                 ;; apply proc, match the result to pat
26909    | (@b{and} @var{pat} ...)                ;; if all of pats match
26910    | (@b{or} @var{pat} ...)                 ;; if any of pats match
26911    | (@b{not} @var{pat} ...)                ;; if all pats don't match at all
26912    | (@b{?} @var{predicate} @var{pat} ...)        ;; if predicate true and all pats match
26913    | (@b{set!} @var{patvar})                ;; anything, and binds setter
26914    | (@b{get!} @var{patvar})                ;; anything, and binds getter
26915    | `qp                          ;; a quasi-pattern
26916
26917patvar : a symbol except @b{_}, @b{quote}, @b{$}, @b{struct}, @b{@@}, @b{object}, @b{=}, @b{and}, @b{or},
26918         @b{not}, @b{?}, @b{set!}, @b{get!}, @b{quasiquote}, @b{...}, @b{___}, @b{..@i{k}}, @b{__@i{k}}.
26919
26920@c @b doesn't work well in pdf version, so we conditionalize...
26921@ifnottex
26922ooo : @b{...}                          ;; zero or more
26923    | @b{___}                          ;; zero or more
26924    | @b{..@i{k}}                          ;; @i{k} or more, where @i{k} is an integer.
26925                                   ;;   Example: @b{..1}, @b{..2} ...
26926    | @b{__@i{k}}                          ;; @i{k} or more, where @i{k} is an integer.
26927                                   ;;   Example: @b{__1}, @b{__2} ...
26928@end ifnottex
26929@iftex
26930ooo : ...                          ;; zero or more
26931    | ___                          ;; zero or more
26932    | ..@slanted{k}                          ;; @i{k} or more, where @i{k} is an integer.
26933                                   ;;   Example: ..1, ..2 ...
26934    | __@slanted{k}                          ;; @i{k} or more, where @i{k} is an integer.
26935                                   ;;   Example: __1, __2 ...
26936@end iftex
26937
26938@end example
26939@c JP
26940@example
26941pat : @var{patvar}                       ;; 任意のオブジェクトにマッチし、patvarを束縛
26942    | @b{_}                            ;; 任意のオブジェクト
26943    | ()                           ;; 空リスト
26944    | #t                           ;; #t
26945    | #f                           ;; #f
26946    | @var{string}                       ;; 文字列
26947    | @var{number}                       ;; 数
26948    | @var{character}                    ;; 文字
26949    | @var{keyword}                      ;; キーワード (*)
26950    | '@var{sexp}                        ;; S式
26951    | '@var{symbol}                      ;; シンボル(S式の特殊ケース)
26952    | (@var{pat1} ... @var{patN})              ;; n 要素のリスト
26953    | (@var{pat1} ... @var{patN} . @var{patN+1})     ;; n 以上の要素を含むリスト
26954    | (@var{pat1} ... @var{patN} @var{patN+1} ooo)   ;; n 以上の要素を含むリスト、残りの各要素は
26955                                   ;; @var{patN+1} にマッチしなければならない
26956    | #(@var{pat1} ... @var{patN})             ;; n 要素のベクタ
26957    | #(@var{pat1} ... @var{patN} @var{patN+1} ooo)  ;; n 以上の要素を含むベクタ、残りの各要素は
26958                                   ;; @var{patN+1} にマッチしなければならない
26959    | (@b{$} @var{class} @var{pat1} ... @var{patN})      ;; オブジェクト (@var{patK} はスロット順でマッチ)
26960    | (@b{struct} @var{class} @var{pat1} ... @var{patN}) ;; 同上 (*)
26961    | (@b{@@} @var{class} (@var{slot1} @var{pat1}) ...)  ;; オブジェクト (スロット名を使う) (*)
26962    | (@b{object} @var{class} (@var{slot1} @var{pat1}) ...) ;; 同上 (*)
26963    | (@b{=} @var{proc} @var{pat})                 ;; procを適用し、結果を pat にマッチさせる
26964    | (@b{and} @var{pat} ...)                ;; すべての pat にマッチするか
26965    | (@b{or} @var{pat} ...)                 ;; マッチする pat があるか
26966    | (@b{not} @var{pat} ...)                ;; どの pat もマッチしないか
26967    | (@b{?} @var{predicate} @var{pat} ...)        ;; predicate が真、かつ、全 pat がマッチ
26968    | (@b{set!} @var{patvar})                ;; 任意のオブジェクトにマッチし、セッタを束縛
26969    | (@b{get!} @var{patvar})                ;; 任意のオブジェクトにマッチし、ゲッタを束縛
26970    | `qp                          ;; 擬似パターン
26971
26972patvar : a symbol except @b{_}, @b{quote}, @b{$}, @b{struct}, @b{@@}, @b{object}, @b{=}, @b{and}, @b{or},
26973         @b{not}, @b{?}, @b{set!}, @b{get!}, @b{quasiquote}, @b{...}, @b{___}, @b{..k}, @b{__k}.
26974
26975@c @b doesn't work well in pdf version, so we conditionalize...
26976@ifnottex
26977ooo : @b{...}                          ;; ゼロまたはそれ以上
26978    | @b{___}                          ;; ゼロまたはそれ以上
26979    | @b{..@i{k}}                          ;; @i{k} またはそれ以上。@i{k}は整数。
26980                                   ;;   例: @b{..1}, @b{..2} ...
26981    | @b{__@i{k}}                          ;; @i{k} またはそれ以上。@i{k}は整数。
26982                                   ;;   例: @b{__1}, @b{__2} ...
26983@end ifnottex
26984@iftex
26985ooo : ...                          ;; ゼロまたはそれ以上
26986    | ___                          ;; ゼロまたはそれ以上
26987    | ..@slanted{k}                          ;; @i{k} またはそれ以上。@i{k}は整数。
26988                                   ;;   例: ..1, ..2 ...
26989    | __@slanted{k}                          ;; @i{k} またはそれ以上。@i{k}は整数。
26990                                   ;;   例: __1, __2 ...
26991@end iftex
26992
26993@end example
26994@c COMMON
26995
26996@itemize @bullet
26997@item
26998@c EN
26999A bare symbol is a "pattern variable"; it matches anything, and
27000the matched part of the expression is bound to the symbol.
27001The following symbols have special meanings and cannot be used
27002as a pattern variable: @code{_}, @code{quote}, @code{$}, @code{struct},
27003@code{@@}, @code{object}, @code{=}, @code{and}, @code{or},
27004@code{not}, @code{?}, @code{set!}, @code{get!}, @code{quasiquote},
27005@code{...}, @code{___}, and @code{..k} and @code{__k} where @emph{k} is
27006an integer.
27007@c JP
27008素のシンボルは「パターン変数」で、あらゆるものとマッチし、
27009式のマッチした部分がそのシンボルに束縛されます。
27010以下のシンボルは特別な意味をもち、パターン変数としては使えません。
27011@code{_}、@code{quote}、@code{$}、@code{struct}、@code{@@}、@code{object}、
27012@code{=}、@code{and}、@code{or}、@code{not}、@code{?}、@code{set!}、
27013@code{get!}、@code{quasiquote}、@code{...}、@code{___} および
27014@code{..k} と @code{__k} (ここで、@emph{k} は整数)。
27015@c COMMON
27016
27017@item
27018@c EN
27019A symbol @code{_} matches anything, without binding a pattern variable.
27020It can be used to show "don't care" placeholder.
27021@c JP
27022シンボル @code{_} はあらゆるものマッチし、パターン変数は束縛しません。
27023プレースホルダであることを示すのに用います。
27024@c COMMON
27025
27026@item
27027@c EN
27028Literals such as emptylist, booleans, strings, numbers, characters and
27029keywords match the same object (in the sense of @code{equal?}).
27030@c JP
27031空リスト、真偽値、文字列、数、文字およびキーワードのリテラルは
27032(@code{equal?}という意味で)同じオブジェクトとマッチします。
27033@c COMMON
27034
27035@item
27036@c EN
27037Quoted expression matches the same expression (in the sense of @code{equal?}).
27038You can use a quoted symbol to match the symbol itself.
27039@c JP
27040クウォートされた式は(@code{equal?} という意味で)同じ式とマッチします。
27041クウォートされたシンボルをそれ自身とマッチさせるのに使えます。
27042@c COMMON
27043
27044@item
27045@c EN
27046A keyword, without a quote, used to match the same keyword object.
27047Since we're in the process of unifying keywords and symbols, the user is
27048recommended to write keywords with a quote in a pattern in order to match
27049the keyword in the input.  @xref{Keyword and symbol integration}, for
27050the details.
27051@c JP
27052キーワードは、以前はクオート無しで同じキーワードにマッチしていました。
27053しかし現在は、キーワードとシンボルの統合に移行中なので、キーワードにマッチさせるために
27054パターンにキーワードを含める際には常にクオートしてください。
27055詳しくは@ref{Keyword and symbol integration}参照。
27056@c COMMON
27057
27058@item
27059@c EN
27060A list and a vector in general match a list or a vector whose elements
27061matches the elements in the pattern recursively, unless the first element
27062of the list is one of the special symbols listed above, it has a special
27063meaning.
27064@c JP
27065通常リストおよびベクタは、それぞれ、パターン中の要素にマッチする要素を
27066もつリストまたはベクタとマッチします。ただし、最初の要素が上であげた
27067特別なシンボルではない限りです。そのような場合には特別な意味を持ちます。
27068@c COMMON
27069
27070@c EN
27071As a special case, the last element of a vector or a list can be
27072followed by a symbol @code{...}.  In that case, the pattern just before
27073the symbol @code{...} can be applied repeatedly until it consumes all the
27074elements in the given expression.  A symbol @code{___} can be used
27075in place of @code{...}; it is useful when you want to produce a pattern
27076by syntax-rules macro.
27077@c JP
27078特別な場合として、ベクタあるいはリストの最後の要素のあとにシンボル
27079@code{...} を付加することができます。この場合には、@code{...} シンボル
27080直前のパターンが与えられた式のすべての要素を尽すまで繰り返し適用されます。
27081シンボル @code{___} は @code{...} の場所で使えます。構文規則マクロによって
27082パターンを生成したいときに便利です。
27083@c COMMON
27084
27085@c EN
27086For a list pattern, you can also use a symbol @code{..1}, @code{..2},
27087@dots{}, which specifies the minimum number of repetition.
27088@c JP
27089リストのパターンに対しては、シンボル @code{..1}、@code{..2}、@dots{} が
27090使えます。これは繰り返しの最小値を指定するものです。
27091@c COMMON
27092
27093@item
27094@c EN
27095@code{($ class pat1 @dots{})} matches an instance of a class @code{class}.
27096Each pattern @code{pat1} @dots{} matches each value of slots,
27097in order of @code{(class-slots class)} by default.
27098(Records are exception; they match the same order as their
27099default constructor since 0.9.6.)
27100@c JP
27101@code{($ class pat1 @dots{})} は @code{class} クラスのインスタンスと
27102マッチします。各パターン @code{pat1} @dots{} はデフォルトではスロットの各値と
27103@code{(class-slots class)} の順にマッチします。
27104(レコードは例外で、0.9.6からデフォルトコンストラクタの順序と同じ順序になりました。)
27105@c COMMON
27106
27107@c EN
27108@code{(struct class pat1 @dots{})} has the same meaning.  Although
27109the original Wright's code doesn't have @code{struct}, PLT Scheme has
27110it in its extended match feature, and it is more descriptive.
27111@c JP
27112@code{(struct class pat1 @dots{})} は同じ意味です。オリジナルの
27113Wright のコードには、@code{struct} はありませんが、PLT Scheme の拡張
27114照合機能にはそなわっています。こちらの方がより説明的です。
27115@c COMMON
27116
27117@c EN
27118This is an adaptation of the original feature that can match structures.
27119It is useful to match a simple instance that you know the order of
27120slots; for example, a simple record created by @code{define-record-type}
27121(@pxref{Record types}) would be easy to match by positioned values.
27122@c JP
27123これはオリジナルの機能を構造(structure)にもマッチするように調整した
27124ものです。スロットの順番が予め分るような単純なインスタンスをマッチする
27125のに便利です。たとえば、@code{define-record-type} (@ref{Record types}参照)で作成した
27126簡単なレコードは簡単に位置指定された値でマッチすることができます。
27127@c COMMON
27128
27129@c EN
27130If the instance's class uses inheritances, it is a bit difficult to
27131match by positions.  You can use @code{@@} or @code{object} pattern
27132below to match using slot names.
27133@c JP
27134インスタンスのクラスが継承を使っている場合、位置によるマッチを
27135おこなうのは少々難しくなります。以下の @code{@@} あるいは @code{object}
27136パターンを使って、スロット名でマッチを行うことができます。
27137@c COMMON
27138
27139@item
27140@c EN
27141@code{(object class (slot1 pat1) @dots{})} matches an instance
27142of a class @code{class} whose value of @var{slot1} @dots{} matches
27143@var{pat1} @dots{}.  This is Gauche's extension.  @code{@@} can be
27144used in place of @code{object}, but @code{object} is recommended
27145because of descriptiveness.
27146@c JP
27147@code{(object class (slot1 pat1) @dots{})} は
27148@var{slot1} @dots{} の値が @var{pat1} @dots{} にマッチするような
27149@code{class} クラスのインスタンスとマッチします。これは、
27150Gauche の拡張です。@code{@@} は @code{object} と同じ場所で使えます。
27151ただし、@code{object} の方が説明的でわかりやすいので、こちらを
27152推奨します。
27153@c COMMON
27154
27155@item
27156@c EN
27157@code{(= proc pat)} first applies @var{proc} to the corresponding
27158expression, then match the result with @var{pat}.
27159@c JP
27160@code{(= proc pat)} は最初に @var{proc} を対応する式に適用し、
27161その結果と @var{pat} をマッチさせます。
27162@c COMMON
27163
27164@item
27165@c EN
27166@code{(and pat @dots{})}, @code{(or pat @dots{})}, and
27167@code{(not pat @dots{})} are boolean operations of patterns.
27168@c JP
27169@code{(and pat @dots{})}、@code{(or pat @dots{})} および
27170@code{(not pat @dots{})} はパターンの真偽値演算子です。
27171@c COMMON
27172
27173@item
27174@c EN
27175@code{(? predicate pat @dots{})} first applies a predicate to the
27176corresponding expression, and if it returns true, applies each
27177@code{pat} @dots{} to the expression.
27178@c JP
27179@code{(? predicate pat @dots{})} は最初、述語を対応する式に適用し、
27180真が返れば、各 @code{pat} @dots{} をその式に適用します。
27181@c COMMON
27182
27183@item
27184@c EN
27185@code{(set! patvar)} matches anything, and binds an one-argument
27186procedure to a pattern variable @var{patvar}.  If the procedure is
27187called, it replaces the value of matched pattern for the given argument.
27188@c JP
27189@code{(set! patvar)} はあらゆるものにマッチし、一引数の手続きを
27190パターン変数 @var{patvar} に束縛します。その手続きが呼ばれると、
27191マッチしたパターンの値を与えられた引数で置き換えます。
27192@c COMMON
27193
27194@item
27195@c EN
27196@code{(get! patvar)} matches anything, and binds a zero-argument
27197procedure to a pattern variable @var{patvar}.  If the procedure is
27198called, it returns the matched value.
27199@c JP
27200@code{(get! patvar)} はあらゆるものにマッチし、引数なしの手続きを
27201パターン変数 @var{patvar} に束縛します。その手続きが呼ばれると、
27202マッチしたパターンの値を返します。
27203@c COMMON
27204
27205@item
27206@c EN
27207@code{`qp} is a quasipattern.  @var{qp} is quoted, in the sense
27208that it matches itself, @emph{except} the pattern that is unquoted.
27209(Don't confuse quasipattern to quasiquote, though the functions are
27210similar.  Quasiquote turns off evaluation except unquoted subtree.
27211Quasiquote turns off the special pattern syntax except unquoted subtree.
27212See the examples below).
27213@c JP
27214@code{`qp}はquasipatternです。@var{qp}は、クオートされたパターンと同様、
27215それそのものにマッチしますが、その中にアンクオートされているパターンがあると、
27216その部分だけは通常のパターンとして解釈されます。
27217(準クオート(quasiquote)とquasipatternを混同しないようにしてください。
27218機能的に両者は似ていますが、準クオートがアンクオートされた部分木以外の
27219部分の評価をoffにするのに対し、quasipatternはアンクオートされた部分木
27220以外の部分のパターン構文を無効にします。下の例も参照して下さい。)
27221@c COMMON
27222@end itemize
27223
27224@c EN
27225@subheading Pattern examples
27226@c JP
27227@subheading パターン例
27228@c COMMON
27229
27230@c EN
27231A simple structure decomposition:
27232@c JP
27233単純な構造の分解
27234@c COMMON
27235@example
27236(match '(0 (1 2) (3 4 5))
27237  [(a (b c) (d e f))
27238   (list a b c d e f)])
27239 @result{} (0 1 2 3 4 5)
27240@end example
27241
27242@c EN
27243Using predicate patterns:
27244@c JP
27245述語パターンの使用
27246@c COMMON
27247@example
27248(match 123
27249  [(? string? x) (list 'string x)]
27250  [(? number? x) (list 'number x)])
27251 @result{} (number 123)
27252@end example
27253
27254@c EN
27255Extracting variables and expressions from @code{let}.
27256Uses repetition and predicate patterns:
27257@c JP
27258@code{let} から変数と式を取り出す
27259反復および述語パターンの利用
27260@c COMMON
27261@example
27262(define let-analyzer
27263  (match-lambda
27264    [('let (? symbol?)
27265           ((var expr) ...)
27266       body ...)
27267     (format "named let, vars=~s exprs=~s" var expr)]
27268    [('let ((var expr) ...)
27269       body ...)
27270     (format "normal let, vars=~s exprs=~s" var expr)]
27271    [_
27272     (format "malformed let")]))
27273
27274(let-analyzer '(let ((a b) (c d)) e f g))
27275 @result{} "normal let, vars=(a c) exprs=(b d)"
27276
27277(let-analyzer '(let foo ((x (f a b)) (y (f c d))) e f g))
27278 @result{} "named let, vars=(x y) exprs=((f a b) (f c d))"
27279
27280(let-analyzer '(let (a) b c d))
27281 @result{} "malformed let"
27282@end example
27283
27284@c EN
27285Using @code{=} function application.  The pattern variable @var{m}
27286is matched to the result of application of the regular expression.
27287@c JP
27288@code{=} 関数適用。パターン変数 @var{m} は正規表現の適用結果にマッチする
27289@c COMMON
27290@example
27291(match "gauche-ref.texi"
27292  ((? string? (= #/(.*)\.([^.]+)$/ m))
27293   (format "base=~a suffix=~a" (m 1) (m 2))))
27294 @result{} "base=gauche-ref suffix=texi"
27295@end example
27296
27297@c EN
27298An example of quasipattern.   In the first expression, the
27299pattern except @code{value} is quoted, so the symbols @code{the},
27300@code{answer}, and @code{is} are not pattern variables but literal
27301symbols.   The second expression shows that; input symbol @code{was}
27302does not match the literal symbol @code{is} in the pattern.
27303If we don't use quasiquote, all symbols in the pattern are pattern
27304variables, so any four-element list matches as the third expression shows.
27305@c JP
27306quasipatternの例です。最初の式では、パターンのうち@code{value}以外の
27307部分がクオートされたことになり、従ってシンボル@code{the}, @code{answer},
27308@code{is}はパターン変数ではなくリテラルシンボルとなります。
273092番目の式がそのことを示しています。入力にあるシンボル@code{was}は
27310パターンの@code{is}とマッチしません。もしクオートを行わないと、
27311全てのシンボルはパターン変数となるので、3番目の例に示すように
27312任意の4つの要素を持つリストとマッチしてしまいます。
27313@c COMMON
27314@example
27315(match '(the answer is 42)
27316  [`(the answer is ,value) value]
27317  [else #f])
27318 @result{} 42
27319
27320(match '(the answer was 42)
27321  [`(the answer is ,value) value]
27322  [else #f])
27323 @result{} #f
27324
27325(match '(a b c d)
27326  [(the answer is value) value]
27327  [else #f])
27328 @result{} d
27329@end example
27330
27331@c EN
27332An example of matching records.
27333The following code implements ``rotation''
27334operation to balance a red-black tree.
27335@c JP
27336レコードのマッチングの例です。
27337次のコードは赤黒木をバランスさせる「ローテーション」操作を実装しています。
27338@c COMMON
27339
27340@example
27341(define-record-type T #t #t
27342  color left value right)
27343
27344(define (rbtree-rotate t)
27345  (match t
27346    [(or ($ T 'B ($ T 'R ($ T 'R a x b) y c) z d)
27347         ($ T 'B ($ T 'R a x ($ T 'R b y c)) z d)
27348         ($ T 'B a x ($ T 'R ($ T 'R b y c) z d))
27349         ($ T 'B a x ($ T 'R b y ($ T 'R c z d))))
27350     (make-T 'R (make-T 'B a x b) y (make-T 'B c z d))]
27351    [else t]))
27352@end example
27353
27354@c ----------------------------------------------------------------------
27355@node SLIB-compatible record type, Relation framework, Pattern matching, Library modules - Utilities
27356@section @code{util.record} - SLIB-compatible record type
27357@c NODE SLIB-互換のレコード型, @code{util.record} - SLIB-互換のレコード型
27358
27359@deftp {Module} util.record
27360@mdindex util.record
27361@c EN
27362This module provides a Guile and SLIB compatible record type API.
27363It is built on top of Gauche's object system.
27364
27365See also @ref{Record types}, which provides a convenience macro
27366@code{define-record-type}.
27367@c JP
27368このモジュールは、Guile と SLIB とに互換性のあるレコード型 API を提供します。
27369これは、Gauche のオブジェクトシステム上に構築されています。
27370
27371便利なマクロ @code{define-record-type} を提供する @ref{Record types} も
27372参照してください。
27373@c COMMON
27374@end deftp
27375
27376@defun make-record-type type-name field-names
27377@c MOD util.record
27378@c EN
27379Returns a new class which represents a new record type.
27380(It is what is called @emph{record-type descriptor} in SLIB).
27381In Gauche, the new class is a subclass of @code{<record>}
27382(see @ref{Record types}).
27383
27384@var{type-name} is a string that is used for debugging purposes.
27385It is converted to a symbol and set as the name of the new class.
27386@var{field-names} is a list of symbols of the names of fields.
27387Each field is implemented as a slot of the new class.
27388@c JP
27389あらしいレコード型を表わす新しいクラスを返します。
27390(これは SLIB では @emph{レコード型記述子}とよばれているものです。)
27391Gauche では、この新しいクラスは @code{<record>} のサブクラスです
27392(@ref{Record types} 参照)。
27393
27394@var{type-name} はデバッグの目的で使われる文字列です。
27395これは、シンボルに変換され、この新しいクラスの名前として設定されます。
27396@var{field-names} はフィールド名のシンボルのリストです。
27397各々のフィールドはこの新しいクラスのスロットとして実装されます。
27398@c COMMON
27399@end defun
27400
27401@c EN
27402In the following procedures, @var{rtd} is the record class
27403created by @code{make-record-type}.
27404@c JP
27405以下の手続きでは、@var{rtd} は @code{make-record-type} によって
27406生成されたクラスです。
27407@c COMMON
27408
27409@defun record-constructor rtd :optional field-names
27410@c MOD util.record
27411@c EN
27412Returns a procedure that constructs an instance
27413of the record type of given @var{rtd}.  The returned
27414procedure takes exactly as many arguments as @var{field-names},
27415which defaults to @code{'()}.  Each argument sets the initial
27416value of the corresponding field in @var{field-names}.
27417@c JP
27418与えられた @var{rtd} レコード型のインスタンスを構築する手続きを
27419返します。返された手続きは @var{field-names} とちょうど同じ数の
27420引数をとります。@var{field-names} のデフォルトは @code{'()} です。
27421それぞれの引数は @var{field-names} の対応するフィールドの初期値を
27422設定します。
27423@c COMMON
27424@end defun
27425
27426@defun record-predicate rtd
27427@c MOD util.record
27428@c EN
27429Returns a procedure that takes one argument, which returns @code{#t}
27430iff the given argument is of type of @var{rtd}.
27431@c JP
27432一つの引数をとり、与えられた引数が @var{rtd} と同じ型であり、その場合に
27433限り @code{#t} を返す手続きを返します。
27434@c COMMON
27435@end defun
27436
27437@defun record-accessor rtd field-name
27438@c MOD util.record
27439@c EN
27440Returns an accessor procedure for the field named by @var{field-name}
27441of type @var{rtd}.  The accessor procedure takes an instance of
27442@var{rtd}, and returns the value of the field.
27443@c JP
27444@var{rtd} 型の @var{field-name} によって名付けられたフィールドへの
27445アクセサ手続きを返します。このアクセサ手続きは、@var{rtd} のインスタンスを
27446一つとり、そのフィールドの値を返します。
27447@c COMMON
27448@end defun
27449
27450@defun record-modifier rtd field-name
27451@c MOD util.record
27452@c EN
27453Returns a modifier procedure for the field named by @var{field-name}
27454of type @var{rtd}.  The modifier procedure takes two arguments,
27455an instance of @var{rtd} and a value, and sets the value to
27456the specified field.
27457@c JP
27458@var{rtd} 型の @var{field-name} によって名付けられたフィールドへの
27459モディファイア手続きを返します。このモディファイア手続きは、
27460@var{rtd} のインスタンスと値のふたつの引数をとり、その引数を
27461指定されたフィールドに設定します。
27462@c COMMON
27463@end defun
27464
27465@example
27466(define rtd (make-record-type "my-record" '(a b c)))
27467
27468rtd @result{} #<class my-record>
27469
27470(define make-my-record (record-constructor rtd '(a b c)))
27471
27472(define obj (make-my-record 1 2 3))
27473
27474obj @result{} #<my-record 0x819d9b0>
27475
27476((record-predicate? rtd) obj)  @result{} #t
27477
27478((record-accessor rtd 'a) obj) @result{} 1
27479((record-accessor rtd 'b) obj) @result{} 2
27480((record-accessor rtd 'c) obj) @result{} 3
27481
27482((record-modifier rtd 'a) obj -1)
27483
27484((record-accessor rtd 'a) obj) @result{} -1
27485@end example
27486
27487@c ----------------------------------------------------------------------
27488@node Relation framework, Stream library, SLIB-compatible record type, Library modules - Utilities
27489@section @code{util.relation} - Relation framework
27490@c NODE リレーションフレームワーク, @code{util.relation} - リレーションフレームワーク
27491
27492@deftp {Module} util.relation
27493@mdindex util.relation
27494@c EN
27495Provides a set of common operations for relations.
27496@c JP
27497リレーションに対する共通の操作を提供します。
27498@c COMMON
27499
27500@c EN
27501Given set of values S1, S2, ..., Sn, a relation R is a set of tuples
27502such that the first element of a tuple is from S1, the second from
27503S2, ..., and the n-th from Sn.  In another word, R is a subset of
27504Cartesian product of S1, ..., Sn.
27505(The definition, as well as the term @emph{relation}, is taken
27506from the Codd's 1970 paper,
27507"A Relational Model of Data for Large Shared Data Banks", in
27508CACM 13(6) pp.377--387.)
27509@c JP
27510値の集合を S1, S2, ..., Sn とするとリレーション R はタプルの集合で、
27511タプルの最初の要素は S1 からの値で、2番目は S2 から、で n 番目は
27512Sn からとなっている。いいかえれば、R は S1, ..., Sn の直積です。
27513(この定義と@emph{リレーション}という用語は 1970年のCoddのペーパー
27514"A Relational Model of Data for Large Shared Data Banks", in
27515CACM 13(6) pp.377--387.によるものです。)
27516@c COMMON
27517
27518@c EN
27519This definition can be applied to various datasets: A set of Gauche
27520object system instances is a relation, if you view each instance as
27521a tuple and each slot value as the actual values.  A list of lists can be a
27522relation.  A stream that reads from CSV table produces a relation.
27523Thus it would be useful to provide a module that implements generic
27524operations on relations, no matter how the actual representation is.
27525@c JP
27526この定義はいろいろなデータベースセットにあてはまります。各インスタンス
27527をタプルとみなし、各スロット値を実際の値と見ると、Gaucheのオブジェクト
27528システムの集合はリレーションです。リストのリストもリレーションです。
27529CSVテーブルからの読み出しストリームはリレーションを生成します。このよ
27530うことから、表現に依存しないリレーション上のジェネリックな操作を実装す
27531るモジュールを用意することは有意義です。
27532@c COMMON
27533
27534@c EN
27535From the operational point of view, we can treat any datastructure
27536that provides the following four methods; @code{relation-rows},
27537which retrieves a collection of tuples (rows);
27538@code{relation-column-names}, @code{relation-accessor}, and
27539@code{relation-modifier}, which provide the means to access
27540meta-information.
27541All the rest of relational operations are built on top of
27542those primitive methods.
27543@c JP
27544操作という観点からいえば、以下の4つのメソッドがあれば、どのようなデー
27545タ構造もあつかえます。タプルのコレクション(行)を取り出す
27546@code{relation-rows}、それから、@code{relation-column-names}、
27547@code{relation-accessor}、@code{relation-modifier}、これらはメタ情報に
27548アクセスする方法を提供しています。これ以外のすべてのリレーション操作は
27549上のプリミティブメソッドを使って組まれています。
27550@c COMMON
27551
27552@c EN
27553A concrete implementation of relation can use duck typing,
27554i.e. it doesn't need to inherit a particular base class to
27555use the relation methods.  However, for the convenience,
27556a base class @code{<relation>} is provided in this module.
27557It works as a mixin class---a concrete class typically wants
27558to inherit @code{<relation>} and @code{<collection>} or
27559@code{<sequence>}.  Check out the sample implementations
27560in the @file{lib/util/relation.scm} in the source tree, if
27561you're curious.
27562@c JP
27563リレーションの具体的な実装にはダックタイピングが適用できます。
27564すなわち、リレーションメソッドを使うのに特定のベースクラスを継承する必
27565要はありません。しかし、利便のためにこのモジュールには、ベースクラス
27566@code{<relation>}が用意されています。これは、ミックスインクラスのよう
27567な働きをします。具象クラスは典型的には@code{<relation>}および
27568@code{<collection>}または@code{<sequence>}を継承することになるでしょう。
27569興味があれば、ソースツリーにある@file{lib/util/relation.scm}に含まれる
27570サンプル実装をチェックするとよいでしょう。
27571@c COMMON
27572
27573@c EN
27574This module is still under development.
27575The plan is to build useful relational operations on top of the
27576common methods.
27577@c JP
27578このモジュールは現時点では開発途上にあります。計画では共通メソッド上に
27579有用なリレーション操作関数群を構築することになっています。
27580@c COMMON
27581@end deftp
27582
27583@c EN
27584@subheading Basic class and methods
27585@c JP
27586@subheading 基本となるクラスとメソッド
27587@c COMMON
27588
27589@deftp {Class} <relation>
27590@clindex relation
27591@c MOD util.relation
27592@c EN
27593An abstract base class of relations.
27594@c JP
27595リレーションの抽象ベースクラス
27596@c COMMON
27597@end deftp
27598
27599@deffn {Method} relation-column-names (r <relation>)
27600@c MOD util.relation
27601@c EN
27602A subclass must implement this method.
27603It should return a sequence of names of the columns.
27604The type of column names is up to the relation; we don't
27605place any restriction on it, as far as they are different
27606each other in terms of @code{equal?}.
27607@end deffn
27608@c JP
27609サブクラスではこのメソッドを必ず実装しなければなりません。
27610カラムの名前のシーケンスを返す必要があります。カラム名の型はリレーショ
27611ンによります。@code{equal?}の意味で相互に異っているかぎり、カラム名に
27612ついて特に制限はありません。
27613@end deffn
27614@c COMMON
27615
27616@deffn {Method} relation-accessor (r <relation>)
27617@c MOD util.relation
27618@c EN
27619A subclass must implement this method.
27620It should return a procedure that takes two arguments, a row from
27621the relation @var{r} and a column name, and returns the value
27622of the specified column.
27623@c JP
27624サブクラスではこのメソッドは必ず実装しなければなりまん。2つの引数をと
27625り、リレーション@var{r}の行とカラム名をとり、指定したカラムの値を返す
27626手続を返さなければなりません。
27627@c COMMON
27628@end deffn
27629
27630@deffn {Method} relation-modifier (r <relation>)
27631@c MOD util.relation
27632@c EN
27633A subclass must implement this method. It should returns a procedure
27634that takes three arguments, a row from the relation @var{r}, a column
27635name, and a value to set.
27636@c JP
27637サブクラスではこのメソッドは必ず実装しなければなりまん。
276383つの引数、リレーション@var{r}の行、カラム名、値をとり、その値をセット
27639する手続を返さなければなりません。
27640@c COMMON
27641
27642@c EN
27643If the relation is read-only, this method returns @code{#f}.
27644@c JP
27645リレーションが読み込み専用の場合はこのメソッドは@code{#f}を返します。
27646@c COMMON
27647@end deffn
27648
27649@deffn {Method} relation-rows (r <relation>)
27650@c MOD util.relation
27651@c EN
27652A subclass must implement this method.
27653It should return the underlying instance of @code{<collection>} or
27654its subclass (e.g.  @code{<sequence>})
27655@c JP
27656サブクラスではこのメソッドは必ず実装しなければなりまん。
27657基盤となっている@code{<collection>}クラスまたはそのサブクラス(たとえば
27658@code{<sequence>})のインスタンスを返さなければなりません。
27659@c COMMON
27660@end deffn
27661
27662@c EN
27663The rest of method are built on top of the above four methods.
27664A subclass of @code{<relation>} may overload some of the
27665methods below for better performance, though.
27666@c JP
27667のこりのメソッドは上の4つのメソッドを使って組まれています。とはいえ、
27668@code{<relation>} のサブクラスでは以下のメソッドを性能を得るためにオー
27669バーロードすることもできます。
27670@c COMMON
27671
27672@deffn {Method} relation-column-name? (r <relation>) column
27673@c MOD util.relation
27674@c EN
27675Returns true iff @var{column} is a valid column name for the relation
27676@var{r}.
27677@c JP
27678@var{column}がリレーション@var{r}において有効なカラム名である場合にの
27679み真を返します。
27680@c COMMON
27681@end deffn
27682
27683@deffn {Method} relation-column-getter (r <relation>) column
27684@deffnx {Method} relation-column-setter (r <relation>) column
27685@c MOD util.relation
27686@c EN
27687Returns a procedure to access the specified column of a row
27688from the relation @var{r}.  @code{Relation-column-getter}
27689should return a procedure that takes one argument, a row.
27690@code{Relation-column-setter} should return a procedure that
27691takes two arguments, a row and a new value to set.
27692@c JP
27693リレーション@var{r}の行の指定したカラムにアクセスする手続を返します。
27694@code{Relation-column-getter}は、1つの引数、行をとる手続きを返さなけれ
27695ばなりません。@code{Relation-column-setter}は2つの引数、行と新しくセッ
27696トする値を取る手続きを返さなければなりません。
27697@c COMMON
27698
27699@c EN
27700If the relation is read-only, @code{relation-column-setter}
27701returns @code{#f}.
27702@c JP
27703リレーションが読み込み専用の場合は@code{relation-column-setter}
27704は@code{#f}を返します。
27705@c COMMON
27706@end deffn
27707
27708@deffn {Method} relation-ref (r <relation>) row column :optional default
27709@c MOD util.relation
27710@c EN
27711@var{Row} is a row from the relation @var{r}.  Returns value of
27712the @var{column} in @var{row}.  If @var{column} is not a valid
27713column name, @var{default} is returned if it is given, otherwise
27714an error is signaled.
27715@c JP
27716@var{row}はリレーション@var{r}の行です。@var{row}の@var{column}の値を
27717返します。@var{column}が不正なカラム名である場合、@var{default}が与え
27718られていればそれを返し、そうでなければ、エラーを示すシグナルがあがりま
27719す。
27720@c COMMON
27721@end deffn
27722
27723@deffn {Method} relation-set! (r <relation>) row column value
27724@c MOD util.relation
27725@c EN
27726@var{Row} is a row from the relation @var{r}.  Sets @var{value}
27727as the value of @var{column} in @var{row}.  This may signal
27728an error if the relation is read-only.
27729@c JP
27730@var{row}はリレーション@var{r}の行です。@var{value}を@var{row}の
27731@var{column}に設定します。リレーションが読み込み専用の場合には
27732エラーを示すシグナルがあがります。
27733@c COMMON
27734@end deffn
27735
27736@deffn {Method} relation-column-getters (r <relation>)
27737@deffnx {Method} relation-column-setters (r <relation>)
27738@c MOD util.relation
27739@c EN
27740Returns full list of getters and setters.  Usually the default
27741method is sufficient, but the implementation may want to cache
27742the list of getters, for example.
27743@c JP
27744ゲッタとセッタの完全なリストを返します。通常はデフォルトのメソッドで十
27745分ですが、たとえばゲッタのリストをキャッシュしたいときもあるでしょう。
27746@c COMMON
27747@end deffn
27748
27749@deffn {Method} relation-coercer (r <relation>)
27750@c MOD util.relation
27751@c EN
27752Returns a procedure that coerces a row into a sequence.
27753If the relation already uses a sequence to represent a row,
27754it can return row as is.
27755@c JP
27756行をシーケンスに変換する手続きを返します。行がすでにシーケンスで表現さ
27757れているリレーションであれば、行をそのまま返す手続きです。
27758@c COMMON
27759@end deffn
27760
27761@deffn {Method} relation-insertable? (r <relation>)
27762@c MOD util.relation
27763@c EN
27764Returns true iff new rows can be inserted to the relation @var{r}.
27765@c JP
27766リレーション@var{r}に新しい行を挿入可能な場合にのみ真を返します。
27767@c COMMON
27768@end deffn
27769
27770@deffn {Method} relation-insert! (r <relation>) row
27771@c MOD util.relation
27772@c EN
27773Insert a row @var{row} to the relation @var{r}.
27774@c JP
27775リレーション@var{r}に行@var{row}を挿入します。
27776@c COMMON
27777@end deffn
27778
27779@deffn {Method} relation-deletable? (r <relation>)
27780@c MOD util.relation
27781@c EN
27782Returns true iff rows can be deleted from the relation @var{r}.
27783@c JP
27784リレーション@var{r}から行を削除可能である場合にのみ真を返します。
27785@c COMMON
27786@end deffn
27787
27788@deffn {Method} relation-delete! (r <relation>) row
27789@c MOD util.relation
27790@c EN
27791Deletes a row @var{row} from the relation @var{r}.
27792@c JP
27793リレーション@var{r}から行@var{row}を削除します。
27794@c COMMON
27795@end deffn
27796
27797@deffn {Method} relation-fold (r <relation>) proc seed column @dots{}
27798@c MOD util.relation
27799@c EN
27800Applies @var{proc} to the values of @var{column} @dots{} of each row,
27801passing @var{seed} as the state value.  That is, for each row in
27802@var{r}, @var{proc} is called as follows:
27803@c JP
27804@var{proc}を各行のカラム@var{column} @dots{} の値に適用します。
27805@var{seed}は状態の値として渡されます。すなわち、リレーション@var{r}の
27806各行ごとに以下のように@var{proc}を呼びます。
27807@c COMMON
27808@example
27809
27810(@var{proc} @var{v_0} @var{v_1} @dots{} @var{v_i} @var{seed})
27811
27812 where @var{v_k} = (relation-ref @var{r} @var{row} @var{column_k})
27813
27814@end example
27815
27816@c EN
27817The result of the call becomes a new seed value, and the final result
27818is returned from @var{relation-fold}.
27819@c JP
27820呼び出しの結果があたらしいシードの値となり、最終の結果が
27821@var{relation-fold}から返ります。
27822@c COMMON
27823
27824@c EN
27825For example, if a relation has a column named @code{amount},
27826and you want to sum up all of them in a relation @var{r},
27827you can write like this:
27828@c JP
27829たとえば、リレーションが @code{amount} という名前のカラムをもつものと
27830し、リレーション @var{r} 内にあるそのカラムをすべて足しあわせたいとす
27831ると以下のように書けます。
27832@c COMMON
27833@example
27834(relation-fold r + 0 'amount)
27835@end example
27836@end deffn
27837
27838@c EN
27839@subheading Concrete classes
27840@c JP
27841@subheading 具象クラス
27842@c COMMON
27843
27844@deftp {Class} <simple-relation>
27845@clindex simple-relation
27846@c MOD util.relation
27847@end deftp
27848
27849@deftp {Class} <object-set-relation>
27850@clindex object-set-relation
27851@c MOD util.relation
27852@end deftp
27853
27854@c ----------------------------------------------------------------------
27855@node Stream library, Topological sort, Relation framework, Library modules - Utilities
27856@section @code{util.stream} - Stream library
27857@c NODE ストリームライブラリ, @code{util.stream} - ストリームライブラリ
27858
27859@deftp {Module} util.stream
27860@mdindex util.stream
27861@c EN
27862This module provides a library of lazy streams, including the
27863functions and syntaxes defined in srfi-40 and srfi-41,
27864the latter of which became a part of R7RS large (as @code{(scheme stream)},
27865
27866Gauche has a built-in lazy sequences (@pxref{Lazy sequences}), which is
27867a lazy stream integrated to a list so that you can use all list procedures
27868on it.  Lazy streams provided in this module are somewhat heavier than
27869lazy sequences and you need to use special procedures,
27870but it is strictly lazy (while a lazy sequence evaluates one element ahead)
27871and portable.
27872@c JP
27873このモジュールは遅延ストリームのライブラリを提供します。このモジュール
27874にはsrfi-40とsrfi-41で定義されている関数および構文が含まれています。
27875後者は@code{(scheme stream)}としてR7RS largeの一部になっています。
27876
27877Gaucheには遅延ストリームとリストを統合したような、組み込みの遅延シーケンスがあります
27878(@ref{Lazy sequences})参照。そちらは通常のリスト手続きを使って扱うことができます。
27879このモジュールで提供される遅延ストームは、遅延シーケンスより重く、
27880扱うために専用の手続きが必要です。ただ、要素の評価は必要になるぎりぎりまで遅延され
27881(遅延シーケンスでは必要な要素のひとつ先まで評価されます)、またポータブルです。
27882@c COMMON
27883@end deftp
27884
27885@menu
27886* Stream primitives::
27887* Stream constructors::
27888* Stream binding::
27889* Stream consumers::
27890* Stream operations::
27891@end menu
27892
27893@node Stream primitives, Stream constructors, Stream library, Stream library
27894@subsection Stream primitives
27895
27896@defun stream? obj
27897[R7RS stream]
27898@c MOD util.stream
27899@c EN
27900Returns @code{#t} iff @var{obj} is a stream created by a procedure
27901of @code{util.stream}.
27902@c JP
27903@var{obj}が@code{util.stream}の手続きによって作成されたストリームであ
27904る場合にかぎり@code{#t}を返します。
27905@c COMMON
27906@end defun
27907
27908@defvar stream-null
27909[R7RS stream]
27910@c MOD util.stream
27911@c EN
27912The singleton instance of NULL stream.
27913@c JP
27914NULLストリームのシングルトンインスタンス。
27915@c COMMON
27916@end defvar
27917
27918@defmac stream-cons object stream
27919[R7RS stream]
27920@c MOD util.stream
27921@c EN
27922A fundamental constructor of a stream.  Adds @var{object} to the
27923head of a @var{stream}, and returns a new stream.
27924@c JP
27925ストリームの基本構成子。@var{object}を@var{stream}の先頭に追加し、新し
27926いストリームを返します。
27927@c COMMON
27928@end defmac
27929
27930@defun stream-null? obj
27931[R7RS stream]
27932@c MOD util.stream
27933@c EN
27934Returns @code{#t} iff @var{obj} is the null stream.
27935@c JP
27936@var{obj}がNULLストリームの場合にのみ@code{#t}を返します。
27937@c COMMON
27938@end defun
27939
27940@defun stream-pair? obj
27941[R7RS stream]
27942@c MOD util.stream
27943@c EN
27944Returns @code{#t} iff @var{obj} is a non-null stream.
27945@c JP
27946@var{obj}がNULLストリームではないストリームのときにのみ@code{#t}を返します。
27947@c COMMON
27948@end defun
27949
27950@defun stream-car s
27951[R7RS stream]
27952@c MOD util.stream
27953@c EN
27954Returns the first element of the stream @var{s}.
27955@c JP
27956ストリーム@var{s}の最初の要素を返します。
27957@c COMMON
27958@end defun
27959
27960@defun stream-cdr s
27961[R7RS stream]
27962@c MOD util.stream
27963@c EN
27964Returns the remaining elements of the stream @var{s}, as a stream.
27965@c JP
27966ストリーム@var{s}の最初の要素を除いた残りの要素をストリームとして
27967返します。
27968@c COMMON
27969@end defun
27970
27971@defmac stream-delay expr
27972[SRFI-40]
27973@c MOD util.stream
27974@c EN
27975Returns a stream which is a delayed form of @var{expr}.
27976@c JP
27977@var{expr}の遅延形式であるストリームを返します。
27978@c COMMON
27979
27980@c EN
27981As a rule of thumb, any stream-producing functions should
27982wrap the resulting expression by @code{stream-delay}.
27983(Or you can use @code{stream-lambda}, @code{stream-let} or @code{stream-define},
27984described below.)
27985@c JP
27986原則として、ストリームを生成する関数はすべからく結果を
27987@code{stream-delay}でラップすべきです。
27988(以下に述べる@code{stream-lambda}, @code{stream-let}, @code{stream-define}を
27989使う手もあります)。
27990@c COMMON
27991@end defmac
27992
27993@defmac stream-lambda formals body body2 @dots{}
27994[R7RS stream]
27995@c MOD util.stream
27996@c EN
27997A convenience macro to create a function that returns a stream.
27998Effectively, @code{(stream-lambda formals body body2 @dots{})} is the same
27999as @code{(lambda formals (stream-delay body body2 @dots{}))}.
28000@c JP
28001ストリームを返す関数を作る簡易マクロです。
28002@code{(stream-lambda formals body body2 @dots{})}は
28003@code{(lambda formals (stream-delay body body2 @dots{}))}と同じです。
28004@c COMMON
28005@end defmac
28006
28007@node Stream constructors, Stream binding, Stream primitives, Stream library
28008@subsection Stream constructors
28009
28010@defun stream obj @dots{}
28011[SRFI-40]
28012@c MOD util.stream
28013@c EN
28014Returns a new stream whose elements are @var{obj} @dots{}.
28015@c JP
28016要素が@var{obj} @dots{}であるような新しいストリームを返します。
28017@c COMMON
28018
28019@c EN
28020Note: This differs from srfi-41's (@code{scheme.stream}'s) @code{stream},
28021which is a macro so that arguments are lazily evaluated.  Srfi-41's
28022@code{stream} is provided as @code{stream+} in this module.
28023@c JP
28024註:これはsrfi-41 (@code{scheme.stream})の@code{stream}とは異なります。
28025srfi-41の方はマクロで、引数の評価が遅延されます。srfi-41版はこのモジュールでは
28026@code{stream+}と言う名前で提供されます。
28027@c COMMON
28028
28029@example
28030(stream 1 2 3))     @result{} @r{a stream that contains} (1 2 3)
28031(stream 1 (/ 1 0))) @result{} @r{error}
28032@end example
28033@end defun
28034
28035@defmac stream+ expr @dots{}
28036@c MOD util.stream
28037@c EN
28038Returns a new stream whose elements are the result of @var{expr} @dots{}.
28039
28040This is the same as srfi-41(@code{scheme.stream})'s @code{stream}.
28041Each @var{expr} isn't evaluated until it is accessed.
28042@c JP
28043要素が@var{expr} @dots{}の結果であるような新たなストリームを作って返します。
28044
28045これはsrfi-41(@code{scheme.stream})の@code{stream}と同じです。
28046各@var{expr}はアクセスされるまで評価されません。
28047@c COMMON
28048
28049@example
28050(define s (stream+ 1 (/ 1 0)))  ;; doesn't yield an error
28051
28052(stream-car s)  @result{} 1
28053
28054(stream-cadr s) @result{} @r{error}
28055@end example
28056@end defmac
28057
28058@defun stream-unfold f p g seed
28059[R7RS stream]
28060@c MOD util.stream
28061@c EN
28062Creates a new stream whose element is determined as follows:
28063
28064@itemize
28065@item
28066A ``go'' predicate @var{p} is called on the current seed value.
28067If it yields @code{#f}, the stream terminates.
28068@item
28069Otherwise, @code{(f s)} is the element of the stream,
28070and @code{(g s)} becomes the next seed value, where
28071@code{s} is the current seed value.  The initial seed value
28072is given by @var{seed}.
28073@end itemize
28074
28075Note: Unfortunately, the order of arguments differs from
28076other @code{*-unfold} procedures, which takes @code{p f g}
28077(predicate, value-generator and seed-generator).  Furthermore,
28078the predicate is stop-predicate (returning true stops iteration).
28079@c JP
28080次の手順で生成される要素をもつ新たなストリームを作成して返します。
28081
28082@itemize
28083@item
28084「続行」述語@var{p}が現在のシード値を引数として呼ばれます。
28085もし@code{#f}が返されたら、ストリームはそこで終了です。
28086@item
28087そうでなければ、@code{s}を現在のシード値として、@code{(f s)}をストリームの
28088現在の要素とし、@code{(g s)}を次のシード値とします。
28089@var{seed}はシード値の初期値を与えます。
28090@end itemize
28091
28092註:残念なことに、この手続きは他の @code{*-unfold} 系手続きと異なる順序で
28093引数を取ります。他の手続きは@code{p f g} (述語、値生成、シード生成) の順です。
28094さらに、他の手続きでは述語は停止する時に真を返します。
28095@c COMMON
28096
28097@example
28098(stream->list
28099 (stream-unfold integer->char (cut < <> 58) (cut + 1 <>) 48))
28100 @result{} (#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
28101@end example
28102@end defun
28103
28104@defun stream-unfoldn f seed n
28105[SRFI-40]
28106@c MOD util.stream
28107@c EN
28108Creates @var{n} streams related each other, whose contents are
28109generated by @var{f} and @var{seed}.
28110@c JP
28111互いに関連する @var{n} 本のストリームを生成します。それぞれの内容は
28112@var{f}および@var{seed}を使って生成します。
28113@c COMMON
28114
28115@c EN
28116The @var{f} is called with the current seed value,
28117and returns @code{@var{n}+1} values:
28118@c JP
28119@var{f}は現在のシード値とともに呼ばれ、@code{@var{n}+1}個の値
28120を返します。
28121@c COMMON
28122@example
28123(@var{f} @var{seed})
28124  => seed result_0 result_1 @dots{} result_n-1
28125@end example
28126
28127@c EN
28128The first value is to be the next seed value.
28129@var{Result_k} must be one of the following forms:
28130@table @code
28131@item (val)
28132@var{val} will be the next car of @var{k}-th stream.
28133@item #f
28134No new information for @var{k}-th stream.
28135@item ()
28136The end of @var{k}-th stream has been reached.
28137@end table
28138@c JP
28139最初の値は次のシード値になります。@var{Result_k}は以下の形式のどれかで
28140なければなりません。
28141@table @code
28142@item (val)
28143@var{val}は@var{k}-番目のストリームの次のcar部になります。
28144@item #f
28145@var{k}-番目のストリームの新しい情報はありません。
28146@item ()
28147@var{k}-番目のストリームの最後に到達しました。
28148@end table
28149@c COMMON
28150
28151@c EN
28152The following example creates two streams, the first one produces
28153an infinite series of odd numbers and the second produces evens.
28154@c JP
28155以下の例では2つのストリームが作られます。最初のものは奇数の無限ストリー
28156ムで、2つめのものは偶数の無限ストリームです。
28157@c COMMON
28158
28159@example
28160gosh> (define-values (s0 s1)
28161        (stream-unfoldn (lambda (i)
28162                          (values (+ i 2)          ;; next seed
28163                                  (list i)         ;; for the first stream
28164                                  (list (+ i 1)))) ;; for the second stream
28165                        0 2))
28166#<undef>
28167gosh> (stream->list (stream-take s0 10))
28168(0 2 4 6 8 10 12 14 16 18)
28169gosh> (stream->list (stream-take s1 10))
28170(1 3 5 7 9 11 13 15 17 19)
28171@end example
28172@end defun
28173
28174@defun stream-unfolds f seed
28175[R7RS stream]
28176@c MOD util.stream
28177@c EN
28178Like @code{stream-unfoldn}, but the number of created streams is
28179determined by the number fo return values from @var{f}.  See
28180@code{stream-unfoldn} above for the details.
28181@c JP
28182@code{stream-unfoldn}と似ていますが、結果のストリームの数は
28183@var{f}の戻り値の数により決定されます。詳しくは
28184上の@code{stream-unfoldn}の説明を参照してください。
28185@c COMMON
28186@end defun
28187
28188@defun stream-constant obj @dots{}
28189[R7RS stream]
28190@c MOD util.stream
28191@c EN
28192Returns an infinite stream that repeats @var{obj} @dots{}.
28193@c JP
28194@var{obj} @dots{}を繰り返す無限ストリームを返します。
28195@c COMMON
28196
28197@example
28198(stream->list 10 (stream-constant 1 2))
28199  @result{} (1 2 1 2 1 2 1 2 1 2)
28200@end example
28201@end defun
28202
28203@defun make-stream n :optional init
28204@c MOD util.stream
28205@c EN
28206Creates a new stream of @var{n} elements of @var{init}.
28207If @var{init} is omitted, @code{#f} is used.
28208Specifying a negative number to @var{n} creates an infinite stream.
28209@c JP
28210@var{n}個の@var{init}を要素とする新しいストリームを生成します。
28211@var{init}が省略された場合@code{#f}が使われます。@var{n}を負の値にする
28212と無限ストリームが生成されます。
28213@c COMMON
28214@end defun
28215
28216@defun stream-tabulate n init-proc
28217@c MOD util.stream
28218@c EN
28219Creates a new stream of @var{n} elements.
28220The @var{k}-th element is obtained by applying @var{init-proc}
28221to @var{k}.  Specifying a negative number to @var{n} creates
28222an infinite stream.
28223@c JP
28224@var{n}個の要素をもつ新しいストリームを生成します。@var{k}-番目の要素
28225は @var{init-proc} を @var{k} に適用して得られます。@var{n}を負の値にする
28226と無限ストリームが生成されます。
28227@c COMMON
28228@end defun
28229
28230@defun stream-iota :optional count start step
28231@c MOD util.stream
28232@c EN
28233Creates a new stream of numbers, starting from @var{start}
28234and incrementing @var{step}.  The length of stream is maximum
28235integer not greater than nonnegative real number @var{count}.
28236The default values of @code{count}, @var{start} and @var{step} are
28237@code{+inf.0}, 0 and 1, respectively.
28238
28239If @var{start} and @var{step} are exact, and @var{count} is exact or
28240infinite, a sequence of exact numbers are created.  Otherwise,
28241a sequence of inexact numbers are created.
28242@c JP
28243@var{start}からはじまり、@var{step}ずつ要素が増加する数値のストリーム
28244を生成します。ストリームの長さは非負の実数@var{count}を越えない最大の整数値です。
28245@var{count}, @var{start}, @var{step}のデフォルト値はそれぞれ
28246@code{+inf.0}, 0 および 1です。
28247
28248@var{start}と@var{step}が正確数で、@var{count}が正確数か無限大の場合、
28249正確数のストリームが作られます。そうでなければ非正確数のストリームになります。
28250@c COMMON
28251@end defun
28252
28253@defun stream-range start :optional end step
28254[R7RS stream]
28255@c MOD util.stream
28256@c EN
28257Creates a new stream of real numbers, starting from @var{start}
28258and stops before @var{end}, stepping by @var{step}.
28259If @var{end} is omitted, positive infinity is assumed.
28260If @var{step} is omitted, @code{1} is assumed if @var{end} is greater
28261than @var{start}, and @code{-1} if @var{end} is less than @var{start}.
28262
28263The generated numbers are exact if @var{start} and @var{step} are exact
28264and @var{end} is either exact or infinite.  Otherwise, inexact numbers
28265are generated.
28266
28267In R7RS @code{scheme.stream}, @var{end} argument is required.
28268@c JP
28269@var{start}から始まり@var{step}おきに@var{end}の手前まで続く実数のストリームを
28270作って返します。@var{end}が省略された場合は正の無限大が使われます。
28271@var{step}が省略された場合、@var{start}が@var{end}より小さければ@code{1}が、
28272大きければ@var{-1}が使われます。
28273
28274@var{start}と@var{step}が正確数で、@var{end}が正確数か無限大の場合は、
28275正確数のシーケンスが、そうでない場合は非正確数のシーケンスが生成されます。
28276
28277R7RSの@code{scheme.stream}では、@var{end}引数は必須です。
28278@c COMMON
28279
28280@example
28281(stream->list (stream-range 0 10))
28282 @result{} (0 1 2 3 4 5 6 7 8 9)
28283@end example
28284@end defun
28285
28286@defun stream-from start :optional step
28287[R7RS stream]
28288@c MOD util.stream
28289@c EN
28290This is yet another number sequence generator.  Generates an infinite
28291sequence whose @var{i}-th element is @code{(+ @var{start} (* i @var{step}))}.
28292If @var{step} is omitted, 1 is assumed.  If both @var{start} and @var{step}
28293are exact, exact numbers are generated.  Otherwise, inexact numbers are
28294generated.
28295@c JP
28296もうひとつの数値シーケンス生成手続きです。@var{i}番目の項が
28297@code{(+ @var{start} (* i @var{step}))}であるような無限シーケンスを返します。
28298@var{step}が省略されたら1が使われます。
28299@var{start}と@var{step}が正確数なら、正確数のシーケンスが、
28300そうでなければ非正確数のシーケンスが返されます。
28301@c COMMON
28302@end defun
28303
28304@defun stream-iterate f seed
28305[R7RS stream]
28306@c MOD util.stream
28307@c EN
28308Returns a stream starting from @var{seed}, and each successive element
28309is calculated by @code{(@var{f} @var{s})} where @var{s} is the previous
28310element.
28311@c JP
28312@var{seed}を初期値とし、ひとつ前の要素@var{s}から次の要素を@code{(@var{f} @var{s})}で
28313計算するような無限長のストリームを返します。
28314@c COMMON
28315
28316@example
28317(stream->list 5 (stream-iterate (cut cons 'x <>) '()))
28318  @result{} (() (x) (x x) (x x x) (x x x x))
28319@end example
28320
28321@c EN
28322See also @code{literate} in @code{gauche.lazy} (@pxref{Lazy sequence utilities}).
28323@c JP
28324@code{gauche.lazy}の@code{literate}も参照
28325(@ref{Lazy sequence utilities}).
28326@c COMMON
28327@end defun
28328
28329@defun stream-xcons a b
28330@c MOD util.stream
28331@c EN
28332@code{(stream-cons b a)}.  Just for convenience.
28333@c JP
28334@code{(stream-cons b a)}のこと。利便性のためだけにある。
28335@c COMMON
28336@end defun
28337
28338@defun stream-cons* elt @dots{} stream
28339@c MOD util.stream
28340@c EN
28341Creates a new stream which appends @var{elt} @dots{} before @var{stream}.
28342@c JP
28343@var{stream}の前に@var{elt} @dots{}を連結した新しいストリームを生成し
28344ます。
28345@c COMMON
28346@end defun
28347
28348@defun list->stream list
28349[R7RS stream]
28350@c MOD util.stream
28351@c EN
28352Returns a new stream whose elements are the elements in @var{list}.
28353@c JP
28354@var{list}の要素を要素とする新たなストリームを作って返します。
28355@c COMMON
28356@end defun
28357
28358@defun string->stream string :optional tail-stream
28359@c MOD util.stream
28360@c EN
28361Converts a string to a stream of characters.  If an optional
28362@var{tail-stream} is given, it becomes the tail of the resulting
28363stream.
28364@c JP
28365文字列を文字のストリームに変換します。@var{tail-stream}が与えられた場合は、
28366文字ストリームの後にそれが付け加えられます。
28367@c COMMON
28368
28369@example
28370@end example
28371(stream->list (string->stream "abc" (list->stream '(1 2 3))))
28372 @result{} (#\a #\b #\c 1 2 3)
28373@end defun
28374
28375@defun stream-format fmt arg @dots{}
28376@c MOD util.stream
28377@c EN
28378Returns a stream which is a result of applying @code{string->stream}
28379to @code{(format fmt arg @dots{})}.
28380@c JP
28381@code{string->stream}を@code{(format fmt arg @dots{})}に適用した結果の
28382ストリームを返します。
28383@c COMMON
28384@end defun
28385
28386@defun port->stream :optional iport reader closer
28387[R7RS stream]
28388@c MOD util.stream
28389@c EN
28390Creates a stream, whose elements consist of the items
28391read from the input port @var{iport}.
28392The default @var{iport} is the current input port.
28393The default @var{reader} is @code{read-char}.
28394
28395The result stream terminates at the point where @var{reader}
28396returns EOF (EOF itself is not included in the stream).
28397The port won't be closed by default when it reaches EOF.
28398
28399If @var{closer} is given, it is called with @var{iport} as
28400an argument just after @var{reader} reads EOF.  You can close the port
28401with it.
28402
28403The @var{reader} and @var{closer} arguments are Gauche's extension.
28404R7RS @code{scheme.stream} only takes one optional argument, @var{iport}.
28405@c JP
28406@var{iport}から@var{reader}を使って読み出されるデータを要素とする新たなストリームを
28407作って返します。@var{iport}のデフォルトは現在の入力ポート、
28408@var{reader}のデフォルトは@code{read-char}です。
28409
28410@var{reader}がEOFを返したらストリームの終端となります (EOF自体は
28411ストリームには含まれません)。
28412EOFに達してもポートはクローズされません。
28413
28414もし@var{closer}引数が与えられたら、それが@var{iport}を引数として
28415EOFが読まれた直後に呼ばれます。そこでポートをクローズするこはできます。
28416
28417@var{reader}と@var{closer}引数はR7RSの@code{scheme.stream}では
28418定義されない、Gaucheの拡張です。
28419@c COMMON
28420@end defun
28421
28422@defun generator->stream gen
28423@c MOD util.stream
28424@c EN
28425Creates a lazy stream of values generated by a generator @var{gen}.
28426A generator is a thunk that returns a value every time it is called,
28427with returning EOF to indicate the end of the input.
28428@xref{Generators}, for the details of generators.
28429@c JP
28430ジェネレータ@var{gen}が生成する値の列からなる遅延ストリームを作って返します。
28431ジェネレータは引数を取らない手続きで、呼ばれる度に値を返し、EOFを返すことで
28432終端を示すものです(EOFはストリームには含まれません)。
28433詳しくは@ref{Generators}を参照してください。
28434@c COMMON
28435
28436@c EN
28437See also @code{generator->lseq}, which is another way to get
28438a lazy sequence from a generator (@pxref{Lazy sequences}, for the details).
28439@c JP
28440似た手続きに、ジェネレータから遅延シーケンスを得る@code{generator->lseq}も
28441あります(@ref{Lazy sequences}参照)。
28442@c COMMON
28443@end defun
28444
28445
28446@defun iterator->stream iter
28447@c MOD util.stream
28448@c EN
28449A generic procedure to turn an internal iterator @var{iter}
28450into a stream of iterated results.
28451@c JP
28452イテレータ@var{iter}から遅延シーケンスを作る手続きです。
28453@c COMMON
28454
28455@c EN
28456The @var{iter} argument is a procedure that takes two arguments,
28457@var{next} and @var{end}, where @var{next} is a procedure that takes
28458one argument and @var{end} is a thunk.
28459@var{Iter} is supposed to iterate over some set and call @var{next}
28460for each argument, then call @var{end} to indicate the end of
28461the iteration.  Here's a contrived example:
28462@c JP
28463@var{iter}は二つの引数@var{next}と@var{end}を取る手続きです。
28464@var{next}は一つの引数を取る手続き、@var{end}は引数を取らない手続きです。
28465@var{iter}手続きは、その中で何らかの値の集合に対して順に@var{next}手続きを呼び、
28466最後に@var{end}手続きを呼びます。次はわざとらしい例です:
28467@c COMMON
28468
28469@example
28470(stream->list
28471 (iterator->stream
28472  (lambda (next end) (for-each next '(1 2 3 4 5)) (end))))
28473 @result{} (1 2 3 4 5)
28474@end example
28475
28476@c EN
28477Internally @code{iterator->stream} uses the ``inversion of iterator''
28478technique, so that @var{iter} only iterates to the element that
28479are needed by the stream.  Thus @var{iter} can iterate over
28480an infinite set.  In the following example, @var{iter} is
28481an infinite loop calling @var{next} with increasing integers,
28482but only the first 10 elements are calculated because of
28483@code{stream-take}:
28484@c JP
28485内部的に、@code{iterator->stream}はいわゆる「イテレータの反転」テクニックを
28486使っていて、@var{iter}は必要なだけしかイテレーションを行いません。なので
28487@var{iter}は無限の要素を扱うこともできます。
28488例えば次の例では、@var{iter}は増加する整数に対して@var{next}を無限に呼び出す
28489ようになっていますが、@code{stream-take}によって最初の10要素しか計算されません。
28490@c COMMON
28491
28492@example
28493(stream->list
28494 (stream-take
28495  (iterator->stream
28496   (lambda (next end)
28497     (let loop ((n 0)) (next n) (loop (+ n 1)))))
28498  10))
28499 @result{} (0 1 2 3 4 5 6 7 8 9)
28500@end example
28501@end defun
28502
28503@defmac stream-of elt-expr clause @dots{}
28504[R7RS stream]
28505@c MOD util.stream
28506@c EN
28507Stream comprehension.  Returns a stream in which each element
28508is computed by @var{elt-expr}.
28509The @var{clause} creates scope of @var{elt-expr}
28510and controls iterations.  Each @var{clause} can be one of the following
28511forms:
28512@c JP
28513ストリーム内包表記。各要素が@var{elt-expr}で計算されるストリームを返します。
28514@var{clause}は@var{elt-expr}のスコープを作り、繰り返しを制御します。
28515各@var{clause}は以下の形のいずれかです:
28516@c COMMON
28517@table @code
28518@item (@var{x} in @var{stream-expr})
28519@c EN
28520Iterate over @var{stream-expr}, binding @var{x} to each element in
28521each iteration.  The variable @var{x} is visible in successive @var{clause}s
28522and @var{elt-expr}
28523@c JP
28524@var{stream-expr}が返すストリームの各要素を、@var{x}に束縛して繰り返します。
28525変数@var{x}のスコープは後続の@var{clause}および@var{elt-expr}です。
28526@c COMMON
28527@item (@var{x} is @var{expr})
28528@c EN
28529Bind a variable @var{x} with the value of @var{expr}.  The variable @var{x}
28530is visible in successive @var{clause}s
28531and @var{elt-expr}.
28532@c JP
28533変数@var{x}に値@var{expr}の結果を束縛します。@var{x}のスコープは
28534後続の@var{clause}および@var{elt-expr}です。
28535@c COMMON
28536@item expr
28537@c EN
28538If @var{expr} evaluates to @code{#f}, this iteration is skipped without
28539generating a new element.
28540@c JP
28541@var{expr}が@code{#f}に評価されたらこの回は値を生成せずに打ちきられ、
28542次の繰り返しに進みます。
28543@c COMMON
28544@end table
28545
28546@c EN
28547The following comprehension generates infinite sequence of pythagorean
28548triples:
28549@c JP
28550次の内包表記はピタゴラス数の無限シーケンスを生成します:
28551@c COMMON
28552
28553@example
28554(define pythagorean-triples
28555  (stream-of (list a b c)
28556    (c in (stream-from 3))
28557    (b in (stream-range 2 c))
28558    (a in (stream-range 1 b))
28559    (= (square c) (+ (square b) (square a)))))
28560
28561(stream->list 5 pythagorean-triples)
28562  @result{} ((3 4 5) (6 8 10) (5 12 13) (9 12 15) (8 15 17))
28563@end example
28564@end defmac
28565
28566@node Stream binding, Stream consumers, Stream constructors, Stream library
28567@subsection Stream binding
28568
28569@defmac define-stream (name . formals)  body body2 @dots{}
28570[R7RS stream]
28571@c MOD util.stream
28572@c EN
28573A convenient macro to define a procedure that yields a stream.
28574Same as the following form:
28575@c JP
28576ストリームを作って返す関数を手軽に定義するマクロです。
28577次のフォームと同じです:
28578@c COMMON
28579
28580@example
28581(define (name . formals)
28582  (stream-delay
28583    (let () body body2 @dots{})))
28584@end example
28585@end defmac
28586
28587@defmac stream-let loop-var ((var init) @dots{}) body body2 @dots{}
28588[R7RS stream]
28589@c MOD util.stream
28590@c EN
28591A handy macro to write a lazy named-let loop.  It is the same as the
28592following:
28593@c JP
28594lazyなnamed-letによるループを書くときに便利なマクロです。次のフォームと同じです:
28595@c COMMON
28596@example
28597(let loop-var ((var init) @dots{})
28598  (stream-delay
28599    (let () body body2 @dots{})))
28600@end example
28601@end defmac
28602
28603@defmac stream-match stream-expr clause @dots{}
28604[R7RS stream]
28605@c MOD util.stream
28606@c EN
28607This allows accessing streams via simple pattern matching.
28608The @var{stream-expr} argument is evaluated and must yield a stream.
28609Each @var{clause}
28610must be either a form of @code{(@var{pattern} @var{expr})} or
28611@code{(@var{pattern} @var{fender} @var{expr})}.
28612
28613The content of the stream is matched to each @var{pattern},
28614which must have one of the following forms:
28615@c JP
28616このマクロは簡単なパターンマッチングを使ってストリームの要素にアクセスします。
28617@var{stream-expr}はストリームを返す式でなければなりません。
28618各@var{clause}は@code{(@var{pattern} @var{expr})}か
28619@code{(@var{pattern} @var{fender} @var{expr})}という形です。
28620
28621入力ストリームは各@var{pattern}に順マッチするかどうかテストされます。
28622@var{pattern}には以下の形のいずれかです:
28623@c COMMON
28624
28625@table @code
28626@item ()
28627@c EN
28628Matches a null stream.
28629@c JP
28630空のストリームとマッチします。
28631@c COMMON
28632@item (@var{p0} @var{p1} @dots{})
28633@c EN
28634Matches a stream that has exactly the same number of elements as
28635the number of pattern elements.
28636@c JP
28637パターン内の要素の数と入力ストリームの要素数が一致した時にマッチします。
28638@c COMMON
28639@item (@var{p0} @var{p1} @dots{} . @var{pRest})
28640@c EN
28641Matches a stream that has at least the same number of elements as
28642the number of pattern elements except @var{pRest}.  The rest of stream
28643matches with @var{pRest}.
28644@c JP
28645入力ストリームの要素数が、@var{pRest}を除いたパターン内の要素の数以上であれば
28646マッチします。@var{pRest}にはストリームの残りがマッチします。
28647@c COMMON
28648@item @var{pRest}
28649@c EN
28650Matches an entire stream.
28651@c JP
28652入力ストリーム全体とマッチします。
28653@c COMMON
28654@end table
28655
28656@c EN
28657Each pattern element can be an identifier or a literal underscore.  If it is
28658an identifier, it is bound to the matched element while evaluating
28659the corresponding @var{fender} and @var{expr}.
28660@c JP
28661パターンの各要素は識別子かリテラルのアンダースコア@code{_}です。
28662アンダースコア以外の識別子の場合は、それらが対応する入力ストリームの要素に
28663束縛された環境で@var{fender}と@var{expr}が評価されます。
28664@c COMMON
28665
28666@c EN
28667If @var{fender} is present in the @var{clause}, it is evaluated; if
28668it yields @code{#f}, the match of the clause fails and next clauses will be
28669tried.
28670@c JP
28671もし@var{fender}があれば、まずそれが評価され、@code{#f}であったらその@var{clause}の
28672マッチは失敗となり、次の@var{clause}が試されます。
28673@c COMMON
28674
28675@c EN
28676Otherwise, @var{expr} is evaluated and the result(s) becomes the result(s)
28677of @code{stream-match}.
28678@c JP
28679そうでなければ@var{expr}が評価され、その結果が@code{stream-match}の結果となります。
28680@c COMMON
28681
28682@c EN
28683Only the elements from the stream that is required to match are accessed.
28684@c JP
28685入力ストリームの要素はマッチに必要なだけ取り出されます。
28686@c COMMON
28687
28688@c EN
28689The following example defines a procedure to count the number of true
28690values in the stream:
28691@c JP
28692次の例は、ストリーム中の真の値の数を数えています:
28693@c COMMON
28694
28695@example
28696(define (num-trues strm)
28697  (stream-match strm
28698    (() 0)
28699    ((head . tail) head (+ 1 (num-trues tail)))
28700    ((_ . tail) (num-trues tail))))
28701
28702(num-trues (stream #f #f #t #f #t #f #t #t))
28703  @result{} 4
28704@end example
28705@end defmac
28706
28707@node Stream consumers, Stream operations, Stream binding, Stream library
28708@subsection Stream consumers
28709
28710@c EN
28711These procedures takes stream(s) and consumes its/their elements
28712until one of the streams is exhausted.
28713@c JP
28714これらの手続きはストリームを取り、その要素を消費し尽します。
28715@c COMMON
28716
28717@defun stream-for-each func . streams
28718[R7RS stream]
28719@c MOD util.stream
28720@c EN
28721Applies @var{func} for each element of @var{streams}.
28722Terminates if one of @var{streams} reaches the end.
28723@c JP
28724@var{func}を@var{streams}の各要素に適用します。
28725@var{streams}が終端に達したところで停止します。
28726@c COMMON
28727@end defun
28728
28729@defun stream-fold f seed stream
28730[R7RS stream]
28731@c MOD util.stream
28732@c EN
28733Apply @var{f} on the current seed value and an element from
28734@var{stream} to obtain the next seed value, and repeat it until
28735@var{stream} is exhausted, then returns the last seed value.
28736The initial seed value is given by @var{seed}.
28737
28738Note: The argument order of @var{f} differs from other @code{*-fold}
28739procedures, e.g. @code{fold} (@pxref{Walking over lists}) takes
28740the element first, then the seed value.
28741@c JP
28742@var{f}を現在のシード値と@var{stream}の要素に適用し、その結果を次のシード値として
28743@var{stream}が終端に達するまで繰り返します。最初のシード値は@var{seed}引数で与えられます。
28744最後のシード値が返されます。
28745
28746註: @var{f}の引数順は、他の@code{*-fold}系関数のそれと異なることに注意してください。
28747例えば@code{fold} (@ref{Walking over lists}参照) では最初に要素、次にシード値が
28748渡されます。
28749@c COMMON
28750
28751@example
28752(stream-fold - 0 (stream 1 2 3 4 5))
28753  @result{} -15
28754@end example
28755@end defun
28756
28757@node Stream operations,  , Stream consumers, Stream library
28758@subsection Stream operations
28759
28760@defun stream-append stream @dots{}
28761[R7RS stream]
28762@c MOD util.stream
28763@c EN
28764Returns a new stream which is concatenation of given @var{stream}s.
28765@c JP
28766与えられた@var{stream}を全部つないだ新たなストリームを返します。
28767@c COMMON
28768@end defun
28769
28770@defun stream-concat streams
28771@defunx stream-concatenate streams
28772[R7RS stream]
28773@c MOD util.stream
28774@c EN
28775R7RS @code{scheme.stream} defines @code{stream-concat}.  Gauche had
28776@code{stream-concatenate}, and keeps it for the backward compatibility.
28777Both are the same.
28778
28779The @var{streams} argument is a stream of streams.  Returns a new stream
28780that is concatenation of them.  Unlike @code{stream-append}, @var{streams}
28781can generate infinite streams.
28782@c JP
28783R7RS @code{scheme.stream}は@code{stream-concat}を定義しました。
28784Gaucheには@code{stream-concatenate}があったので互換性のためにそちらも残しています。
28785どちらも同じです。
28786
28787@var{streams}はストリームのストリームです。各ストリームを連結したストリームを作って
28788返します。@code{stream-append}と違い、@var{streams}は無限個のストリームを生成
28789することができます。
28790@c COMMON
28791@end defun
28792
28793
28794@defun stream-map func stream stream2 @dots{}
28795[R7RS stream]
28796@c MOD util.stream
28797@c EN
28798Returns a new stream, whose elements are calculated by
28799applying @var{func} to each element of @var{stream} @dots{}.
28800@c JP
28801@var{streams}の各要素に@var{func}を適用した値を要素とする新しいストリー
28802ムを返します。
28803@c COMMON
28804@end defun
28805
28806@defun stream-scan func seed stream
28807[R7RS stream]
28808@c MOD util.stream
28809@c EN
28810Returns a stream of @code{@var{seed}}, @code{(@var{func} @var{seed} @var{e0})},
28811@code{(@var{func} (@var{func} @var{seed} @var{e0}) @var{e1})}, @dots{}, where
28812@var{e0}, @var{e1} @dots{} are the elements from the input @var{stream}.
28813If @var{stream} is finite, the result stream has one more elements than
28814the number of elements in the original stream.
28815@c JP
28816@code{@var{seed}}、
28817@code{(@var{func} @var{seed} @var{e0})}、
28818@code{(@var{func} (@var{func} @var{seed} @var{e0}) @var{e1})} @dots{}
28819で構成されるストリームを返します。ここで
28820@var{e0}、@var{e1} @dots{}は入力ストリーム@var{stream}の要素です。
28821@var{stream}が有限なら、その要素よりひとつ多い要素が出力ストリームには含まれます。
28822@c COMMON
28823
28824@example
28825(stream->list
28826  (stream-scan xcons '() (stream 1 2 3 4 5)))
28827 @result{} (() (1) (2 1) (3 2 1) (4 3 2 1) (5 4 3 2 1))
28828@end example
28829@end defun
28830
28831@defun stream-zip stream @dots{}
28832[R7RS stream]
28833@c MOD util.stream
28834@c EN
28835Returns a new stream whose elements are lists of corresponding
28836elements from input @var{stream}s.  The output stream ends
28837when one of input streams is exhausted.
28838@c JP
28839入力ストリームの対応する要素のリストを要素とするストリームを作って返します。
28840入力ストリームのいずれかが終端に達した時に出力ストリームも終わります。
28841@c COMMON
28842
28843@example
28844(stream->list
28845 (stream-zip (stream 1 2 3) (stream 'a 'b 'c 'd)))
28846 @result{} ((1 a) (2 b) (3 c))
28847@end example
28848
28849@end defun
28850
28851@defun stream-filter pred stream
28852[R7RS stream]
28853@c MOD util.stream
28854@c EN
28855Returns a new stream including only elements passing @var{pred}.
28856@c JP
28857@var{pred}をパスする要素のみからなる新しいストリームを返します。
28858@c COMMON
28859@end defun
28860
28861@defun stream-remove pred stream
28862@c MOD util.stream
28863@c EN
28864Returns a new stream including only elements that doesn't satisfy @var{pred}.
28865@c JP
28866述語@var{pred}を満たさない要素のみからなる新しいストリームを返します。
28867@c COMMON
28868@end defun
28869
28870@defun stream-partition pred stream
28871@c MOD util.stream
28872@c EN
28873Returns two streams, one consists of the elements in @var{stream}
28874that satisfy @var{pred}, the other consists of the ones that doesn't
28875satisfy @var{pred}.
28876@c JP
28877二つのストリームを返します。最初のストリームは@var{stream}の要素のうち
28878述語@var{pred}を満たすもの、次のストリームは@var{pred}を満たさないもので構成されます。
28879@c COMMON
28880@end defun
28881
28882@defun stream->list stream
28883@defunx stream->list n stream
28884[R7RS stream]
28885@c MOD util.stream
28886@c EN
28887Converts a stream to a list.  In the first form, all elements from
28888@var{stream} are taken (thus it never returns if @var{stream} is infinite).
28889In the second form, at most @var{n} elements are taken, where
28890@var{n} must be a nonnegative exact integer.
28891
28892Note: In usual Scheme conventions, the optional @var{n} comes after
28893the main argument (@var{stream}).
28894@c JP
28895ストリームをリストに変換します。最初の形式では、@var{stream}の全ての要素が
28896取り出されます (従って@var{stream}が無限ストリームであればこの関数は永遠に戻りません)。
28897二番めの形式では最大で@var{n}要素までがストリームから取り出されそのリストが返されます。
28898@var{n}は非負の正確な整数でなければなりません。
28899
28900註:通常のSchemeの慣例では、省略可能な@var{n}は@var{stream}の後に来ますが、
28901この関数はそうでないことに注意。
28902@c COMMON
28903@end defun
28904
28905@defun stream->string stream
28906@c MOD util.stream
28907@c EN
28908Converts a stream to a string.
28909All elements of @var{stream} must be characters, or an error is signaled.
28910@c JP
28911ストリームを文字列に変換します。
28912@var{stream}の全ての要素は文字でなければなりません。
28913そうでない場合はエラーが投げられます。
28914@c COMMON
28915@end defun
28916
28917
28918@defun stream-lines stream
28919@c MOD util.stream
28920@c EN
28921Splits @var{stream} where its element equals to @code{#\n}, and
28922returns a stream of splitted streams.  The character @code{#\n} won't
28923be included in the results.
28924@c JP
28925@var{stream}を、文字@code{#\n}が要素である箇所で分割し、
28926分割されたストリームのストリームを返します。@code{#\n}自体は結果に含まれません。
28927@c COMMON
28928
28929@example
28930(stream->list
28931 (stream-map stream->string
28932             (stream-lines (string->stream "abc\ndef\nghi"))))
28933 @result{} ("abc" "def" "ghi")
28934@end example
28935@end defun
28936
28937@defun stream= elt= stream @dots{}
28938@c MOD util.stream
28939@c EN
28940Returns true iff each corresponding element of @var{stream} @dots{}
28941are the same in terms of @var{elt=}, which takes two arguments.
28942This procedure won't terminate
28943if all of @var{stream}s is infinite.
28944@c JP
28945引数のストリームの全ての対応する要素がそれぞれ、2引数を取る@var{elt=}で比較して等しい場合に
28946@code{#t}を、そうでなければ@code{#f}を返します。
28947全ての@var{stream}が無限である場合、この手続きは終了しません。
28948@c COMMON
28949@end defun
28950
28951@defun stream-prefix= stream prefix :optional elt=
28952@c MOD util.stream
28953@c EN
28954Compares initial elements of @var{stream} against
28955a list @var{prefix} by @var{elt=}.  Returns true iff they match.
28956Only as many elements of @var{stream}
28957as @var{prefix} has are checked.
28958@c JP
28959@var{stream}の最初の方の要素をリスト@var{prefix}と比較します。各要素は
28960@var{elt=}で比較されます。@var{prefix}と全てマッチしたら@code{#t}を、
28961そうでなければ@code{#f}を返します。最大でも@var{prefix}の要素分だけ@var{stream}から
28962要素が取り出されます。
28963@c COMMON
28964@end defun
28965
28966@defun stream-caar s
28967@defunx stream-cadr s
28968@findex stream-cdar
28969@findex stream-cddr
28970@findex stream-caaar
28971@findex stream-caadr
28972@findex stream-cadar
28973@findex stream-caddr
28974@findex stream-cdaar
28975@findex stream-cdadr
28976@findex stream-cddar
28977@findex stream-cdddr
28978@findex stream-caaaar
28979@findex stream-caaadr
28980@findex stream-caadar
28981@findex stream-caaddr
28982@findex stream-cadaar
28983@findex stream-cadadr
28984@findex stream-caddar
28985@findex stream-cadddr
28986@findex stream-cdaaar
28987@findex stream-cdaadr
28988@findex stream-cdadar
28989@findex stream-cdaddr
28990@findex stream-cddaar
28991@findex stream-cddadr
28992@dots{}
28993@end defun
28994@defun stream-cdddar s
28995@defunx stream-cddddr s
28996@c MOD util.stream
28997@code{(stream-caar s)} = @code{(stream-car (stream-car s))} etc.
28998@end defun
28999
29000@defun stream-ref stream pos
29001[R7RS stream]
29002@c MOD util.stream
29003@c EN
29004Returns the @var{pos}-th element in the stream.  @var{Pos}
29005must be a nonnegative exact integer.
29006@c JP
29007ストリームの@var{pos}番目の要素を返します。@var{pos}は非負の正確な整数でなければなりません。
29008@c COMMON
29009@end defun
29010
29011@defun stream-first s
29012@defunx stream-second s
29013@defunx stream-third s
29014@defunx stream-fourth s
29015@defunx stream-fifth s
29016@defunx stream-sixth s
29017@defunx stream-seventh s
29018@defunx stream-eighth s
29019@defunx stream-ninth s
29020@defunx stream-tenth s
29021@c MOD util.stream
29022@code{(stream-first s)} = @code{(stream-ref s 0)} etc.
29023@end defun
29024
29025@defun stream-take stream count
29026@defunx stream-take-safe stream count
29027@c MOD util.stream
29028Returns a new stream that consists of the first @var{count} elements
29029of the given stream.   If the given stream has less than
29030@var{count} elements, the stream returned by @code{stream-take}
29031would raise an error when the elements beyond the original stream
29032is accessed.  On the other hand, the stream returned by
29033@code{stream-take-safe} will return a shortened stream when
29034the given stream has less than @var{count} elements.
29035
29036@example
29037(stream->list (stream-take (stream-iota -1) 10))
29038 @result{} (0 1 2 3 4 5 6 7 8 9)
29039
29040(stream-take (stream 1 2) 5)
29041 @result{} @r{stream}
29042
29043(stream->list (stream-take (stream 1 2) 5))
29044 @result{} @r{error}
29045
29046(stream->list (stream-take-safe (stream 1 2) 5))
29047 @result{} (1 2)
29048@end example
29049
29050Note: srfi-41 (@code{scheme.stream}) also defines @code{stream-take}, but
29051the argument order is reversed, and also it allows @var{stream} to have
29052less than @code{count} elements.
29053@end defun
29054
29055@defun stream-drop stream count
29056@defunx stream-drop-safe stream count
29057@c MOD util.stream
29058Returns a new stream that consists of the elements in the given
29059stream except the first @var{count} elements.
29060If the given stream has less than @var{count} elements,
29061@code{stream-drop} returns a stream that raises an error
29062if its element is accessed, and @code{stream-drop-safe}
29063returns an empty stream.
29064
29065Note: srfi-41 (@code{scheme.stream}) also defines @code{stream-drop}, but
29066the argument order is reversed, and also it allows @var{stream} to have
29067less than @code{count} elements.
29068@end defun
29069
29070@defun stream-intersperse stream element
29071@c MOD util.stream
29072Returns a new stream in which @var{element} is
29073inserted between elements of @var{stream}.
29074@end defun
29075
29076@defun stream-split stream pred
29077@c MOD util.stream
29078Split @var{stream} on elements that satisfy @var{pred},
29079and returns a stream of splitted streams.  The delimiting element
29080won't be included in the result.
29081@end defun
29082
29083@defun stream-last stream
29084@c MOD util.stream
29085Returns the last element of @var{stream}.  If @var{stream} is infinite,
29086this procedure won't return.
29087@end defun
29088
29089@defun stream-last-n stream count
29090@c MOD util.stream
29091Returns a stream that contains the last @var{count} elements
29092in @var{stream}.  The @var{count} argument must be a nonnegative exact
29093integer.  If the length of @var{stream} is smaller than @var{count},
29094the resulting stream is the same as @var{stream}.
29095If @var{stream} is infinite,
29096this procedure won't return.
29097@end defun
29098
29099@defun stream-butlast stream
29100@c MOD util.stream
29101Returns a stream which is the same as @var{stream} but without the
29102last element.  If @var{stream} is empty, an empty stream is returned.
29103@end defun
29104
29105@defun stream-butlast-n stream count
29106@c MOD util.stream
29107Returns a stream which is the same as @var{stream} but without the
29108last @var{count} elements.  The @var{count} argument must be a nonnegative exact
29109integer.  If @var{stream} is shorter than @var{count}, a null stream
29110is returned.
29111@end defun
29112
29113@defun stream-length stream
29114[R7RS stream]
29115@c MOD util.stream
29116Returns the number of elements in @var{stream}.  It diverges if @var{stream}
29117is infinite.
29118@end defun
29119
29120@defun stream-length>= stream n
29121@defunx stream-length= stream n
29122@c MOD util.stream
29123Returns true iff the length of @var{stream} is greater than or equal to,
29124and exactly equal to, @var{n}, respectively.
29125These procedures only realizes @var{stream} up to @var{n} elements.
29126@end defun
29127
29128@defun stream-reverse stream :optional tail-stream
29129[R7RS stream]
29130@c MOD util.stream
29131@c EN
29132Returns a stream that returns the elements of @var{stream} in reverse order.
29133If @var{tail-stream} is given, it is added after the reversed stream.
29134
29135The optional argument is Gauche's extension.  The description of @code{reverse}
29136(@pxref{Other list procedures}) for more details.
29137@c JP
29138@var{stream}の要素を逆順にしたストリームを返します。@var{tail-stream}が与えられた
29139場合、逆順にしたストリームの後にそれ付け加えられます。
29140
29141省略可能な@var{tail-stream}はGaucheの拡張です。詳しくは
29142@code{reverse}の説明を参照してください (@ref{Other list procedures})。
29143@c COMMON
29144@end defun
29145
29146@defun stream-count pred stream @dots{}
29147@c MOD util.stream
29148@end defun
29149
29150@defun stream-find pred stream
29151@c MOD util.stream
29152@end defun
29153
29154@defun stream-find-tail pred stream
29155@c MOD util.stream
29156@end defun
29157
29158@defun stream-take-while pred stream
29159[R7RS stream]
29160@c MOD util.stream
29161@end defun
29162
29163@defun stream-drop-while pred stream
29164[R7RS stream]
29165@c MOD util.stream
29166@end defun
29167
29168@defun stream-span pred stream
29169@c MOD util.stream
29170@end defun
29171
29172@defun stream-break pred stream
29173@c MOD util.stream
29174@end defun
29175
29176@defun stream-any pred stream @dots{}
29177@c MOD util.stream
29178@end defun
29179
29180@defun stream-every pred stream @dots{}
29181@c MOD util.stream
29182@end defun
29183
29184@defun stream-index pred stream @dots{}
29185@c MOD util.stream
29186@end defun
29187
29188@defun stream-member obj stream :optional elt=
29189@defunx stream-memq obj stream
29190@defunx stream-memv obj stream
29191@c MOD util.stream
29192@end defun
29193
29194@defun stream-delete obj stream :optional elt=
29195@c MOD util.stream
29196@end defun
29197
29198@defun stream-delete-duplicates stream :optional elt=
29199@c MOD util.stream
29200@end defun
29201
29202@defun stream-grep re stream
29203@c MOD util.stream
29204@end defun
29205
29206@defun write-stream stream :optional oport writer
29207@c MOD util.stream
29208@end defun
29209
29210@c ----------------------------------------------------------------------
29211@node Topological sort, Unification, Stream library, Library modules - Utilities
29212@section @code{util.toposort} - Topological sort
29213@c NODE トポロジカルソート, @code{util.toposort} - トポロジカルソート
29214
29215@deftp {Module} util.toposort
29216@mdindex util.toposort
29217@c EN
29218Implements topological sort algorithm.
29219@c JP
29220トポロジカルソートのアルゴリズムを実装します。
29221@c COMMON
29222@end deftp
29223
29224@defun topological-sort graph :optional eqproc
29225@c MOD util.toposort
29226@c EN
29227@var{Graph} represents a directed acyclic graph (DAG) by a list
29228of connections, where each connection is the form
29229@example
29230(<node> <downstream> <downstream2> ...)
29231@end example
29232that means a node @code{<node>} is connected to other nodes
29233@code{<downstream>} etc.   @code{<node>} can be arbitrary
29234object, as far as it can be compared by the procedure @var{eqproc},
29235which is @var{eqv?} by default (@pxref{Equality}).
29236Returns a list of @code{<node>}s sorted topologically.
29237
29238If the graph contains circular reference, an error is signaled.
29239@c JP
29240@var{Graph}は有向非循環グラフ(DAG)を表現するリストです。
29241リストの各要素は次の形をしています。
29242@example
29243(<node> <downstream> <downstream2> ...)
29244@end example
29245これで、ノード@code{<node>}から別のノード@code{<downstream>}等への接続が
29246あることを表現します。@code{<node>}はどんなオブジェクトであっても構いませんが、
29247同一性の判定が@var{eqproc}で行えなければなりません。@var{eqproc}の既定値は
29248@code{eqv?}です (@ref{Equality}参照)。
29249トポロジカルにソートされたノードのリストを返します。
29250
29251グラフに循環が検出された場合はエラーとなります。
29252@c COMMON
29253@end defun
29254
29255@c ----------------------------------------------------------------------
29256@node Unification, CGI utility, Topological sort, Library modules - Utilities
29257@section @code{util.unification} - Unification
29258@c NODE ユニフィケーション, @code{util.unification} - ユニフィケーション
29259
29260@deftp {Module} util.unification
29261@mdindex util.unification
29262@c EN
29263Implements unification algorithm.
29264@c JP
29265ユニフィケーションのアルゴリズムを実装します。
29266@c COMMON
29267
29268@c EN
29269The base API operates on abstract trees, while it is
29270agnostic to the actual representation of the tree.
29271The caller passes comparators and operators along the trees
29272to unify.
29273@c JP
29274基本APIは、抽象的な木に対して動作しますが、木が実際にどう実装されているかは
29275関知しません。
29276呼び出し側は、ユニファイする木といっしょに、比較器や操作手続きを渡します。
29277@c COMMON
29278
29279@c EN
29280We assume the abstract tree has the following structure:
29281@c JP
29282抽象的な木は、次の構造を持っていると考えます。
29283@c COMMON
29284
29285@example
29286Tree : Variable | Value | Tuple
29287Tuple : @{ Tree ... @}
29288@end example
29289
29290@c EN
29291Here, @code{@{...@}} just represents a sequence of trees.
29292@c JP
29293ここで、@code{@{...@}}は単に木の並びを表します。
29294@c COMMON
29295
29296@c EN
29297A variable can be bound to a tree.  A value can only match itself.
29298@c JP
29299変数(Variable)は木に束縛されます。値(Value)はそれ自身とのみマッチします。
29300@c COMMON
29301
29302@c EN
29303To operate on this tree, we need the following comparators and procedures,
29304which the API takes as arguments:
29305@c JP
29306この木を扱うために、APIは以下の比較器と手続きを引数として取ります。
29307@c COMMON
29308
29309@table @asis
29310@item Variable comparator: @code{var-cmpr}
29311@c EN
29312A comparator to see if an item is a variable, and also
29313check equality of two variables.  It must be hashable.
29314@xref{Basic comparators}, for the details of comparators.
29315@c JP
29316要素が変数であるかどうかを調べ、また二つの変数が同じかどうかを判定
29317するための比較器です。ハッシュ可能でなければなりません。
29318比較器については@ref{Basic comparators}を参照してください。
29319@c COMMON
29320@item Value comparator: @code{val-cmpr}
29321@c EN
29322A comparator to see if an item is a value, and also
29323check equality of two values.
29324Note that if a tree satisfies neither @var{var-cmpr} nor @var{val-compr},
29325it is regarded as a tuple.
29326@c JP
29327要素が値であるかどうかを調べ、また二つの値が等しいかどうかを
29328判定するための比較器です。@var{var-cmpr}も@var{val-cmpr}も
29329満たさない要素はタプルであるとみなされます。
29330@c COMMON
29331@item Tuple folder: @code{tuple-fold}
29332@c EN
29333A procedure @code{(tuple-folde proc seed tuple1 [tuple2])}.
29334This procedure should work like @code{fold} (@pxref{Walking over lists})
29335over the elements in the tuple(s).  It is only called with
29336either one or two tuples.
29337@c JP
29338@code{(tuple-folde proc seed tuple1 [tuple2])}の形で呼び出される手続きです。
29339この手続きは、タプル中の要素について@code{fold}のように動作します
29340(@ref{Walking over lists}参照)。常にひとつかふたつのタプルを引数とします。
29341@c COMMON
29342@item Tuple constructor: @code{make-tuple}
29343@c EN
29344A procedure @code{(make-tuple proto elements)}, where
29345@var{proto} is a tuple and @var{elements} are a list of trees.
29346It must return a new tuple with the given elements,
29347while all other properties are the same as @var{proto}.
29348This procedure isn't needed by @code{unify}.
29349@c JP
29350@code{(make-tuple proto elements)}の形式で呼び出される手続きです。
29351@var{proto}はタプルで、@var{elements}は木のリストです。
29352@var{proto}と同じ型のタプルで、要素だけを@var{elements}と置き換えた
29353新たなタプルを作成して返します。
29354@code{unify}はこの手続きを必要としません。
29355@c COMMON
29356@end table
29357@end deftp
29358
29359@defun unify a b var-cmpr val-cmpr tuple-fold
29360@c MOD util.unification
29361@c EN
29362Unify two trees @var{a} and @var{b} and returns a substitution
29363dictionary, which is a dictionary that maps variables
29364to its bounded trees.
29365@c JP
29366二つの木、@var{a}と@var{b}を単一化し、置換辞書を返します。
29367置換辞書は、変数をその値にマップするものです。
29368@c COMMON
29369
29370@c EN
29371See the entry of @code{util.unification} above for the description
29372of @var{var-cmpr}, @var{val-cmpr} and @var{tuple-fold}.
29373@c JP
29374引数@var{var-cmpr}、@var{val-cmpr}、@var{tuple-fold}に関しては
29375上の@code{util.unification}の説明を参照してください。
29376@c COMMON
29377
29378@example
29379(dict->alist (unify '(a 3 (c b)) '(c b (2 e))
29380                    symbol-comparator
29381                    number-comparator
29382                    fold))
29383 @result{} ((e . 3) (a . c) (b . 3) (c . 2))
29384@end example
29385
29386@c EN
29387As you can see in the example above,
29388a variable may be mapped to another variable, or even to
29389a tree that contains variables.  If you apply the substitution
29390to the original tree, you must do it recursively until all the
29391variables in the dictionary is eliminated.
29392@c JP
29393この例にも見られるように、一つの変数の値が別の変数であったり、
29394別の変数を含む木であったりする場合があります。
29395元の木に置換を適用する場合は、辞書にある変数がすべて消去されるまで
29396再帰的に置換を行う必要があります。
29397@c COMMON
29398
29399@c EN
29400If two trees cannot be unified, @code{#f} is returned.
29401@c JP
29402二つの木が単一化できない場合は@code{#f}が返されます。
29403@c COMMON
29404
29405@example
29406(unify '(a (a)) '(x x) symbol-comparator number-comparator fold)
29407 @result{} #f
29408@end example
29409
29410@end defun
29411
29412@defun unify-merge a b var-cmpr val-cmpr tuple-fold make-tuple
29413@c MOD util.unification
29414@c EN
29415Unify two trees @var{a} and @var{b}, and apply the result substitutions
29416to create a new tree eliminating variables.
29417@c JP
29418二つの木、@var{a}と@var{b}を単一化し、結果の置換を適用して変数を消去した
29419新たな木を返します。
29420@c COMMON
29421
29422@c EN
29423See the entry of @code{util.unification} above for the description
29424of @var{var-cmpr}, @var{val-cmpr}, @var{tuple-fold} and
29425@var{make-tuple}.
29426@c JP
29427引数@var{var-cmpr}、@var{val-cmpr}、@var{tuple-fold}、@var{make-tuple}に関しては
29428上の@code{util.unification}の説明を参照してください。
29429@c COMMON
29430
29431@example
29432(unify-merge '(a 3 (c b)) '(c b (2 e))
29433             symbol-comparator
29434             number-comparator
29435             fold
29436             (^[_ elts] elts))
29437 @result{} (2 3 (2 3))
29438@end example
29439
29440@c EN
29441If two trees can't be unified, @code{#f} is returned.
29442@c JP
29443二つの木が単一化できなければ、@code{#f}が返されます。
29444@c COMMON
29445@end defun
29446
29447
29448@c ----------------------------------------------------------------------
29449@node CGI utility, CGI testing, Unification, Library modules - Utilities
29450@section @code{www.cgi} - CGI utility
29451@c NODE CGIユーティリティ, @code{www.cgi} - CGIユーティリティ
29452
29453@deftp {Module} www.cgi
29454@mdindex www.cgi
29455@c EN
29456Provides a few basic functions useful to write a CGI script.
29457
29458In order to write CGI script easily, you may want to use
29459other modules, such as @code{rfc.uri} (@pxref{URI parsing and construction}),
29460@code{text.html-lite} (@pxref{Simple HTML document construction}) and
29461@code{text.tree} (@pxref{Lazy text construction}).
29462
29463Note: it seems that there is no active formal specification for CGI.
29464See @uref{http://w3c.org/CGI/} for more information.
29465@c JP
29466CGIスクリプトを書くのに便利ないくつかの基本的な手続きを提供します。
29467
29468CGIスクリプトを手軽に書くにはこのモジュールの他に、
29469@code{rfc.uri} (@ref{URI parsing and construction})、
29470@code{text.html-lite} (@ref{Simple HTML document construction})、
29471@code{text.tree} (@ref{Lazy text construction}) 等のモジュールを併せて
29472使うとよいでしょう。
29473
29474注:現在有効な、CGIに関する「正式な」仕様というのはどうも無いようです。
29475@uref{http://w3c.org/CGI/}あたりを参照して下さい。
29476@c COMMON
29477@end deftp
29478
29479@c EN
29480@subheading Metavariables
29481@c JP
29482@subheading メタ変数
29483@c COMMON
29484
29485@deffn {Parameter} cgi-metavariables :optional metavariables
29486@c MOD www.cgi
29487@c EN
29488Normally, httpd passes a cgi program various information
29489via environment variables.
29490Most procedures in @code{www.cgi} refer to them (meta-variables).
29491However, it is sometimes inconvenient to require environment variable access
29492while you're developing cgi-related programs.
29493With this parameter, you can overrides the information of meta-variables.
29494
29495@var{Metavariables} should be a list of two-element lists.
29496Car of each inner list names the variable, and its cadr gives the
29497value of the variable by string.
29498
29499For example, the following code overrides @code{REQUEST_METHOD}
29500and @code{QUERY_STRING} meta-variables during execution of
29501@code{my-cgi-procedure}.  (@xref{Parameters},
29502for the details of @code{parameterize}).
29503@c JP
29504通常、httpdはcgiプログラムに様々な情報を環境変数経由で渡します。
29505@code{www.cgi}中の多くの手続きはその情報(メタ変数)を参照します。
29506しかし、cgiに関連するプログラムを開発中に環境変数にアクセスするのは
29507不便な場合もあります。
29508このパラメータを使うと、メタ変数をオーバライドすることができます。
29509
29510@var{Metavariables}は2要素のリストのリストです。
29511内側のリストは、最初の要素が変数名を、2つめの要素がその値を、それぞれ
29512文字列で与えます。
29513
29514例えば次のコードは@code{REQUEST_METHOD}と
29515@code{QUERY_STRING}のメタ変数を@code{my-cgi-procedure}の実行期間中に
29516上書きします。(@code{parameterize}の詳細については
29517@ref{Parameters}を参照して下さい)。
29518@c COMMON
29519
29520@example
29521(parameterize ((cgi-metavariables '(("REQUEST_METHOD" "GET")
29522                                    ("QUERY_STRING" "x=foo"))))
29523  (my-cgi-procedure))
29524@end example
29525@end deffn
29526
29527@defun cgi-get-metavariable name
29528@c MOD www.cgi
29529@c EN
29530Returns a value of cgi metavariable @var{name}.
29531This function first searches the parameter @code{cgi-metavariables},
29532and if the named variable is not found, calls @code{sys-getenv}.
29533
29534CGI scripts may want to use @code{cgi-get-metavariable} instead
29535of directly calling @code{sys-getenv}; doing so makes reuse of
29536the script easier.
29537@c JP
29538@var{name}で指定されるCGIメタ変数の値を返します。
29539この関数はまずパラメータ@code{cgi-metavariables}を探し、
29540指定されたメタ変数が見つからなければ@code{sys-getenv}を呼びます。
29541
29542CGIスクリプトは、なるべく@code{sys-getenv}を直接呼ぶのではなく
29543@code{cgi-get-metavariable}を使うのが良いでしょう。
29544スクリプトの再利用もしやすくなります。
29545@c COMMON
29546@end defun
29547
29548@c EN
29549@subheading Parameter extraction
29550@c JP
29551@subheading パラメータの取得
29552@c COMMON
29553
29554@defun cgi-parse-parameters :key :query-string :merge-cookies :part-handlers
29555@c MOD www.cgi
29556@c EN
29557Parses query string and returns associative list of parameters.
29558When a keyword argument @var{query-string} is given, it is used
29559as a source query string.  Otherwise, the function checks the
29560metavariable @code{REQUEST_METHOD} and obtain the query string
29561depending on the value (either from stdin or from the
29562metavariable @code{QUERY_STRING}).
29563If such a metavariable is not defined and
29564the current input port is a terminal, the function prompts the user
29565to type parameters; it is useful for interactive debugging.
29566@c JP
29567CGIプログラムに渡されたquery stringをパーズして、パラメータの連想リストにして
29568返します。文字列がキーワード引数@var{query-string}に与えられればそれがパーズすべき
29569query stringとなります。その引数が渡されなければこの手続きは
29570メタ変数@code{REQUEST_METHOD}を参照し、その値によって標準入力もしくは
29571メタ変数@code{QUERY_STRING}からquery stringが取られます。
29572そのようなメタ変数が定義されておらず、かつ現在の入力ポートが端末である場合、
29573インタラクティブにデバッグをしているものと考えて、
29574この手続きはプロンプトを出してユーザにパラメータの入力を促します。
29575@c COMMON
29576
29577@c EN
29578If @code{REQUEST_METHOD} is @code{POST}, this procedure can handle
29579both @code{application/x-www-form-urlencoded} and
29580@code{multipart/form-data} as the enctype.  The latter is usually
29581used if the form has file-uploading capability.
29582
29583When the post data is sent by @code{multipart/form-data},
29584each content of the part is treated as a value of the parameter.
29585That is, the content of uploaded file will be seen as one big
29586chunk of a string.  The other information, such as the original file
29587name, is discarded.   If it is not desirable to read entire file
29588into a string, you can customize the behavior by the @var{part-handler}
29589argument.  The details are explained in the "Handling file uploads"
29590section below.
29591@c JP
29592@code{REQUEST_METHOD}が@code{POST}の場合、この手続きはenctypeとして
29593@code{application/x-www-form-urlencoded}と@code{multipart/form-data}の
29594両方を処理できます。後者は通常、ファイルアップロード機能を持つフォームに使われます。
29595
29596POSTデータが@code{multipart/form-data}で送られて来た場合、
29597各パートの内容がパラメータの値となります。すなわち、アップロードされた
29598ファイルはその内容がひとつの文字列として得られることになります。
29599元のファイル名のようなその他の情報は捨てられます。これが望ましい動作で
29600ない場合は、@var{part-handlers}引数によって動作をカスタマイズすることができます。
29601詳しくは下の「ファイルアップロードの処理」で説明します。
29602@c COMMON
29603
29604@c EN
29605When a true value is given to @var{merge-cookies}, the cookie
29606values obtained from the metavariable @code{HTTP_COOKIE}
29607are appended to the result.
29608@c JP
29609キーワード引数@var{merge-cookies}に真の値が与えられた場合は、
29610メタ変数@code{HTTP_COOKIE}からクッキーの値が読まれ、解析されて
29611結果に追加されます。
29612@c COMMON
29613
29614@c EN
29615Note that the query parameter may have multiple values,
29616so @code{cdr} of each element in the result is a list, not an atom.
29617If no value is given to the parameter, @code{#t} is placed as its value.
29618See the following example:
29619@c JP
29620パラメータは複数の値を取り得るため、結果のパラメータに対応する値は常にリストになります。
29621パラメータに値が与えられていなければ、結果のパラメータに対する値には@code{#t}が置かれます。
29622次の例を参照して下さい。
29623@c COMMON
29624@example
29625(cgi-parse-parameters
29626  :query-string "foo=123&bar=%22%3f%3f%22&bar=zz&buzz")
29627 @result{} (("foo" "123") ("bar "\"??\"" "zz") ("buzz" #t))
29628@end example
29629@end defun
29630
29631
29632@defun cgi-get-parameter name params :key :default :list :convert
29633@c MOD www.cgi
29634@c EN
29635A convenient function to obtain a value of the parameter @var{name} from
29636parsed query string @var{params}, which is the value
29637@code{cgi-parse-parameters} returns.  @var{Name} should be a string.
29638@c JP
29639@code{cgi-parse-parameters}が返す、パーズされたQuery文字列@var{params}から、
29640名前@var{name}を持つパラメータの値を簡単に取り出すための手続きです。
29641@var{name}は文字列です。
29642@c COMMON
29643
29644@c EN
29645Unless true value is given to @var{list}, the returned value is
29646a scalar value.  If more than one value is associated to @var{name},
29647only the first value is returned.  If @var{list} is true, the
29648returned value is always a list, even @var{name} has only one value.
29649@c JP
29650キーワード引数@var{list}に真の値が与えられていなければ、
29651返される値はスカラー値です。パラメータ@var{name}に複数の値が与えられた場合でも、
29652最初の値のみが返されます。@var{list}に真の値が与えられれば、返されるのは
29653常に値のリストとなります。
29654@c COMMON
29655
29656@c EN
29657After the value is retrieved, you can apply a procedure to
29658convert the string value to the appropriate type by giving
29659a procedure to the @var{convert} argument.  The procedure must
29660take one string argument.  If @var{list} is true, the convert
29661procedure is applied to each values.
29662@c JP
29663キーワード引数@var{convert}に手続きを与えると、対応する値が取り出された後でその
29664手続きが値を引数として呼ばれます。これによって値を文字列から必要な型へと変換することが
29665できます。@var{list}に真の値が与えられている場合、変換手続きは各値に対して呼ばれ、
29666その結果のリストが@var{cgi-get-parameter}から返されます。
29667@c COMMON
29668
29669@c EN
29670If the parameter @var{name} doesn't appear in the query,
29671a value given to the keyword argument @var{default} is returned;
29672the default value of @var{default}
29673is @code{#f} if @var{list} is false, or @code{()} otherwise.
29674@c JP
29675パラメータ@var{name}がQuery中に現れなかった場合は、
29676@var{default}に与えられた値がそのまま
29677返されます。@var{default}が省略された場合、@var{list}が偽であれば@code{#f}が、
29678真であれば@code{()}が返されます。
29679@c COMMON
29680@end defun
29681
29682@c EN
29683@subheading Output generation
29684@c JP
29685@subheading 出力の生成
29686@c COMMON
29687
29688
29689@defun cgi-header :key status content-type location cookies
29690@c MOD www.cgi
29691@c EN
29692Creates a text tree (@pxref{Lazy text construction}) for the
29693HTTP header of the reply message.  The most simple form is
29694like this:
29695@c JP
29696HTTPリプライメッセージのヘッダを、テキストツリー形式(@ref{Lazy text construction}参照)
29697で作成して返します。最も簡単な呼び出しでは次のようになります。
29698@c COMMON
29699@example
29700(tree->string (cgi-header))
29701  @result{} "Content-type: text/html\r\n\r\n"
29702@end example
29703
29704@c EN
29705You can specify alternative content-type by the keyword argument
29706@var{content-type}.   If you want to set cookies to the client,
29707specify a list of cookie strings to the keyword argument @var{cookies}.
29708You can use @code{construct-cookie-string} (@pxref{HTTP cookie handling})
29709to build such a list of cookie strings.
29710@c JP
29711キーワード引数@var{content-type}によってContent typeを指定できます。
29712また、@var{cookies}にクッキー文字列のリストを渡すことにより、
29713クライアントにクッキーを設定できます。クッキー文字列を構築するには手続き
29714@code{construct-cookie-string} (@ref{HTTP cookie handling}参照)
29715が使えます。
29716@c COMMON
29717
29718@c EN
29719The keyword argument @var{location} may be used to generate
29720a @code{Location:} header to redirect the client to the specified URI.
29721You can also specify the @code{Status:} header by the keyword argument
29722@var{status}.   A typical way to redirect the client is as follows:
29723@c JP
29724キーワード引数@var{location}は、@code{Location}ヘッダを作成して
29725クライアントを別のURIに誘導するのに使えます。また、@code{Status}ヘッダを
29726指定するために@var{status}キーワード引数が使えます。クライアントを
29727別URIに転送するよくある方法は次のようなものです。
29728@c COMMON
29729
29730@example
29731(cgi-header :status "302 Moved Temporarily"
29732            :location target-uri)
29733@end example
29734
29735@end defun
29736
29737@deffn {Parameter} cgi-output-character-encoding :optional encoding
29738@c MOD www.cgi
29739@c EN
29740The value of this parameter specifies the character encoding scheme (CES)
29741used for CGI output by @code{cgi-main} defined below.
29742The default value is Gauche's native encoding.
29743If the parameter is set other than the native encoding, @code{cgi-main}
29744converts the output
29745encoding by @code{gauche.charconv} module
29746(@pxref{Character code conversion}).
29747@c JP
29748このパラメータの値は次に説明する@code{cgi-main}が出力するデータの
29749文字符合化法(CES)を指定します。デフォルトの値はGaucheのネイティブエンコーディング
29750です。それ以外の値がセットされている場合、@code{cgi-main}は
29751@code{gauche.charconv}モジュールを用いて出力のエンコーディングの変換を
29752行います。
29753(@ref{Character code conversion}参照)。
29754@c COMMON
29755@end deffn
29756
29757
29758@c EN
29759@subheading Convenience procedures
29760@c JP
29761@subheading 便利な手続き
29762@c COMMON
29763
29764@defun cgi-main proc :key on-error merge-cookies output-proc part-handlers
29765@c MOD www.cgi
29766@c EN
29767A convenient wrapper function for CGI script.
29768This function calls @code{cgi-parse-parameters}, then calls
29769@var{proc} with the result of @code{cgi-parse-parameters}.
29770The keyword argument @var{merge-cookies} is passed to
29771@code{cgi-parse-parameters}.
29772@c JP
29773CGIスクリプトのための便利なラッパー手続きです。
29774この手続きは、まず@code{cgi-parse-parameters}を呼び出してCGIスクリプトに
29775渡されたパラメータを解析し、続いてその結果を引数として@var{proc}を呼び出します。
29776キーワード引数@var{merge-cookies}は、与えられればそのまま
29777@code{cgi-parse-parameters}に渡されます。
29778@c COMMON
29779
29780@c EN
29781@var{proc} has to return a tree of strings
29782(@pxref{Lazy text construction}), including the HTTP header.
29783@code{cgi-main} outputs the returned tree to the current output port
29784by @code{write-tree}, then returns zero.
29785@c JP
29786手続き@var{proc}はHTTPヘッダを含むドキュメントを
29787テキストツリー構造(@ref{Lazy text construction}参照)で
29788返さなければなりません。@code{cgi-main}はそれを@code{write-tree}を使って
29789現在の出力ポートに書き出し、0を返します。
29790@c COMMON
29791
29792@c EN
29793If an error is signaled in @var{proc}, it is caught and an HTML
29794page reporting the error is generated.  You can customize the
29795error page by providing a procedure to the @var{on-error} keyword argument.
29796The procedure takes an @code{<condition>} object (@pxref{Conditions}),
29797and has to return a tree of string for the error reporting HTML
29798page, including an HTTP header.
29799@c JP
29800もし@var{proc}内でエラーが起こった場合、そのエラーは捕捉されて、エラーを報告する
29801HTMLページが作成されて出力されます。このエラーページは、@var{on-error}キーワード引数に
29802手続きを渡すことでカスタマイズできます。@var{on-error}に渡された手続きは
29803エラー発生時に@code{<condition>}オブジェクト(@ref{Conditions}参照)
29804を引数として呼ばれ、HTTPヘッダを含むドキュメントをテキストツリー構造で返さねばなりません。
29805@c COMMON
29806
29807@c EN
29808When output the result, @code{cgi-main} refers to
29809the value of the parameter @code{cgi-output-character-encoding},
29810and converts the character encoding if necessary.
29811@c JP
29812@code{cgi-main}は最終的な結果を出力を書き出す時に
29813パラメータ@code{cgi-output-character-encoding}を参照し、
29814必要ならば出力の文字エンコーディングを変換します。
29815@c COMMON
29816
29817@c EN
29818The output behavior of @code{cgi-main} can be customized
29819by a keyword argument @var{output-proc}; if it is given,
29820the text tree (either the normal return value of @var{proc},
29821or an error page constructed by the error handler) is passed
29822to the procedure given to @var{output-proc}.  The procedure
29823is responsible to format and output a text to the current
29824output port, including character conversions, if necessary.
29825@c JP
29826@code{cgi-main}の出力のふるまいはキーワード引数@var{output-proc}で
29827カスタマイズできます。@var{output-proc}が渡された場合、それは
29828@var{proc}の戻り値、あるいはエラーハンドラが作成したテキストツリー構造を
29829受け取る手続きでなければなりません。その手続きはテキストツリーを
29830フォーマットして現在の出力ポートに出力しなければなりません。
29831必要ならば文字エンコーディングの変換もその手続き内で行います。
29832@c COMMON
29833
29834@c EN
29835The keyword argument @var{part-handlers} are simply passed to
29836@code{cgi-parse-parameters}, by which you can customize
29837how the file uploads should be handled.  See the "Handling file
29838uploads" section below for the details.
29839
29840If you specify to use temporary file(s) by it, @code{cgi-main}
29841makes sure to clean up them whenever @var{proc} exits,
29842even by error.   See @code{cgi-add-temporary-file} below
29843to utilize this feature for other purpose.
29844@c JP
29845キーワード引数@var{part-handlers}は、そのまま@code{cgi-parse-parameters}
29846に渡されます。この引数によって、ファイルアップロードの際の動作をカスタマイズ
29847できます。詳しくは下の「ファイルアップロードの処理」の項を参照して下さい。
29848
29849この引数で、一時ファイルを使うように指定した場合、@code{cgi-main}は
29850@var{proc}から抜ける際に(エラーでも正常終了でも)一時ファイルを
29851消去します。この機能を他でも利用するには@code{cgi-add-temporary-file}の項を
29852参考にして下さい。
29853@c COMMON
29854
29855@c EN
29856Before calling @var{proc}, @code{cgi-main} changes the buffering mode
29857of the current error port to @code{:line} (See @code{port-buffering}
29858in @ref{Common port operations} for the details about the buffering mode).
29859This makes the error output easier for web servers to capture.
29860@c JP
29861@var{proc}を呼ぶ前に、@code{cgi-main}はカレントエラーポートの
29862バッファリングモードを@code{:line}に変更します。
29863(バッファリングモードの詳細については@ref{Common port operations}の
29864@code{port-buffering}の項を参照してください)。
29865これはwebサーバがcgiスクリプトのエラー出力を捕捉しやすくするためです。
29866@c COMMON
29867
29868@c EN
29869The following example shows the parameters given to the CGI program.
29870@c JP
29871以下の例はCGIに渡されたパラメータ全てをテーブルにして表示します。
29872@c COMMON
29873
29874@example
29875#!/usr/local/bin/gosh
29876
29877(use text.html-lite)
29878(use www.cgi)
29879
29880(define (main args)
29881  (cgi-main
29882    (lambda (params)
29883      `(,(cgi-header)
29884        ,(html-doctype)
29885        ,(html:html
29886          (html:head (html:title "Example"))
29887          (html:body
29888           (html:table
29889            :border 1
29890            (html:tr (html:th "Name") (html:th "Value"))
29891            (map (lambda (p)
29892                   (html:tr
29893                    (html:td (html-escape-string (car p)))
29894                    (html:td (html-escape-string (x->string (cdr p))))))
29895                 params))))
29896       ))))
29897@end example
29898@end defun
29899
29900
29901@defun cgi-add-temporary-file filename
29902@c MOD www.cgi
29903@c EN
29904This is supposed to be called inside @var{proc} of @code{cgi-main}.
29905It registers @var{filename} as a temporary file, which should be
29906unlinked when @var{proc} exits.  It is a convenient way to ensure
29907that your cgi script won't leave garbages even if it throws an error.
29908It is OK in @var{proc} to unlink or rename @var{filename} after
29909calling this procedure.
29910@c JP
29911この手続きは@code{cgi-main}に渡される@var{proc}中で呼ばれることを
29912想定しています。
29913この手続きは、@var{filename}を一時ファイルとして登録し、@var{proc}が
29914終了する際に消去されるようにします。cgiスクリプトがエラー終了した場合
29915などでもごみを残さないようにする便利な方法です。
29916この手続きを呼んだ後で、@var{proc}が@var{filename}を消去したり
29917名前を変えたりしても構いません。
29918@c COMMON
29919@end defun
29920
29921@deffn {Parameter} cgi-temporary-files
29922@c MOD www.cgi
29923@c EN
29924Keeps a list of filenames registered by @code{cgi-add-temporary-file}.
29925@c JP
29926@code{cgi-add-temporary-file}で登録された一時ファイルを保持するパラメータです。
29927@c COMMON
29928@end deffn
29929
29930@c EN
29931@subheading Handling file uploads
29932@c JP
29933@subheading ファイルアップロードの処理
29934@c COMMON
29935
29936@c EN
29937As explained in @code{cgi-parse-parameters} above, file uploads
29938are handled transparently by default, taking the file content
29939as the value of the parameter.   Sometimes you might want to change this
29940behavior, for the file might be quite big and you don't want
29941to keep around a huge chunk of a string in memory.  It is possible to
29942customize handling of file uploads of @code{cgi-parse-parameters}
29943and @code{cgi-main} by @var{part-handlers} argument.
29944(The argument is only effective for the form data submitted by
29945@code{multipart/form-data} enctype)
29946@c JP
29947@code{cgi-parse-parameters}の項で説明したように、ファイルアップロードは
29948デフォルトでは透過的に扱われます。すなわち、アップロードされた
29949ファイルの内容がパラメータの値となります。
29950これは望みの動作ではないかもしれません。例えばアップロードされるファイルが
29951巨大であることが予想されるなら、それを全てメモリに読み込んで持ち回りたくは
29952ないかもしれません。@code{cgi-parse-parameters}や@code{cgi-main}の
29953@var{part-handlers}引数によって、ファイルアップロードの
29954処理をカスタマイズすることが可能です。
29955(この引数は、フォームデータが@code{multipart/form-data} enctypeで
29956送られた場合にのみ意味を持ちます)。
29957@c COMMON
29958
29959@c EN
29960The @var{part-handlers} argument is, if given, a list of lists;
29961each inner list is a form of
29962@code{(@var{name-pattern} @var{action} @var{kv-list} @dots{})}.
29963Each uploaded file with a matching parameter name with @var{name-pattern} is
29964handled according to @var{action}.  (Here, a parameter name
29965is the 'name' attribute given to the @code{input} element in the
29966submitted form, not the name of the uploaded file).
29967@c JP
29968@var{part-handlers}引数が与えられている場合、それはリストのリストで、
29969内部のリストは@code{(@var{name-pattern} @var{action} @var{kv-list} @dots{})} の形式で
29970なければなりません。
29971アップロードされたファイルは、そのパラメータ名が@var{name-pattern}に
29972マッチした場合に@var{action}で指示されるように処理されます。
29973(ここで、パラメータ名とはsubmitされたフォームの@code{input}要素に与えられた
29974'name'属性のことです。アップロードされたファイルの名前ではありません)。
29975@c COMMON
29976
29977@c EN
29978@var{Name-pattern} must be either a list of string (matches one of them),
29979a regexp, or @code{#t} (matches anything).
29980@c JP
29981@var{name-pattern}は文字列のリストか、正規表現か、@code{#t}です。
29982文字列のリストの場合はそれのいずれかとパラメータ名が等しければマッチと
29983みなされます。@code{#t}は全てのものにマッチします。
29984@c COMMON
29985
29986@c EN
29987@var{Action} must be either one of the followings:
29988@table @code
29989@item #f
29990Default action, i.e. the content of the uploaded file is turned into
29991a string and becomes the value of the parameter.
29992@item ignore
29993The uploaded content is discarded.
29994@item file
29995The uploaded content is saved in a temporary file.  The value of
29996the parameter is the pathname of the temporary file.
29997
29998For this action, you can write an entry like
29999@code{(@var{name-pattern} file @var{prefix})}, to specify the
30000prefix of the pathname of the temporary file.  For example, if you
30001specify @code{("image" file "/var/mycgi/incoming/img")},
30002the file uploaded as @code{"image"} parameter will be stored as
30003something like @file{/var/mycgi/incoming/img49g2Ua}.
30004
30005The application should move the temporary file to appropriate
30006location; if you're using @code{cgi-main}, the temporary files
30007created by this action will be unlinked when @code{cgi-main} exits.
30008
30009@item file+name
30010Like @code{file}, but the value of the parameter is a list of
30011temporary filename and the filename passed by the client.
30012It is useful if you want to use client's filename (but do not
30013blindly assume the client sends a valid pathname; for example,
30014you shouldn't use it to rename the uploaded file without
30015validating it).
30016
30017@item @var{procedure}
30018In this case, @var{procedure} is called to handle the uploaded
30019contents.  It is called with four arguments:
30020@code{(procedure @var{name} @var{filename} @var{part-info} @var{iport})}.
30021
30022@var{Name} is the name of the parameter.  @var{Filename} is
30023the name of the original file (pathname in the client).
30024@var{Part-info} is a @code{<mime-part>} object that keeps information
30025about this mime part,  and @var{iport} is where the body can be
30026read from.
30027For the details about these arguments,
30028see @ref{MIME message handling}; you might be able to
30029use procedures provided by @code{rfc.mime}, such as @code{mime-retrieve-body},
30030to construct your own procedure.
30031
30032If you create a temporary file in @var{procedure}, you can call
30033@code{cgi-add-temporary-file} to make sure it is removed even if
30034an error occurs during cgi processing.
30035@end table
30036@c JP
30037@code{action}は次のいずれかの値でなければなりません。
30038@table @code
30039@item #f
30040デフォルトのアクションです。すなわち、アップロードされたファイルの内容が
30041文字列として読み込まれ、パラメータの値となります。
30042@item ignore
30043アップロードされたファイルの内容を無視します。
30044@item file
30045アップロードされたファイルの内容は一時ファイルへと格納されます。
30046パラメータの値は、一時ファイルの名前となります。
30047
30048このアクションを使う場合は、エントリを
30049@code{(@var{name-pattern} file @var{prefix})} のように書くことも
30050でき、その場合は@var{prefix}が一時ファイルのパス名のプリフィクスとして
30051使われます。例えば@code{("image" file "/var/mycgi/incoming/img")}
30052のようにしておくと、@code{"image"}パラメータとしてアップロードされた
30053ファイルが@file{/var/mycgi/incoming/img49g2Ua}のような一時ファイルに
30054格納されることになります。
30055
30056アプリケーションは、この一時ファイルを(必要ならば)適切な場所に
30057移動しなければなりません。@code{cgi-main}を用いている場合は、
30058一時ファイルは@code{cgi-main}を抜ける際に(まだあれば)unlinkされます。
30059
30060@item file+name
30061@code{file}と同様ですが、パラメータの値が一時ファイル名と
30062クライアントが送ってきたファイル名からなるリストになります。
30063クライアントが送信したファイル名を利用したい場合に便利です
30064(ただ、クライアントが常に正しいファイル名を送って来ると仮定しては
30065いけません。例えば、アップロードされたファイルを
30066チェック無しにクライアントが送ってきた名前にrenameするというような
30067ことは避けてください)。
30068
30069
30070@item @var{procedure}
30071この場合、アップロードされた内容を処理するために、手続き@var{procedure}が
30072呼ばれます。手続きは4つの引数を伴って呼ばれます:
30073@code{(procedure @var{name} @var{filename} @var{part-info} @var{iport})}.
30074
30075@var{name}はパラメータの名前、@var{filename}はオリジナルファイルの名前
30076(クライアント側でのパス名)です。@var{part-info}は@code{<mime-part>}オブジェクトで、
30077このMIMEパートの情報を保持しており、そして@var{iport}は内容を読むための入力ポートです。
30078これらの引数の詳しい意味については@ref{MIME message handling}を
30079参照して下さい。独自の@var{procedure}を書く際に、@code{rfc.mime}の
30080@code{mime-retrieve-body}のような手続きが使えるかもしれません。
30081
30082@var{procedure}内で一時ファイルを作る場合は、それを
30083@code{cgi-add-temporary-file}で登録しておけば、cgi処理中に
30084エラーが起きた場合でも一時ファイルが消去されるようにすることができます。
30085@end table
30086@c COMMON
30087
30088@c EN
30089If @var{kv-list} is given after @var{action}, it must be a
30090keyword-value list and further modifies action.  The following
30091keywords are supported.
30092@c JP
30093@var{action}の後ろに@var{kv-list}が与えられた場合、それは
30094キーワード-値リストでなければなりません。次のキーワードがサポートされています。
30095@c COMMON
30096
30097@table @code
30098@item :prefix
30099@c EN
30100Valid only if @var{action} is either @code{file} or @code{file+name}.
30101Specifies the prefix of the temporary file.  If you give
30102@code{:prefix "/tmp/foo"}, for example, the file is saved
30103as something like @file{/tmp/fooxAgjeQ}.
30104@c JP
30105@var{action}が@code{file}か@code{file+name}の時のみ有効です。
30106一時ファイルのプリフィクスを指定します。例えば@code{:prefix "/tmp/foo"}を
30107与えると、ファイルは@file{/tmp/fooxAgjeQ}のような名前でセーブされます。
30108@c COMMON
30109@item :mode
30110@c EN
30111Valid only if @var{action} is either @code{file} or @code{file+name}.
30112Specifies the mode of the temporary file in unix-style integer.  By default
30113it is @code{#o600}.
30114@c JP
30115@var{action}が@code{file}か@code{file+name}の時のみ有効です。
30116一時ファイルのモードをunix式の整数で指定します。デフォルトは@code{#o600}です。
30117@c COMMON
30118@end table
30119
30120
30121@c EN
30122Note that the parameters that are not file uploads are not the subject
30123of @var{part-handlers}; such parameter values are always turned into a string.
30124@c JP
30125ファイルアップロード以外のパラメータは@var{part-handlers}の対象外である
30126ことに注意して下さい。それらのパラメータの値は常に文字列へと変換されます。
30127@c COMMON
30128
30129
30130@c EN
30131Here's a short example.  Suppose you have a form like this:
30132@c JP
30133簡単な例を示します。例えば次のようなフォームがあったとします。
30134@c COMMON
30135
30136@example
30137<form enctype="multipart/form-data" method="POST" action="mycgi.cgi">
30138<input type="file" name="imagefile" />
30139<input type="text" name="description" />
30140<input type="hidden" name="mode" value="normal" />
30141</form>
30142@end example
30143
30144@c EN
30145If you use @code{cgi-parse-parameters} in @file{mycgi.cgi}
30146without @var{part-handlers} argument,
30147you'll get something like the following as the result.
30148(The actual values depend on how the web client filled the form).
30149@c JP
30150@file{mycgi.cgi}内で、@code{cgi-parse-parameters}を
30151@var{part-handlers}引数なしで使った場合は、
30152例えば次のようなリストがパラメータパージングの結果として得られるでしょう。
30153(実際の値は、webクライアントがどのようにフォームを埋めたかに依存します)。
30154@c COMMON
30155
30156@example
30157(("imagefile" #*".....(image file content as a string)....")
30158 ("description" "my image")
30159 ("mode" "normal"))
30160@end example
30161
30162@c EN
30163If you pass @code{'(("imagefile" file :prefix "/tmp/mycgi"))}
30164to @var{part-handlers}
30165instead,
30166you might get something like the following, with the
30167content of uploaded file saved in @file{/tmp/mycgi7gq0B}
30168@c JP
30169ここでもし、@code{'(("imagefile" file :prefix "/tmp/mycgi"))}を
30170@var{part-handlers}に
30171渡したなら、替わりに次のような結果が得られるでしょう。
30172ここで、アップロードされたファイルは@file{/tmp/mycgi7gq0B}にセーブ
30173されていることになります。
30174@c COMMON
30175
30176@example
30177(("imagefile" "/tmp/mycgi7gq0B")
30178 ("description" "my image")
30179 ("mode" "normal"))
30180@end example
30181
30182@c EN
30183If you use a symbol @code{file+name} instead of @code{file} above,
30184you'll get something like @code{("/tmp/mycgi7gq0B" "logo.jpg")} as
30185the value of @code{"imagefile"}, where @code{"logo.jpg"} is the
30186client-side filename.   (Note: the client can send any string
30187as the name of the file, so @emph{never} assume it is a valid
30188pathname).
30189@c JP
30190上の例でシンボル@code{file}のかわりに@code{file+name}を使えば、
30191例えば@code{"imagefile"}の値として@code{("/tmp/mycgi7gq0B" "logo.jpg")}
30192のようなものが得られるでしょう。ここで@code{"logo.jpg"}は
30193アップロードされたファイルのクライアント側でのパス名です。
30194(注意:クライアントは任意の文字列をファイル名として送信することが
30195できるため、その文字列が有効なパス名であることを仮定してはなりません。)
30196
30197@c COMMON
30198
30199@c @c EN
30200@c Now, you pass the following structure to @var{part-handlers}:
30201@c @c JP
30202@c 次のような構造を@var{part-handlers}に渡した場合:
30203@c @c COMMON
30204
30205@c @example
30206@c `(("imagefile"
30207@c   ,(lambda (name fname info iport)
30208@c      (receive (outp tmpfile) (sys-mkstemp "/var/log/mycgi/tmp")
30209@c        (mime-retrieve-body info iport outp)
30210@c        (close-output-port outp)
30211@c        (cgi-add-temporary-file tmpfile)
30212@c        (string-append fname ":" tmpfile))))
30213@c  )
30214@c @end example
30215
30216@c @c EN
30217@c You'll get something like the following; i.e. the cgi application
30218@c can see the client-side file name as well as the temporary file name.
30219@c @c JP
30220@c 例えば次のようなパーズ結果が得られるでしょう。つまり、
30221@c cgiアプリケーションは一時ファイル名と同時に
30222@c クライアント側でのファイル名も参照することができます。
30223@c @c COMMON
30224
30225@c @example
30226@c (("imagefile" "logo.jpg:/var/log/mycgi/tmp820iQj")
30227@c  ("description" "my image")
30228@c  ("mode" "normal"))
30229@c @end example
30230
30231
30232@c ----------------------------------------------------------------------
30233@node CGI testing, CSS parsing and construction, CGI utility, Library modules - Utilities
30234@section @code{www.cgi.test} - CGI testing
30235@c NODE CGIのテスト, @code{www.cgi.test} - CGIのテスト
30236
30237@deftp {Module} www.cgi.test
30238@mdindex www.cgi.test
30239@c EN
30240This module defines a useful procedures to test CGI script.
30241The test actually runs the named script, with specified environment
30242variable settings, and retrieve the output.  Your test procedure
30243then examine whether the output is as expected or not.
30244@c JP
30245CGIスクリプトをテストするための便利な手続きを定義しています。
30246このテストは、指定された環境変数をセットし、実際にスクリプトを
30247実行し、出力を取得します。ユーザのテスト手続きは、その出力が
30248期待したものであるかどうかを検査します。
30249@c COMMON
30250@end deftp
30251
30252@defun cgi-test-environment-ref envvar-name
30253@defunx {(setter cgi-test-environment-ref)} envvar-name value
30254@c MOD www.cgi.test
30255@c EN
30256The module keeps a table of default values of environment variables
30257with which the cgi script will be run.  These procedures allow
30258the programmer to get/set those default values.
30259
30260Note that you can override these default values and/or pass additional
30261environment variables for each call of cgi script.
30262@c JP
30263モジュールにより、CGIスクリプトが実行される際の環境変数の
30264デフォルト値のテーブルが保持されます。プログラマは、これらの
30265手続きを使ってそのデフォルト値を取得したり設定したりできます。
30266
30267CGIスクリプトの呼び出し毎に、これらのデフォルト値を上書きしたり、
30268追加の環境変数を渡したりできます。
30269
30270@c EN
30271The following environment variables are set by default.
30272@c JP
30273デフォルトでは、下記の環境変数が設定されています。
30274@c COMMON
30275@multitable @columnfractions .5 .5
30276@item Name @tab Value
30277@item @code{SERVER_SOFTWARE}
30278@tab @code{cgitest/1.0}
30279@item @code{SERVER_NAME}
30280@tab @code{localhost}
30281@item @code{GATEWAY_INTERFACE}
30282@tab @code{CGI/1.1}
30283@item @code{SERVER_PROTOCOL}
30284@tab @code{HTTP/1.1}
30285@item @code{SERVER_PORT}
30286@tab @code{80}
30287@item @code{REQUEST_METHOD}
30288@tab @code{GET}
30289@item @code{REMOTE_HOST}
30290@tab @code{remote}
30291@item @code{REMOTE_ADDR}
30292@tab @code{127.0.0.1}
30293@end multitable
30294@end defun
30295
30296@defun call-with-cgi-script script proc :key (environment ()) (parameters #f)
30297@c MOD www.cgi.test
30298@c EN
30299Runs a script with given environment, and calls @var{proc} with
30300one argument, an input port which is connected to the pipe of script's
30301standard output.
30302@c JP
30303与えられた環境でスクリプトを実行し、そのスクリプトの標準出力のパイプに
30304接続された入力ポートを1つ引数に取る @var{proc} を呼び出します。
30305
30306@c EN
30307The argument @var{script} should be a list of
30308program name and its arguments.  Each element are
30309passed to @code{x->string} first to stringify.
30310@c JP
30311引数 @var{script} は、プログラムの名前とその引数のリストでなければ
30312なりません。リストの要素はそれぞれ、文字列化されるためにまず
30313@code{x->string}に渡されます。
30314
30315@c EN
30316The script is run under the environment given by @var{environment}
30317variable and the default test environment described above.
30318The @var{environment} argument must be an associative list, in which each
30319key (@code{car}) is the name of the environment variable and
30320its @code{cdr} is the value.  Both are passed to @code{x->string} first.
30321If the same environment variable appears in @var{environment} and
30322the default test environment, the one in @var{environment} is used.
30323@c JP
30324スクリプトは、変数 @var{environment} で与えられる環境と、上述した
30325デフォルトのテスト環境の下で実行されます。
30326@var{environment}は、キー(@code{car})がその環境変数の名前、
30327@code{cdr}が対応する値であるような連想リストでなければなりません。
30328両方ともまず @code{x->string} に渡されます。
30329@var{environment} とデフォルトのテスト環境に同じ環境変数がある場合は、
30330@var{environment} にあるものが使われます。
30331
30332@c EN
30333Additionally, if an associative list is given to the @var{parameters}
30334argument, a query string is built from it and passed the script.
30335The actual method to pass the query string depends on the value
30336of @code{REQUEST_METHOD} environment variable in the setting.
30337If @code{REQUEST_METHOD} is either @code{GET} or @code{HEAD},
30338the query string is put in an environment variable @code{QUERY_STRING}.
30339If it is @code{POST}, the query string is fed to the standard
30340input of the script.  In the latter case, @code{CONTENT_TYPE}
30341is set to @code{application/x-www-form-urlencoded} and
30342@code{CONTENT_LENGTH} are set to the length of @code{QUERY_STRING}
30343automatically.  If @code{REQUEST_METHOD} is other values,
30344@var{parameters} is ignored.
30345You can bypass this mechanism and set up environment variable
30346@code{QUERY_STRING} directly, if you wish.
30347@c JP
30348さらに、引数 @var{parameters} に連想リストが渡された場合、そこから
30349クエリストリングが作られスクリプトに渡されます。
30350クエリストリングを渡す実際のメソッドは、環境変数 @code{REQUEST_METHOD}の
30351値に依存します。@code{REQUEST_METHOD} が @code{GET} か @code{HEAD} で
30352ある場合は、クエリストリングは環境変数 @code{QUERY_STRING} に置かれます。
30353@code{REQUEST_METHOD} が @code{POST} の場合は、クエリストリングは
30354スクリプトの標準入力から取得されます。後者の場合、@code{CONTENT_TYPE} には
30355@code{application/x-www-form-urlencoded}が、
30356@code{CONTENT_LENGTH} には @code{QUERY_STRING}の長さが、それぞれ自動的に
30357セットされます。@code{REQUEST_METHOD} がその他の値の場合は、
30358@var{parameters} は無視されます。
30359必要であれば、このメカニズムをバイパスして、環境変数 @code{QUERY_STRING} を
30360直接セットアップすることも可能です。
30361@c COMMON
30362@end defun
30363
30364@defun run-cgi-script->header&body script reader :key environment parameters
30365@c MOD www.cgi.test
30366@c EN
30367A convenient wrapper of @code{call-with-cgi-script}.
30368The @var{script}, @var{environment} and @var{parameters} are passed
30369to @code{call-with-cgi-script} as they are.
30370The output of the script is parsed by
30371@code{run-cgi-script->header&body}.
30372First, the RFC2822 header fields are parsed by
30373@code{rfc822-read-headers} (@pxref{RFC822 message parsing}).
30374Then, the @var{reader} is called with an input port which
30375is piped to the script's output.
30376@c JP
30377@code{call-with-cgi-script} の便利なラッパー手続きです。
30378@var{script}、@var{environment}、@var{parameters}は、
30379そのまま @code{call-with-cgi-script}に渡されます。
30380スクリプトの出力は、@code{run-cgi-script->header&body}により
30381パーズされます。
30382最初に、RFC2822ヘッダフィールドが @code{rfc822-read-headers}
30383(@ref{RFC822 message parsing}参照)によりパーズされます。
30384次に、@var{reader}が、スクリプトの出力にパイプされた入力ポートと
30385ともに呼ばれます。
30386
30387@c EN
30388@code{Run-cgi-script->header&body} returns two values,
30389the list of headers (as parsed by @code{rfc822-read-headers}),
30390and the return value of @var{reader}.
30391@c JP
30392@code{run-cgi-script->header&body}は、ヘッダのリスト
30393(@code{rfc822-read-headers}によりパーズされたもの)と
30394@var{reader}の戻り値の2つの値を返します。
30395@c COMMON
30396@end defun
30397
30398@defun run-cgi-script->sxml script :key environment parameters
30399@c MOD www.cgi.test
30400@c EN
30401This is a procedure that uses @code{ssax:xml->sxml}
30402(@pxref{Functional XML parser}) as the @var{reader}
30403in @code{run-cgi-script->header&body}.
30404Useful when you're testing a cgi script that produces
30405well-formed HTML and/or XML document.
30406@c JP
30407この手続きでは、@code{run-cgi-script->header&body}の
30408@var{reader}として、@code{ssax:xml->sxml}
30409(@ref{Functional XML parser}参照)を使います。
30410整形式(Well-formed)のHTMLやXMLドキュメントを生成する
30411CGIスクリプトをテストする場合に便利です。
30412@c COMMON
30413@end defun
30414
30415@defun run-cgi-script->string script :key environment parameters
30416@defunx run-cgi-script->string-list script :key environment parameters
30417@c MOD www.cgi.test
30418@c EN
30419These procedures use @code{port->string}
30420and @code{port->string-list}
30421(@pxref{Input utility functions}) as the @var{reader}
30422in @code{run-cgi-script->header&body}, respectively.
30423@c JP
30424これらの手続きは、@code{run-cgi-script->header&body}の
30425@var{reader}として、それぞれ @code{port->string}、
30426@code{port->string-list}を使います。
30427@c COMMON
30428@end defun
30429
30430@c EN
30431An example:
30432@c JP
30433例:
30434@c COMMON
30435@example
30436(run-cgi-script->string-list "bbs.cgi"
30437                             :environment '((REMOTE_ADDR . "12.34.56.78"))
30438                             :parameters '((command . "view")
30439                                           (page . 1234)))
30440@end example
30441
30442
30443@c ----------------------------------------------------------------------
30444@node CSS parsing and construction,  , CGI testing, Library modules - Utilities
30445@section @code{www.css} - CSS parsing and construction
30446@c NODE CSSのパーズと構築, @code{www.css} - CSSのパーズと構築
30447
30448@deftp {Module} www.css
30449@c EN
30450This module provides tools to convert between S-expression and CSS.
30451
30452The S-expression CSS (SxCSS) is a convenient way to manipulate
30453CSS in Scheme.
30454@c JP
30455このモジュールはS式とCSSを相互変換するツールを提供します。
30456
30457S式CSS(SxCSS)はCSSをSchemeから操作するのに便利な方法です。
30458@c COMMON
30459@end deftp
30460
30461@c EN
30462For example, the following CSS and SxCSS are equivalent, and
30463can be converted back and forth:
30464@c JP
30465例えば、次のCSSとSxCSSは等価で、相互に変換可能です。
30466@c COMMON
30467
30468CSS:
30469@example
30470body @{ padding-left: 11em;
30471       font-family: Georgia, "Times New Roman", Times, serif;
30472       color: purple;
30473       background-color: #d8da3d @}
30474ul.navbar li @{ background: white;
30475               margin: 0.5em 0;
30476               padding: 0.3em;
30477               border-right: 1em solid black @}
30478ul#spec > a @{ text-decoration: none @}
30479a:visited @{ color: purple !important @}
30480@end example
30481
30482SxCSS:
30483@example
30484((style-rule body
30485   (padding-left (11 em))
30486   (font-family (:or Georgia "Times New Roman" Times serif))
30487   (color purple)
30488   (background-color (color "d8da3d")))
30489 (style-rule ((ul (class navbar)) li)
30490   (background white)
30491   (margin #((0.5 em) 0))
30492   (padding (0.3 em))
30493   (border-right #((1 em) solid black)))
30494 (style-rule ((ul (id spec)) > a) (text-decoration none))
30495 (style-rule (a (: visited)) (color purple !important)))
30496@end example
30497
30498@c EN
30499See the ``CSS in S-expression'' section below for the complete
30500specification.
30501@c JP
30502完全な仕様については下の ``S式CSS'' を参照してください。
30503@c COMMON
30504
30505@c EN
30506@subheading Constructing CSS
30507@c JP
30508@subheading CSSの構築
30509@c COMMON
30510
30511@defun construct-css sxcss :optional oport
30512@c MOD www.css
30513@c EN
30514Take SxCSS and writes out CSS to the given port, defaulted to
30515the current output port.
30516@c JP
30517SxCSSを取り、与えられたポートにCSSを書き出します。@var{oport}のデフォルトは
30518現在の出力ポートです。
30519@c COMMON
30520@end defun
30521
30522@c EN
30523@subheading Parsing CSS
30524@c JP
30525@subheading CSSのパーズ
30526@c COMMON
30527
30528@defun parse-css :optional iport
30529@c MOD www.css
30530@c JP
30531Read CSS from the given port, defaulted to the current input port,
30532and returns SxCSS.
30533
30534When it encounters unparsable CSS (either a malformed CSS, or
30535unsupported syntax), it emits a warning message, ignore the
30536unparsable part and tries to continue reading the rest.
30537
30538NB: Currently we don't handle @code{@@charset} directive; we assume
30539the text is already in the port's encoding.  We may support
30540it in future versions.
30541@c JP
30542CSSを与えられたポートから読み、SxCSSを返します。@var{iport}のデフォルトは
30543現在の入力ポートです。
30544
30545パーズできないCSS (不正なCSSか、サポートされていない構文) に出会った場合、
30546warningメッセージを出力してその箇所を飛ばし、次にパーズできるところから処理を続けます。
30547
30548註:今のところ、@code{@@charset}ディレクティブは無視され、
30549入力テキストはポートのエンコーディングであると仮定されます。将来は対応するかもしれません。
30550@c COMMON
30551@end defun
30552
30553@defun parse-css-file file :key encoding
30554@c MOD www.css
30555@c EN
30556Read the CSS text from the given file and parse it using
30557@code{parse-css}.  Again, we don't handle @code{@@charset} directive
30558yet, and you have to pass @code{encoding} argument if
30559the CSS text isn't in the Gauche's native character encoding.
30560@c JP
30561与えられたファイルからCSSを読み、@code{parse-css}を使ってパーズして結果をSxCSSで
30562返します。@code{@@charset}ディレクティブはまだ認識されないので、
30563CSSファイルがGaucheのネイティブエンコーディングと異なるエンコーディングで書かれている
30564場合は、@var{encoding}にエンコーディング名を渡してください。
30565@c COMMON
30566@end defun
30567
30568@defun parse-css-selector-string str
30569@c MOD www.css
30570@c EN
30571This parses the selector part of the CSS.
30572@c JP
30573CSSのセレクター部分をパーズするユーティリティです。
30574@c COMMON
30575
30576@example
30577(parse-css-selector-string "ul li.item span#foo")
30578  @result{} (ul (li (class item)) (span (id foo)))
30579
30580(parse-css-selector-string "h1,h2")
30581  @result{} (:or h1 h2)
30582@end example
30583@end defun
30584
30585@c EN
30586@subheading CSS in S-expression
30587@c JP
30588@subheading S式CSS
30589@c COMMON
30590
30591@c EN
30592The following is the complete rules of SxCSS syntax.
30593@c JP
30594完全なSxCSSの構文規則を以下に示します。
30595@c COMMON
30596
30597@smallexample
30598<sxcss>      : (@{<style-rule> | <at-rule>@} ...)
30599
30600<style-rule> : (style-rule <pattern> <declaration> ...)
30601             | (style-decls <declaration> ...)
30602
30603<pattern>   : <selector> | (:or <selector> ...)
30604<selector>  : <simple-selector>
30605            | <chained-selector>
30606<chained-selector> : (<simple-selector> . (<op>? . <chained-selector>))
30607<op>        : > | + | ~
30608<simple-selector> : <element-name>
30609            | (<element-name> <option> ...)
30610<option>    : (id <name>)                           ; E#id
30611            | (class <ident>)                       ; E.class
30612            | (has <ident>)                         ; E[attrib]
30613            | (= <ident> <attrib-value>)            ; E[attrib=val]
30614            | (~= <ident> <attrib-value>)           ; E[attrib~=val]
30615            | (:= <ident> <attrib-value>)           ; E[attrib|=val]
30616            | (*= <ident> <attrib-value>)           ; E[attrib*=val]
30617            | (^= <ident> <attrib-value>)           ; E[attrib^=val]
30618            | ($= <ident> <attrib-value>)           ; E[attrib$=val]
30619            | (:not <negation-arg>)                 ; E:not(s)
30620            | (: <ident>)                           ; E:pseudo-class
30621            | (: (<fn> <ident> ...))                ; E:pseudo-class(arg)
30622            | (:: <ident>)                          ; E::pseudo-element
30623<element-name> : <ident> | *
30624<attrib-value> : <ident> | <string>
30625<negation-arg> | <element-name> | * | <option>  ; except <negation-arg>
30626
30627<declaration>  : (<ident> <expr> <expr2> ... <important>?)
30628<important> : !important
30629<expr>      : <term>
30630            | (/ <term> <term> ...)
30631            | (:or <term> <term> ...)
30632            | #(<term> <term> ...)             ; juxtaposition
30633<term>      : <quantity> | (- <quantity>) | (+ <quantity>)
30634            | <string> | <ident> | <url> | <hexcolor> | <function>
30635<quantity>  : <number>
30636            | (<number> %)
30637            | (<number> <ident>)
30638<url>       | (url <string>)
30639<hexcolor>  | (color <string>)  ; <string> must be hexdigits
30640<function>  | (<fn> <arg> ...)
30641<arg>       | <term> | #(<term> ...) | (/ <term> <term> ...)
30642
30643<at-rule>    : <at-media-rule> | <at-import-rule>
30644                   ; NB: Other at-rules are not supported yet
30645<at-media-rule>  : (@@media (<symbol> ...) <style-rule> ...)
30646<at-import-rule> : (@@import <string> (<symbol> ...))
30647@end smallexample
30648
30649@c EN
30650NB: Negation op is @code{:not} instead of @code{not},
30651since @code{(not <negation-arg>)}
30652would be ambiguous from the simple node named "not" with one option.
30653@c JP
30654註: 否定オペレータは@code{not}ではなく@code{:not}です。
30655というのは、@code{(not <negation-arg>)}だと ``not'' と言う名前を持ち
30656一つのオプションを持つノードと区別できないからです。
30657@c COMMON
30658
30659@c EN
30660NB: @code{style-decls} selector rule is currently won't appear in
30661the @code{parse-css} output; it can be used in SxCSS to make
30662@code{construct-css} render declarations only, which can be
30663used in the @code{style} attribute of the document, for example.
30664@c JP
30665註: @code{style-decls}セレクタルールは@code{parse-css}の出力には
30666現れません。
30667ドキュメントの@code{style}属性に渡すCSS断片を生成したい場合に、
30668@code{(style-decls <declaration> ...)}を@code{construct-css}に渡します。
30669@c COMMON
30670@example
30671(with-output-to-string
30672 (cut construct-css
30673      '((style-decls (width (50 %))
30674                     (padding #(0 (10 pt) 0 (10 pt)))))))
30675  @result{} "width:50%;padding:0 10pt 0 10pt"
30676@end example
30677
30678@c Local variables:
30679@c mode: texinfo
30680@c coding: utf-8
30681@c end:
30682