Debian Codegraph @

doc/modutil.texi

raw
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 * Backward-compatible real elementary functions:: compat.real-elementary-functions
13 * Concurrent sequences:: control.cseq
14 * Futures:: control.future
15 * A common job descriptor for control modules:: control.job
16 * Plumbing ports:: control.plumbing
17 * Parallel map:: control.pmap
18 * Scheduler:: control.scheduler
19 * Thread pools:: control.thread-pool
20 * Password hashing:: crypt.bcrypt
21 * Cache:: data.cache
22 * Heap:: data.heap
23 * Immutable deques:: data.ideque
24 * Immutable map:: data.imap
25 * Priority map:: data.priority-map
26 * Queue:: data.queue
27 * Random data generators:: data.random
28 * Range:: data.range
29 * Ring buffer:: data.ring-buffer
30 * Skew binary random-access lists:: data.skew-list
31 * Sparse data containers:: data.sparse
32 * Trie:: data.trie
33 * Universally unique lexicographically sortable identifier:: data.ulid
34 * Database independent access layer:: dbi
35 * Generic DBM interface:: dbm
36 * File-system dbm:: dbm.fsdbm
37 * GDBM interface:: dbm.gdbm
38 * NDBM interface:: dbm.ndbm
39 * Original DBM interface:: dbm.odbm
40 * Filtering file content:: file.filter
41 * Filesystem utilities:: file.util
42 * Mathematical constants:: math.const
43 * Mersenne-Twister random number generator:: math.mt-random
44 * Prime numbers:: math.prime
45 * Simplex solver:: math.simplex
46 * Windows support:: os.windows
47 * PEG parser combinators:: parser.peg
48 * RFC822 message parsing:: rfc.822
49 * Base64 encoding/decoding:: rfc.base64
50 * HTTP cookie handling:: rfc.cookie
51 * FTP:: rfc.ftp
52 * HMAC keyed-hashing:: rfc.hmac
53 * HTTP client:: rfc.http
54 * ICMP packets:: rfc.icmp
55 * IP packets:: rfc.ip
56 * JSON parsing and construction:: rfc.json
57 * MD5 message digest:: rfc.md5
58 * MIME message handling:: rfc.mime
59 * Quoted-printable encoding/decoding:: rfc.quoted-printable
60 * SHA message digest:: rfc.sha
61 * Transport layer security:: rfc.tls
62 * URI parsing and construction:: rfc.uri
63 * UUID:: rfc.uuid
64 * Zlib compression library:: rfc.zlib
65 * SLIB:: slib
66 * Functional XML parser:: sxml.ssax
67 * SXML query language:: sxml.sxpath
68 * Manipulating SXML structure:: sxml.tools
69 * Serializing XML and HTML from SXML:: sxml.serializer
70 * Text terminal control:: text.console
71 * CSV tables:: text.csv
72 * Calculate difference of text streams:: text.diff
73 * EDN parsing and construction:: text.edn
74 * Running external editor:: text.external-editor
75 * Text filling:: text.fill
76 * Gap buffer:: text.gap-buffer
77 * Localized messages:: text.gettext
78 * Simple HTML document construction:: text.html-lite
79 * Accessing info document:: text.info
80 * Multicolumn formatting:: text.multicolumn
81 * Display with pager:: text.pager
82 * Parsing input stream:: text.parse
83 * Showing progress on text terminals:: text.progress
84 * Segmented string matching:: text.segmented-match
85 * Shell text utilities:: text.sh
86 * SQL parsing and construction:: text.sql
87 * Simple template expander:: text.template
88 * Transliterate characters:: text.tr
89 * Lazy text construction:: text.tree
90 * Combination library:: util.combinations
91 * Message digester framework:: util.digest
92 * Calculate dominator tree:: util.dominator
93 * R6RS identifier syntax:: util.identifier-syntax
94 * Determine isomorphism:: util.isomorph
95 * The longest common subsequence:: util.lcs
96 * Levenshtein edit distance:: util.levenshtein
97 * Pattern matching:: util.match
98 * SLIB-compatible record type:: util.record
99 * Relation framework:: util.relation
100 * Stream library:: util.stream
101 * Temporal relation:: util.temporal-relation
102 * Topological sort (legacy):: util.toposort
103 * Unification:: util.unification
104 * CGI utility:: www.cgi
105 * CGI testing:: www.cgi.test
106 * CSS parsing and construction:: www.css
107 @end menu
108
109 @c ----------------------------------------------------------------------
110 @node Binary I/O, Packing binary data, Library modules - Utilities, Library modules - Utilities
111 @section @code{binary.io} - Binary I/O
112 @c NODE バイナリI/O, @code{binary.io} - バイナリI/O
113
114 @deftp {Module} binary.io
115 @mdindex binary.io
116 @c EN
117 This module provides basic procedures to perform binary I/O
118 of numeric data. Each datum can be read from or written to a port,
119 and got from or put to a uniform vector (see @ref{Uniform vectors}).
120 For structured binary data I/O,
121 more convenient @code{pack} utility is implemented
122 on top of this module (see @ref{Packing binary data}).
123 You might want to use this module directly if you need
124 speed or want a flexible control of endianness.
125
126 See also @ref{Uniform vectors}, which provides binary block I/O.
127 @c JP
128 このモジュールは数値データを読み書きするバイナリ入出力用の基本手続きを提
129 供します。各データはポートあるいはユニフォームベクタ
130 (@ref{Uniform vectors}参照)から読み込み、あるいはそれらへ書き出すことが
131 できます。
132 構造をもつバイナリデータの入出力については、便利な
133 @code{pack}ユーティリティがこのモジュールを使って実装されています
134 (@ref{Packing binary data}を参照してください)。
135 スピードあるいはエンディアンの柔軟な制御などをやりたいときにこのモジュー
136 ルが使えます。
137
138 バイナリのブロック入出力については@ref{Uniform vectors}を参照してくだ
139 さい。
140 @c COMMON
141 @end deftp
142
143 @c EN
144 @subheading Endianness
145 Most procedures of this module take an optional @var{endian} argument,
146 specifying the byte order of the binary input.
147 It must be either one of symbols @code{big-endian}, @code{little-endian},
148 or @code{arm-little-endian}.
149 If the endian argument is omitted, the current value of the builtin
150 parameter @code{default-endian} is used (@pxref{Endianness}).
151 (For 8-bit I/O procedures like @code{read-u8} the endian
152 argument has no effect, but is accepted for consistency).
153 @c JP
154 @subheading エンディアン
155 このモジュールのほとんどの手続はオプション引数として@var{endian}引数を
156 とります。これは@code{big-endian}、@code{little-endian}、
157 @code{arm-little-endian}のいずれかのシンボルでなければなりません。
158 エンディアン引数が省略された場合には、組込みパラメータ@code{default-endian}
159 の現在値が使われます (@ref{Endianness}参照)。
160 (@code{read-u8}の ような
161 8ビット入出力手続ではエンディアン引数は意味がありませんが、
162 一貫性のため受け入れるようにしてあります。)
163 @c COMMON
164
165 @c EN
166 @subheading I/O using port
167 @c JP
168 @subheading ポートを用いたI/O
169 @c COMMON
170
171 @defun read-u8 :optional port endian
172 @defunx read-u16 :optional port endian
173 @defunx read-u32 :optional port endian
174 @defunx read-u64 :optional port endian
175 @c MOD binary.io
176 @c EN
177 Reads 8, 16, 32 or 64 bit unsigned integer from @var{port}
178 with specified endian, respectively. If @var{port} is omitted,
179 current input port is used. If @var{port} reaches EOF before
180 a complete integer is read, EOF is returned.
181 @c JP
182 それぞれ指定したエンディアンで@var{port}から8、16、32、64ビット符号無
183 整数を読み込みます。@var{port}が省略された場合は、現在の入力ポートが使
184 われます。@var{port}が整数の読み込みが完了する前にEOFに到達してしまっ
185 た場合にはEOFが返ります。
186 @c COMMON
187 @end defun
188
189 @defun read-s8 :optional port endian
190 @defunx read-s16 :optional port endian
191 @defunx read-s32 :optional port endian
192 @defunx read-s64 :optional port endian
193 @c MOD binary.io
194 @c EN
195 Reads 8, 16, 32 or 64 bit 2's complement signed integer from @var{port}
196 with specified endian, respectively. If @var{port} is omitted,
197 current input port is used. If @var{port} reaches EOF before
198 a complete integer is read, EOF is returned.
199 @c JP
200 それぞれ指定したエンディアンで@var{port}から8、16、32、64ビット、2の補
201 数符号付き整数を読み込みます。@var{port}が省略された場合は、現在の入力
202 ポートが使われます。@var{port}が整数の読み込みが完了する前にEOFに到
203 達してしまった場合にはEOFが返ります。
204 @c COMMON
205 @end defun
206
207 @defun read-uint size :optional port endian
208 @defunx read-sint size :optional port endian
209 @c MOD binary.io
210 @c EN
211 More flexible version. Reads @var{size}-octet unsigned
212 or signed integer from @var{port} with specified endian.
213 If @var{port} reaches EOF before a complete integer is read,
214 EOF is returned.
215 @c JP
216 さらに柔軟性が高く、@var{size}オクテットの符号無しあるいは符号付き整数
217 を@var{port}から指定のエンディアンで読み込みます。
218 @var{port}が整数の読み込みが完了する前にEOFに到
219 達してしまった場合にはEOFが返ります。
220 @c COMMON
221 @end defun
222
223 @defun read-ber-integer :optional port
224 @c MOD binary.io
225 @c EN
226 Reads BER compressed integer a la X.209.
227 A BER compressed integer is an unsigned integer in base 128,
228 most significant digit first, where the high bit is set on all but the
229 final (least significant) byte.
230 @c JP
231 X.209のBER圧縮形式整数を読み込みます。BER圧縮形式整数は128進符号無し整
232 数です。最上位桁が最初にきます。最下位桁のバイトをのぞき、すべてのバイ
233 トの最上位ビットはオンになっています。
234 @c COMMON
235 @end defun
236
237 @defun write-u8 val :optional port endian
238 @defunx write-u16 val :optional port endian
239 @defunx write-u32 val :optional port endian
240 @defunx write-u64 val :optional port endian
241 @c MOD binary.io
242 @c EN
243 Writes a nonnegative integer @var{val} as 8, 16, 32 or 64 bit
244 unsigned integer
245 to @var{port} with specified endian, respectively. @var{Val} must be within
246 the range of integers representable by the specified bits.
247 When @var{port} is omitted, current output port is used.
248 @c JP
249 それぞれ指定したエンディアンで@var{port}へ 8、16、32、64ビット、符号無
250 し整数として表現されている非負整数@var{val}を書き出します。
251 @var{val}はそれぞれ指定したビット数の範囲で表現できる値でなければなり
252 ません。@var{port}が省略された場合は、現在の出力ポートが使われます。
253 @c COMMON
254 @end defun
255
256 @defun write-s8 val :optional port endian
257 @defunx write-s16 val :optional port endian
258 @defunx write-s32 val :optional port endian
259 @defunx write-s64 val :optional port endian
260 @c MOD binary.io
261 @c EN
262 Writes an integer @var{val} as 8, 16, 32 or 64 bit
263 as 2's complement signed integer to @var{port} with specified endian,
264 respectively. @var{Val} must be within
265 the range of integers representable by the specified bits.
266 When @var{port} is omitted, current output port is used.
267 @c JP
268 それぞれ指定したエンディアンで@var{port}へ 8、16、32、64ビット、2の補
269 数符号付き整数として表現されている整数@var{val}を書き出します。
270 @var{val}はそれぞれ指定したビット数の範囲で表現できる値でなければなり
271 ません。@var{port}が省略された場合は、現在の出力ポートが使われます。
272 @c COMMON
273 @end defun
274
275 @defun write-uint size val :optional port endian
276 @defunx write-sint size val :optional port endian
277 @c MOD binary.io
278 @c EN
279 More flexible version. Writes an integer @var{val} as unsigned
280 or signed integer of @var{size} bytes to @var{port} with
281 specified endian.
282 When @var{port} is omitted, current output port is used.
283 @c JP
284 さらに柔軟性が高く、@var{size}オクテットの符号無しあるいは符号付き整数
285 @var{val}を@var{port}へ、指定のエンディアンで書き出します。
286 @var{port}が省略された場合は、現在の出力ポートが使われます。
287 @c COMMON
288 @end defun
289
290 @defun write-ber-integer val :optional port
291 @c MOD binary.io
292 @c EN
293 Writes a nonnegative integer @var{val} in BER compressed integer
294 to @var{port}. See @code{read-ber-integer} above for BER format.
295 @c JP
296 BER圧縮形式の非負整数@var{val}を@var{port}へ書き出します。
297 BER圧縮形式については前述の@code{read-ber-integer}を見てください。
298 @c COMMON
299 @end defun
300
301 @defun read-f16 :optional port endian
302 @defunx read-f32 :optional port endian
303 @defunx read-f64 :optional port endian
304 @c MOD binary.io
305 @c EN
306 Reads 16, 32, or 64-bit floating point numbers, respectively.
307 32bit is IEEE754 single-precision, and 64bit is
308 IEEE754 double-precision numbers. 16-bit floating
309 point number consists of 1-bit sign, 5-bit exponent and
310 10-bit mantissa, as used in some HDR image format.
311
312 If @var{port} is omitted,
313 current input port is used. If @var{port} reaches EOF before
314 a complete number is read, EOF is returned.
315 @c JP
316 それぞれ、16、32、64ビットの浮動小数点数を読み込みます。
317 32ビットはIEEE754単精度、64ビットは倍精度の浮動小数点数です。
318 16ビット浮動小数点数は、1ビットの符号、5ビットの指数、10ビットの仮数からなる、
319 HDRイメージフォーマット等に使われている形式です。
320
321 @var{port}が省略された場合には、
322 現在の入力ポートが使われます。@var{port}が数値の読み込みが完了する前に
323 EOFに到達してしまった場合にはEOFが返ります。
324 @c COMMON
325 @end defun
326
327 @defun write-f16 val :optional port endian
328 @defunx write-f32 val :optional port endian
329 @defunx write-f64 val :optional port endian
330 @c MOD binary.io
331 @c EN
332 Writes a real number @var{val} to @var{port} in 16,
333 32, or 64-bit floating point number, respectively.
334 If @var{port} is omitted, current output port is used.
335 @c JP
336 実数値@var{val}を、それぞれ16、32、64ビットの浮動小数点数として
337 書き出します。
338 @var{port}が省略された場合には、現在の出力ポートが使われます。
339 @c COMMON
340 @end defun
341
342
343 @c EN
344 @subheading I/O using uniform vectors
345 @c JP
346 @subheading ユニフォームベクタを用いたI/O
347 @c COMMON
348
349 @c EN
350 In the following routines, the argument @var{uv} can be any
351 type of uniform vector; if it is not a @code{u8vector}, it is
352 treated as if @code{(uvector-alias <u8vector> @var{uv})} is
353 called---that is, it reads directly from the memory image
354 that holds the uvector's content. The @var{pos} argument
355 specifies the byte position from the beginning of the memory
356 area (it is always byte position, regardless of the uniform
357 vector's element size).
358 @c JP
359 以下のルーチンでは、引数 @var{uv} は任意の型のユニフォームベクタをとり
360 えます。@code{u8vector} ではない場合には @code{(uvector-alias
361 <u8vector> @var{uv})} が呼ばれたのと同様の扱いになります。すなわち、
362 uvectorの内容を保持するメモリイメージから直接読み込まれます。@var{pos}
363 引数は当該のメモリ領域の最初からのバイト位置を指定するのに使います(こ
364 れはユニフォームベクタの要素のサイズにかかわらず、つねにバイト位置です)。
365 @c COMMON
366
367 @defun get-u8 uv pos :optional endian
368 @defunx get-u16 uv pos :optional endian
369 @defunx get-u32 uv pos :optional endian
370 @defunx get-u64 uv pos :optional endian
371 @defunx get-s8 uv pos :optional endian
372 @defunx get-s16 uv pos :optional endian
373 @defunx get-s32 uv pos :optional endian
374 @defunx get-s64 uv pos :optional endian
375 @defunx get-f16 uv pos :optional endian
376 @defunx get-f32 uv pos :optional endian
377 @defunx get-f64 uv pos :optional endian
378 @c MOD binary.io
379 @c EN
380 Reads a number of a specific format from a uniform vector @var{uv},
381 starting at a byte position @var{pos}. An error is signaled
382 if the specified position makes reference outside of the uniform
383 vector's content. Returns the read number.
384 @c JP
385 ユニフォームベクタ @var{uv} のバイト位置 @var{pos} から指定したフォー
386 マットで数値を読み込み、その数値を返します。指定した位置が当該ユニフォー
387 ムベクタの内容のある範囲外を参照するものであった場合、エラーを示すシグ
388 ナルがあがります。
389 @c COMMON
390 @end defun
391
392 @defun get-u16be uv pos
393 @defunx get-u16le uv pos
394 @defunx get-u32be uv pos
395 @defunx get-u32le uv pos
396 @defunx get-u64be uv pos
397 @defunx get-u64le uv pos
398 @defunx get-s16be uv pos
399 @defunx get-s16le uv pos
400 @defunx get-s32be uv pos
401 @defunx get-s32le uv pos
402 @defunx get-s64be uv pos
403 @defunx get-s64le uv pos
404 @defunx get-f16be uv pos
405 @defunx get-f16le uv pos
406 @defunx get-f32be uv pos
407 @defunx get-f32le uv pos
408 @defunx get-f64be uv pos
409 @defunx get-f64le uv pos
410 @c MOD binary.io
411 @c EN
412 These are big-endian (@code{be}) or little-endian (@code{le}) specific
413 versions of @code{get-*} procedures. In speed-sensitive code,
414 you might want to use these to avoid the overhead of optional-argument
415 handling.
416 @c JP
417 これらは、@code{get-*} 手続のエンディアン(ビッグエンディアン @code{be}
418 あるいはリトルエンディアン @code{le})を指定した版です。スピードを要求
419 されるコードではオプション引数処理のオーバーヘッドを避けるためこちらを
420 使うのがいいでしょう。
421 @c COMMON
422 @end defun
423
424 @defun get-uint size uv pos :optional endian
425 @defunx get-sint size uv pos :optional endian
426 @c MOD binary.io
427 @c EN
428 Read @var{size} octets from uvector @var{uv},
429 starting from @var{pos}-th octet, as an unsigned or signed integer,
430 respectively.
431 @c JP
432 ユニフォームベクタ@var{uv}の@var{pos}番目のオクテットから@var{size}オクテットを、
433 それぞれ符号無し、符号つき整数として読み取ります。
434 @c COMMON
435
436 @example
437 (get-uint 3 '#u8(1 2 3 4) 1 'big-endian)
438 @result{} 131884 ; @r{#x020304}
439
440 (get-sint 3 '#u9(1 2 3 #xff) 1 'little-endian)
441 @result{} -64766 ; @r{sign extended #xff0302}
442 @end example
443 @end defun
444
445 @defun put-u8! uv pos val :optional endian
446 @defunx put-u16! uv pos val :optional endian
447 @defunx put-u32! uv pos val :optional endian
448 @defunx put-u64! uv pos val :optional endian
449 @defunx put-s8! uv pos val :optional endian
450 @defunx put-s16! uv pos val :optional endian
451 @defunx put-s32! uv pos val :optional endian
452 @defunx put-s64! uv pos val :optional endian
453 @defunx put-f16! uv pos val :optional endian
454 @defunx put-f32! uv pos val :optional endian
455 @defunx put-f64! uv pos val :optional endian
456 @c MOD binary.io
457 @c EN
458 Writes a number @var{val} into a uniform vector @var{uv} in
459 a specific format, starting at a byte position @var{pos}.
460 An error is signaled
461 if the specified position makes reference outside of the uniform
462 vector's content.
463 @c JP
464 数値 @var{val} をユニフォームベクタ @var{uv} のバイト位置 @var{pos} か
465 ら指定されたフォーマットで書き出します。指定した位置が当該ユニフォーム
466 ベクタの内容のある範囲外を参照するものであった場合、エラーを示すシグナ
467 ルがあがります。
468 @c COMMON
469 @end defun
470
471 @defun put-u16be! uv pos val
472 @defunx put-u16le! uv pos val
473 @defunx put-u32be! uv pos val
474 @defunx put-u32le! uv pos val
475 @defunx put-u64be! uv pos val
476 @defunx put-u64le! uv pos val
477 @defunx put-s16be! uv pos val
478 @defunx put-s16le! uv pos val
479 @defunx put-s32be! uv pos val
480 @defunx put-s32le! uv pos val
481 @defunx put-s64be! uv pos val
482 @defunx put-s64le! uv pos val
483 @defunx put-f16be! uv pos val
484 @defunx put-f16le! uv pos val
485 @defunx put-f32be! uv pos val
486 @defunx put-f32le! uv pos val
487 @defunx put-f64be! uv pos val
488 @defunx put-f64le! uv pos val
489 @c MOD binary.io
490 @c EN
491 These are big-endian (@code{be}) or little-endian (@code{le}) specific
492 versions of @code{put-*} procedures. In speed-sensitive code,
493 you might want to use these to avoid the overhead of optional-argument
494 handling.
495 @c JP
496 これらは、@code{put-*} 手続のエンディアン(ビッグエンディアン @code{be}
497 あるいはリトルエンディアン @code{le})を指定した版です。スピードを要求
498 されるコードではオプション引数処理のオーバーヘッドを避けるためこちらを
499 使うのがいいでしょう。
500 @c COMMON
501 @end defun
502
503 @defun put-uint! size uv pos val :optional endian
504 @defunx put-sint! size uv pos val :optional endian
505 @c MOD binary.io
506 @c EN
507 Write an unsigned or signed integer @var{val} into
508 an uvector @var{uv} starting from @var{pos}-th octet,
509 for @var{size} octets, respectively.
510 @c JP
511 それぞれ符号無しまたは符号つき整数@var{val}を、
512 ユニフォームベクタ@var{uv}の@var{pos}番目のオクテットから@var{size}オクテット分に
513 書き込みます。
514 @c COMMON
515 @end defun
516
517
518 @c EN
519 @subheading Compatibility notes
520 @c JP
521 @subheading 互換性への注
522 @c COMMON
523
524 @c EN
525 @code{read-u8} etc. were called @code{read-binary-uint8} etc., and
526 @code{read-f32} and @code{read-f64} were called @code{read-binary-float}
527 and @code{read-binary-double}, respectively.
528 These old names are still supported for the backward compatibility
529 but their use is deprecated. The reason of the changes is
530 for brevity and for consistency with the uniform vectors.
531 @c JP
532 @code{read-u8} などは @code{read-binary-uint8} と呼ばれていたもので、
533 @code{read-f32} や @code{read-f64} はそれぞれ @code{read-binary-float}、
534 @code{read-binary-double} と呼ばれていたものです。
535 これらの古い名前は後方互換のためいまのところサポートされていますが、使
536 用については非推奨とします。この変更は名前の短縮とユニフォームベクタと
537 の一貫性維持のために行われました。
538 @c COMMON
539
540 @c ----------------------------------------------------------------------
541 @node Packing binary data, Running Chibi-scheme test suite, Binary I/O, Library modules - Utilities
542 @section @code{binary.pack} - Packing binary data
543 @c NODE バイナリデータのパック, @code{binary.pack} - バイナリデータのパック
544
545 @deftp {Module} binary.pack
546 @mdindex binary.pack
547 @c EN
548 This module provides an interface for packing and unpacking (writing
549 and reading) binary data with templates. The functionality was
550 inspired largely by the Perl pack/unpack functions, with comparison of
551 similar features from other languages, however an effort was made to
552 make it more general and more efficient, to be usable for
553 database-like processing. To that end, the most notable differences
554 are that any packable value is unpackable (and vice versa), and the
555 default behavior is to pack and unpack using port I/O, so you can seek
556 in a large file and unpack from it. Also, templates may be stored as
557 dispatch closures to pack, unpack or even skip over values without
558 re-parsing the template.
559 @c JP
560 このモジュールは、バイナリデータをテンプレートを使って
561 パック/アンパック(読み書き)するためのインタフェースを提供します。
562 この機能は、その多くをPerlのpack/unpack関数から着想し、他の言語での
563 同じような機能と比較しながら、しかし、データベースライクな処理に
564 便利なように、より一般的でより効率が良くなるように実装しました。
565 これを受けて、最も大きな相違点は、全てのパック可能な値はアンパック
566 可能で(逆も同様)、パック/アンパックのデフォルトの振る舞いはポートI/Oを
567 使うので、巨大なファイルを読みながらそこからアンパックすることが
568 できます。また、テンプレートはディスパッチクロージャとして格納でき、
569 パック、アンパック、あるいは値のスキップさえも、テンプレートを
570 パーズし直すことなく行えます。
571 @c COMMON
572
573 @c See also binary.io - Binary I/O for utilities to read and write
574 @c individual binary values.
575 @end deftp
576
577 @defun pack template list :key output to-string?
578 @c MOD binary.pack
579 @c EN
580 Writes the values in @var{list} to the current output port, according
581 to the format specified by the string @var{template}. The template
582 string is a series of single character codes, optionally followed by a
583 numeric count (which defaults to 1).
584 @c JP
585 @var{list}にある値を、文字列@var{template}で指定されたフォーマットに
586 したがって、現在の出力ポートに書き出します。テンプレート文字列は、
587 1文字のコードの連続で、オプションで(デフォルトが1である)カウント用の数字
588 が続きます。
589
590 @c EN
591 The format characters can generally be divided into string types,
592 which interpret the count as a string byte size, and object types,
593 which treat the count as a repetition indicator. The count may be
594 specified as the character @code{*}, which means to use the full
595 size of the string for string types, and use all remaining values for
596 object types.
597 @c JP
598 フォーマット文字は一般的に、カウントを文字のバイト数と解釈する
599 文字列型と、カウントを繰り返し指示子と解釈するオブジェクト型に
600 分けられます。カウントは文字@code{*}で指定され、文字列型では
601 文字列の全体の長さを、オブジェクト型では残りの全ての値を使うことを
602 意味します。
603
604 @c EN
605 Counts may also be specified as a template enclosed in brackets, which
606 means the count is the byte size of the enclosed template. For
607 example, @code{x[L]} skips a long.
608 @c JP
609 カウントは大括弧に囲まれたテンプレートとしても指定でき、その場合
610 カウントはその大括弧を囲んでいるテンプレートのバイト数を意味します。
611 例えば、@code{x[L]}はlongをスキップします。
612
613 @c EN
614 The special format character @code{/} may be used to indicate a
615 structure where the packed data contains a dynamic count followed by
616 the value itself. The template is written as
617 @code{<count-item>/<value-item>}, where @code{<count-item>} is any
618 template character to be interpreted as a numeric count, and
619 @code{<value-item>} is any other template character to use this count.
620 If a normal count is given after @code{<value-item>} it is ignored.
621 @c JP
622 特別なフォーマット文字@code{/}は、パックされたデータが、値に続く
623 動的なカウント分を含むという構造を表すために使われます。
624 テンプレートは、@code{<count-item>/<value-item>}のように書かれ、
625 ここでは@code{<count-item>}は数値のカウントと解釈されるいかなる
626 テンプレート文字、@code{<value-item>}はこのカウントを使ういかなる
627 他のテンプレート文字です。
628 @code{<value-item}>の後に通常のカウントが与えられても、無視されます。
629
630 @c EN
631 The format character @code{@@} may be used with a count to pad to an
632 absolute position since the start of the template.
633 @c JP
634 フォーマット文字@code{@@}は、カウントとともに使われ、テンプレートの
635 最初からの絶対位置までパディングします。
636
637 @c EN
638 Sub-templates may be grouped inside parentheses. If angle-brackets
639 are used, then they also behave as group operators but recursively
640 operate on nested lists.
641 @c JP
642 サブテンプレートは、括弧の中にグループ化されます。<>が使われると、
643 ネストされたリストに再帰的に適用されるグループ化オペレータとしても
644 振舞います。
645
646 @c EN
647 The string types:
648 @c JP
649 文字列型:
650
651 @c COMMON
652 @table @code
653 @item a
654 @c EN
655 An arbitrary incomplete string, null padded.
656 @c JP
657 任意の不完全文字列。NULLでパディングされます。
658 @c COMMON
659
660 @item A
661 @c EN
662 A text string, space padded.
663 @c JP
664 テキスト文字列。空白スペースでパディングされます。
665 @c COMMON
666
667 @item Z
668 @c EN
669 A null terminated (ASCIZ) string, null padded.
670 @c JP
671 NULL終端(ASCIZ)文字列。NULLでパディングされます。
672 @c COMMON
673
674 @item b
675 @c EN
676 A bit string (ascending bit order inside each byte).
677 @c JP
678 ビット文字列(それぞれのバイトにおけるビットオーダーは昇順)。
679 @c COMMON
680
681 @item B
682 @c EN
683 A bit string (descending bit order inside each byte).
684 @c JP
685 ビット文字列(それぞれのバイトにおけるビットオーダーは降順)。
686 @c COMMON
687
688 @item h
689 @c EN
690 A hex string (low nybble first).
691 @c JP
692 16進文字列(低いニブルが先)。
693 @c COMMON
694
695 @item H
696 @c EN
697 A hex string (high nybble first).
698 @c JP
699 16進文字列(高いニブルが先)。
700 @c COMMON
701 @end table
702
703 @c EN
704 The object types:
705 @c JP
706 オブジェクト型:
707 @c COMMON
708
709 @table @code
710 @item c
711 @c EN
712 A signed 8bit integer.
713 @c JP
714 符号付き8ビット整数。
715 @c COMMON
716
717 @item C
718 @c EN
719 An unsigned 8bit integer.
720 @c JP
721 符号なし8ビット整数。
722 @c COMMON
723
724 @item s
725 @c EN
726 A signed short (16 bit) value.
727 @c JP
728 符号付き16ビット整数。
729 @c COMMON
730
731 @item S
732 @c EN
733 An unsigned short (16 bit) value.
734 @c JP
735 符号なし16ビット整数。
736 @c COMMON
737
738 @item i
739 @c EN
740 A signed integer (>= 32 bit) value.
741 @c JP
742 符号付き整数(>= 32ビット)。
743 @c COMMON
744
745 @item I
746 @c EN
747 An unsigned integer (>= 32 bit) value.
748 @c JP
749 符号なし整数(>= 32ビット)。
750 @c COMMON
751
752 @item l
753 @c EN
754 A signed long (32 bit) value.
755 @c JP
756 符号付きlong(32ビット)。
757 @c COMMON
758
759 @item L
760 @c EN
761 An unsigned long (32 bit) value.
762 @c JP
763 符号なしlong(32ビット)。
764 @c COMMON
765
766 @item n, n!
767 @c EN
768 An unsigned and signed short (16 bit) in "network" (big-endian) order.
769 @c JP
770 ネットワークオーダー(ビッグエンディアン)での符号なし/符号つきshort(16ビット)。
771 @c COMMON
772
773 @item N, N!
774 @c EN
775 An unsigned and signed long (32 bit) in "network" (big-endian) order.
776 @c JP
777 ネットワークオーダー(ビッグエンディアン)での符号なし/符号つきlong(32ビット)。
778 @c COMMON
779
780 @item v, v!
781 @c EN
782 An unsigned and signed short (16 bit) in "VAX" (little-endian) order.
783 @c JP
784 VAXオーダー(リトルエンディアン)での符号なし/符号つきshort(16ビット)。
785 @c COMMON
786
787 @item V, V!
788 @c EN
789 An unsigned and signed long (32 bit) in "VAX" (little-endian) order.
790 @c JP
791 VAXオーダー(リトルエンディアン)での符号なし/符号つきlong(32ビット)。
792 @c COMMON
793
794 @item q
795 @c EN
796 A signed quad (64 bit) value.
797 @c JP
798 符号付きquad(64ビット)。
799 @c COMMON
800
801 @item Q
802 @c EN
803 An unsigned quad (64 bit) value.
804 @c JP
805 符号なしquad(64ビット)。
806 @c COMMON
807
808 @item f
809 @c EN
810 A single-precision float in the native format.
811 @c JP
812 ネイティブ形式の単精度float。
813 @c COMMON
814
815 @item d
816 @c EN
817 A double-precision float in the native format.
818 @c JP
819 ネイティブ形式の倍精度float。
820 @c COMMON
821
822 @item w
823 @c EN
824 A BER compressed integer. An unsigned integer in base 128, most
825 significant digit first, where the high bit is set on all but the
826 final (least significant) byte. Thus any size integer can be encoded,
827 but the encoding is efficient and small integers don't take up any
828 more space than they would in normal char/short/int encodings.
829 @c JP
830 BER圧縮された整数。ベース128における符号なし整数で、最も大きな桁が
831 最初で、高いビットが最後の(一番小さな)バイト以外にセットされる。
832 したがって、どのような大きさの整数もエンコードできるが、
833 エンコーディングは効率的で、小さな整数は通常のchar/short/int
834 エンコーディングの場合よりも占有する空間が少ない。
835 @c COMMON
836
837 @item x
838 @c EN
839 A null byte.
840 @c JP
841 NULLバイト。
842 @c COMMON
843
844 @item o
845 @c EN
846 An sexp, handled with @code{read} and @code{write}.
847 @c JP
848 S式。@code{read}と@code{write}で扱われる。
849 @c COMMON
850
851 @end table
852
853 @c EN
854 If the optional keyword @var{:output} is given that port is used
855 instead of the current output port. If @var{:to-string?} is given and
856 true, then pack accumulates and returns the output as a string.
857
858 Note that the returned string may be an incomplete string
859 if the packed string contains a byte sequence invalid as
860 a character sequence.
861 @c JP
862 オプションのキーワード@var{:output}が与えられると、
863 現在の出力ポートの代わりにそのポートが使われます。
864 @var{:to-string?}が与えられそれが真である場合は、
865 パックは蓄積され、その出力は文字列として返ります。
866 @c COMMON
867
868 @example
869 (pack "CCCC" '(65 66 67 68) :to-string? #t)
870 @result{} "ABCD"
871
872 (pack "C/a*" '("hello") :to-string? #t)
873 @result{} "\x05hello"
874 @end example
875 @end defun
876
877 @defun unpack template :key :input :from-string
878 @c MOD binary.pack
879 @c EN
880 The complement of pack, unpack reads values from the current input
881 port assuming they've been packed according to the string template and
882 returns the values as a list. unpack accepts the same format strings
883 as pack. Further, the following tautology holds:
884 @c JP
885 packの逆を行うもので、unpackは現在の入力ポートから、値が文字列の
886 templateでパックされているものとして読み込み、その値をリストとして
887 返します。unpackはpackと同じフォーマット文字列を受け付けます。
888 また、いかなるリスト@var{x}とフォーマット文字列@var{fmt}においても、
889 次のようなトートロジーが維持されます。
890 @c COMMON
891
892 @example
893 (equal? x (unpack fmt :from-string (pack fmt x :to-string? #t)))
894 @end example
895
896 @c EN
897 for any list @var{x} and format string @var{fmt}. The only exceptions
898 to this are when the template includes a @code{*} and when the
899 @code{o} template is used, since Scheme numeric literals cannot be
900 reliably delimited (though future versions of @code{pack} may
901 circumvent this by registering a new read syntax).
902
903 If the optional keyword @var{:input} is given that port is used
904 instead of the current input port. If @var{:from-string} is given,
905 then pack reads input from that string.
906 @c JP
907 ただ一つの例外は、テンプレートが@code{*}を含み、@code{o}テンプレートが
908 使われている場合です。これは、Schemeの数値リテラルは確実に区切られる
909 ことができないからです(@code{pack}の将来のバージョンでは、
910 新しいread構文を登録することによってこれは回避されるでしょう)。
911
912 オプションのキーワード@var{:input}が与えられると、現在の入力ポートの
913 代わりにそのポートが使われます。@var{:from-string}が与えられると、
914 packはその文字列を入力とします。
915 @c COMMON
916
917 @example
918 (unpack "CCCC" :from-string "ABCD")
919 @result{} '(65 66 67 68)
920
921 (unpack "C/a*" :from-string "\x05hello")
922 @result{} '("hello")
923 @end example
924
925 @c EN
926 @emph{Note:} in the current version, @code{@@} in @code{unpack}
927 template has a bug and does not work as supposed. It will
928 be fixed in the future version.
929 @c JP
930 @emph{註:} 現在のバージョンには、@code{unpack}のテンプレートの
931 @code{@@}が想定したように動かないというバグがあります。
932 将来のバージョンでfixされます。
933 @c COMMON
934 @end defun
935
936 @defun unpack-skip template :key :input
937 @c MOD binary.pack
938 @c EN
939 unpack-skip is the same as unpack except it does not return the
940 values. In some cases, particularly with fixed-size templates, this
941 can be much more efficient when you just want to skip over a value.
942 @c JP
943 unpack-skipは、値を返さないことを除いてunpackと同じです。
944 いくつかのケースでは、特に固定サイズのテンプレートを使うときには、
945 単に値を読み飛ばしたいときにより効率的です。
946 @c COMMON
947 @end defun
948
949 @defun make-packer template
950 @c MOD binary.pack
951 @c EN
952 The low-level interface. This function returns a dispatch closure
953 that can be used to pack, unpack and skip over the same cached
954 template. The dispatch closure accepts symbol methods as follows:
955 @c JP
956 低レベルなインタフェースです。この関数は、pack、unpackやキャッシュ
957 された同じテンプレートを読み飛ばす時に使われるディスパッチクロージャを
958 返します。ディスパッチクロージャは、以下のようにシンボルメソッドを
959 受け付けます。
960 @c COMMON
961
962 @table @code
963 @item 'pack list
964 @c EN
965 pack the items in list to the current output port.
966 @c JP
967 listにあるアイテムを、現在の出力ポートへpackします。
968 @c COMMON
969
970 @item 'unpack
971 @c EN
972 unpack items from the current input port.
973 @c JP
974 現在の入力ポートからアイテムをunpackします。
975 @c COMMON
976
977 @item 'skip
978 @c EN
979 skip items from the current input port.
980 @c JP
981 現在の入力ポートからのアイテムをスキップします。
982 @c COMMON
983
984 @item 'packer
985 @c EN
986 return the cached 'pack closure
987 @c JP
988 キャッシュされた'packクロージャを返します。
989 @c COMMON
990
991 @item 'unpacker
992 @c EN
993 return the cached 'unpack closure.
994 @c JP
995 キャッシュされた'unpackクロージャを返します。
996 @c COMMON
997
998 @item 'skipper
999 @c EN
1000 return the cached 'skip closure.
1001 @c JP
1002 キャッシュされた'skipクロージャを返します。
1003 @c COMMON
1004
1005 @item 'length
1006 @c EN
1007 return the known fixed length of the template.
1008 @c JP
1009 テンプレートの知られている固定された長さを返します。
1010 @c COMMON
1011
1012 @item 'variable-length?
1013 @c EN
1014 return #t if the template has variable length elements.
1015 @c JP
1016 テンプレートが可変長の要素を持っている場合に#tを返します。
1017 @c COMMON
1018 @end table
1019 @end defun
1020
1021 @c ----------------------------------------------------------------------
1022
1023 @node Running Chibi-scheme test suite, Rational-less arithmetic, Packing binary data, Library modules - Utilities
1024 @section @code{compat.chibi-test} - Running Chibi-scheme test suite
1025 @c NODE Chibi schemeテストの実行, @code{compat.chibi-test} - Chibi schemeテストの実行
1026
1027 @deftp {Module} compat.chibi-test
1028 @mdindex compat.chibi-test
1029 @c EN
1030 Quite a few srfis come with test suites that's to be run with
1031 Chibi Scheme test framework. This module enables Gauche to run
1032 the test code as is.
1033 @c JP
1034 多くのsrfiには、Chibi Schemeのテストフレームワークで実行できるテストコードが
1035 付いてきます。このモジュールはGaucheでそのテストコードを実行できるようにします。
1036 @c COMMON
1037 @end deftp
1038
1039 @defmac chibi-test code @dots{}
1040 @c MOD compat.chibi-test
1041 @c EN
1042 Run @var{code} @dots{}, while translating Chibi test framework
1043 to Gauche's.
1044 @c JP
1045 ChibiのテストフレームワークをGaucheのそれに置き換えながら、
1046 @code{code} @dots{}を実行します。
1047 @c COMMON
1048
1049 @c EN
1050 A typical usage is to write a wrapper that includes the original
1051 test code (suppose it's called @file{test-suite.scm}):
1052 @c JP
1053 典型的な使い方は、元のテストコード(@file{test-suite.scm}とします)を
1054 includeするラッパーを書くことです。
1055 @c COMMON
1056
1057 @example
1058 (use gauche.test)
1059 (test-start "running test-suite.scm")
1060 (chibi-test
1061 (include "test-suite.scm"))
1062 (test-end)
1063 @end example
1064
1065 @c EN
1066 Chibi's test directives are translated to Gauche's test directives
1067 (@pxref{Unit testing}, for Gauche's test framework).
1068 @c JP
1069 Chibiのテストディレクティブは、Gaucheのテストフレームワークのテストディレクティブへと
1070 変換されます(@ref{Unit testing}参照)。
1071 @c COMMON
1072
1073 @c EN
1074 The main thing is that Chibi allows expressions and definitions to
1075 be intermingled within a body, while Gauche only allows all definitions
1076 before expressions within a body.
1077 We expand such body into nested @code{let} by @code{chibi-test} macro.
1078 Chibi test macros (e.g. @code{test-assert}) are defined as local macros
1079 in @code{chibi-test} expansion, which expand into @code{gauche.test}
1080 macros.
1081 @c JP
1082 Chibiはボディ中に式と定義が交互に現れることを許していますが、Gaucheでは
1083 ボディ中で全ての定義が式に先立たねばなりません。そこで、@code{chibi-test}マクロは
1084 @code{code} @dots{}をネストした@code{let}に変換します。
1085 また、Chibiテストマクロ(@code{test-assert}等)は変換後のコードではローカルマクロとして
1086 定義され、そのローカルマクロは@code{gauche.test}マクロへと展開されます。
1087 @c COMMON
1088
1089 @c EN
1090 Note that we ignore @code{use} forms inside @code{chibi-test}; we might
1091 want to use different modules that work better in Gauche. Necessary
1092 modules need to be @code{use}'d before you call @code{chibi-test}.
1093 @c JP
1094 なお、@code{chibi-test}中の@code{use}フォームは無視されます。
1095 これは、Gaucheで実行するのに別のモジュールを使った方が良い場合があるからです。
1096 必要なモジュールは@code{chibi-test}を呼ぶ前に@code{use}しておいてください。
1097 @c COMMON
1098
1099 @c EN
1100 You may want to check out @file{test/srfi.scm} in Gauche source tree
1101 for the use case.
1102 @c JP
1103 Gaucheのソースツリーの@file{test/srfi.scm}に実際の使用例を見ることができます。
1104 @c COMMON
1105 @end defmac
1106
1107
1108 @c ----------------------------------------------------------------------
1109
1110 @node Rational-less arithmetic, Backward-compatible real elementary functions, Running Chibi-scheme test suite, Library modules - Utilities
1111 @section @code{compat.norational} - Rational-less arithmetic
1112 @c NODE 有理数のない算術演算, @code{compat.norational} - 有理数のない算術演算
1113
1114 @deftp {Module} compat.norational
1115 @mdindex compat.norational
1116
1117 @c EN
1118 Until release 0.8.7, Gauche didn't have exact rational numbers.
1119 It was able to read the rational number literals such as
1120 @code{2/3}, but they are immediately coerced to inexact real
1121 numbers (except when it represents a whole integer).
1122 And if you divided an exact integer by another exact integer,
1123 the result could be coerced to an inexact real if the result
1124 wasn't a whole integer.
1125 @c JP
1126 リリース 0.8.7 までは、Gauche は正確な有理数をサポートしていませんでし
1127 た。@code{2/3}のような有理数リテラルを読み込むことはできていましたが、
1128 約分して整数になる場合をのぞいては、その場で非正確な実数に変換されてい
1129 ました。正確な整数を正確な整数で割った場合も約分して整数になる場合をの
1130 ぞき、結果は非正確な実数になりました。
1131 @c COMMON
1132
1133 @c EN
1134 As of 0.8.8, this is not the case anymore. Exact division
1135 always yields exact result, except when the divisor is zero.
1136 @c JP
1137 リリース 0.8.8 ではもうこのようなことはありません。正確な数同士の割り
1138 算の結果は常に正確な数になります。ゼロで割ったときはもちろん例外です。
1139 @c COMMON
1140 @example
1141 (/ 2 3) @result{} 2/3
1142 (/ 5) @result{} 1/5
1143 (/ 4 2) @result{} 2
1144 @end example
1145
1146 @c EN
1147 This is more precise, but has one drawback: exact rational
1148 arithmetic is much slower than the integer and inexact real
1149 arithmetic. If you inadvertently produce
1150 a rational number in the early stage of calculation, and
1151 continue to apply exact arithmetic, performance would be
1152 degraded miserably.
1153 @c JP
1154 計算は正確な値でできますが、ひとつ欠点もあります。正確有理数演算は整
1155 数演算や非正確実数同士の演算にくらべてはるかに遅いのです。意図せず、計
1156 算の初期段階で有理数を生成してしまうとその後の計算にはすべて正確な演算
1157 が適用されてしまい性能は悲惨なことになります。
1158 @c COMMON
1159
1160 @c EN
1161 The proper way to solve this is to insert @code{exact->inexact}
1162 to appropriate places. However, to ease the transition, you can
1163 just import this module and the division @code{/} behaves
1164 in the way it used to.
1165 @c JP
1166 この問題を解決する適切は方法は適切な場所に@code{exact->inexact}を挿入
1167 することです。しかし、この変換を簡単におこなうには、このモジュールをイ
1168 ンポートし、割り算に@code{/}を使うだけですみます。
1169 @c COMMON
1170
1171 @example
1172 (use compat.norational)
1173
1174 (/ 2 3) @result{} 0.6666666666666666
1175 (/ 5) @result{} 0.2
1176 (/ 4 2) @result{} 2
1177 @end example
1178
1179 @c EN
1180 The effect is not global, but only to the modules you explicitly
1181 import @code{compat.norational}.
1182 @c JP
1183 効果はグローバルには起こらず、明示的に@code{compat.norational}をインポー
1184 トしたモジュールでのみ有効です。
1185 @c COMMON
1186
1187 @c EN
1188 This module only redefines @code{/}. So if your code has
1189 exact rational literals, they are treated as exact rationals
1190 rather than coerced to inexact reals. You should prefix
1191 rational literals with @code{#i} to force Gauche to coerce
1192 them to inexact reals:
1193 @c JP
1194 このモジュールは@code{/}を再定義しているだけです。したがって、コードに
1195 正確な有理数のリテラルが含まれていても、それは非正確な実数に変換される
1196 ことはなく、正確な有理数としてあつかわれます。Gaucheに非正確な実数とし
1197 て有理数リテラルを扱わせるには、@code{#i}という接頭辞を追加しなければ
1198 なりません。
1199 @c COMMON
1200 @example
1201 gosh> 1/3
1202 1/3
1203 gosh> #i1/3
1204 0.3333333333333333
1205 @end example
1206 @end deftp
1207
1208 @c ----------------------------------------------------------------------
1209 @node Backward-compatible real elementary functions, Concurrent sequences, Rational-less arithmetic, Library modules - Utilities
1210 @section @code{compat.real-elementary-functions} - Backward-compatible real elementary functions
1211 @c NODE 後方互換な実数初等関数, @code{compat.real-elementary-functions} - 後方互換な実数初等関数
1212
1213 @deftp {Module} compat.real-elementary-functions
1214 @mdindex compat.real-elementary-functions
1215 @c EN
1216 Gauche 0.9.12 and earlier had undocumented real-only elementary functions,
1217 such as @code{%sin} and @code{%exp}. They were intended to be a building
1218 block of the complex elementary functions, hence prefixed with @code{%}.
1219 However, they were visible in @code{gauche} module, and sometimes used
1220 directly because they were fast.
1221 @c JP
1222 Gauche 0.9.12とそれ以前のバージョンでは、正式にドキュメントされていませんでしたが、
1223 実数のみを対象とした@code{%sin}や@code{%exp}といった初等関数が提供されていました。
1224 複素数までを対象にした初等関数はそれらの上に構築されていて、
1225 実数対象バージョンは内部ルーチンという意図でした(なので@code{%}が頭についています)が、
1226 @code{gauche}モジュールで見えるようになっていたのと、複素数バージョンより速かったので、
1227 過去のコードでこれらの関数を直接呼んでいるコードがあります。
1228 @c COMMON
1229
1230 @c EN
1231 SRFI-94 introduced names for real-only elementary functions
1232 such as @code{real-sin}, so we changed built-in @code{%sin} etc.
1233 to follow that names. @xref{Arithmetics}, for those real-only
1234 elementary functions.
1235 @c JP
1236 SRFI-94で、実数のみ対象の初等関数に@code{real-sin}などの名前が規定されたので、
1237 0.9.13から@code{%sin}などを@code{real-sin}にリネームした上で正式にドキュメントしました。
1238 @ref{Arithmetics}に説明があります。
1239 @c COMMON
1240
1241 @c EN
1242 This module is to ease migration from the legacy code that uses
1243 old names. Just add the following form at the beginning of
1244 old code and the source would work with both versions.
1245 @c JP
1246 このモジュールは、古い名前を使っている既存のコードからの移行を補助するためのものです。
1247 次のフォームを付け加えてやれば、古いコードはどのバージョンのGaucheでも動きます。
1248 @c COMMON
1249
1250 @example
1251 (cond-expand
1252 [(library (compat real-elementary-functions))
1253 (use compat.real-elementary-functions)]
1254 [else])
1255 @end example
1256
1257 @c EN
1258 New code must use @code{real-sin} etc. instead of the names provided here.
1259 @c JP
1260 新規コードは、このモジュールにある名前ではなく@code{real-sin}などの名前を使ってください。
1261 @c COMMON
1262 @end deftp
1263
1264 @defun %exp x
1265 @defunx %sin x
1266 @defunx %cos x
1267 @defunx %tan x
1268 @defunx %sinpi x
1269 @defunx %cospi x
1270 @defunx %tanpi x
1271 @defunx %asin x
1272 @defunx %acos x
1273 @defunx %atan x
1274 @defunx %sinh x
1275 @defunx %cosh x
1276 @defunx %tanh x
1277 @defunx %sqrt x
1278 @defunx %expt x a
1279 @c MOD compat.real-elementary-functions
1280 @c EN
1281 These are the same as the built-in procedures replacing preceding @code{%}
1282 with @code{real-}; e.g. @code{%exp} @equiv{} @code{real-exp}.
1283 @xref{Arithmetics}, for the description of built-in procedures.
1284 @c JP
1285 これらは、@code{%}を@code{real-}で置き換えた組み込み手続きと同じです。
1286 (例: @code{%exp} @equiv{} @code{real-exp})。
1287 これらの組み込み手続きについては@ref{Arithmetics}を参照してください。
1288 @c COMMON
1289 @end defun
1290
1291 @defun %log x :optional base
1292 @c MOD compat.real-elementary-functions
1293 @c EN
1294 This is a real-only logarithm of @var{x} base @var{base}.
1295 @var{x} must be a non-negative real
1296 number, and @var{base} must be a positive real number.
1297 If @var{base} is omitted, Napier's number is assumed, that is,
1298 it returns a natural logarithm of @var{x}.
1299 If @var{x} is 0, @code{-inf.0} is returned.
1300 @c JP
1301 これは実数のみを対象とした、@var{base}を底とする@var{x}の対数関数です。
1302 @var{x}は非負実数、@var{base}は正の実数でなければなりません
1303 @var{base}が省略された時はネイピア数が使われます。
1304 すなわち、@var{x}の自然対数を返します。
1305 @var{x}が0の時は@code{-inf.0}が返されます。
1306 @c COMMON
1307
1308 @c EN
1309 Gauche does not have built-in @code{real-log}, to avoid conflict with
1310 SRFI-94's @code{real-log} which takes @var{base} argument first.
1311 For real-only natural logarithm, Gauche has @code{real-ln}.
1312 @c JP
1313 Gaucheは組み込みでは@code{real-log}を提供しません。
1314 SRFI-94が底を第一引数にする@code{real-logを}を定義しているので、混同を避けるためです。
1315 実数対象の自然対数には、組み込みの@code{real-ln}が使えます。
1316 @c COMMON
1317
1318 @c EN
1319 @xref{R7RS flonum}, which defines flonum-only version of logarithms
1320 sich as @code{fllog}, @code{fllog2}, and @code{fllog10}.
1321 @c JP
1322 また、@ref{R7RS flonum}には、flonum専用の対数関数である
1323 @code{fllog}、@code{fllog2}、@code{fllog10}等が定義されています。
1324 @c COMMON
1325 @end defun
1326
1327
1328 @c ----------------------------------------------------------------------
1329 @node Concurrent sequences, Futures, Backward-compatible real elementary functions, Library modules - Utilities
1330 @section @code{control.cseq} - Concurrent sequences
1331 @c NODE 並行シーケンス, @code{control.cseq} - 並行シーケンス
1332
1333 @deftp {Module} control.cseq
1334 @mdindex control.cseq
1335 @c EN
1336 Concurrent sequence (cseq) is a lazy sequence (@pxref{Lazy sequences}), but
1337 the generator runs in a separate thread. You can use producer-consumer
1338 pararellism very easily using cseq; from the consumer side,
1339 it just looks like an ordinary list. Synchornization is implicitly
1340 taken care of.
1341
1342 Internally, it uses mtqueue (@pxref{Queue}) for synchronization.
1343 @c JP
1344 並行シーケンス (cseq) はジェネレータが別スレッドで走る遅延シーケンスです
1345 (遅延シーケンスについては@ref{Lazy sequences}参照)。
1346 cseqを使うと、生産者-消費者型の並列性を簡単に書けます。
1347 消費者側からは、cseqは単なるリストに見え、同期は自動的に取られます。
1348
1349 内部的には、同期のためにmtqueueが使われています (@ref{Queue}参照)。
1350 @c COMMON
1351 @end deftp
1352
1353 @defun generator->cseq gen :key queue-length
1354 @c MOD control.cseq
1355 @c EN
1356 Create a lazy sequence from generator, much like @code{generator->lseq},
1357 except that @var{gen} runs in a separate thread.
1358 @c JP
1359 @code{generator->lseq}のように、ジェネレータから遅延シーケンスを作って返しますが、
1360 ジェネレータ@var{gen}自体は別スレッドで実行されます。
1361 @c COMMON
1362
1363 @c EN
1364 The returend value looks like an ordinary list, but its
1365 cdrs are computed in parallel. If a cdr isn't computed yet, the reader
1366 thread waits until a value becomes available. The generator @var{gen}
1367 can be called to generate values asynchronously, until the internal queue
1368 gets full. (Compare this to an ordinary lseq, in which @var{gen} is called
1369 when it is required, and it runs in the same thread as the caller.)
1370 @c JP
1371 返される値は通常のリストのように見えますが、cdr方向のリストの要素は
1372 並行して計算されます。cdrを取ろうとしてそれがまだ計算されていなければ、
1373 読み出し側のスレッドはその値が計算されるまで待ちます。
1374 ジェネレータ@var{gen}は別スレッドで非同期に実行され、
1375 内部キューがいっぱいになるまで値を生成し続けます。
1376 (対比として、
1377 通常のlseqでは、@var{gen}は値が必要になった時に、読み出すスレッドで実行されます。)
1378 @c COMMON
1379
1380 @c EN
1381 If @var{gen} raises an error, it is caught, and reraised when the
1382 consumer reads to the point when @var{gen} raised the error.
1383 @c JP
1384 @var{gen}がエラーを投げた場合、それは捕捉され、
1385 消費者がそのエラーが起きたポイントまで読み進めた時に消費者側のスレッドで再度投げられます。
1386 @c COMMON
1387
1388 @c EN
1389 The optional @var{queue-length} must be a nonnegative exact integer or @code{#f}.
1390 If it is an integer, it specifies the length of the internal queue.
1391 If it is @code{#f}, an appropriate value is selected by the library
1392 (currently 64).
1393 @c JP
1394 省略可能な引数@var{queue-length}は非負の正確な整数か@code{#f}でなければなりません。
1395 整数の場合は、内部のキューの長さを指定します。
1396 @code{#f}の場合はライブラリのデフォルトの長さが使われます。
1397 @c COMMON
1398
1399 @c EN
1400 Note that Gauche's lseq read-ahead one item (@pxref{Lazy sequences}). So
1401 even if you set the queue length to 0, @var{gen} is called before
1402 the consumer reads out any value.
1403 @c JP
1404 Gaucheのlseqは一要素先読みすることに注意してください(@ref{Lazy sequences}参照)。
1405 キュー長を0に指定しても、@var{gen}は消費者が値を呼び出す前に一回呼び出されます。
1406 @c COMMON
1407 @end defun
1408
1409
1410 @defun coroutine->cseq proc :key queue-length
1411 @c MOD control.cseq
1412 @c EN
1413 Returns an lseq, whose value is generated in @var{proc}, which is called
1414 in a separate thread. (See also @code{coroutine->lseq},
1415 @ref{Lazy sequence constructors}).
1416 The @var{proc} argument is a procedure to be called with one argument,
1417 @var{yield}. The @var{yield} argument is a procedure, and whenever it is
1418 called with a value, that value becomes the next item of the resulting lseq.
1419 When @var{proc} returns, it becomes the end of the lseq.
1420 @c JP
1421 @code{coroutine->lseq} (@ref{Lazy sequence constructors}) のように、
1422 値が@var{proc}によって生成されるlseqを返しますが、@var{proc}自体は別スレッドで
1423 実行されます。
1424 @var{proc}引数は、引数@var{yield}を取る手続きです。
1425 @var{yield}引数は1引数の手続きで、それが呼び出されると、引数に渡された値が
1426 lseqの次の要素になります。
1427 @var{proc}がリターンしたら、lseqはそこで終端となります。
1428 @c COMMON
1429
1430 @c EN
1431 If @var{proc} raises an error, it is caught, and reraised when the
1432 consumer reads to the point when previously generated values are all read
1433 and next value is about to read.
1434 @c JP
1435 @var{proc}がエラーを投げた場合、それは捕捉され、
1436 消費者がその箇所まで読み進めた時に消費者スレッドで再度投げ直されます。
1437 @c COMMON
1438
1439 @c EN
1440 The optional @var{queue-length} must be a nonnegative exact integer or @code{#f}.
1441 If it is an integer, it specifies the length of the internal queue.
1442 If it is @code{#f}, an appropriate value is selected by the library
1443 (currently 64).
1444 @c JP
1445 省略可能な引数@var{queue-length}は非負の正確な整数か@code{#f}でなければなりません。
1446 整数の場合は、内部のキューの長さを指定します。
1447 @code{#f}の場合はライブラリのデフォルトの長さが使われます。
1448 @c COMMON
1449 @end defun
1450
1451
1452 @c ----------------------------------------------------------------------
1453 @node Futures, A common job descriptor for control modules, Concurrent sequences, Library modules - Utilities
1454 @section @code{control.future} - Futures
1455 @c NODE Future, @code{control.future} - Future
1456
1457 @deftp {Module} control.future
1458 @mdindex control.future
1459 @c EN
1460 A @emph{future} is a simple construct for concurrent computation.
1461
1462 It encloses an expression, and compute its value concurrently. The result
1463 of computation can be retrieved later with @code{future-get}.
1464 @c JP
1465 @emph{future}は並行計算を簡単にする構造です。
1466
1467 指定された式の計算を並行して行います。計算結果は@code{future-get}で取り出すことができます。
1468 @c COMMON
1469
1470 @c EN
1471 Futures are introduced in MultiLisp, in which retrieval of the computed
1472 value is implicit---a future is substituted with the result automatically.
1473 Racket and Guile have futures as a library, though the primitive to
1474 retrieve the result is called @code{touch}. We avoided to use the name
1475 since @code{touch} is too generic.
1476 @c JP
1477 futureはMultiLispで実装されました。
1478 MultiLispのfutureは暗黙的、つまり計算が終わるとその結果に自動的に置き換わるものでした。
1479 RacketとGuileはライブラリでfutureを提供していますが、
1480 結果の取り出しを@code{touch}と呼んでいます。@code{touch}という名前は一般的にすぎるので、
1481 Gaucheでは@code{future-get}と呼ぶことにしました。
1482 @c COMMON
1483 @end deftp
1484
1485 @defmac future expr
1486 @c MOD control.future
1487 @c EN
1488 Returns a future object, which runs the computation of @var{expr} in
1489 a separate thread. The result(s) of @var{expr} can be retrieved by
1490 @code{future-get}. Note that @var{expr} can yield multiple values.
1491 @c JP
1492 @var{expr}を別スレッドで計算するfutureオブジェクトを返します。
1493 @var{expr}の結果は@code{future-get}で取り出せます。
1494 (@var{expr}は多値を生成することもできます)。
1495 @c COMMON
1496
1497 @c EN
1498 The @var{expr} is evaluated in the same environment
1499 as @code{future} appears, though if an exception raised within @var{expr}
1500 is not caught, its delivery is delayed until you call @code{future-get}.
1501 @c JP
1502 @var{expr}は@code{future}式と同じ環境で評価されます。
1503 ただし、@var{expr}が捕捉されない例外を投げた場合は、@code{future-get}が呼ばれるまで
1504 その例外の配送は遅延されます。
1505 @c COMMON
1506
1507 @c EN
1508 The following example runs HTTP access concurrently with other computation,
1509 and retrieves the result later.
1510 @c JP
1511 次の例では、HTTPアクセスを他の計算と並行して走らせて、後で結果を取り出しています。
1512 @c COMMON
1513
1514 @example
1515 (use control.future)
1516 (use rfc.http)
1517
1518 (let1 f (future (http-get "example.com" "/"))
1519 ... some computation ...
1520 (receive (code headers body) (future-get f)
1521 ...))
1522 @end example
1523
1524 @end defmac
1525
1526 @defun make-future thunk
1527 @c MOD control.future
1528 @c EN
1529 Returns a future that calls @var{thunk} in a separate thread.
1530 @c JP
1531 @var{thunk}を別スレッドで呼ぶfutureを返します。
1532 @c COMMON
1533
1534 @example
1535 (future expr) @equiv{} (make-future (lambda () expr))
1536 @end example
1537 @end defun
1538
1539
1540 @defun future? obj
1541 @c MOD control.future
1542 @c EN
1543 Returns @code{#t} if @var{obj} is a future, @code{#f} otherwise.
1544 @c JP
1545 @var{obj}がfutureなら@code{#t}を、そうでなければ@code{#t}を返します。
1546 @c COMMON
1547 @end defun
1548
1549
1550 @defun future-get future :optional timeout timeout-val
1551 @c MOD control.future
1552 @c EN
1553 The argument must be a future. Retrieve the result(s) of @var{future}.
1554 @c JP
1555 引数はfutureでなければなりません。@var{future}の結果を取り出します。
1556 @c COMMON
1557
1558 @c EN
1559 If the result of @var{future} is already available, it is returned immediately.
1560 If @var{future} is still computing, @code{future-get} blocks until
1561 the result is ready by default. You can limit how long you will wait by
1562 @var{timeout} argument, which can be @code{#f} (default, no timeout),
1563 a nonnegative real numebr (relative time in seconds), or
1564 a @code{<time>} object (absolute timepoint). If the timeout reaches
1565 before the result is available, @var{timeout-val} is returned, which
1566 defaults to @code{#f}.
1567 Calling @code{future-get} more than once returns the same result.
1568 @c JP
1569 @var{future}の結果が既に求まっていれば、この手続きはただちにそれを返します。
1570 まだ計算中であった場合は、デフォルトでこの手続きは計算が終わるまでブロックします。
1571 待つ時間の上限を@var{timeout}引数で指定することもできます。
1572 @var{timeout}が@code{#f}(デフォルト)なら無制限に待ち、
1573 非負実数ならその秒数だけ待ち、@code{<time>}オブジェクトならそれで指定される
1574 絶対時間まで待ちます。タイムアウトが起きた場合は@var{timeout-val}が返されます。
1575 デフォルトは@code{#f}です。
1576 @code{future-get}を複数回呼んでも同じ結果が返されます。
1577 @c COMMON
1578
1579 @c EN
1580 If an uncaught exception is raised during computation in the future,
1581 it is kept and reraised from @code{future-get}. It is handled
1582 in the dynamic environment of @code{future-get} (not the one in the original
1583 @code{future} call).
1584 If you call @code{future-get}
1585 again on such future, the effect is undefined
1586 (currently it returns @code{#<undef>} without raising an exception, but
1587 it may change in future).
1588 @c JP
1589 futureの計算中に捕捉されない例外が投げられた場合、それは@code{future-get}を呼んだ時点で
1590 @code{future-get}の動的環境で再び投げられます。
1591 そのfutureにもう一度@code{future-get}を呼んだ場合の動作は未定義です
1592 (現在は、二度目以降は例外を投げることなく@code{#<undef>}が返されますが、
1593 将来変わる可能性があります)。
1594 @c COMMON
1595 @end defun
1596
1597
1598 @defun future-done? future
1599 @c MOD control.future
1600 @c EN
1601 Returns @code{#t} if computation in @var{future} is finished,
1602 @code{#f} otherwise.
1603 @c JP
1604 @var{future}の計算が終わっていれば@code{#t}を、そうでなければ@code{#f}を返します。
1605 @c COMMON
1606 @end defun
1607
1608
1609
1610 @c ----------------------------------------------------------------------
1611 @node A common job descriptor for control modules, Plumbing ports, Futures, Library modules - Utilities
1612 @section @code{control.job} - A common job descriptor for control modules
1613 @c NODE 制御モジュールのための汎用ジョブ記述子, @code{control.job} - 制御モジュールのための汎用ジョブ記述子
1614
1615 @deftp {Module} control.job
1616 @mdindex control.job
1617 @c EN
1618 This module provides a @code{job} record type, a lightweight
1619 structure to be used in the control flow subsystems
1620 (@code{control.*} modules).
1621 Currently the only user is @code{control.thread-pool}, but
1622 some other modules are planned to use @code{job} records.
1623 @c JP
1624 このモジュールは、制御フローサブシステム(@code{control.*}モジュール)
1625 の中で使う軽量な構造である @code{job} レコード型を提供します。
1626 現在のところ、これを使っているのは@code{control.thread-pool}だけですが、
1627 他にもいくつかのモジュールが@code{job}レコードを使う予定です。
1628 @c COMMON
1629
1630 @c EN
1631 A @code{job} record may be returned to an application
1632 by other @code{control.*} modules so that the application
1633 can keep track of the job. It's not meant for
1634 general use, however. An application isn't supposed to
1635 create a new job, or to modify its content; it can just query
1636 the job's properties.
1637 @c JP
1638 @code{control.*}モジュールは、アプリケーションがジョブを追跡できるように
1639 @code{job}レコードを返すことができます。ただし、
1640 これは、アプリケーションが普通に使用するための
1641 ものではありません。アプリケーションが新しいジョブを
1642 作成したり、その内容を変更したりすることは想定されていません;
1643 できるのは、そのジョブの属性について問い合わせることだけです。
1644 @c COMMON
1645
1646 @c EN
1647 In this section we only describe procedures an application
1648 needs to know. The interface for control subsystems is still
1649 fluid and may be changed as more subsystems are developed.
1650 @c JP
1651 この節では、アプリケーションが知るべき手続きだけを説明します。
1652 制御サブシステムのためのインタフェースは未だ流動的であり、
1653 さらなるサブシステムの開発が進むにつれて、変更されるかもしれません。
1654 @c COMMON
1655
1656 @c EN
1657 Different control flow subsystems may use job structure differently.
1658 This section only describes the common properties. Check the
1659 individual control flow module to know how to handle returned job
1660 objects.
1661 @c JP
1662 異なる制御フローサブシステムは、ジョブ構造の使い方が異なる
1663 かもしれません。この節では、共通する属性のみを説明します。
1664 返されたジョブオブジェクトの扱い方については、個々の制御フロー
1665 モジュールを調べて下さい。
1666 @c COMMON
1667 @end deftp
1668
1669 @deftp {Record type} job
1670 @c MOD control.job
1671 @c EN
1672 A record type denotes the job. Applications should treat it
1673 as an opaque structure.
1674 @c JP
1675 ジョブを表すレコード型です。アプリケーションはこれを、不透明(opaque)な
1676 構造として扱うべきです。
1677 @c COMMON
1678 @end deftp
1679
1680 @defun job? obj
1681 @c MOD control.job
1682 @c EN
1683 Returns @code{#t} iff @var{obj} is a job record, @code{#f} otherwise.
1684 @c JP
1685 @var{obj}がジョブレコードだったら@code{#t}を、そうでなければ@code{#f}を返します。
1686 @c COMMON
1687 @end defun
1688
1689 @defun job-status job
1690 @c MOD control.job
1691 @c EN
1692 Returns the status of the job. It may be either one of the followings.
1693 @c JP
1694 ジョブの状態を返します。ジョブの状態は以下のいずれかになります。
1695 @c COMMON
1696 @table @code
1697 @item #f
1698 @c EN
1699 Newborn or orphaned job. Usually an application won't see a job
1700 in this status.
1701 @c JP
1702 作成したてか、孤児のジョブです。通常、アプリケーションがジョブの
1703 この状態に遭遇することはありません。
1704 @c COMMON
1705 @item acknowledged
1706 @c EN
1707 A job is recognized by a control flow library, but haven't yet
1708 been run.
1709 @c JP
1710 ジョブは制御フローライブラリによって認識されていますが、まだ
1711 実行されてはいません。
1712 @c COMMON
1713 @item running
1714 @c EN
1715 A job is being processed.
1716 @c JP
1717 ジョブは実行中です。
1718 @c COMMON
1719 @item done
1720 @c EN
1721 A job is finished. An application can retrieve its result
1722 by @code{job-result}.
1723 @c JP
1724 ジョブは完了しています。アプリケーションはその処理の結果を、
1725 @code{job-result}を使って受け取ることができます。
1726 @c COMMON
1727 @item error
1728 @c EN
1729 A job is terminated by an error. An application can retrieve the
1730 error causing condition by @code{job-result}.
1731 @c JP
1732 ジョブはエラーで終了しています。アプリケーションはエラーの原因となった
1733 コンディションを、@code{job-result}を使って受け取ることができます。
1734 @c COMMON
1735 @item killed
1736 @c EN
1737 A job is killed by external force. An application can retrieve the
1738 reason of kill (which is specific to a particular control flow
1739 subsystem) by @code{job-result}.
1740 @c JP
1741 ジョブは外部から殺されています。アプリケーションは殺された理由を、
1742 @code{job-result}を使って受け取ることができます。
1743 どのような理由でジョブが殺されるかは制御フローサブシステムによります。
1744 @c COMMON
1745 @end table
1746 @end defun
1747
1748 @defun job-result job
1749 @c MOD control.job
1750 @c EN
1751 If the job is in @code{done} status, it returns the result of the job.
1752 If the job is in @code{error} status, it returns the condition object
1753 that describes the error.
1754 If the job is in @code{killed} status, it returns an object describing
1755 the reason of kill. The details of the object depends on a particular
1756 control flow library.
1757 Calling @code{job-result} on a job in any other status may return
1758 anything; you can't rely on the result.
1759 @c JP
1760 与えられたジョブが@code{done}状態だったら、そのジョブの処理結果を返します。
1761 与えられたジョブが@code{error}状態だったら、そのエラーを説明する
1762 コンディションオブジェクトを返します。そのジョブが@code{killed}状態だったら、
1763 殺された理由を説明するオブジェクトを返します。このオブジェクトの詳細は、
1764 実際の制御フローライブラリに依存することになります。これら以外の状態の
1765 ジョブに対して@code{job-result}を読んだ場合、何が返るかはわかりません;
1766 その結果を当てにすることはできません。
1767 @c COMMON
1768 @end defun
1769
1770 @defun job-wait job :optional timeout timeout-val
1771 @c MOD control.job
1772 @c EN
1773 Suspends the calling thread until the job becomes either
1774 @code{done}, @code{error} or @code{killed} status. If the job
1775 is already in one of those status, it returns immediately.
1776 Returns job's status.
1777 @c JP
1778 与えられたジョブが@code{done}、@code{error}もしくは@code{killed}
1779 状態になるまで、呼び出したスレッドの実行をサスペンドします。
1780 ジョブがすでにこれらの状態であった時は、ただちに制御を戻します。
1781 ジョブの状態が返ります。
1782 @c COMMON
1783
1784 @c EN
1785 If @var{timeout} is given and not @code{#f}, it must be
1786 a valid timeout spec (a @code{<time>} object that represents
1787 an absolute time point, or a real number that represents a
1788 relative time in seconds.) The meaning of @var{timeout} is
1789 the same as in @code{mutex-unlock!} (@pxref{Synchronization primitives}).
1790 Once the timeout reaches, @code{job-wait} returns no matter
1791 how the job's status is, and returns the value specified
1792 to @var{timeout-val}, which defaults to @code{#f}.
1793 @c JP
1794 @var{timeout}が与えられ、それが@code{#f}ではない場合は、
1795 タイムアウトのスペックとして有効なもの(時間の絶対値を表す
1796 @code{<time>}か、現時点からの相対的な秒数を表す実数)で
1797 なければなりません。@var{timeout}の意味は、@code{mutex-unlock!}
1798 (@pxref{Synchronization primitives})のそれと同じです。
1799 タイムアウトすると、そのジョブの状態が何であれ、
1800 @code{job-wait}は引数@var{timeout-val}として指定された
1801 値を返します。デフォルト値は@code{#f}です。
1802 @c COMMON
1803
1804 @c EN
1805 Depending on the control flow subsystem, jobs created by it
1806 may not be waitable; check out each subsystem's documentation for the details.
1807 @c JP
1808 そのジョブを作成する制御フローサブシステムによっては、
1809 待ち受けできないかもしれません。それぞれのサブシステムの
1810 ドキュメントを調べて詳細を確認してください。
1811 @c COMMON
1812 @end defun
1813
1814 @defun job-acknowledge-time job
1815 @defunx job-start-time job
1816 @defunx job-finish-time job
1817 @c MOD control.job
1818 @c EN
1819 If the control flow subsystem keeps track of timestamps,
1820 these procedure returns the time (in @code{<time>} objects)
1821 when the job is acknowledged, started and finished (either normally,
1822 or abnormally by an error or by being killed). If the job hasn't
1823 reached to certain status, @code{#f} is returned instead.
1824 @c JP
1825 制御フローサブシステムがジョブのタイムスタンプを記録する場合、
1826 これらの手続きは、そのジョブがサブシステムによって認識された時刻、
1827 開始された時刻、(正常に、あるいはエラーや殺されるなど異常に)
1828 終了した時刻を(@code{<time>}オブジェクトとして)返します。
1829 ジョブがそうした状態に達していない場合は@code{#f}を返します。
1830 @c COMMON
1831
1832 @c EN
1833 If the subsystem does not track timestamps, these procedures
1834 always returns @code{#f}.
1835 @c JP
1836 そのサブシステムがタイムスタンプを記録しない場合、これらの
1837 手続きは常に@code{#f}を返します。
1838 @c COMMON
1839 @end defun
1840
1841 @c ----------------------------------------------------------------------
1842 @node Plumbing ports, Parallel map, A common job descriptor for control modules, Library modules - Utilities
1843 @section @code{control.plumbing} - Plumbing ports
1844 @c NODE ポートの配管, @code{control.plumbing} - ポートの配管
1845
1846 @deftp {Module} control.plumbing
1847 @mdindex control.plumbing
1848 @c EN
1849 This module provides utilities to use ports as communication channles
1850 between threads. Although some use cases don't involve threads,
1851 the general mechanism implicitly use threads. For example, a @emph{pump}
1852 connects an input port and an output port, making the data available
1853 from the input port to be written to the output port. It spawns a
1854 thread to read from the given input.
1855 @c JP
1856 このモジュールは、ポートをスレッド間のコミュニケーションチャネルとして使う
1857 ユーティリティを提供します。ユースケースによってはスレッドを必ずしも必要としませんが、
1858 一般的なメカニズムとして、暗黙のスレッドが使われることがあります。
1859 例えば「ポンプ」と呼ばれるデバイスは入力ポートと出力ポートをつなぎ、
1860 入力ポートに届いたデータを自動的に出力ポートに送ります。
1861 このデバイスは内部で入力ポートからデータを読み出すスレッドをspawnします。
1862 @c COMMON
1863
1864 @c EN
1865 With this module, you can construct a system that takes data from
1866 ports, and delivers it to other ports. It is like you construct
1867 plumbing system with multiple inlets and outlets; hence we named it
1868 @emph{plumbing}.
1869 @c JP
1870 このモジュールを使って、1つ以上のポートからデータを吸い出し、それを1つ以上のポートへと
1871 送り届けるシステムを作ることができます。
1872 あたかも注水口(inlet)と排水口(outlet)がある配管(plumbing)システムを作るような
1873 ものなので、このシステムを@emph{plumbing}と呼びます。
1874 @c COMMON
1875
1876 @c EN
1877 See @code{make-plumbing} below for the complete specification of
1878 plumbing.
1879 @c JP
1880 plumbingの完全な仕様については下の@code{make-plumbing}の項を参照してください。
1881 @c COMMON
1882 @end deftp
1883
1884 @c EN
1885 @subheading Plumbing system
1886 @c JP
1887 @subheading 配管システム
1888 @c COMMON
1889
1890 @defun make-plumbing
1891 @c MOD control.plumbing
1892 @c EN
1893 Creates and returns a new plumbing.
1894 @c JP
1895 新たなplumbingを作って返します。
1896 @c COMMON
1897
1898 @c EN
1899 To function, a plumbing need to have one or more @emph{inlets} and
1900 one or more @emph{outlets}. Data flowing in from inlets will flow out to
1901 outlets.
1902 @c JP
1903 機能させるためには、plumbingは1つ以上の@emph{inlet} (注水口) と
1904 1つ以上の@emph{outlet} (排水口)を持つ必要があります。
1905 データはinletから流れ込み、outletから流れ出してゆきます。
1906 @c COMMON
1907
1908 @c EN
1909 Each inlet/outlet port can be either an input port or an output port; so
1910 we'll have the following four cases:
1911 @c JP
1912 inlet, outletそれぞれどちらにも、入力ポート、出力ポートのいずれもつなぐことができます。
1913 すなわち、次の4つの組み合わせがあり得ます。
1914 @c COMMON
1915
1916 @table @asis
1917 @c EN
1918 @item Inlet input port
1919 @c JP
1920 @item Inlet入力ポート
1921 @c COMMON
1922 @c EN
1923 An input port that provides data from a producer. A dedicated thread
1924 is spanwed to read and handle the data from this port.
1925 @c JP
1926 生産者から送られるデータを読み出せる入力ポートです。
1927 このポートが繋がれた場合、専用のスレッドが作られポートからデータを読み出します。
1928 @c COMMON
1929 @c EN
1930 @item Inlet output port
1931 @c JP
1932 @item Inlet出力ポート
1933 @c COMMON
1934 @c EN
1935 An output port, to which a producer can write data. Data written to
1936 this port will be available to outlet ports.
1937 @c JP
1938 このポートに書き込まれたデータが配管システムに流れてゆきます。
1939 @c COMMON
1940 @c EN
1941 @item Outlet input port
1942 @c JP
1943 @item Outlet入力ポート
1944 @c COMMON
1945 @c EN
1946 An input port from which a consumer can read data. It has an internal buffer
1947 to keep data flowed in from inlets.
1948 @c JP
1949 配管を流れたデータが送られて、消費者がそこから流されたデータを読み出すことができる
1950 入力ポートです。内部に、送られたデータを読み出されるまで保持しておくバッファを持っています。
1951 @c COMMON
1952 @c EN
1953 @item Outlet output port
1954 @c JP
1955 @item Outlet出力ポート
1956 @c COMMON
1957 @c EN
1958 An output port to which the data will be written.
1959 @c JP
1960 配管を流れたデータが送られる出力ポートです。
1961 @c COMMON
1962 @end table
1963
1964 @c EN
1965 All read/write operations are mutexed, so you can use a plumbing
1966 as a communication channel between threads.
1967 @c JP
1968 読み書きの動作は排他制御されているので、plumbingをスレッド間のコミュニケーションチャネル
1969 として使うことができます。
1970 @c COMMON
1971
1972 @c EN
1973 The following example connects subprocess's stdout and stderr into
1974 the current output port. Both output of the subprocess is automatically
1975 read from the pipe and sent to the current output port as produced.
1976 @c JP
1977 下の例は、サブプロセスのstdoutとstderrを現在の出力ポートにつなぐ例です。
1978 サブプロセスからの両出力は、自動的にパイプから読み出されて逐次
1979 現在の出力ポートへと送られます。
1980 @c COMMON
1981
1982 @example
1983 (use gauche.process)
1984 (use control.plumbing)
1985
1986 (let ([p (run-process '(ping "127.0.0.1") :output :pipe :error :pipe)]
1987 [plumbing (make-plumbing)])
1988 (add-inlet-input-port! plumbing (process-output p))
1989 (add-inlet-input-port! plumbing (process-error p))
1990 (add-outlet-output-port! plumbing (current-output-port)))
1991 @end example
1992
1993 @c EN
1994 For typical plumbing configurations, there are utility procedures
1995 defined so that you don't need to connect pots manually; see
1996 ``Preconfigured plumbings'' section below.
1997 @c JP
1998 典型的な配管構成については、ユーティリティ手続きが定義されていて
1999 いちいちポートをひとつづつ繋がなくても良いようになっています。
2000 下の ``組み立て済みplumbing'' の項を参照してください。
2001 @c COMMON
2002 @end defun
2003
2004 @defun plumbing? obj
2005 @c MOD control.plumbing
2006 @c EN
2007 Returns @code{#t} if @var{obj} is a plumbing, @code{#f} if not.
2008 @c JP
2009 @var{obj}がplumbingであれば@code{#t}を、そうでなければ@code{#f}を返します。
2010 @c COMMON
2011 @end defun
2012
2013 @defun plumbing-inlet-ports plumbing
2014 @defunx plumbing-outlet-ports plumbing
2015 @c MOD control.plumbing
2016 @c EN
2017 Returns a list of ports connected to the @var{plumbing}'s inlets
2018 and outlets, respectively.
2019 @c JP
2020 それぞれ、@var{plumbing}のinletおよびoutletに接続されたポートのリストを返します。
2021 @c COMMON
2022 @end defun
2023
2024 @defun plumbing-get-port plumbing name
2025 @c MOD control.plumbing
2026 @c EN
2027 The @var{name} argument must be a symbol.
2028 Returns a port connected to @var{plumbing} and with @var{name}.
2029 Returns @code{#f} if there's no such ports.
2030 @c JP
2031 @var{name}引数はシンボルでなければなりません。
2032 @var{plumbing}に接続されたポートで、名前@var{name}を持つものを返します。
2033 該当するポートが無ければ@code{#f}が返ります。
2034 @c COMMON
2035 @end defun
2036
2037 @defun port-plumbing port
2038 @c MOD control.plumbing
2039 @c EN
2040 A port opened for a plumbing with @code{open-outlet-input-port},
2041 @code{open-inlet-output-port}, or other utility procedures, keeps
2042 which plumbing it belongs to. This procedure returns the plumbing
2043 associated with @var{port}. If @var{port} is not made from
2044 a plumbing, @code{#f} is returned.
2045 @c JP
2046 @code{open-outlet-input-port}や@code{open-inlet-output-port}、あるいは
2047 それらを使うユーティリティ手続きによって、plumbingのために作られたポートは、
2048 そのプロパティとして元になったplumbingへの参照を保持しています。
2049 この手続きは@var{port}が保持しているplumbingを返します。
2050 @var{port}がplumbingによって作られたものでない場合は@code{#f}が返されます。
2051 @c COMMON
2052
2053 @c EN
2054 Note that an existing port added to a plumbing by
2055 @code{add-inlet-output-port!} etc. does not keep the plumbing
2056 it is attached to, and this procedure returns @code{#f} on such a port.
2057 @c JP
2058 既にあるポートを@code{add-inlet-output-port!}等でplumbingに接続した場合は、
2059 そのポートはplumbingによって作られたわけではないので、この手続きは@code{#f}を返す
2060 ことに注意してください。
2061 @c COMMON
2062 @end defun
2063
2064 @c EN
2065 @subheading Creating and attaching ports to plumbing
2066 @c JP
2067 @subheading plumbingにポートを作ったり接続したりする
2068 @c COMMON
2069
2070 @defun open-inlet-output-port plumbing :optional name
2071 @c MOD control.plumbing
2072 @c EN
2073 Creates an output port connected to @var{plumbing}'s inlet; that is,
2074 the data written to the port will flow to @var{plumbing}'s outlets.
2075 @c JP
2076 @var{plumbing}のinletに接続された出力ポートを作って返します。
2077 このポートに書き込まれたデータは、@var{plumbing}を通ってそのoutletに流れてゆきます。
2078 @c COMMON
2079
2080 @c EN
2081 The optional @var{name} should be a symbol or @code{#f}. If it is
2082 a symbol, the port will be retrieved from @var{plumbing} with
2083 @code{plumbing-get-port}.
2084 @c JP
2085 省略可能な@var{name}引数はシンボルか@code{#f}でなければなりません。
2086 これがシンボルの場合、作られたポートは@code{plumbing-get-port}で
2087 @var{plumbing}から取り出すことができます。
2088 @c COMMON
2089
2090 @c EN
2091 Applying @code{port-plumbing} on the returned port returns @var{plumbing}.
2092 @c JP
2093 また、返されたポートに@code{port-plumbing}を適用すると@var{plumbing}が得られます。
2094 @c COMMON
2095
2096 @c EN
2097 Once you close the returned port, the port is removed from @var{plumbing}.
2098 Once all inlet ports are closed, the outlet ports of @var{plumbing}
2099 get EOF.
2100 @c JP
2101 返されたポートをクローズすると、それは@var{plumbing}から取り除かれます。
2102 全てのinletポートがクローズされた時に、@var{plumbing}のoutletポートはEOFを受け取ります。
2103 @c COMMON
2104 @end defun
2105
2106 @defun add-inlet-input-port! plumbing iport :optional name
2107 @c MOD control.plumbing
2108 @c EN
2109 Connects an existing input port @var{iport} to @var{plumbing}'s inlet.
2110 A thread in @var{plumbing} reads from @var{iport} and feeds the data
2111 to its outlets.
2112 @c JP
2113 既存の入力ポート@var{iport}を@var{plumbing}のinletに接続します。
2114 @var{iport}からデータを読み出し、それを@var{plumbing}のoutletに送るための
2115 スレッドが作られます。
2116 @c COMMON
2117
2118 @c EN
2119 The optional @var{name} should be a symbol or @code{#f}. If it is
2120 a symbol, the port will be retrieved from @var{plumbing} with
2121 @code{plumbing-get-port}.
2122 @c JP
2123 省略可能な@var{name}引数はシンボルか@code{#f}でなければなりません。
2124 これがシンボルの場合、作られたポートは@code{plumbing-get-port}で
2125 @var{plumbing}から取り出すことができます。
2126 @c COMMON
2127
2128 @c EN
2129 Once EOF is read from @var{iport}, it is removed from @var{plumbing}.
2130 Once all inlet ports are closed, the outlet ports of @var{plumbing}
2131 get EOF.
2132 @c JP
2133 @var{iport}からEOFが読まれたら、そのポートは@var{plumbing}から取り除かれます。
2134 全てのinletポートがクローズされた時に、@var{plumbing}のoutletポートはEOFを受け取ります。
2135 @c COMMON
2136 @end defun
2137
2138 @defun open-outlet-input-port plumbing :optional name
2139 @c MOD control.plumbing
2140 @c EN
2141 Creates an input port connected to @var{plumbing}'s outlet; that is,
2142 from that port you can read the data fed to @var{plumbing}'s inlets.
2143 @c JP
2144 @var{plumbing}のoutletに接続された入力ポートを作って返します。
2145 @var{plumbing}のinletに流れ込んだデータをそのポートから読み出すことができます。
2146 @c COMMON
2147
2148 @c EN
2149 The optional @var{name} should be a symbol or @code{#f}. If it is
2150 a symbol, the port will be retrieved from @var{plumbing} with
2151 @code{plumbing-get-port}.
2152 @c JP
2153 省略可能な@var{name}引数はシンボルか@code{#f}でなければなりません。
2154 これがシンボルの場合、作られたポートは@code{plumbing-get-port}で
2155 @var{plumbing}から取り出すことができます。
2156 @c COMMON
2157
2158 @c EN
2159 Applying @code{port-plumbing} on the returned port returns @var{plumbing}.
2160 @c JP
2161 返されたポートに@code{port-plumbing}を適用すると@var{plumbing}が得られます。
2162 @c COMMON
2163
2164 @c EN
2165 Once all inlets are closed, the returned port yields EOF.
2166 You can close the returned port at any time; then the port is removed
2167 from @var{plumbing}'s outlets and no data will be delivered to it.
2168 @c JP
2169 全てのinletがクローズされると、返されたポートからEOFが読まれます。
2170 返されたポートはいつでもクローズできます。クローズされるとそれは
2171 @var{plumbing}のoutletから取り除かれ、データは送られなくなります。
2172 @c COMMON
2173 @end defun
2174
2175 @defun add-outlet-output-port! plumbing oport :optional name :key close-on-eof asynchronous
2176 @c MOD control.plumbing
2177 @c EN
2178 Connects an existing output port @var{oport} to @var{plumbing}'s outlet.
2179 Data flowed in from @var{plumbing}'s inlet will be written to @var{oport}.
2180 @c JP
2181 既存の出力ポート@var{oport}を@var{plumbing}のoutletに接続します。
2182 @var{plumbing}に流れ込んだデータはその都度@var{oport}に送られます。
2183 @c COMMON
2184
2185 @c EN
2186 The optional @var{name} should be a symbol or @code{#f}. If it is
2187 a symbol, the port will be retrieved from @var{plumbing} with
2188 @code{plumbing-get-port}.
2189 @c JP
2190 省略可能な@var{name}引数はシンボルか@code{#f}でなければなりません。
2191 これがシンボルの場合、作られたポートは@code{plumbing-get-port}で
2192 @var{plumbing}から取り出すことができます。
2193 @c COMMON
2194
2195 @c EN
2196 You can close the returned port at any time; then the port is removed
2197 from @var{plumbing}'s outlets and no data will be delivered to it.
2198 @c JP
2199 返されたポートはいつでもクローズできます。クローズされるとそれは
2200 @var{plumbing}のoutletから取り除かれ、データは送られなくなります。
2201 @c COMMON
2202
2203 @c EN
2204 By default, @var{oport} is left as is after all inlets are closed;
2205 @var{plumbing} won't write anything to @var{oport} but you can still write to
2206 it. If you specify a true value to the @var{close-on-eof} keyword argument,
2207 however, @var{plumbing} will close @var{oport} when all of its inlets are closed.
2208 It is useful, for example, when @var{oport} is a file output port and
2209 you want to close it once @var{plumbing} is done. However, if @var{oport}
2210 is a standard output port for logging purpose, you don't want it to be
2211 automatically closed.
2212 @c JP
2213 デフォルトでは、全てのinletがクローズされた後でも@var{oport}はオープンしたままにされます。
2214 @var{plumbing}がそれ以降そこに書き込むことはありませんが、
2215 @var{oport}に追加で出力することはできます。
2216 ただし、@var{close-on-eof}キーワード引数に真の値を指定すると、
2217 @var{plumbing}は全てのinletがクローズされた時点で@var{oport}をクローズします。
2218 これは、例えばファイルを出力用にオープンしてそのポートを@var{oport}として
2219 渡し、データが来なくなったら自動的にクローズしたい、という場合に便利です。
2220 けれども、例えばログ出力を監視するために@var{oport}に標準出力を渡すといった場合は、
2221 勝手にクローズされると困るでしょう。
2222 @c COMMON
2223
2224 @c EN
2225 If a true value is given to the @var{asynchronous} keyword argument,
2226 a thread is spawn to feed the data to @var{oport}; it is useful if
2227 @var{oport} can be blocked, e.g. an OS pipe or a socket.
2228 Without @var{asynchronous}, blocked output to @var{oport} causes
2229 data flow to inlets to be blocked as well. With @var{asynchronous},
2230 other threads can keep feeding to inlets.
2231 @c JP
2232 @var{asynchronous}キーワード引数に真の値が渡された場合、
2233 @var{oport}にデータを送るための専用スレッドが作られます。
2234 これは、@var{oport}がOSのパイプやソケットのようにブロックする可能性がある場合に
2235 便利です。@var{asynchronous}が無い場合、@var{oport}がブロックすると
2236 plumbing全体がブロックしてしまう可能性があります。
2237 @var{asynchronous}を指定しておくと、このポートへの出力以外は動きつづけます。
2238 @c COMMON
2239 @end defun
2240
2241 @defun plumbing spec @dots{}
2242 @c MOD control.plumbing
2243 @c EN
2244 A utility plumbing constructor. It creates a new plumbing,
2245 and adds inlets and outlets as specified by @var{spec}s,
2246 then returns the plumbing. Each @var{spec} must be one of
2247 the following forms. In the description, @var{iport}
2248 is an input port, @var{oport} is an output port, and
2249 @var{name} is a symbol.
2250 @c JP
2251 plumbingを簡単に組み立てるためのユーティリティです。
2252 新しいplumbingを作り、@var{spec}に従ってinletとoutletを接続して、
2253 作られたplumbingを返します。各@var{spec}は以下に挙げる形式のいずれかです。
2254 説明中、@var{iport}は入力ポート、@var{oport}は出力ポート、
2255 @var{name}はシンボルです。
2256 @c COMMON
2257
2258 @table @code
2259 @item (< @var{iport})
2260 @itemx (< @var{iport} @var{name})
2261 @c EN
2262 Adds @var{iport} to the plumbing's inlet, optionally naming it
2263 with @var{name}.
2264 @c JP
2265 @var{iport}をplumbingのinletに接続します。名前@var{name}をつけることもできます。
2266 @c COMMON
2267 @item (< @var{name})
2268 @c EN
2269 Creates an inlet output port with name @var{name}.
2270 The output port can be retrieved by @code{plumbing-get-port}.
2271 @c JP
2272 名前@var{name}を持つinlet出力ポートを作ります。
2273 作られた出力ポートは@code{plumbing-get-port}で取り出すことができます。
2274 @c COMMON
2275 @item (> @var{oport})
2276 @itemx (> @var{oport} @var{name})
2277 @itemx (> @var{oport} (@var{option} @dots{}))
2278 @itemx (> @var{oport} @var{name} (@var{option} @dots{}))
2279 @c EN
2280 Adds @var{oport} to the plumbing's outlet, optional naming it
2281 with @var{name}. Options can be one of the keywords @code{:close-on-eof},
2282 @code{:coe}, @code{asynchronous}, and @code{:async}. @code{:close-on-eof}
2283 and @code{asynchronous} has the effect of giving true to those keyword
2284 arguments to @code{add-outlet-output-port!}. @code{:coe} and @code{:async}
2285 are synonyms of @code{:close-on-eof} and @code{:asynchronous}, respectively.
2286 @c JP
2287 @var{oport}をplumbingのouletに接続します。@var{name}が与えられればそれが
2288 名前になります。また、@var{option}としてキーワード
2289 @code{:close-on-eof}、@var{:coe}、@code{:asynchronous}、@code{:async}の
2290 組み合わせを指定することができます。@code{:close-on-eof}、@code{:asynchronous}は
2291 @code{add-outlet-output-port!}で同名のキーワード引数に真の値を指定するのと同じ効果
2292 を持ちます。@code{:coe}と@code{:async}はそれぞれ@code{:close-on-eof}と
2293 @code{:asynchronous}の省略形です。
2294 @c COMMON
2295 @item (> @var{name})
2296 @c EN
2297 Creates an outlet input port with name @var{name}.
2298 The output port can be retrieved by @code{plumbing-get-port}.
2299 @c JP
2300 名前@var{name}を持つoutlet入力ポートを作ります。
2301 作られたポートは@code{plumbing-get-port}で取り出せます。
2302 @c COMMON
2303 @end table
2304 @end defun
2305
2306 @c EN
2307 @subheading Preconfigured plumbings
2308 @c JP
2309 @subheading 組み立て済みplumbing
2310 @c COMMON
2311
2312 @c EN
2313 The following are convenience procedures to construct typical
2314 plumbings.
2315 @c JP
2316 以下に挙げるのは、典型的な組み立てのplumbingを作る便利手続きです。
2317 @c COMMON
2318
2319 @defun make-pipe :key num-inlets num-outlets
2320 @c MOD control.plumbing
2321 @c EN
2322 A pipe is a passive plumbing device that has inlet output port(s) and
2323 outlet input port(s).
2324 Data written to the inlet output ports
2325 will be buffered and available to read from the outlet input ports.
2326 This procedure creates a pipe
2327 with @var{num-inlets} inlet output ports
2328 and @var{num-outlets} outlet input ports,
2329 and returns two values, a list of inlet ports and a list of outlet ports.
2330 @c JP
2331 パイプはinlet出力ポートとoutlet入力ポートを持つ受動的なplumbingです。
2332 inlet出力ポートに書き込まれたデータは各outlet入力ポートにバッファされ、
2333 読み出されるのを待ちます。
2334 この手続きは、@var{num-inlets}個のinlet出力ポートと、
2335 @var{num-outlets}個のoutlet出力ポートを持つパイプを作り、
2336 inletポートのリストとoutletポートのリストの2つの値を返します。
2337 @c COMMON
2338
2339 @c EN
2340 Both @var{num-inlets}
2341 and @var{num-outlets} should be a positive exact integer. If omitted,
2342 1 is assumed.
2343 @c JP
2344 @var{num-inlets}と@var{num-outlets}はともに正の正確な整数でなければなりません。
2345 省略された場合は1とみなされます。
2346 @c COMMON
2347
2348 @c EN
2349 If there are more than one outlets, data is duplicated; each consumer
2350 reads the same data. Buffers are attached to each outlet, so each
2351 consumer can read the outlet in its own pace.
2352 @c JP
2353 outletが複数ある場合、データは複製されます。つまり、それぞれの消費者は
2354 同じデータを読み出します。それぞれのoutletが独立したバッファを持つので、
2355 各消費者はそれぞれのペースで読み出すことができます。
2356 @c COMMON
2357
2358 @c EN
2359 The created plumbing can be obtained by applying @code{port-plumbing}
2360 to any of the returned ports.
2361 @c JP
2362 作られたplumbingを得るには、返されたポートのいずれかに@code{port-plumbing}を
2363 適用します。
2364 @c COMMON
2365
2366 @c EN
2367 This procedure is similar to @code{sys-pipe}, which creates a pair
2368 of ports using OS's pipe mechanism (@pxref{Other file operations}).
2369 However, the pipe device
2370 created by @code{make-pipe} is a user-land construct and only for
2371 inter-thread communication; it can't be used for inter-process
2372 communication. On the other hand, you can have n-in m-out pipe
2373 using @code{make-pipe}.
2374 @c JP
2375 この手続きは@code{sys-pipe}と似ていますが、
2376 @code{sys-pipe}はOSのパイプを使い、その両端に繋がれた入力ポートと出力ポートを
2377 返します (@ref{Other file operations}参照)。
2378 @code{make-pipe}が作るパイプはあくまでユーザ空間の構築物で、
2379 プロセス間通信には使えず、スレッド間通信にしか使えません。
2380 一方、@code{make-pipe}はn-入力/m-出力のパイプを作ることができます。
2381 @c COMMON
2382 @end defun
2383
2384 @defun make-pump inlet-iports outlet-oports
2385 @c MOD control.plumbing
2386 @c EN
2387 A pump is an active plumbing device that reads data from
2388 the given inlet input ports, and write it out to the given
2389 outlet output ports.
2390 @c JP
2391 ポンプは与えられた入力ポートからデータを読み出し、それを
2392 与えられた出力ポートへと送り出す、アクティブなplumbingです。
2393 @c COMMON
2394
2395 @c EN
2396 The @var{inlet-iports} argument must be a list of input ports,
2397 and @var{outlet-oports} argument must be a list of output ports.
2398 @c JP
2399 @var{inlet-iports}引数は入力ポートのリスト、
2400 @var{outlet-oports}引数は出力ポートのリストでなければなりません。
2401 @c COMMON
2402
2403 @c EN
2404 A dedicated thread is spawn to each inlet input port to read
2405 from it.
2406 @c JP
2407 各inlet入力ポートそれぞれに対し、そこから読み出すスレッドがスポーンされます。
2408 @c COMMON
2409 @end defun
2410
2411 @defun open-broadcast-output-port oport @dots{}
2412 @c MOD control.plumbing
2413 @c EN
2414 All the arguments must be output ports.
2415 Returns an output port such that data written to it go to every @var{oport}.
2416 Internally, it creates a plumbing, adds @var{oport}s to its outlet,
2417 and returns a new inlet output port. The plumbing can be retrieved
2418 by calling @code{port-plumbing} on the returned port.
2419 @c JP
2420 引数は全て出力ポートでなければなりません。
2421 新たな出力ポートを返します。そのポートに書かれたデータは、全ての@var{oport}へと送られます。
2422 内部的には、この手続きはplumbingを作り、@var{oport} @dots{}をoutletに接続し、
2423 そしてinlet出力ポートを返します。返されたポートに@code{port-plumbing}を適用すれば
2424 plumbingが得られます。
2425 @c COMMON
2426
2427 @c EN
2428 This is Common Lisp's @code{make-broadcast-stream}.
2429 @c JP
2430 これはCommon Lispの@code{make-broadcast-stream}にあたります。
2431 @c COMMON
2432 @end defun
2433
2434 @defun open-tapping-input-port inlet-iport outlet-oport :key close-on-eof
2435 @c MOD control.plumbing
2436 @c EN
2437 It creates a pump, a plumbing that reads from @var{inlet-iport} and
2438 writes out the read data to @var{outlet-oport}. Additionally, it creates
2439 and returns an outlet input port, from which you can read the data
2440 flowing in the pump.
2441 @c JP
2442 これは、@var{inlet-port}からデータを吸出し@var{outlet-oport}に送り出すポンプを
2443 作りますが、同時にそこに流れるデータを読み出せるoutlet入力ポートを作って返します。
2444 @c COMMON
2445
2446 @c EN
2447 An example use case is to monitor process output. You spawn a process
2448 with its stdout connected to a pipe, then call
2449 @code{(open-tapping-input-port (process-output subprocess) (current-output-port))}.
2450 With this, the subprocess's output automatically flows to your process's output.
2451 However, that data is also available from the returned input port,
2452 and you can check it.
2453 @c JP
2454 例えばそれは、プロセスの出力を監視するのに使えます。
2455 標準出力をパイプに流す子プロセスを作り、
2456 @code{(open-tapping-input-port (process-output subprocess) (current-output-port))} を呼びます。
2457 すると、子プロセスの出力は自動的に現在の出力ポートに流されますが、
2458 そのデータは戻り値の入力ポートから読み出せるので、そこで監視することができます。
2459 @c COMMON
2460
2461 @c EN
2462 Note that the data passed from @var{inlet-iport} to @var{outlet-oport} are
2463 buffered for the returned input port until you read from it. If you're
2464 done with monitoring, you can close the returned input port safely; the
2465 data will no longer be buffered, but the pump will keep running until
2466 the input reaches EOF.
2467 @c JP
2468 @var{inlet-iport}から読み出され@var{outlet-oport}に送られるデータは、
2469 戻り値の入力ポートからも読み出せるようにバッファされることに注意してください。
2470 監視する必要がなくなったらいつでも、戻り値の入力ポートを閉じることができます。
2471 そうすれば流れるデータはバッファされなくなりますが、ポンプはinletからのデータが
2472 EOFに達するまで動きつづけます。
2473 @c COMMON
2474
2475 @c EN
2476 The pump plumbing is available by calling @code{port-plumbing} on the
2477 returned input port.
2478 @c JP
2479 ポンプのplumbingは、戻り値の入力ポートに@code{port-plumbing}を適用すると得られます。
2480 @c COMMON
2481 @end defun
2482
2483 @c ----------------------------------------------------------------------
2484 @node Parallel map, Scheduler, Plumbing ports, Library modules - Utilities
2485 @section @code{control.pmap} - Parallel map
2486 @c NODE 並列map, @code{control.pmap} - 並列map
2487
2488 @deftp {Module} control.pmap
2489 @mdindex control.pmap
2490 @c EN
2491 This module provides high-level utilities to run code in parallel
2492 using threads.
2493 For example, the @code{pmap} procedure applies the given procedure
2494 on each elements in the collection and gathers the restuls into a list,
2495 just like @code{map}, but the appliation of the procedure is done in parallel.
2496 @c JP
2497 このモジュールは、コードを複数スレッドで並列に走らせる高レベルユーティリティを提供します。
2498 例えば@code{pmap}は、@code{map}と同様に、
2499 与えられたコレクションの各要素に手続きを適用してその結果をリストにして返しますが、
2500 手続きの適用は並列に行われます。
2501 @c COMMON
2502
2503 @c EN
2504 A desired parallelization strategy differs for application, so we also
2505 pvovide @emph{mapper} objects, that encapsulate how the work is distributed.
2506 @c JP
2507 応用によって望ましい並列化戦略が違うので、仕事の割り振りの戦略をカプセル化する
2508 @emph{mapper}オブジェクトも提供されます。
2509 @c COMMON
2510 @end deftp
2511
2512 @c EN
2513 @subheading High-level API
2514 @c JP
2515 @subheading 高レベルAPI
2516 @c COMMON
2517
2518 @defun pmap proc collection :key mapper
2519 @c MOD control.pmap
2520 @c EN
2521 The @var{proc} argument must be a procedure that takes one argument,
2522 and @var{collection} must be a collection (@pxref{Collection framework}).
2523 @c JP
2524 @var{proc}はひとつの引数を取る手続き、@var{collection}はコレクションです
2525 (@ref{Collection framework}参照)。
2526 @c COMMON
2527
2528 @c EN
2529 Applies @var{proc} on each element of @var{collection}, possibly concurrently
2530 using multiple threads. The result is gathered into a list and
2531 returned.
2532 @c JP
2533 @var{collection}の各要素に、@var{proc}を適用します。
2534 適用は複数のスレッドを使って並行して行われるかもしれません。結果はリストにまとめられて返されます。
2535 @c COMMON
2536
2537 @c EN
2538 You can pass a mapper to the @var{mapper} keyword argument to specify how
2539 the task is distibuted to multiple threads.
2540 @c JP
2541 @var{mapper}キーワード引数にmapperを渡すことで、各スレッドにどのように仕事が
2542 割り振られるかをカスタマイズできます。
2543 @c COMMON
2544 @end defun
2545
2546 @defun pfind pred collection :key mapper
2547 @defunx pany pred collection :key mapper
2548 @c MOD control.pmap
2549 @c EN
2550 These are to be used to find one element that satisfies the predicate @var{pred}.
2551 As soon as the element is found, other tasks are cancelled.
2552 @c JP
2553 これらは、@var{pred}を満たす要素を一つ見つけたい時に使えます。
2554 条件に合う要素が見つかった時点で、他のタスクはキャンセルされます。
2555 @c COMMON
2556
2557 @c EN
2558 @code{pfind} is like @code{find} that returns the element that satisfies
2559 @var{pred}, while @code{pany} is like @code{any} that returns the result
2560 of @var{pred} that isn't @code{#f}.
2561 @c JP
2562 @code{pfind}は@code{find}のように、@var{pred}を満たす要素を見つけたらその要素自身を
2563 返します。一方、@code{pany}は@code{any}と同じように、
2564 @var{pred}が@code{#f}でない値を返したらその返り値を返します。
2565 @c COMMON
2566
2567 @c EN
2568 If no element satisfies @var{pred}, @code{#f} is returned.
2569 @c JP
2570 @var{pred}を満たす要素が一つも無ければ@code{#f}が返ります。
2571 @c COMMON
2572
2573 @c EN
2574 If there are more than one element that satisfy @var{pred}, which one is picked
2575 depends on various factors, so you shouln't count on a deterministic behavior.
2576 @c JP
2577 @var{pred}を満たす要素が複数あった場合にどれが返るかは様々な状況に依存するので、
2578 決定的な振る舞いを期待すべきではありません。
2579 @c COMMON
2580 @end defun
2581
2582 @subheading Mappers
2583
2584 @c EN
2585 A mapper is an object that encapsulates a storategy to run
2586 tasks in parallel. We provide the following mappers.
2587 @c JP
2588 mapperはタスクを並列に走らせる戦略をカプセル化したものです。
2589 次のmapperが提供されます。
2590 @c COMMON
2591
2592 @table @code
2593 @item Static mapper
2594 @c EN
2595 Creates several threads and distribute the tasks evenly. It is suitable
2596 when the number of tasks are large and each task is expected to take
2597 mostly same amount of time, for it takes less overhead than other
2598 multi-threading mappers.
2599 @c JP
2600 いくつかのスレッドを作り、タスクを均等に割り振ります。
2601 タスク数が多く、各タスクにかかる時間がそれほど分散しない場合に適しています。
2602 他のマルチスレッドmapperよりもオーバヘッドが少ないです。
2603 @c COMMON
2604 @item Pool mapper
2605 @c EN
2606 Uses thread pool to process the tasks. It is suitable when the number
2607 of tasks are large and/or the execution time of each task varies
2608 a lot. You can also reuse the pooled threads, so that you can
2609 reduce the overhead of thread creation.
2610 @c JP
2611 スレッドプールを使ってタスクを処理します。タスク数が多いか、
2612 各タスクの実行にかかる時間の分散が大きい場合に適しています。
2613 また、スレッドプールを再利用することもでき、スレッド作成のオーバヘッドを削減できます。
2614 @c COMMON
2615 @item Fully concurrent mapper
2616 @c EN
2617 Creates one thread per each task. It is suitable when the task
2618 involves blocking I/O calls, and the number of tasks are not so large.
2619 @c JP
2620 タスクの数だけスレッドを作成して実行します。タスク数がそれほど多くなく、
2621 タスクの中でブロッキングI/Oをする場合に適しています。
2622 @c COMMON
2623 @item Sequential mapper
2624 @c EN
2625 This runs tasks sequentially in a calling thread. No concurrency involved.
2626 It serves two purposes: (1) On a single-core system, this is the least
2627 overhead strategy, and (2) You can test the algorithmic correctness
2628 without complication of concurrency. On single-core systems,
2629 this mapper is the default value of @code{default-mapper}.
2630 @c JP
2631 これは呼び出したスレッド内でタスクを逐次的に実行します。並行実行は行われません。
2632 これには2つの目的があります。(1)シングルコアのシステムでは、
2633 これが最もオーバヘッドの少ない戦略です。(2)並行性による複雑さを除外してアルゴリズムの
2634 動作を確かめるのに使えます。
2635 シングルコアシステムでは、これが@code{default-mapper}の初期値です。
2636 @c COMMON
2637 @end table
2638
2639 @deffn {Parameter} default-mapper
2640 @c MOD control.pmap
2641 @c EN
2642 A parameter keeping a mapper to be used by @code{pmap} etc. when no
2643 mapper is specified.
2644 @c JP
2645 @code{pmap}等が使うmapperの省略時の値を保持するパラメータです。
2646 @c COMMON
2647
2648 @c EN
2649 The default is a static mapper (with the number of threads same as
2650 the number of available cores) if Gauche is running system with
2651 more than one core, or a sequential mapper otherwise.
2652 @c JP
2653 Gaucheが複数コアのシステム上で走っている場合はコア数と同じスレッドを使う
2654 static mapperが、そうでなければsequential mapperが初期値となります。
2655 @c COMMON
2656
2657 @c EN
2658 The mapper set to this parameter is reused, or even is used
2659 simultaneously from multiple @code{pmap} calls.
2660 Pool mappers with external pool keeps a given thread pool in it,
2661 so you should be careful to use such mapper as the default mapper.
2662 @c JP
2663 このパラメータにセットされたmapperは再利用されたり、複数の@code{pmap}呼び出しから
2664 同時に使われたりする可能性があります。
2665 外部スレッドプールを使うpool mapperはスレッドプールを共有するので、
2666 それをデフォルトのmapperに設定する時は注意してください。
2667 @c COMMON
2668 @end deffn
2669
2670 @defun sequential-mapper
2671 @c MOD control.pmap
2672 @c EN
2673 Returns a sigleton instance of the sequential mapper.
2674 @c JP
2675 sequential mapperのシングルトンインスタンスを返します。
2676 @c COMMON
2677 @end defun
2678
2679 @defun make-static-mapper :optional num-threads
2680 @c MOD control.pmap
2681 @c EN
2682 Returns a new instance of a static mapper, which spawns @var{num-threads}
2683 threads on execution, each of which handles evenly divided tasks.
2684 This mapper is suitable if you have large number of small tasks with
2685 even load.
2686
2687 If @var{num-threads} is omitted, the number of available
2688 processors returned by @code{sys-available-processors}
2689 is used (@pxref{Environment inquiry}).
2690 @c JP
2691 static mapperの新しいインスタンスを作って返します。
2692 このmapperは@code{pmap}の実行のたびに@var{num-threads}のスレッドを作成し、
2693 必要な仕事を均等に割り振ります。小さく均等なタスクを大量にこなす場合に便利です。
2694
2695 @var{num-threads}が省略された場合は、@code{sys-available-processors}
2696 が返すプロセッサ数を使います
2697 (@ref{Environment inquiry}参照)。
2698 @c COMMON
2699 @end defun
2700
2701 @defun make-pool-mapper :optional external-pool
2702 @c MOD control.pmap
2703 @c EN
2704 Returns a new instance of a pool mapper, which uses a thread pool
2705 (@pxref{Thread pools}) to run the tasks. It is suitable when the load
2706 of tasks varies a lot.
2707 @c JP
2708 スレッドプールを使うpool mapperの新たなインスタンスを作って返します。
2709 タスクごとに計算負荷が大きく変動する場合に適しています。
2710 @c COMMON
2711
2712 @c EN
2713 If @var{external-pool} is not given, the mapper creats a thread
2714 pool, and shut it down, every time high-level mapping operation is called.
2715 This usage is local; that is, the thread pool is contained within
2716 one call of @code{pmap} etc., and won't be shared.
2717 @c JP
2718 @var{external-pool}が指定されなければ、mapperは高レベルのマッピング操作が呼ばれる
2719 度に新たなスレッドプールを作り、マッピング操作が終わったらプールをシャットダウンします。
2720 この場合、ひとつのスレッドプールは一回の@code{pmap}などの呼び出しだけに使われ、
2721 他と共有されることはありません。
2722 @c COMMON
2723
2724 @c EN
2725 Alternatively, you can pass an existing thread pool to @var{external-pool}
2726 to be used. The pool will be reused every time you use this mapper instance.
2727 Using an external pool will eliminate overhead of thread pool creation and
2728 shutting down every time you run @code{pmap}; however, you have to be
2729 aware of those caveats:
2730 @c JP
2731 あるいは、既にあるスレッドプールを@var{external-pool}引数に渡すこともできます。
2732 その場合、このmapperインスタンスが使われる場面全てで、そのスレッドプールは再利用されます。
2733 外部スレッドプールを使うことで、@code{pmap}を呼ぶ度にスレッドプールを作ったり
2734 シャットダウンしたりするオーバヘッドを避けることができます。
2735 しかし、次の点に注意しなければなりません。
2736 @c COMMON
2737 @itemize @bullet
2738 @item
2739 @c EN
2740 It's your responsibility to shut down the thread pool after you're done
2741 with the mapper.
2742 @c JP
2743 mapperをもう使わなくなってからスレッドプールをシャットダウンするのは、
2744 ユーザの責任です。
2745 @c COMMON
2746 @item
2747 @c EN
2748 The mapper keeps the given thread pool and reuses it every time
2749 it is passed to @code{pmap} etc., so you have to make sure that
2750 one mapper is not used simultaneously in more than one @code{pmap} etc..
2751 Be careful using this type of pool mapper as the default mapper.
2752 @c JP
2753 mapperは渡されたスレッドプールを@code{pmap}の呼び出しに使いまわすので、
2754 ひとつのpool mapperが複数の@code{pmap}呼び出しで同時に使われることがないように
2755 管理してやる必要があります。特に、デフォルトのmappersとして外部スレッドプールを
2756 使うpool mapperを設定するのは危険です。
2757 @c COMMON
2758 @end itemize
2759 @end defun
2760
2761 @defun make-fully-concurrent-mapper :optional timeout timeout-val
2762 @c MOD control.pmap
2763 @c EN
2764 Returns a new instance of a fully-concurrent mapper, which spawns
2765 as many threads as the elements in the given collection to perform
2766 the operation concurrently. It is suitable when you don't have
2767 many tasks, but each task may perform blocking I/O calls.
2768 The overhead of creating threads are relatively large, but
2769 you may be able to utilize CPU more while most of the threads are
2770 waiting I/O.
2771 @c JP
2772 タスクの数だけスレッドを作成し、全てを並行に評価する完全並行mapperを作って返します。
2773 タスクの数が比較的少数で、各タスクがI/Oなどでブロックする場合に適しています。
2774 スレッドを作成するオーバヘッドが比較的大きいですが、スレッドがI/O待ちの間に
2775 CPUを有効活用できます。
2776 @c COMMON
2777
2778 @c EN
2779 The optional @var{timeout} argument can specify
2780 the timeout value for threads to run. As in @code{thread-join!},
2781 it can be either a @code{<time>} object to specify an absolute
2782 point of time, a real number for the number of seconds from
2783 the current time, or @code{#f} to run it indefinitely.
2784 The default is @code{#f}.
2785
2786 If timeout reaches, @var{timeout-val} is used in place of
2787 the result of @var{proc}, which is defaulted to @code{#f}.
2788 @c JP
2789 省略可能な@var{timeout}引数で、スレッドにタイムアウトを指定できます。
2790 @code{thread-join!}のtimeout引数と同様に、@code{<time>}オブジェクトによる
2791 絶対時刻、実数による現在時刻からの相対秒、そしてタイムアウトを設けない@code{#f}が
2792 指定できます。省略時はタイムアウトしません。
2793
2794 タイムアウトした場合、@var{timeout-val}が@var{proc}の結果の代わりに使われます。
2795 @var{timeout-val}の省略時値は@code{#f}です。
2796 @c COMMON
2797
2798 @c EN
2799 NB: If @var{timeout} reaches, the running threads are terminated by
2800 @code{thread-terminate!}. If the thread is locking a mutex
2801 when it occurs, the mutex becomes `abandoned' state. The resources
2802 being used then may not be properly cleaned up. If you need
2803 to ensure proper cleanup in bounded time, you need to code it in @var{proc}
2804 explicitly.
2805 @c JP
2806 註: スレッドがタイムアウトした場合、
2807 走行中のスレッドは@code{thread-terminate!}で終了させられます。
2808 この時スレッドがmutexをロックしていればそれはabandoned状態になりますし、
2809 リソースを掴んでいたら適切なクリーンアップがなされないかもしれません。
2810 スレッドの実行を制限時間内に納め、かつクリーンアップを確実にしたい場合は、
2811 そういうロジックを明示的に@var{proc}に組み込んでください。
2812 @c COMMON
2813 @end defun
2814
2815 @c ----------------------------------------------------------------------
2816 @node Scheduler, Thread pools, Parallel map, Library modules - Utilities
2817 @section @code{control.scheduler} - Scheduler
2818 @c NODE スケジューラ, @code{control.scheduler} - スケジューラ
2819
2820 @deftp {Module} control.scheduler
2821 @mdindex control.scheduler
2822 @c EN
2823 A scheduler is a device to run tasks in scheduled time.
2824 @c JP
2825 スケジューラは、予定された時刻にタスクを走らせるデバイスです。
2826 @c COMMON
2827
2828 @c EN
2829 Each scheduler manages one or more tasks. Each task has attached
2830 time to run. A task can be run once, or can be run periodically.
2831 @c JP
2832 各スケジューラは一つ以上のタスクを管理します。各タスクには、それがいつ走るかを
2833 指定する時刻が付随します。タスクは一回だけ走らせることも、
2834 定期的に走らせることもできます。
2835 @c COMMON
2836
2837 @c EN
2838 For portable code, you can use SRFI-120 (@pxref{Timer APIs}),
2839 which is written on top of this module.
2840 @c JP
2841 ポータブルなコードでは、このモジュールの上に構築された
2842 SRFI-120を使うこともできます(@ref{Timer APIs}参照)。
2843 @c COMMON
2844 @end deftp
2845
2846 @deftp {Class} <scheduler>
2847 @clindex scheduler
2848 @c MOD control.scheduler
2849 @c EN
2850 A device to run tasks in scheduled time. Each instance of this class
2851 have its own thread, and maintains a list of tasks along the information
2852 when each task should be run. Tasks can be registered by
2853 @code{scheduler-schedule!}.
2854 @c JP
2855 タスクを予定された時刻に走らせるデバイスです。
2856 各スケジューラインスタンスは独自のスレッドを持ち、
2857 タスクとそれをいつ走らせるかのリストを管理しています。
2858 タスクは@code{scheduler-schedule!}で登録できます。
2859 @c COMMON
2860
2861 @c EN
2862 If a task throws an error, a procedure bound to @code{error-handler}
2863 slot is invoked with the thrown condition as the only argument.
2864 If no @code{error-handler} is registered, or @code{error-handler}
2865 throws an error again, then the scheduler stops. The thrown condition
2866 is kept in the scheduler and can be retrieved with
2867 @code{scheduler-terminate!}.
2868 @c JP
2869 タスクがエラーを投げた場合、@code{error-handler}スロットに格納された手続きが、
2870 コンディションオブジェクトを引数として呼ばれます。
2871 @code{error-handler}が設定されていない場合、あるいは@code{error-handler}が
2872 エラーを投げた場合はスケジューラが停止します。
2873 投げられたコンディションはスケジューラの中に保存され、
2874 @code{scheduler-terminate!}で取り出せます。
2875 @c COMMON
2876
2877 @defivar {<scheduler>} error-handler
2878 @c EN
2879 This slot can be initialized with @code{:error-handler} keyword argument.
2880 It must be either @code{#f} or a procedure that takes one argument.
2881 If it is a procedure, it is invoked when a task throws an error,
2882 and the argument is the raised condition.
2883 The result of @code{error-handler} procedure is discarded.
2884 @c JP
2885 このスロットは@code{:error-handler}キーワード引数で初期化できます。
2886 値は@code{#f}もしくは引数をひとつ取る手続きでなければなりません。
2887 手続きの場合、それはタスクがエラーを投げた時に、
2888 投げられたコンディションオブジェクトを引数として呼び出されます。
2889 手続きの戻り値は捨てられます。
2890 @c COMMON
2891 @end defivar
2892 @end deftp
2893
2894 @defun scheduler-running? scheduler
2895 @c MOD control.scheduler
2896 @c EN
2897 Returns @code{#t} iff @var{scheduler} is running.
2898 @c JP
2899 @var{scheduler}が動作中なら@code{#t}を、そうでなければ@code{#f}を返します。
2900 @c COMMON
2901 @end defun
2902
2903
2904 @defun scheduler-schedule! scheduler thunk when :optional interval
2905 @c MOD control.scheduler
2906 @c EN
2907 Inserts a new tasks that runs @var{thunk} into @var{scheduler}.
2908 The task can be run once, or periodically.
2909 @c JP
2910 @var{thunk}を走らせる新たなタスクを@var{scheduler}に加えます。
2911 タスクは一回だけ走らせることも、定期的に走らせることもできます。
2912 @c COMMON
2913
2914 @c EN
2915 The @var{when} argument specifies when the task should first run.
2916 It can be either one of the followings:
2917 @c JP
2918 @var{when}引数が、最初にタスクを走らせるタイミングを指定します。
2919 次のいずれかの値が使えます。
2920 @c COMMON
2921
2922 @table @asis
2923 @c EN
2924 @item @code{<time>} object of @code{type-utc} or @code{time-tai} type
2925 Specifies the aboslute point of time.
2926 @c JP
2927 @item @code{type-utc}か@code{time-tai}型の@code{<time>}オブジェクト
2928 絶対的な時刻を指定します。
2929 @c COMMON
2930 @c EN
2931 @item @code{<time>} object of @code{time-duration} type
2932 Specifies the relative time since this procedure is called.
2933 @c JP
2934 @item @code{time-duration}型の@code{<time>}オブジェクト
2935 この手続きを呼んだ時点からの相対的な時刻を指定します。
2936 @c COMMON
2937 @c EN
2938 @item real number
2939 Specifies the relative time in seconds since this procedure is called.
2940 @c JP
2941 @item 実数
2942 この手続きを呼んだ時点からの秒数を指定します。
2943 @c COMMON
2944 @end table
2945
2946 @c EN
2947 The optional @var{interval} argument can be @code{#f}, real number
2948 or @code{<time>} object of @code{time-duration} type. If it is @code{#f}
2949 or 0, the task is one-shot, that is, not repeated. Otherwise,
2950 the task is repeated with the specified interval---the real number
2951 specifies the number of seconds.
2952 @c JP
2953 省略可能な@var{interval}引数は、@code{#f}、実数、もしくは@code{time-duration}型の
2954 @code{<time>}オブジェクトです。@code{#f}または@code{0}の場合、
2955 タスクは一回だけ実行され、繰りかえされません。
2956 そうでなければ、タスクは指定の時間間隔で繰り返し実行されます。
2957 実数の場合の単位は秒です。
2958 @c COMMON
2959
2960 @c EN
2961 Returns an integer that identifies the task. The task id can
2962 be used to cancel or reschedule the task.
2963 @c JP
2964 手続きは、タスクを指定する整数を返します。この値は後でタスクをリスケジュールしたり
2965 キャンセルするのに使えます。
2966 @c COMMON
2967 @end defun
2968
2969
2970 @defun scheduler-reschedule! scheduler task-id when :optional interval
2971 @c MOD control.scheduler
2972 @c EN
2973 Change the schedule of the task specified by @var{task-id} in the
2974 scheduler. The meaning of @var{when} and @var{interval} argument is
2975 the same as @code{scheduler-schedule!}.
2976 @c JP
2977 @var{task-id}で指定されるタスクのスケジュールを変更します。
2978 @var{when}および@var{interval}の意味は@code{scheduler-schedule!}と同じです。
2979 @c COMMON
2980
2981 @c EN
2982 The same types of values as @code{scheduler-schedule!} are allowed for
2983 @var{when} and @var{interval} arguments, as well as a symbol
2984 @code{unchanged}, which indicates that value is left alone by
2985 the operation. Note that omitting @var{interval} means task will be
2986 non-repeating. If you want to change just the next time the repeating
2987 task is executed, pass @code{unchanged} to the @var{interval}.
2988 @c JP
2989 @var{when}と@var{interval}引数は、@code{scheduler-schedule!}と同じものの他、
2990 シンボル@code{unchanged}も許されます。@code{unchanged}が渡された場合は
2991 その引数に関して以前の設定が引き継がれます。@var{interval}を省略することは
2992 タスクを繰り返さないという指定になることに注意してください。
2993 次にタスクが実行される時刻を変更したいが、繰り返しの周期はそのままにしておきたい、
2994 という場合は@var{interval}に@code{unchanged}を渡してください。
2995 @c COMMON
2996
2997 @c EN
2998 If the scheduler doesn't have a task with @var{task-id}, an exception
2999 is raised.
3000 @c JP
3001 @var{task-id}に該当するタスクがなければエラーが投げられます。
3002 @c COMMON
3003 @end defun
3004
3005
3006 @defun scheduler-remove! scheduler task-id
3007 @c MOD control.scheduler
3008 @c EN
3009 Remove the task specified by @var{task-id} from the scheduler.
3010 If the task is actually removed, @code{#t} is returned.
3011 If the scheduler doesn't have a task with @var{task-id}, @code{#f} is returned.
3012 @c JP
3013 @var{task-id}で指定されるタスクをスケジューラから取り除きます。
3014 実際にタスクが取り除かれたら@code{#t}を、
3015 該当するタスクが無かった場合は@code{#f}を返します。
3016 @c COMMON
3017 @end defun
3018
3019
3020 @defun scheduler-exists? scheduler task-id
3021 @c MOD control.scheduler
3022 @c EN
3023 Returns @code{#t} iff the scheduler has the task with @var{task-id}
3024 in the queue. Note that once the task is executed and not repeating,
3025 the task is removed from the queue.
3026 @c JP
3027 スケジューラが@var{task-id}で指定されるタスクを持っていれば@code{#t}を、
3028 そうでなければ@code{#f}を返します。
3029 繰り返さないタスクは一度実行されたらスケジューラから取り除かれることに注意してください。
3030 @c COMMON
3031 @end defun
3032
3033 @defun scheduler-terminate! scheduler :key on-error
3034 @c MOD control.scheduler
3035 @c EN
3036 Stop the scheduler. Tasks still in the scheduler's queue won't executed,
3037 and no new task will be accepted. Once the scheduler is terminated,
3038 it can't be restarted.
3039 @c JP
3040 スケジューラを停止します。スケジューラのキューに残っているタスクはもう実行されず、
3041 また新しいタスクを追加することもできなくなります。
3042 一度停止したスケジューラを再起動することはできません。
3043 @c COMMON
3044
3045 @c EN
3046 If no task has raised an exception, or all exceptions are handled
3047 by the error-handler of the scheduler, this procedure returns @code{#t}
3048 after the scheduler is stopped.
3049 @c JP
3050 タスクがこれまで例外をあげたことがないか、スケジューラの@code{error-handler}で
3051 例外が全て処理済みであった場合、この手続きはスケジューラが停止した後で
3052 @code{#t}を返します。
3053 @c COMMON
3054
3055 @c EN
3056 If any task has raised an exception and not handled by
3057 the error-handler, the behavior depends on the @var{on-error}
3058 keyword argumnent, which should be one of the following:
3059 @c JP
3060 タスクが例外を上げていてスケジューラの@code{error-handler}で処理されて
3061 いなかった場合、この手続きの振る舞いは@var{on-error}引数で決まります。
3062 可能な値は次のいずれかです。
3063 @c COMMON
3064
3065 @table @code
3066 @item :reraise
3067 @c EN
3068 The exception is reraised from @code{scheduler-terminate!}.
3069 This is the default.
3070 @c JP
3071 処理されなかった例外が、@code{scheduler-terminate!}から改めて投げられます。
3072 これがデフォルトの振る舞いです。
3073 @c COMMON
3074 @item :return
3075 @c EN
3076 The exception is returned from @code{scheduler-terminate!}.
3077 @c JP
3078 処理されなかった例外が@code{scheduler-terminate!}の戻り値として返されます。
3079 @c COMMON
3080 @end table
3081 @end defun
3082
3083 @c ----------------------------------------------------------------------
3084 @node Thread pools, Password hashing, Scheduler, Library modules - Utilities
3085 @section @code{control.thread-pool} - Thread pools
3086 @c NODE スレッドプール, @code{control.thread-pool} - スレッドプール
3087
3088 @deftp {Module} control.thread-pool
3089 @mdindex control.thread-pool
3090 @c EN
3091 Provides thread pools.
3092 @c JP
3093 スレッドプールを提供します。
3094 @c COMMON
3095 @end deftp
3096
3097 @deftp {Class} <thread-pool>
3098 @clindex thread-pool
3099 @c MOD control.thread-pool
3100 @c EN
3101 A class for thread pool objects. It maintains a set of worker threads, and
3102 let them work on the jobs you ask to do asynchronously.
3103
3104 Currently the size of pool (number of threads) is fixed
3105 and you have to specify it when creating a pool.
3106 In future we might add a feature to grow or shrink the pool.
3107
3108 You can also set maximum backlog of the job queue. You cannot
3109 put a job when the queue already reaches the max length (see
3110 @code{add-job!} below).
3111 @c JP
3112 スレッドプールオブジェクトのクラスです。ワーカースレッドのセットを保持し、
3113 投入されたジョブを非同期に実行します。
3114
3115 現在の実装では、プールのサイズ (スレッド数) は固定で、プール作成時に
3116 指定しなければなりません。いずれスレッド数を動的に増減させる機能を
3117 追加する予定です。
3118
3119 また、ジョブのキューの最大長を指定することもできます。ジョブのキューが
3120 一杯になると、空きができるまでは新たなジョブを投入することができなくなります
3121 (下記の@code{add-job!}参照)。
3122 @c COMMON
3123 @end deftp
3124
3125
3126 @deftp {Condition type} <thread-pool-shut-down>
3127 @c MOD control.thread-pool
3128 @c EN
3129 A condition indicating that a thread pool is already shut down
3130 by @code{terminate-all!} and no longer accepting new jobs.
3131 Inherits @code{<error>}. The following slot is provided.
3132 @c JP
3133 スレッドプールが@code{terminate-all!}によって停止され、
3134 新規のジョブを受け付けていないことを示すコンディションです。
3135 @code{<error>}を継承します。次のスロットが提供されます。
3136 @c COMMON
3137
3138 @defivar <thread-pool-shut-down> pool
3139 @c EN
3140 The thread pool object that caused the condition.
3141 @c JP
3142 例外の原因となったスレッドプールオブジェクト
3143 @c COMMON
3144 @end defivar
3145 @end deftp
3146
3147 @defun make-thread-pool size :key (max-backlog 0)
3148 @c MOD control.thread-pool
3149 @c EN
3150 Creates a new thread pool of size @var{size} (the number of
3151 worker threads). Optionally you can give a nonnegative integer
3152 to the maximum backlog; 0 means unlimited.
3153 @c JP
3154 大きさ(ワーカースレッド数)@var{size}のスレッドプールを作成して返します。
3155 省略可能引数@var{max-backlog}によってジョブのバックログの最大値を
3156 指定することもできます。0を与えた場合(デフォルト)は無制限です。
3157 @c COMMON
3158 @end defun
3159
3160 @defun thread-pool-results pool
3161 @c MOD control.thread-pool
3162 @c EN
3163 When you put a job to a thread pool, you can specify
3164 whether you need to check its result or not. If you say you need
3165 a result, the terminated job is queued to a @emph{result queue},
3166 an @code{<mt-queue>} object, in the pool.
3167 This procedure returns the pool's result queue.
3168 @xref{Queue}, for the details of @code{<mt-queue>}.
3169 @c JP
3170 ジョブをスレッドプールに投入する際に、ジョブの結果を知る必要があるかどうかを
3171 指定することができます。結果を要求した場合は、終了したジョブレコードが
3172 プール中の結果キュー(@code{<mt-queue>}オブジェクト)にエンキューされます。
3173 この手続きは、プールの結果キューを返します。
3174 @code{<mt-queue>}の詳細については@ref{Queue}を参照してください。
3175 @c COMMON
3176 @end defun
3177
3178 @defun thread-pool-shut-down? pool
3179 @c MOD control.thread-pool
3180 @c EN
3181 Returns @code{#t} if the thread pool is shut down and no longer
3182 accepting new jobs, or @code{#f} otherwise.
3183 @c JP
3184 スレッドプールが停止され、新規のジョブを受け付けていない場合に@code{#t}を、
3185 そうでなければ@code{#f}を返します。
3186 @c COMMON
3187 @end defun
3188
3189 @defun add-job! pool thunk :optional (need-result #f) (timeout #f)
3190 @c MOD control.thread-pool
3191 @c EN
3192 Add a @var{thunk} to be executed in the thread pool @var{pool}.
3193 Returns a @code{job} record (@pxref{A common job descriptor for control modules}).
3194 @c JP
3195 @var{thunk}がスレッドプール@var{pool}のスレッドにより実行されるように設定します。
3196 @code{job}レコードを返します。
3197 (@ref{A common job descriptor for control modules}参照)。
3198 @c COMMON
3199
3200 @c EN
3201 The returned job record is not waitable; if you need to track
3202 its result, you have to give a true value to @var{need-result}
3203 argument. Then when the job is terminated (either normally or
3204 abnormally) the job is queued to the @code{result-queue} of
3205 the pool, and you can check the queue. If you don't pass
3206 a true value to @var{need-result}, the job won't be queued
3207 to @code{result-queue} even it is terminated.
3208 @c JP
3209 返される@code{job}レコードはwaitableにはなっていません。結果を知る必要が
3210 ある場合は、省略可能引数@var{need-result}に真の値を渡してください。
3211 そうするとジョブが終了した時点 (正常終了でも異常終了でも) で、
3212 @code{job}レコードがスレッドプールの@code{result-queue}に
3213 入るので、そのキューから結果を受け取ることができます。
3214 @var{need-result}を省略したり偽値を渡した場合は、ジョブが終了しても
3215 @code{job}レコードは@code{result-queue}に入れられません。
3216 @c COMMON
3217
3218 @c EN
3219 The returned job is timestamped. You can examine acknowledged
3220 time, start time and finish time of the job (if the job hasn't
3221 been started and/or finished, the corresponding timestamp fields
3222 are @code{#f}.) It's sometimes
3223 handy to find out how long the job was waiting in the
3224 queue and how long it took to run.
3225 @c JP
3226 返される@code{job}レコードにはタイムスタンプが付加され、
3227 受付時間、実行開始時間、実行終了時間が記録されます。
3228 (ジョブがまだ実行されていなかったり、終了されていない場合は、対応する
3229 タイムスタンプは@code{#f}になっています)。
3230 ジョブがどのくらいキューの中で待たされ、どのくらい実行にかかったかを
3231 知るのに便利でしょう。
3232 @c COMMON
3233
3234 @c EN
3235 If the pool has positive @code{max-backlog} value, and it
3236 already has that many jobs to be waiting, then @code{add-job!}
3237 blocks until some jobs are start being executed.
3238 You can give a real number in seconds, or a @code{<time>} object
3239 as an absolute point of time, to the @var{timeout} argument
3240 to set the time limit of blocking. If timeout is reached,
3241 @code{add-job!} returns @code{#f} without creating any job.
3242 Omitting @var{timeout}
3243 or giving @code{#f} to it sets no timeout.
3244 @c JP
3245 スレッドプールが非負の@code{max-backlog}値を持ち、
3246 既にその数だけジョブが待ち行列に入っている場合は、
3247 @code{add-job!}は待ち行列に空きができるまでブロックします。
3248 @var{timeout}引数に、実数値の秒数、あるいは絶対時刻を指定する@code{<time>}
3249 オブジェクトを渡すことでタイムアウトを指定できます。タイムアウトに
3250 達した場合は、@code{add-job!}はジョブを作らずに@code{#f}を返します。
3251 @var{timeout}引数を省略するか、@code{#f}を渡した場合はタイムアウトが設定されません。
3252 @c COMMON
3253
3254 @c EN
3255 (Note: This behavior is different from 0.9.1, in which @code{add-job!}
3256 didn't take the timeout argument and always behaved as if zero
3257 timeout value was given. To achieve the same behavior, you have
3258 to give 0 to the @var{timeout} argument explicitly.)
3259 @c JP
3260 (註: この動作は0.9.1から変更されました。0.9.1では、@code{add-job!}は
3261 タイムアウト引数を取らず、常にタイムアウトに0秒が指定されたかのように
3262 振る舞っていました。現在のバージョンで同じ動作をさせるには、@var{timeout}引数
3263 に0を明示的に渡します。)
3264 @c COMMON
3265
3266 @c EN
3267 If the thread pool is shut down, this procedure
3268 raises @code{<thread-pool-shut-down>} condition.
3269 @c JP
3270 スレッドプールが停止していた場合、この手続きは
3271 @code{<thread-pool-shut-down>}コンディションを投げます。
3272 @c COMMON
3273 @end defun
3274
3275 @defun wait-all pool :optional (timeout #f) (check-interval #e5e8)
3276 @c MOD control.thread-pool
3277 @c EN
3278 Wait for the job queue to be empty and
3279 all worker threads to finish. It is done by polling the
3280 pool's status in every @var{check-interval} nanoseconds.
3281 Returns @code{#t} if all jobs are finished.
3282
3283 You can give a real number in seconds, or a @code{<time>} object
3284 as an absolute point of time, in @var{timeout} optional argument.
3285 When timeout is reached, @code{wait-all} returns @code{#f}.
3286
3287 While this procedure is called, no new jobs should be put into @var{pool}.
3288 @c JP
3289 ジョブ待ち行列が空になり、すべての実行中のジョブも終了するまで待ちます。
3290 終了待ちは@var{check-interval}にナノ秒で指定される間隔でスレッドプールを
3291 ポールすることで行われます。すべてのジョブが終了したら@code{#t}を返します。
3292
3293 秒数を表す実数か、絶対時刻を表す@code{<time>}オブジェクトを@var{timeout}
3294 引数に渡すことで、タイムアウトを指定できます。タイムアウトに達した場合は、
3295 @code{wait-all}は@code{#f}を返します。
3296
3297 この手続きが呼ばれている間、新しいジョブが@var{pool}に投入されてはなりません。
3298 @c COMMON
3299 @end defun
3300
3301 @defun terminate-all! pool :key (force-timeout #f) (cancel-queued-jobs #f)
3302 @c MOD control.thread-pool
3303 @c EN
3304 Wait for all the queued jobs to be finished, then ask all threads
3305 to terminate. After calling this procedure, the pool no longer
3306 accepts new jobs. Calling @code{add-job!} on this module would
3307 raise a @code{<thread-pool-shut-down>} condition.
3308 This is intended to be called when shutting down the application.
3309
3310 By default, this procedure first waits for all queued jobs
3311 to be handled, then tries to terminate threads gracefully.
3312
3313 Giving a true value to the @var{cancel-queued-jobs} argument
3314 immediately cancels queued but not started jobs; the status
3315 of such jobs is set @code{killed}.
3316 It does not cancels already started jobs, though.
3317
3318 If you want to cancel already started jobs,
3319 you can give a timeout value (either @code{<time>} object to
3320 specify absolute point of time, or a real number indicating
3321 relative time in seconds) to the @var{force-timeout} argument.
3322 Once timeout is reached, it forcefully terminates the threads
3323 and the jobs handled at that time are also killed.
3324
3325 Forcing termination of threads is an extreme measure; the terminated
3326 thread may not have a chance to clean up properly. So it is usually
3327 better to give some time for the thread to finish the executing jobs.
3328 @c JP
3329 投入されたジョブがすべて終了するのを待ち、すべてのスレッドを終了させます。
3330 ひとたびこの手続きを呼ぶと、スレッドプール@var{pool}は新規のジョブを受けつけ
3331 ません。この状態のスレッドプールに対して@code{add-job!}を呼ぶと
3332 @code{<thread-pool-shut-down>}コンディションが投げられます。
3333 この手続きはアプリケーションのシャットダウン時などに呼ばれることを意図しています。
3334
3335 デフォルトでは、この手続きはまずキューに既に投入されたジョブが全て処理されるのを
3336 待ち、それからスレッドを穏やかに終了させます。
3337
3338 真の値を@var{cancel-queued-jobs}引数に与えると、キューに入っているが
3339 まだ開始されていないジョブは直ちにキャンセルされます。それらのジョブの
3340 ステータスには@code{killed}がセットされます。
3341 ただし、既に開始されたジョブについてはキャンセルされません。
3342
3343 既に開始されたジョブも中断したい場合は、
3344 タイムアウト値(秒数を表す実数か、絶対時刻を表す@code{<time>}オブジェクト)を
3345 @var{force-timeout}引数に渡します。
3346 タイムアウトに達した時点で残っているスレッドは強制終了され、実行中のジョブも
3347 キャンセルされます。
3348
3349 スレッドの強制終了は極端な処置です。終了されるスレッドは、適切なクリーンアップを
3350 行う機会も与えられないかもしれません。したがって通常は、
3351 スレッドが処理中のジョブを終わらせるための適切な時間的猶予を与えるのが良いでしょう。
3352 @c COMMON
3353 @end defun
3354
3355 @c ----------------------------------------------------------------------
3356 @node Password hashing, Cache, Thread pools, Library modules - Utilities
3357 @section @code{crypt.bcrypt} - Password hashing
3358 @c NODE パスワードハッシュ, @code{crypt.bcrypt} - パスワードハッシュ
3359
3360 @deftp {Module} crypt.bcrypt
3361 @mdindex crypt.bcrypt
3362 @c EN
3363 This module implements a password hashing algorithm using blowfish,
3364 and compatible to OpenBSD's bcrypt algorithm (version 2a, 2b).
3365 @c JP
3366 このモジュールは、blowfishを使ったパスワードハッシュアルゴリズムを実装します。
3367 OpenBSDのbcryptアルゴリズム(version 2a, 2b)と互換です。
3368 @c COMMON
3369
3370 @c EN
3371 Don't use version ``2a'' for new code. It's vulnerable.
3372 Use version ``2b''.
3373 @c JP
3374 version 2a は脆弱性が発見されているので、新規のコードでは使用しないで
3375 ください。代わりに version 2b を使用して下さい。
3376 @c COMMON
3377
3378 @c EN
3379 The typical usage of this module is simple enough.
3380 To get a new password hash value (e.g. for a new user), pass the
3381 password string to @code{bcrypt-hashpw} as the only argument:
3382 @c JP
3383 典型的な使い方は非常にシンプルです。新しいパスワードハッシュ値を
3384 得たい場合 (例えば新しいユーザのために、など) は、パスワード文字列を
3385 唯一の引数として@code{bcrypt-hashpw}を呼び出してください。
3386 @c COMMON
3387
3388 @example
3389 (bcrypt-hashpw @var{password})
3390 @result{} @r{hashed-string}
3391 @end example
3392
3393 @c EN
3394 The routine automatically adds a salt value. The returned hash
3395 string can be stored in the user database. To check if the given
3396 password matches the stored one, pass the
3397 hashed string as the second argument of @code{bcrypt-hashpw} to
3398 check the password.
3399 @c JP
3400 このルーチンは自動的にソルト値を付加します。戻り値の文字列はそのままユーザ
3401 データベースに格納できます。与えられたパスワードがハッシュ値に一致するか
3402 どうかを調べるには、ハッシュ値そのものを第二引数として@code{bcrypt-hashpw}に
3403 渡します。
3404 @c COMMON
3405
3406 @example
3407 (bcrypt-hashpw @var{password} @var{hashed-string})
3408 @result{} @r{hashed-string}
3409 @end example
3410
3411 @c EN
3412 If the given password is correct, the returned value should
3413 exactly matches @var{hash-string}.
3414 @c JP
3415 パスワードが正しければ、戻り値は@var{hashed-string}と完全に一致するはずです。
3416 @c COMMON
3417 @end deftp
3418
3419 @defun bcrypt-hashpw password :optional setting
3420 @c MOD crypt.bcrypt
3421 @c EN
3422 Calculates a hash value of @var{password}, using the salt value
3423 and parameters included in @var{setting}. If @var{setting} is
3424 omitted, a suitable default settings and random salt value is
3425 chosen automatically.
3426
3427 The returned hash value contains the salt value and parameters,
3428 and can be used as @var{setting}. So, to check the password
3429 against existing hash value, just pass the hash value to
3430 @var{setting}; if the password is correct, the returned hash value
3431 should match the one you passed in.
3432
3433 The bcrypt algorithm supports up to 72 octets for the password.
3434
3435 To tweak parameters when you calculate a new hash value,
3436 use @code{bcrypt-gensalt} below to get the initial @var{setting}
3437 value.
3438 @c JP
3439 @var{password}のハッシュ値を計算します。@var{setting}は
3440 ソルト値とパラメータを指定する文字列です。@var{setting}が
3441 省略された場合は、適切なデフォルトのパラメータとランダムなソルト値が
3442 自動的に選択されます。
3443
3444 戻り値のハッシュ値文字列にはソルト値とパラメータが含まれているので、
3445 それを再び@var{setting}に渡すことができます。したがって、パスワードを
3446 既存のハッシュ値に一致するかチェックしたい場合は、ハッシュ値を@var{setting}に渡し、
3447 戻ってきた文字列が渡したハッシュ値と一致するかを見れば良いことになります。
3448
3449 bcryptアルゴリズムは最大72オクテットまでのパスワードを使えます。
3450
3451 新しいハッシュ値を計算する際にパラメータを指定したい場合は、次に説明する
3452 @code{bcrypt-gensalt}を使うと@var{setting}に使える文字列を得ることができます。
3453 @c COMMON
3454 @end defun
3455
3456 @defun bcrypt-gensalt :key prefix count entropy-source
3457 @c MOD crypt.bcrypt
3458 @c EN
3459 Returns a string that contains given parameters and suitable to
3460 pass to the @var{setting} argument of @code{bcrypt-hashpw}.
3461
3462 The @var{prefix} argument specifies the version/scheme of
3463 password hashing. Currently @code{$2a$} and @code{$2b$} are supported,
3464 which means the blowfish algorithm compatible to bcrypt.
3465 But @code{$2a$} is vulnerable. Use @code{$2b$} for new code.
3466 If you omit @var{prefix}, use @code{$2b$} for default value.
3467
3468 The @var{count} argument specifies the amount of iterations;
3469 the larger the value is, the more time is required to calculate
3470 the hash value. Note that for the password hashing, taking more
3471 time is actually a good thing, for it works against the dictionary attack.
3472 For normal password checking you need to run the hash routine only
3473 once per login, so it doesn't matter if the calculation takes a fraction
3474 of second.
3475 The bcrypt algorithm iterates @code{(expt 2 @var{count})} times.
3476
3477 The @var{entropy-source} argument is a @code{u8vector} to feed
3478 a random bytes. For bcrypt algorithm it must be at least 16 octet long.
3479 @c JP
3480 与えられたパラメータを折り込んだ、
3481 @code{bcrypt-hashpw}の@var{setting}引数に使える文字列を返します。
3482
3483 @var{prefix}引数はハッシュ関数およびそのバージョンを指定する文字列です。
3484 現在のところ、@code{bcrypt}互換である@code{$2a$}と@code{$2b$}がサポート
3485 されています。
3486 ただし、@code{$2a$}には脆弱性が発見されていますので、
3487 新規のコードには@code{$2b$}を使用して下さい。
3488 @var{perfix}引数を省略した場合は@code{$2b$}が用いられます。
3489
3490 @var{count}引数はハッシュの繰り返し回数に関係します。大きな値を指定すれば、
3491 ハッシュ値の計算により長い時間がかかります。パスワードハッシュにおいては、
3492 時間をかけた方が良いことに注意してください。一回のハッシュの時間が長くなれば
3493 辞書攻撃への防御になります。一方で、通常のパスワードチェックでは
3494 ログインの度にたかだか一回しはハッシュ関数を呼ばないので、それがたとえコンマ数秒
3495 かかったとしてもたいした負荷ではありません。
3496 bcryptアルゴリズムでは、@code{(expt 2 @var{count})}回ハッシュが繰り返されます。
3497
3498 @var{entropy-source}引数はランダムなバイト列を格納した@code{u8vector}です。
3499 bcryptアルゴリズムでは少なくとも16バイトの長さが必要です。
3500 @c COMMON
3501 @end defun
3502
3503 @c ----------------------------------------------------------------------
3504 @node Cache, Heap, Password hashing, Library modules - Utilities
3505 @section @code{data.cache} - Cache
3506 @c NODE キャッシュ, @code{data.cache} - キャッシュ
3507
3508 @deftp {Module} data.cache
3509 @mdindex data.cache
3510 @c EN
3511 A cache works similarly as a dictionary, associating keys to values,
3512 but its entries may disappear according to the policy of the cache
3513 algorithm. This module defines
3514 a common protocol for cache datatypes, and also provides several
3515 typical cache implementations.
3516 @c JP
3517 キャッシュは、キーと値を結びつけるという点では辞書と似たように動作しますが、
3518 キャッシュアルゴリズムの方針によってエントリが消去されることがあります。
3519 このモジュールは、キャッシュについて共通のプロトコルを定義し、
3520 またいくつかの典型的なキャッシュの実装を提供します。
3521 @c COMMON
3522 @end deftp
3523
3524 @c EN
3525 @subheading Examples
3526 @c JP
3527 @subheading 例
3528 @c COMMON
3529
3530 @c EN
3531 Let's start from simple examples to get the idea.
3532 @c JP
3533 まず簡単な例によって、どんな具合かを示しましょう。
3534 @c COMMON
3535
3536 @c EN
3537 Suppose you want to read given files and you want to
3538 cache the frequently read ones. The following code defines
3539 a cached version of @code{file->string}:
3540 @c JP
3541 指定されたファイルを読み込むルーチンに、
3542 頻繁に読むファイルをキャッシュする機能をつけたいとします。
3543 次のコードは@code{file->string}にキャッシュ機能を持たせたものです。
3544 @c COMMON
3545
3546 @example
3547 (use data.cache)
3548 (use file.util)
3549
3550 (define file->string/cached
3551 (let1 file-cache (make-lru-cache 10 :comparator string-comparator)
3552 (^[path] (cache-through! file-cache path file->string))))
3553 @end example
3554
3555 @c EN
3556 The procedure closes a variable @code{file-cache},
3557 which is an LRU (least recently used) cache that associates
3558 string pathnames to the file contents.
3559 The actual logic is in @code{cache-through!}, which first consults the
3560 cache if it has an entry for the @code{path}. If the cache has
3561 the entry, its value (the file content) is returned. If not,
3562 it calls @code{file->string} with the @var{path} to fetch the file content,
3563 register it to the cache, and return it. The capacity of the cache is
3564 set to 10 (the first argument of @code{make-lru-cache}), so when the
3565 11th file is read, the least recently used file will be evicted from the
3566 cache.
3567 @c JP
3568 この手続きは@code{file-cache}変数をクロージャの中に綴じ込んでいます。
3569 その値は文字列のパス名とファイルの中身を結びつけるLRU(least recently used)キャッシュです。
3570 キャッシュの動作は@code{cache-through!}で実現されています。
3571 この手続きは、
3572 まず@var{path}をキーとして持つエントリが@code{file-cache}にあるかどうか調べます。
3573 そのキーを持つエントリがキャッシュ中にあればその値(ファイルの中身)が返されます。
3574 キャッシュ中に無ければ、@code{file->string}が@var{path}を引数として呼ばれ、
3575 それが返したファイルの中身がキャッシュに登録され、返されます。
3576 キャッシュの容量は@code{make-lru-cache}の第1引数で指定され、ここでは10になっています。
3577 つまり、11個目のファイルが読まれた時に、一番長く使われていない
3578 (least recently used)ファイルがキャッシュから消去されます。
3579 @c COMMON
3580
3581 @c EN
3582 The effect of the cache isn't very visible in the above example. You
3583 can insert some print stubs to see the cache is actually in action,
3584 as the following example.
3585 Try read various files using @code{file->string/cached}.
3586 @c JP
3587 上の例そのままではキャッシュの効果が見え辛いです。
3588 次の例の通り、printスタブをいれて、いろいろなファイルを
3589 @code{file->string/cached}で読んでみて下さい。
3590 いつキャッシュが実際にファイルの中身を取りにゆくかわかるでしょう。
3591 @c COMMON
3592
3593 @example
3594 (define file->string/cached
3595 (let1 file-cache (make-lru-cache 10 :comparator string-comparator)
3596 (^[path]
3597 (print #"file->string/cached called on ~path")
3598 (cache-through! file-cache path
3599 (^[path]
3600 (print #"cache miss. fetching ~path")
3601 (file->string path))))))
3602 @end example
3603
3604 @c EN
3605 Caveat: A cache itself isn't MT-safe. If you are using it in
3606 multithreaded programs, you have to wrap it with an atom
3607 (@pxref{Synchronization primitives}):
3608 @c JP
3609 注意: キャッシュ自身はスレッドセーフではありません。
3610 マルチスレッドプログラムでキャッシュを使う場合は、キャッシュをatomでラップしてください。
3611 @c COMMON
3612
3613 @example
3614 (use data.cache)
3615 (use file.util)
3616 (use gauche.threads)
3617
3618 (define file->string/cached
3619 (let1 file-cache (atom (make-lru-cache 10 :comparator string-comparator))
3620 (^[path]
3621 (atomic file-cache (cut cache-through! <> path file->string)))))
3622 @end example
3623
3624 @c EN
3625 @subheading Common properties of caches
3626 @c JP
3627 @subheading キャッシュに共通の性質
3628 @c COMMON
3629
3630 @c EN
3631 A cache of any kind has a comparator and a storage.
3632 The comparator is used to compare keys; in the example above,
3633 we use @code{string-comparator} to compare string pathnames
3634 (@pxref{Basic comparators}, for more about comparators).
3635 @c JP
3636 どんなキャッシュにも、比較器とストレージがあります。
3637 比較器はキーを比較するのに使われます。上の例ではパス名を比較するために
3638 @code{string-comparator}を渡しています
3639 比較器について詳しくは@ref{Basic comparators}を参照してください。
3640 @c COMMON
3641
3642 @c EN
3643 The storage is a dictionary that maps keys to internal
3644 structures of the cache. It needs to implement the dictionary
3645 protocol (@pxref{Dictionary framework}).
3646 By default, a hashtable is
3647 created automatically using the given comparator (or,
3648 if a comparator is omitted, using @code{default-comparator}).
3649 The comparator must have the hash function.
3650 @c JP
3651 ストレージは、キーとキャッシュ内部の構造とをマッピングする辞書です。
3652 ディクショナリプロトコルを実装しているクラスのオブジェクトでなければなりません
3653 (@ref{Dictionary framework}参照)。
3654 デフォルトでは与えられた比較器を使うハッシュテーブルが使われるので、
3655 比較器はハッシュ関数を持っていなければなりません。
3656 比較器が省略された場合は@code{default-comparator}が使われます。
3657 @c COMMON
3658
3659 @c EN
3660 Alternatively, you can give a pre-filled dictionary
3661 (copied from another instance of the same kind of cache)
3662 to start cache with some data already in it. Note that
3663 what the cache keeps in the dictionary totally depends on the
3664 cache algorithm, so you can't just pass a random dictionary;
3665 it has to be created by the same kind of cache.
3666 If you pass in the storage, the comparator is taken from it.
3667 @c JP
3668 あるいは、
3669 (同じ種類のキャッシュからコピーされた)辞書をストレージとして渡すことで、
3670 既にエントリがある状態のキャッシュを作ることもできます。
3671 キャッシュが辞書に登録している構造はキャッシュアルゴリズムごとに異なるので、
3672 何でも辞書を渡せるわけではないことに注意してください。
3673 同じ種類のキャッシュによって作られた辞書しか渡せません。
3674 ストレージとなる辞書を渡した場合、比較器はその辞書から取られます。
3675 @c COMMON
3676
3677 @c EN
3678 Thus, the cache constructors uniformly take keyword arguments
3679 @var{comparator} and @var{storage}; you can specify either one,
3680 or omit both to use the defaults.
3681 @c JP
3682 従ってキャッシュのコンストラクタは共通して@var{comparator}と@var{storage}の
3683 キーワード引数を取ります。デフォルトの動作で良ければ、
3684 どちらかひとつ、あるいは両方とも省略することができます。
3685 @c COMMON
3686
3687 @c EN
3688 @subheading Predefined caches
3689 @c JP
3690 @subheading 定義済みのキャッシュ
3691 @c COMMON
3692
3693 @c EN
3694 For the @var{storage} and @var{comparator} keyword arguments, see above.
3695 @c JP
3696 @var{storage}と@var{comparator}キーワード引数については上の節を参照してください。
3697 @c COMMON
3698
3699 @defun make-fifo-cache capacity :key storage comparator
3700 @c MOD data.cache
3701 @c EN
3702 Creates and returns a FIFO (first-in, first-out) cache that can
3703 hold up to @var{capacity} entries.
3704 If the number of entries exceeds @var{capacity}, the oldest entry
3705 is removed.
3706 @c JP
3707 @var{capacity}個までのエントリを保持できる、FIFO(先入れ先出し)キャッシュを作って返します。
3708 エントリ数が@var{capacity}を越えそうになった場合、一番古いものから削除されます。
3709 @c COMMON
3710 @end defun
3711
3712 @defun make-lru-cache capacity :key storage comparator
3713 @c MOD data.cache
3714 @c EN
3715 Creates and returns an LRU (least recently used) cache that can
3716 hold up to @var{capacity} entries.
3717 If the number of entries exceeds @var{capacity}, the least recently used
3718 entry is removed.
3719 @c JP
3720 @var{capacity}個までのエントリを保持できる、
3721 LRU(least recently used)キャッシュを作って返します。
3722 エントリ数が@var{capacity}を越えそうになった場合、一番長く使われなかったものから削除されます。
3723 @c COMMON
3724 @end defun
3725
3726 @defun make-ttl-cache timeout :key storage comparator timestamper
3727 @c MOD data.cache
3728 @c EN
3729 Creates and returns a TTL (time to live) cache with the timeout value
3730 @var{timeout}.
3731 Each entry is timestamped when it's inserted, and it is removed
3732 when the current time passes @var{timeout} unit from the timestamp.
3733 The actual entry removal is done when the cache is accessed.
3734 @c JP
3735 タイムアウト値@var{timeout}を持つTTL(生存時間)キャッシュを作って返します。
3736 各エントリには、挿入された時間が記録されます。@var{timeout}を経過したエントリは削除されます。
3737 実際の削除は、キャッシュがアクセスされた時に行われます。
3738 @c COMMON
3739
3740 @c EN
3741 By default, the Unix system time (seconds from Epoch) is used
3742 as a timestamp, and @var{timeout} is in seconds. It may not be
3743 fine-grained enough if you add multiple entries in shorter intervals
3744 than seconds. You can customize
3745 it by giving a thunk to @var{timestamper}; the thunk is called to
3746 obtain a timestamp, which can be any monotonically increasing real number
3747 (it doesn't need to be associated with physical time).
3748 If you give @var{timestamper}, the unit of @var{timeout} value should
3749 be the same as whatever @var{timestamper} returns.
3750 @c JP
3751 デフォルトではUnixシステム時間(Epochからの秒数)がタイムスタンプに使われます。
3752 1秒より短い間隔でたくさんのエントリが追加される場合にはこれでは分解能が足りないかもしれません。
3753 @var{timestamper}にサンクを与えることで、タイムスタンプをカスタマイズすることができます。
3754 キャッシュは時刻が必要になる度に@var{timestamper}を引数無しで呼び出します。
3755 @var{timestamper}は単調非減少な実数を返さねばなりません(物理的な時間と結びついている必要は
3756 ありません)。
3757 @var{timestamper}を与えた場合、@var{timeout}引数の単位は
3758 @var{timestamper}が返す値の単位と同じでなければなりません。
3759 @c COMMON
3760 @end defun
3761
3762 @defun make-ttlr-cache timeout :key storage comparator timestamper
3763 @c MOD data.cache
3764 @c EN
3765 A variation of TTL cache, but the entry's timestamp is updated
3766 (refreshed) whenever the entry is read. Hence we call it TTL with refresh
3767 (TTLR). But you can also think it as a variation of LRU cache with
3768 timeout.
3769 @c JP
3770 TTLキャッシュのバリエーションで、エントリは書き込まれた時だけでなく、
3771 読み出された時にもタイムスタンプが更新されます。
3772 手続きの名前TTLRは、リフレッシュ付きTTL(TTL with refresh)という意味です。
3773 ただ、これをタイムアウト付きLRUキャッシュと見ることもできます。
3774 @c COMMON
3775
3776 @c EN
3777 The unit of timeout, and the role of @var{timestamper} argument, are
3778 the same as @code{make-ttl-cache}.
3779 @c JP
3780 タイムアウトの単位および@var{timestamper}引数の役割については、
3781 @code{make-ttl-cache}と同じです。
3782 @c COMMON
3783 @end defun
3784
3785 @c EN
3786 @subheading Common operations of caches
3787 @c JP
3788 @subheading キャッシュに共通の操作
3789 @c COMMON
3790
3791 @c EN
3792 The following APIs are for the users of a cache.
3793 @c JP
3794 以下のAPIはキャッシュのユーザに向けたものです。
3795 @c COMMON
3796
3797 @defun cache-lookup! cache key :optional default
3798 @c MOD data.cache
3799 @c EN
3800 Look for an entry with @var{key} in @var{cache}, and returns its
3801 value if it exists. If there's no entry, the procedure returns @var{default}
3802 if it is provided, or throws an error otherwise.
3803
3804 Some types of cache algorithms update @var{cache} by this operation
3805 (e.g. access timestamp), hence
3806 the bang is in the name.
3807 @c JP
3808 @var{cache}から@var{key}に結びつけられたエントリを探し、見つかれば返します。
3809 エントリが無い場合は、@var{default}が与えられていればそれを返し、
3810 与えられていなければエラーを投げます。
3811
3812 キャッシュアルゴリズムによってはこの操作で@var{cache}がアップデートされる場合があるため
3813 (アクセスタイムスタンプ等)、名前にエクスクラメーションマークがついています。
3814 @c COMMON
3815 @end defun
3816
3817 @defun cache-through! cache key value-fn
3818 @c MOD data.cache
3819 @c EN
3820 Look for an entry with @var{key} in @var{cache}, and returns its
3821 value if it exists. If there's no entry, a procedure @var{value-fn}
3822 is called with @var{key} as the argument, and its return value
3823 is inserted into @var{cache} and also returned.
3824 The insertion may cause eviction of exising entries.
3825 @c JP
3826 @var{cache}から@var{key}に結びつけられたエントリを探し、見つかれば返します。
3827 見つからなかった場合、@var{value-fn}が@var{key}を引数として呼び出され、
3828 その結果が@var{cache}に新たなエントリとして追加され、また@code{cache-through!}の
3829 戻り値として返されます。
3830 エントリの追加によって、既存のエントリがキャッシュから削除されるかもしれません。
3831 @c COMMON
3832 @end defun
3833
3834 @deffn {Generic function} cache-write! cache key value
3835 @c MOD data.cache
3836 @c EN
3837 This inserts association of @var{key} and @var{value} into @var{cache}.
3838 If there's already an entry with @var{key}, it is overwritten.
3839 Otherwise a new entry is created.
3840
3841 The same effect can be achieved by calling @code{cache-evict!} then
3842 @code{cache-through!}, but cache algorithms may provide efficient
3843 way through this method.
3844 @c JP
3845 @var{cache}に、@var{key}と@var{value}の関係を追加します。既に@var{key}に
3846 結びつけられたエントリがあった場合は上書きされ、そうでなければ新たなエントリが作られます。
3847
3848 同じ効果は、@code{cache-evict!}を呼んでから@code{cache-through!}を呼ぶことでも
3849 達成できますが、アルゴリズムによっては@code{cache-write!}に対して効率のよい
3850 実装を提供しているかもしれません。
3851 @c COMMON
3852 @end deffn
3853
3854 @deffn {Generic function} cache-evict! cache key
3855 @c MOD data.cache
3856 @c EN
3857 Removes an entry with @var{key} from @var{cache}, if it exists.
3858 @c JP
3859 @var{cache}から@var{key}に結びついたエントリを(もしあれば)削除します。
3860 @c COMMON
3861 @end deffn
3862
3863 @deffn {Generic function} cache-clear! cache
3864 @c MOD data.cache
3865 @c EN
3866 Removes all entries from @var{cache}.
3867 @c JP
3868 @var{cache}内のエントリを全て取り除きます。
3869 @c COMMON
3870 @end deffn
3871
3872 @c EN
3873 @subheading Implementing a cache algorithm
3874 @c JP
3875 @subheading キャッシュアルゴリズムの実装
3876 @c COMMON
3877
3878 @c EN
3879 Each cache algorithm must define a class inheriting @code{<cache>},
3880 and implement the following two essential methods.
3881 The higher-level API calls them.
3882 @c JP
3883 新たなキャッシュアルゴリズムを提供するには、@code{<cache>}を継承したクラスを定義し、
3884 次の二つの必須メソッドを実装します。高レベルAPIはこれらの必須メソッドを呼び出します。
3885 @c COMMON
3886
3887 @deffn {Generic function} cache-check! cache key
3888 @c MOD data.cache
3889 @c EN
3890 Looks for an entry with @var{key} in @var{cache}.
3891 If it exists, returns a pair of @var{key} and the associated value.
3892 Otherwise, returns @code{#f}. It may update the cache,
3893 for example, the timestamp of the entry for being read.
3894 @c JP
3895 @var{cache}から@var{key}に結びついたエントリを探します。
3896 見つかれば、@var{key}とその値とのペアを、見つからなければ@code{#f}を返します。
3897 この時、必要ならばキャッシュを更新して構いません。
3898 例えば読み出されたエントリのタイムスタンプを更新するなどです。
3899 @c COMMON
3900 @end deffn
3901
3902 @deffn {Generic function} cache-register! cache key value
3903 @c MOD data.cache
3904 @c EN
3905 Add an entry with @var{key} and associated @var{value} into @var{cache}.
3906 This is called after @var{key} is confirmed not being in @var{cache}.
3907 @c JP
3908 @var{cache}に、@var{key}と対応する@var{value}を追加します。
3909 このメソッドは、@var{cache}に@var{key}に対応するエントリが無いことが確認された後で
3910 呼び出されます。
3911 @c COMMON
3912 @end deffn
3913
3914 @c EN
3915 Additionally, the implementation should consider the following points.
3916 @c JP
3917 アルゴリズムの実装は、また以下の点を考慮しなければなりません。
3918 @c COMMON
3919
3920 @itemize @bullet
3921 @item
3922 @c EN
3923 The @code{initialize} method must call @code{next-method} first, which sets up
3924 the @code{comparator} and @code{storage} slots. You should check
3925 if @code{storage} has pre-filled entries, and if so, set up other
3926 internal structures appropriately.
3927 @c JP
3928 @code{initialize}メソッドは最初に@code{next-method}を呼ばなければなりません。
3929 それによって@code{comparator}と@code{storage}スロットが適切に初期化されます。
3930 また、@code{storage}スロットに既にデータが入っているかどうかを調べ、
3931 そうであれば他の内部構造をそれに合わせて初期化する必要があります。
3932 @c COMMON
3933 @item
3934 @c EN
3935 The default methods of @code{cache-evict!} and @code{cache-clear!} only
3936 takes care of the storage of the cache. You should implement them
3937 if your auxiliary structure needs to be taken care of.
3938 @c JP
3939 @code{cache-evict!}と@code{cache-clear!}のデフォルトメソッドはキャッシュの
3940 @code{storage}だけを更新します。サブクラスが他の内部状態を持っている場合は、
3941 それらの一貫性を保つようなメソッドを定義する必要があります。
3942 @c COMMON
3943 @item
3944 @c EN
3945 The default method of @code{cache-write!} is just @code{cache-evict!}
3946 followed by @code{cache-register!}. You may provide an alternative method
3947 if you can do it more efficiently, which is often the case.
3948 @c JP
3949 @code{cache-write!}のデフォルトメソッドは、@code{cache-evict!}を呼んでから
3950 @code{cache-register!}を呼ぶだけです。
3951 より効率の良い実装があれば(あることが多いでしょう)、
3952 このメソッドをオーバライドするのが良いでしょう。
3953 @c COMMON
3954 @end itemize
3955
3956 @c EN
3957 There are several procedures that help implementing cache subclasses:
3958 @c JP
3959 キャッシュのサブクラスを実装するのに便利な手続きがいくつか用意してあります:
3960 @c COMMON
3961
3962 @defun cache-comparator cache
3963 @defunx cache-storage cache
3964 @c MOD data.cache
3965 @c EN
3966 Returns the comparator and the storage of the cache, respectively.
3967 @c JP
3968 キャッシュの@code{comparator}と@code{storage}を返します。
3969 @c COMMON
3970 @end defun
3971
3972 @c EN
3973 Typical caches may be constructed with a storage (dictionary) and
3974 a queue, where the storage maps keys to @code{(<n> . <value>)},
3975 and queues holds @code{(<key> . <n>)}, @code{<n>} being a number
3976 (timestamp, counter, etc.) Here are some common operations work
3977 on this queue-and-dictionary scheme:
3978 @c JP
3979 典型的なキャッシュは、storageとしての辞書と、キューで作られます。
3980 ここでstorageは、キーを@code{(<n> . <value>)}にマップし、
3981 キューは@code{(<key> . <n>)}を保持します。
3982 ただし@code{<n>}はタイムスタンプやカウンタなど何からの数値です。
3983 キャッシュがこの「キューと辞書」を使って実装されている場合は、
3984 以下の共通手続きが使えるでしょう:
3985 @c COMMON
3986
3987 @defun cache-populate-queue! queue storage
3988 @c MOD data.cache
3989 @c EN
3990 You can call this in the @code{initialize} method to set up the
3991 queue. This procedure walks @var{storage} (a dictionary that maps
3992 keys to @code{(<n> . <value>)}) to construct @code{(<key> . <n>)}
3993 pairs, sorts it in increasing order of @code{<n>}, and pushes them
3994 into the @var{queue}.
3995 @c JP
3996 @code{initialize}メソッドの中でこの手続きを呼ぶことにより、
3997 キューを初期化できます。この手続きは、キーを@code{(<n> . <value>)}にマップする辞書である
3998 @var{storage}を走査し、@code{(<key> . <n>)}というペアを作り、
3999 @code{<n>}の昇順にソートしてそれを@var{queue}にプッシュします。
4000 @c COMMON
4001 @end defun
4002
4003 @defun cache-compact-queue! queue storage
4004 @c MOD data.cache
4005 @c EN
4006 The queue may contain multiple pairs with the same key. Sometimes the
4007 queue gets to have too many duplicated entries (e.g. the same entry
4008 is read repeatedly, and you push the read timestamp to the queue
4009 for every read). This procedure scans the queue and removes duplicated entries
4010 but the up-to-date one. After this operation, the length of the queue
4011 and the number of entries in the storage should match.
4012 @c JP
4013 キューに、同じキーを持つエントリが複数含まれることがあります。
4014 しばしば、そういった重複エントリが多くなりすぎる場合があります
4015 (例えばキーが読み出される度にタイムスタンプをキューにプッシュしていて、
4016 同じキーが何度も読まれた場合)。この手続きはキューを走査し、
4017 キーが重複しているエントリは最新のもの以外を取り除きます。
4018 この操作の後では、キューの長さとstorageのエントリ数は一致しているはずです。
4019 @c COMMON
4020 @end defun
4021
4022 @defun cache-renumber-entries! queue storage
4023 @c MOD data.cache
4024 @c EN
4025 This procedure renumbers @code{<n>}s in the queue and the storage
4026 starting from 0, without changing their order, and returns the
4027 maximum @code{<n>}. The duplicated entries in the queue is removed
4028 as in @code{cache-compact-queue!}.
4029 @c JP
4030 この手続きはキュー内の@code{<n>}を、順序を変えることなく、0から昇順に付け直し、
4031 @code{<n>}の最大値を返します。キーが重複するエントリは@code{cache-compact-queue!}と
4032 同様に、最新のもの以外取り除かれます。
4033 @c COMMON
4034
4035 @c EN
4036 When you're using monotonically increasing counter for @code{<n>} and
4037 you don't want @code{<n>} to get too big (i.e. bignums), you can
4038 call this procedure occasionally to keep @code{<n>}'s in a reasonable range.
4039 @c JP
4040 @code{<n>}に単調増加する数を使っていて、長い時間の後では@code{<n>}がbignum
4041 になって効率が落ちる心配があれば、この手続きを適宜呼ぶことで@code{<n>}を適切な
4042 範囲内に収めることができるでしょう。
4043 @c COMMON
4044 @end defun
4045
4046
4047 @c ----------------------------------------------------------------------
4048 @node Heap, Immutable deques, Cache, Library modules - Utilities
4049 @section @code{data.heap} - Heap
4050 @c NODE ヒープ, @code{data.heap} - ヒープ
4051
4052 @deftp {Module} data.heap
4053 @mdindex data.heap
4054 @c EN
4055 A heap is a data container that allows efficient retrieval of
4056 the minimum or maximum entry. Unlike a @code{<tree-map>}
4057 (@pxref{Treemaps}), which always keeps all entries in order,
4058 a heap only cares the minimum or the maximum of the current set;
4059 the other entries are only partially ordered, and reordered
4060 when the minimu/maximum entry is removed. Hence it is more
4061 efficient than a treemap if all you need is minimum/maximum value.
4062 Besides binary heaps can store entries in packed, memory-efficient way.
4063 @c JP
4064 ヒープは最小値また最大値を効率よく取り出せるデータコンテナです。
4065 @code{<tree-map>}は全てのエントリの順序を常に保っていますが (@ref{Treemaps}参照)、
4066 ヒープは最小値/最大値以外については部分的にしか順序を保持していません。
4067 最小値/最大値が取り除かれる時点で内部を再構成して、次の最小値/最大値を見つけます。
4068 したがって、最小値/最大値のみが必要な場合、treemapより効率が良いです。
4069 さらに、バイナリヒープでは値をメモリ効率の良い詰められた形で保持できます。
4070 @c COMMON
4071 @end deftp
4072
4073 @deftp {Class} <binary-heap>
4074 @clindex binary-heap
4075 @c MOD data.heap
4076 @c EN
4077 An implementation of a binary heap. Internally it uses min-max heap,
4078 so that you can find both minimum and maximum value in O(1).
4079 Pushing a new value and popping the minimum/maximum value are both O(log n).
4080
4081 It also stores its values in a flat vector, a lot more compact
4082 than a general tree structure that needs a few pointers per node.
4083 By default it uses a sparse vector for the backing storage, allowing
4084 virtually unlimited capacity (@pxref{Sparse vectors}).
4085 But you can use an ordinal vector
4086 or a uniform vector as a backing storage instead.
4087 @c JP
4088 バイナリヒープの実装です。内部的にmin-maxヒープを使っており、
4089 最大値と最小値のどちらにもO(1)でアクセスできます。新たな値をpushしたり、
4090 最大最小値をpopするのはO(log n)です。
4091
4092 バイナリヒープはまた、値をフラットなベクタに格納します。一般的なツリー構造が
4093 ノードあたりいくつかのポインタを必要とするのに比べずっとコンパクトです。
4094 デフォルトでは疎なベクタ (@ref{Sparse vectors}) がバッキングストレージとして使われ、
4095 事実上上限なしでデータを格納できますが、通常のベクタやユニフォームベクタを
4096 バッキングストレージとして指定することもできます。
4097 @c COMMON
4098
4099 @c EN
4100 A binary heap isn't MT-safe structure; you must put it in atom
4101 or use mutexes if multiple threads can access to it
4102 (@pxref{Synchronization primitives}).
4103 @c JP
4104 バイナリヒープはスレッドセーフではありません。複数のスレッドでアクセスする
4105 可能性がある場合は、atomに入れるか、mutexを適切に使ってください(@ref{Synchronization primitives}参照)。
4106 @c COMMON
4107 @end deftp
4108
4109 @defun make-binary-heap :key comparator storage key
4110 @c MOD data.heap
4111 @c EN
4112 Creates and returns a new binary heap.
4113
4114 The @var{comparator} keyword argument specifies how to compare the
4115 entries. It must have comparison procedure or ordering predicate.
4116 The default is @code{default-comparator}.
4117 @xref{Basic comparators}, for the details of comparators.
4118
4119 The @var{storage} keyword argument gives alternative
4120 backing storage. It must be either a vector, a uniform vector,
4121 or an instance of a sparse vector (@pxref{Sparse vectors}).
4122 The default is an instance of @code{<sparse-vector>}.
4123 If you pass a vector or a uniform vector, it determines
4124 the maximum number of elements the heap can hold.
4125 The heap won't be extend the storage once it gets full.
4126
4127 The @var{key} keyword argument must be a procedure; it is applied
4128 on each entry before comparison. Using key procedure allows you to
4129 store auxiliary data other than the actual value to be compared.
4130 The following example shows the entries are compared by their @code{car}'s:
4131 @c JP
4132 新しいバイナリヒープを作って返します。
4133
4134 @var{comparator}キーワード引数は、エントリの比較方法を指定する比較器です。
4135 比較手続きを持っていなければなりません。省略時は@code{default-comparator}が
4136 使われます。比較器について詳しくは@ref{Basic comparators}を参照してください。
4137
4138 @var{storage}キーワード引数には、データの格納に使うデータ構造を渡します。引数は
4139 ベクタ、ユニフォームベクタ、あるいは疎ベクタ(@ref{Sparse vectors}参照)の
4140 インスタンスでなければなりません。省略時は@code{<sparse-vector>}の
4141 インスタンスが使われます。
4142
4143 ベクタまたはユニフォームベクタを渡した場合、そのベクタの大きさが
4144 ヒープが格納できる要素の最大数を決めます。
4145 それが一杯になった時に自動的に拡張されることはありません。
4146
4147 @var{key}キーワード引数は手続きでなければならず、要素の比較の前に各要素に適用されます。
4148 この手続きを使って、実際に比較される値に付随するデータを格納しておくことができます。
4149 次の例では、データの@code{car}を使って比較しています。
4150 @c COMMON
4151
4152 @example
4153 (define *heap* (make-binary-heap :key car))
4154 (binary-heap-push! *heap* (cons 1 'a))
4155 (binary-heap-push! *heap* (cons 3 'b))
4156 (binary-heap-push! *heap* (cons 1 'c))
4157
4158 (binary-heap-find-min *heap*) @result{} (1 . c)
4159 (binary-heap-find-max *heap*) @result{} (3 . b)
4160 @end example
4161 @end defun
4162
4163 @defun build-binary-heap storage :key comparator key num-entries
4164 @c MOD data.heap
4165 @c EN
4166 Create a heap from the data in @var{storage}, and returns it.
4167 (Sometimes this operation is called @emph{heapify}.)
4168 This allows you to create a heap without allocating a new storage.
4169 The @var{comparator} and @var{key} arguments are the same as
4170 @code{make-binary-heap}.
4171
4172 @var{Storage} must be either a vector, a uniform vector,
4173 or an instance of a sparse vector. The storage is modified
4174 to satisfy the heap property, and will be used as the backing
4175 storage of the created heap. Since the storage will be owned
4176 by the heap, you shouldn't modify the storage later.
4177
4178 The storage supposed to have keys from index 0 below
4179 @var{num-entries}.
4180 If @var{num-entries} is omitted or @code{#f}, entire vector or
4181 uniform vector, or up to @code{sparse-vector-num-entries} on
4182 the sparse vector, is heapified.
4183 @c JP
4184 @var{storage}に入っているデータを使ってヒープを作り返します。
4185 (この操作はしばしばヒープ化(@emph{heapify})と呼ばれます。)
4186 データ格納場所を新たにアロケートせずにヒープを作ることが可能です。
4187 @var{comparator}および@var{key}引数は@code{make-binary-heap}と同じです。
4188
4189 @var{storage}はベクタ、ユニフォームベクタ、疎ベクタのインスタンスでなければ
4190 なりません。このデータはヒープの属性を満たすために変更され、さらには
4191 作られたヒープのデータ格納場所となります。ヒープの一部になるので、
4192 @var{storage}を後から変更してはなりません。
4193
4194 @var{storage}の要素のうち、先頭から@var{num-entries}までの要素が
4195 有効であるとしてヒープ化されます。@var{num-entries}が省略されるか
4196 @code{#f}であれば、ベクタおよびユニフォームベクタはその全てが、
4197 疎ベクタは@code{sparse-vector-num-entries}までの要素がヒープ化されます。
4198 @c COMMON
4199 @end defun
4200
4201 @defun binary-heap-copy heap
4202 @c MOD data.heap
4203 @c EN
4204 Copy the heap. The backing storage is also copied.
4205 @c JP
4206 ヒープをコピーして返します。データ格納場所も全てコピーされます。
4207 @c COMMON
4208 @end defun
4209
4210 @defun binary-heap-clear! heap
4211 @c MOD data.heap
4212 @c EN
4213 Empty the heap.
4214 @c JP
4215 ヒープを空にします。
4216 @c COMMON
4217 @end defun
4218
4219 @defun binary-heap-num-entries heap
4220 @c MOD data.heap
4221 @c EN
4222 Returns the current number of entries in the heap.
4223 @c JP
4224 ヒープ中の要素数を返します。
4225 @c COMMON
4226 @end defun
4227
4228 @defun binary-heap-empty? heap
4229 @c MOD data.heap
4230 @c EN
4231 Returns @code{#t} if the heap is empty, @code{#f} otherwise.
4232 @c JP
4233 ヒープが空なら@code{#t}を、そうでなければ@code{#f}を返します。
4234 @c COMMON
4235 @end defun
4236
4237 @defun binary-heap-push! heap item
4238 @c MOD data.heap
4239 @c EN
4240 Insert @var{item} into the @var{heap}. This is O(log n) operation.
4241 If the heap is already full, an error is raised.
4242 @c JP
4243 @var{item}を@var{heap}に挿入します。O(log n)の操作です。
4244 ヒープが既に一杯であった場合はエラーが通知されます。
4245 @c COMMON
4246 @end defun
4247
4248 @defun binary-heap-find-min heap :optional fallback
4249 @defunx binary-heap-find-max heap :optional fallback
4250 @c MOD data.heap
4251 @c EN
4252 Returns the minimum and maximum entry of the heap, respectively.
4253 The heap will be unmodified. This is O(1) operation.
4254
4255 If the heap is empty, @var{fallback} is returned when it is provided,
4256 or an error is signaled.
4257 @c JP
4258 それぞれヒープ中の最小および最大の要素を返します。O(1)の操作です。
4259 ヒープ自体は変更されません。
4260
4261 ヒープが空の場合、@var{fallback}が与えられればそれが返され、
4262 そうでなければエラーが通知されます。
4263 @c COMMON
4264 @end defun
4265
4266 @defun binary-heap-pop-min! heap
4267 @defunx binary-heap-pop-max! heap
4268 @c MOD data.heap
4269 @c EN
4270 Removes the minimum and maximum entry of the heap and returns it,
4271 respectively. O(log n) operation.
4272 If the heap is empty, an error is signaled.
4273 @c JP
4274 それぞれヒープから最小および最大の要素を取り除き、取り除いた要素を返します。
4275 O(log n)の操作です。
4276 ヒープが空ならエラーが通知されます。
4277 @c COMMON
4278 @end defun
4279
4280 @c EN
4281 The following procedures are not heap operations, but provided
4282 for the convenience.
4283 @c JP
4284 以下の手続きは一般的なデータ構造としてのヒープの操作には含まれませんが、
4285 便利なので用意してあります。
4286 @c COMMON
4287
4288 @defun binary-heap-swap-min! heap item
4289 @defunx binary-heap-swap-max! heap item
4290 @c MOD data.heap
4291 @c EN
4292 These are operationally equivalent to the followings, respectively:
4293 @c JP
4294 これらはそれぞれ以下のコードと操作的には等価です。
4295 @c COMMON
4296
4297 @example
4298 (begin0 (binary-heap-pop-min! heap)
4299 (binary-heap-push! heap item))
4300
4301 (begin0 (binary-heap-pop-max! heap)
4302 (binary-heap-push! heap item))
4303 @end example
4304
4305 @c EN
4306 However, those procedures are slightly efficient,
4307 using heap property maintaining procedure only once per function call.
4308 @c JP
4309 ただしこれらの手続きは、
4310 ヒープ特性を維持するための手続きを呼び出し毎に1回しか行わないので、
4311 やや効率的です。
4312 @c COMMON
4313 @end defun
4314
4315
4316
4317 @defun binary-heap-find pred heap :optional failure
4318 @c MOD data.heap
4319 @c EN
4320 Returns an item in the heap that satisfies @var{pred}.
4321 If there are more than one item that satisfy @var{pred},
4322 any one of them can be returned. If no item satisfy @var{pred},
4323 the thunk @var{failure} is called, whose default is @code{(^[] #f)}.
4324 This is O(n) operation.
4325 @c JP
4326 ヒープの中で、述語@var{pred}を満たす要素を返します。@var{pred}を満たす要素が
4327 複数ある場合にどれが返るかは不定です。@var{pred}を満たす要素が無ければ
4328 サンク@var{failure}が呼ばれます。@var{failure}のデフォルトは
4329 @code{(^[] #f)}です、O(n)の操作です。
4330 @c COMMON
4331
4332 @c EN
4333 Note: The argument order used to be @code{(binary-heap-find heap pred)}
4334 until 0.9.10. We changed it to align other *-find procedures.
4335 The old argument order still work for the backward compatibility,
4336 but the new code should use the current order.
4337 @c JP
4338 註: 0.9.10まで、引数の順序は@code{(binary-heap-find heap pred)}でしたが、
4339 他の *-find 系インタフェースと合わせるために変更されました。
4340 互換性のため、古いインタフェースで呼び出しても動作するようになっていますが、
4341 新たに書くコードは新しいインタフェースを使ってください。
4342 @c COMMON
4343 @end defun
4344
4345 @defun binary-heap-remove! heap pred
4346 @c MOD data.heap
4347 @c EN
4348 Remove all items in the heap that satisfy @var{pred}. This is O(n) operation.
4349 @c JP
4350 @var{pred}を満たす要素を全てヒープから取り除きます。O(n)の操作です。
4351 @c COMMON
4352 @end defun
4353
4354 @defun binary-heap-delete! heap item
4355 @c MOD data.heap
4356 @c EN
4357 Delete all items in the heap that are equal to @var{item},
4358 in terms of the heap's comparator and key procedure. This is O(n) operation.
4359
4360 Note that the key procedure is applied to @var{item} as well
4361 before comparison.
4362 @c JP
4363 @var{item}に等しい要素を全てヒープから取り除きます。「等しい」の判定には
4364 ヒープの比較器およびキー手続きが使われます。O(n)の操作です。
4365
4366 キー手続きは、比較の前に@var{item}にも適用されます。
4367 @c COMMON
4368 @end defun
4369
4370 @c ----------------------------------------------------------------------
4371 @node Immutable deques, Immutable map, Heap, Library modules - Utilities
4372 @section @code{data.ideque} - Immutable deques
4373 @c NODE 変更不可な両端キュー, @code{data.ideque} - 変更不可な両端キュー
4374
4375 @deftp {Module} data.ideque
4376 @mdindex data.ideque
4377 @c EN
4378 This module provides a functional double-ended queue (deque,
4379 pronounced as ``deck'').
4380 @c JP
4381 このモジュールは、両端キュー (deque、「デック」と読みます) の機能を提供します。
4382 @c COMMON
4383
4384 @c EN
4385 Almost all procedures in this module are now a part of R7RS large.
4386 @xref{R7RS immutable deques}, for description of the following
4387 @c JP
4388 このモジュールのほぼ全ての手続きは、R7RS-largeに取り込まれました。
4389 以下の手続きについては@ref{R7RS immutable deques}を参照してください。
4390 @c COMMON
4391 procedures:
4392
4393 @example
4394 ideque ideque-unfold ideque-unfold-right
4395 ideque-tabulate ideque? ideque-empty?
4396 ideque-add-front ideque-add-back
4397 ideque-remove-front ideque-remove-back
4398 ideque-front ideque-back
4399 ideque-reverse ideque= ideque-ref
4400 ideque-take ideque-drop
4401 ideque-take-right ideque-drop-right
4402 ideque-split-at ideque-append ideque-zip
4403 ideque-map ideque-for-each ideque-for-each-right
4404 ideque-fold ideque-fold-right ideque-append-map
4405 ideque-filter ideque-remove
4406 ideque-find ideque-find-right
4407 ideque-take-while ideque-take-while-right
4408 ideque-drop-while ideque-drop-while-right
4409 ideque-span ideque-break
4410 ideque-any ideque-every
4411 ideque->list list->ideque
4412 ideque->generator generator->ideque
4413 @end example
4414 @end deftp
4415
4416 @defun make-ideque n :optional init
4417 @c MOD data.ideque
4418 @c EN
4419 Creates an ideque of length @var{n} with all the elements being
4420 @var{init}. If @var{init} is omitted, @code{#f} is used.
4421 @c JP
4422 @var{n}個の@var{init}で初期化されたidequeを作って返します。
4423 @var{init}が省略された場合は@code{#f}が使われます。
4424 @c COMMON
4425
4426 @c EN
4427 This is provided just for the symmetry with other container data
4428 structures; it's not in SRFI-134, and the portable code can use
4429 @code{ideque-tabulate}.
4430 @c JP
4431 この手続きは、他のデータ構造との対称性のためだけに提供されていて、
4432 SRFI-134には含まれていません。ポータブルなコードは
4433 @code{ideque-tabulate}を使って同じようなことができます。
4434 @c COMMON
4435 @end defun
4436
4437
4438 @c ----------------------------------------------------------------------
4439 @node Immutable map, Priority map, Immutable deques, Library modules - Utilities
4440 @section @code{data.imap} - Immutable map
4441 @c NODE 変更不可なマップ, @code{data.imap} - 変更不可なマップ
4442
4443 @deftp {Module} data.imap
4444 @mdindex data.imap
4445 @c EN
4446 This module provides a immutable data structure with O(log n)
4447 access and update operations (here, update means to return a
4448 new structure with requested changes).
4449 The current implementation is
4450 based on the functional red-black tree.
4451 @c JP
4452 このモジュールは、O(log n)でアクセスと更新が可能な、変更不可のデータ構造を
4453 提供します(ここでの「更新」とは、要求された変更を取り込んだ新たな構造を
4454 作って返すことです)。
4455 現在の実装は関数的な赤黒木に基づいています。
4456 @c COMMON
4457 @end deftp
4458
4459 @c EN
4460 Although lists and alists are useful for stack-like immutable
4461 operations, where you can add and remove items to the head of
4462 existing data without modifying them, they require O(n) access time
4463 and sometimes you need better one. The @code{<imap>} object
4464 provides O(log n) access, in exchange of O(log n) insertion and
4465 deletion.
4466 @c JP
4467 リストや連想リストは、スタック風の変更不可なデータ構造として使えます。
4468 つまり既存のデータ構造自体に変更を加えることなく、その先頭に要素を追加したり、
4469 先頭から要素を取り除いたりできるということです。一方で、リストや連想リストは
4470 任意の要素にアクセスするにはO(n)の時間を必要としますが、もっと速いアクセスが必要な
4471 場合もあります。@code{<imap>}オブジェクトはO(log n)のアクセスを可能にします。
4472 そのかわり、要素の追加や削除にもO(log n)を必要とします。
4473 @c COMMON
4474
4475 @deftp {Class} <imap-meta>
4476 @c MOD data.imap
4477 @c EN
4478 Metaclass of @code{<imap>}.
4479 @c JP
4480 @code{<imap>}のメタクラスです。
4481 @c COMMON
4482 @end deftp
4483
4484 @deftp {Class} <imap>
4485 @c MOD data.imap
4486 @c EN
4487 Immutable map class. An instance of @code{<imap-meta>}.
4488
4489 Inherits @code{<ordered-dictionary>}, conforms dictionary protocol
4490 except mutating operators (@pxref{Dictionary framework}).
4491 As a sequence, you can access key-value
4492 pairs in increasing order of keys.
4493 @c JP
4494 変更不可なマップのクラスです。@code{<imap-meta>}をメタクラスとします。
4495
4496 @code{<ordered-dictionary>}を継承し、変更操作を除くディクショナリプロトコル
4497 を実装します(@ref{Dictionary framework}参照)。
4498 シーケンスとしてアクセスした場合は、キーと値のペアをキーの昇順に取り出すことができます。
4499 @c COMMON
4500 @end deftp
4501
4502 @defun make-imap
4503 @defunx make-imap comparator
4504 @defunx make-imap key=? key<?
4505 @c MOD data.imap
4506 @c EN
4507 Creates a new empty immutable map. Without arguments,
4508 @code{default-comparator} is used to compare keys. To give a
4509 specific comparator, use the second form; the @var{comparator}
4510 argument should have comparison procedure.
4511 For the details of comparators, @pxref{Basic comparators}.
4512 The third form creates a key comparator from a equality
4513 predicate @var{key=?} and less-than predicate @code{key<?},
4514 both must accept two keys. This interface is consistent with
4515 @code{tree-map} (@pxref{Treemaps}).
4516 @c JP
4517 空の変更不可なマップを新たに作って返します。
4518 引数無しの場合は、キーの比較には@code{default-comparator}が使われます。
4519 キーの比較方法を指定したい場合は、比較手続きを持つ比較器@var{comparator}を
4520 引数に渡してください。比較器については@ref{Basic comparators}を参照。
4521 3番目の呼び出し形式は、キーの等価性を調べる述語@var{key=?}と
4522 大小比較の述語@var{key<?}から比較器を作ります。どちらの述語も
4523 ふたつの引数をとらなければなりません。このインタフェースは
4524 @code{tree-map}との一貫性のためにサポートされています (@ref{Treemaps}参照)。
4525 @c COMMON
4526 @end defun
4527
4528 @defun alist->imap alist
4529 @defunx alist->imap alist comparator
4530 @defunx alist->imap alist key=? key<?
4531 @c MOD data.imap
4532 @c EN
4533 Creates and returns an immutable map containing
4534 key-value associations given by an assoc-list @var{alist}.
4535 This may be a bit more efficient than creating an empty map with
4536 @code{make-imap} and populates it with @code{imap-put}
4537 one by one.
4538 @c JP
4539 連想リスト@var{alist}で指定されるキーと値の組み合わせを持つ変更不可なマップを新たに作って返します。
4540 これは@code{make-imap}で空のimapを作ってから@code{imap-put}で一要素づつ値を追加するよりも効率的です。
4541 @c COMMON
4542
4543 @c EN
4544 The @var{comparator} argument specifies how to compare the keys.
4545 It must have comparison procedure. If omitted, @code{default-comparator}
4546 is used. @xref{Basic comparators}, for the details.
4547 @c JP
4548 @var{comparator}引数はキーの比較に使うので比較手続きを持っていなければなりません。
4549 省略された場合は@code{default-comparator}が使われます。
4550 比較器について詳しくは@ref{Basic comparators}を参照してください。
4551 @c COMMON
4552
4553 @c EN
4554 The third form creates a key comparator from a equality
4555 predicate @var{key=?} and less-than predicate @code{key<?},
4556 both must accept two keys.
4557 @c JP
4558 三つ目の形式は、等価判定述語@var{key=?}と比較述語@var{key<?}の組み合わせで
4559 キーの比較方法を指定するものです。どちらの述語も二つのキーを取ります。
4560 @c COMMON
4561
4562 @example
4563 (define m (alist->imap '((a . 1) (b . 2))))
4564
4565 (imap-get m 'a) @result{} 1
4566 (imap-get m 'b) @result{} 2
4567 @end example
4568 @end defun
4569
4570 @defun tree-map->imap tree-map
4571 @c MOD data.imap
4572 @c EN
4573 Returns a new immutable map with the same content (and the same comparator)
4574 as @var{tree-map}.
4575 @c JP
4576 @var{tree-map}と同じ内容、同じ比較器を持つ変更不可なマップを返します。
4577 @c COMMON
4578 @end defun
4579
4580 @defun imap? obj
4581 @c MOD data.imap
4582 @c EN
4583 Returns @code{#t} if @var{obj} is an immutable map,
4584 @code{#f} otherwise.
4585 @c JP
4586 @var{obj}が変更不可なマップなら@code{#t}を、そうでなければ@code{#f}を返します。
4587 @c COMMON
4588 @end defun
4589
4590 @defun imap-empty? immap
4591 @c MOD data.imap
4592 @c EN
4593 Returns @code{#t} if an immutable map @var{immap} is empty,
4594 @code{#f} otherwise.
4595 @c JP
4596 変更不可なマップ@var{immap}が空なら@code{#t}を、そうでなければ@code{#f}を返します。
4597 @c COMMON
4598 @end defun
4599
4600 @defun imap-exists? immap key
4601 @c MOD data.imap
4602 @c EN
4603 Returns @code{#t} if @var{key} exists in an immutable map @var{immap}.
4604 @c JP
4605 変更不可なマップ@var{immap}がキー@var{key}を持っていれば@code{#t}を、
4606 そうでなければ@code{#f}を返します。
4607 @c COMMON
4608 @end defun
4609
4610 @defun imap-get immap key :optional default
4611 @c MOD data.imap
4612 @c EN
4613 Returns the value associated with @var{key} in an immutable map @var{immap}.
4614 If @var{immap} doesn't have @var{key}, @var{default} is returned
4615 when provided, otherwise an error is signalled.
4616 @c JP
4617 変更不可なマップ@var{immap}中のキー@var{key}に対応する値を返します。
4618 @var{immap}が@var{key}を持っていない場合、@var{default}引数が与えられていれば
4619 その値を返し、なければエラーが投げられます。
4620 @c COMMON
4621 @end defun
4622
4623 @defun imap-put immap key val
4624 @c MOD data.imap
4625 @c EN
4626 Returns a new immutable map where association of @var{key} to @var{val}
4627 is added to (or replaced in) an immutable map @var{immap}.
4628 This operation is O(log n).
4629 @c JP
4630 変更不可なマップ@var{immap}に、キー@var{key}と値@var{val}の対応を付け加えた
4631 (あるいは、既に対応があった場合は置き換えた)新たな変更不可なマップを作って返します。
4632 この操作はO(log n)です。
4633 @c COMMON
4634
4635 @example
4636 (define m1 (alist->imap '((a . 1) (b . 2))))
4637
4638 (define m2 (imap-put m1 'a 3))
4639
4640 (imap-get m2 'a) @result{} 3
4641 (imap-get m1 'a) @result{} 1 ; not affected
4642 @end example
4643 @end defun
4644
4645 @defun imap-delete immap key
4646 @c MOD data.imap
4647 @c EN
4648 Returns a new immutable map where @var{key} is removed from
4649 @var{immap}. If @var{immap} doesn't have @var{key}, returned
4650 map has the same content as @var{immap}.
4651 @c JP
4652 変更不可なマップ@var{immap}から、キー@var{key}に対応するエントリを
4653 取り除いた新たな変更不可なマップを作って返します。
4654 @var{immap}に@var{key}が含まれていなかった場合、返されるマップは
4655 元のマップと同じ内容を持ちます。
4656 @c COMMON
4657
4658 @example
4659 (define m1 (alist->imap '((a . 1) (b . 2))))
4660
4661 (define m2 (imap-delete m1 'a))
4662
4663 (imap-get m2 'a #f) @result{} #f
4664 (imap-get m1 'a) @result{} 1 ; not affected
4665 @end example
4666 @end defun
4667
4668 @defun imap-min immap
4669 @defunx imap-max immap
4670 @c MOD data.imap
4671 @c EN
4672 Returns a pair of key and value with the minimum or maximum
4673 key in @var{immap}, respectively. If @var{immap} is empty,
4674 @code{#f} is returned.
4675 @c JP
4676 変更不可なマップ@var{immap}中で、最小または最大のキーと、それに対応する値を
4677 ペアにして返します。@var{immap}が空の場合は@code{#f}を返します。
4678 @c COMMON
4679 @end defun
4680
4681 @c ----------------------------------------------------------------------
4682 @node Priority map, Queue, Immutable map, Library modules - Utilities
4683 @section @code{data.priority-map} - Priority map
4684 @c NODE プライオリティマップ, @code{data.priority-map} - プライオリティマップ
4685
4686 @deftp {Module} data.priority-map
4687 @mdindex data.priority-map
4688 @c EN
4689 Priority map is a dictionary that can map keys to values, while
4690 the entires are sorted by their @emph{values}.
4691 (If the entires are sorted by keys, it's a treemap--@pxref{Treemaps}).
4692 @c JP
4693 プライオリティマップは、キーを値にマッピングする辞書で、
4694 エントリが値によってソートされているものです
4695 (エントリがキーでソートされているのはツリーマップです。@ref{Treemaps}参照)。
4696 @c COMMON
4697
4698 @c EN
4699 It is useful when you wanted a sorted sequence, with quick access by
4700 keys that are associated to each value.
4701 @c JP
4702 ソートされたシーケンスだけれど、
4703 キーによって特定の値に素早くアクセスする必要もある、という場合に便利です。
4704 @c COMMON
4705
4706 @c EN
4707 Note: If what you need is just a priority queue, you can use
4708 @code{data.heap} (@pxref{Heap}).
4709 @c JP
4710 註: 必要なものがプライオリティキューなら、
4711 @code{data.heap}が使えます (@ref{Heap}参照)。
4712 @c COMMON
4713 @end deftp
4714
4715 @deftp {Class} <priority-map>
4716 @cindex priority-map
4717 @c MOD data.priority-map
4718 @c EN
4719 Priority map class. It has no public slots.
4720 Instances of priority maps must be created by
4721 @code{make-priority-map} procedure instead of @code{make} method on
4722 the class.
4723 @c JP
4724 プライオリティマップのクラスです。公開スロットはありません。
4725 プライオリティマップのインスタンスは、@code{make}メソッドではなく
4726 @code{make-priority-map}で作る必要があります。
4727 @c COMMON
4728
4729 @c EN
4730 Inherits @code{<ordered-dictionary>}, and implements dictionary protocol.
4731 Operations concerning
4732 associations of keys and values are done through dictionary generic
4733 functions (@pxref{Generic functions for dictionaries}).
4734 @c JP
4735 @code{<ordered-dictioary>}を継承し、ディクショナリプロトコルを実装しています。
4736 キーから値へのマッピングに関わる操作は、ディクショナリのジェネリック関数を
4737 使ってください(@ref{Generic functions for dictionaries}参照)。
4738 @c COMMON
4739
4740 @c EN
4741 When iterated, it iterates increasing order of values.
4742 @c JP
4743 イテレートする場合は、値の増加順になります。
4744 @c COMMON
4745 @end deftp
4746
4747 @defun make-priority-map :key key-comparator value-comparator
4748 @c MOD data.priority-map
4749 @c EN
4750 Creates and returns an empty priority map.
4751 It can take @var{key-comparator}, which is used to compare keys,
4752 and @var{value-comparator}, which must have ordering predicate
4753 and is used to order values.
4754 When omitted, @code{default-comparator} is assumed.
4755 @c JP
4756 空のプライオリティマップを作って返します。
4757 @var{key-comparator}はキーの比較に使われる比較器であり、
4758 また@var{value-comparator}は値の順序づけに使われる
4759 順序手続きを持った比較器でなければなりません。
4760 省略された場合はどちらも@code{default-comparator}が使われます。
4761 @c COMMON
4762
4763 @c EN
4764 If you apply @code{dict-comparator} on a priority map,
4765 its @var{key-comparator} is returned.
4766 @c JP
4767 プライオリティマップに@code{dict-comparator}を適用すると、
4768 @var{key-comparator}が返されます。
4769 @c COMMON
4770 @end defun
4771
4772 @defun dict->priority-map dict :optional value-comparator
4773 @c MOD data.priority-map
4774 @c EN
4775 Creates and returns a priority map that contains the same key-value entries
4776 as given dictionary @var{dict}.
4777 The priority map's key comparator is the same as the key comparator
4778 of @var{dict}, and its value comparator is @var{value-comparator},
4779 defaulted to @code{default-comparator}.
4780 @c JP
4781 ディクショナリ@var{dict}と同じキー-値のエントリを持つプライオリティマップを作って
4782 返します。作られるマップのキー比較器は@var{dict}のキー比較器と同一で、
4783 値比較器は@var{value-comparator}です。後者が省略された場合は
4784 @code{default-comparator}が使われます。
4785 @c COMMON
4786 @end defun
4787
4788 @defun alist->priority-map alist :optional key-comparator value-comparator
4789 @c MOD data.priority-map
4790 @c EN
4791 Creates and returns a priority map that contains the key-value pairs
4792 in an assoc list @var{alist}.
4793 The optional @var{key-comparator} and @var{value-comparator}
4794 are used to build a priority map. When omitted, @code{default-comparator}
4795 is used.
4796 @c JP
4797 連想リスト@var{alist}に含まれるキー-値ペアを内容とするプライオリティマップを作って
4798 返します。省略可能引数@var{key-comparator}と@var{value-comparator}が
4799 プライオリティマップの構築に使われます。省略された場合は@code{default-comparator}
4800 となります。
4801 @c COMMON
4802 @end defun
4803
4804 @defun priority-map-min pmap
4805 @defunx priority-map-max pmap
4806 @c MOD data.priority-map
4807 @c EN
4808 Return a pair of a key and a value, where the value is smallest or
4809 largest in the priority map @var{pmap}, respectively.
4810
4811 If @var{pmap} is empty, @code{#f} is returned.
4812
4813 If @var{pmap} has more than one value that are equal to each other
4814 (w.r.t. @var{value-comparator} given to the constructor),
4815 either one of them is picked.
4816 @c JP
4817 プライオリティマップ@var{pmap}中の、それぞれ最小の値および最大の値を持つエントリの
4818 キーと値をペアにして返します。
4819
4820 @var{pmap}が空の場合は@code{#f}を返します。
4821
4822 @var{pmap}中に、@var{value-comparator}で比較して同じになる値を持つエントリが
4823 複数ある場合は、そのうちのどれか一つが返されます。
4824 @c COMMON
4825 @end defun
4826
4827 @defun priority-map-min-all pmap
4828 @defunx priority-map-max-all pmap
4829 @c MOD data.priority-map
4830 @c EN
4831 Return a pair of a list of keys and a value, where the value is smallest or
4832 largest in the priority map @var{pmap}, respectively. The keys includes
4833 all the entries that has the same value. The caller shouldn't modify
4834 the returned key list.
4835 @c JP
4836 プライオリティマップ@var{pmap}中の、それぞれ最小の値および最大の値を持つエントリを
4837 全て選び、そのキーのリスト、および値そのものをペアにして返します。
4838 そのリストにあるキーは全て同じ値を持つということです。
4839 返されるキーのリストは変更してはなりません。
4840 @c COMMON
4841
4842 @c EN
4843 If @var{pmap} is empty, @code{#f} is returned.
4844 @c JP
4845 @var{pmap}が空の場合は@code{#f}を返します。
4846 @c COMMON
4847 @end defun
4848
4849 @defun priority-map-pop-min! pmap
4850 @defunx priority-map-pop-max! pmap
4851 @c MOD data.priority-map
4852 @c EN
4853 Remove one entry with the smallest or largest value, respectively,
4854 and returns a pair of the key and the value of removed entry.
4855
4856 If @var{pmap} is empty, @var{#f} is returned.
4857
4858 If @var{pmap} has more than one value that are equal to each other
4859 (w.r.t. @var{value-comparator} given to the constructor),
4860 either one of them is picked.
4861 @c JP
4862 それぞれ、最小および最大の値を持つエントリをひとつ@var{pmap}から取り除き、
4863 そのエントリのキーと値をペアにして返します。
4864
4865 @var{pmap}が空の場合は@code{#f}を返します。
4866
4867 @var{pmap}中に、@var{value-comparator}で比較して同じになる値を持つエントリが
4868 複数ある場合は、そのうちのどれか一つが選ばれます。
4869 @c COMMON
4870 @end defun
4871
4872 @c ----------------------------------------------------------------------
4873 @node Queue, Random data generators, Priority map, Library modules - Utilities
4874 @section @code{data.queue} - Queue
4875 @c NODE キュー, @code{data.queue} - キュー
4876
4877 @deftp {Module} data.queue
4878 @mdindex data.queue
4879 @c EN
4880 Provides a queue (FIFO). You can create a simple queue,
4881 which is lightweight but not thread-safe, or an MTqueue,
4882 a thread-safe queue. Basic queue operations work on
4883 both type of queues. When an mtqueue is passed to the
4884 procedures listed in this section, each operation is
4885 done in atomic way, unless otherwise noted.
4886
4887 There are also a set of procedures for mtqueues that
4888 can be used for thread synchronization; for example,
4889 you can let the consumer thread block if an
4890 mtqueue is empty, and/or the producer thread block if the number
4891 of items in the mtqueue reaches a specified limit.
4892 Using these procedures allows the program to use an mtqueue
4893 as a @emph{channel}.
4894
4895 The simple queue API is a superset of SLIB's queue implementation,
4896 which supports not only @code{enqueue!} (add item to the end of the sequence)
4897 and @code{dequeue!} (take item from the front of the sequence), but also
4898 @code{queue-push!} (add item to the front of the sequence), so that
4899 it can be used as a stack as well.
4900
4901 If you also want to take item from the end of the sequence in O(1),
4902 you need a deque (double-ended queue).
4903 @xref{Ring buffer}, which works as an efficient (both speed and space)
4904 dequeue on top of vectors. Or you can use immutable deques
4905 provided by @code{data.ideque} (@pxref{Immutable deques}).
4906
4907 See also @code{scheme.list-queue} (@ref{R7RS list queues}), which defines a
4908 portable API for list-based queue.
4909 @c JP
4910 キュー(FIFO)機能を提供します。
4911 極めて軽量ですがスレッドセーフでないシンプルなキューと、
4912 スレッドセーフなmtqueueがあります。基本的なキュー操作手続きは
4913 どちらのキューに対しても使うことができます。本節で説明されている
4914 手続きをmtqueueに適用した場合、特に断りが無い限り、操作は
4915 アトミックに行われます。
4916
4917 また、スレッド間同期に使えるmtqueue用の手続きも用意されています。
4918 例えばキューが空の時に読み出しスレッドをブロックさせたり
4919 キューの長さが指定値に達した場合に書き込みスレッドをブロックさせることができ、
4920 いわゆる「チャネル」としてキューを使うことができます。
4921
4922 シンプルキューのAPIはSLIBのキュー実装の上位互換になっています。
4923 要素を並びの末尾に追加する@code{enqueue!}と、要素を並びの先頭から取り除く
4924 @code{dequeue!}だけでなく、要素を並びの先頭に追加する@code{queue-push!}も
4925 提供されているので、スタックとしても使えます。
4926
4927 要素を並びの末尾からO(1)で取り除くAPIも欲しい場合は、
4928 deque (double-ended queue)が必要です。@code{data.ring-buffer}モジュール
4929 は、ベクタの上に実装された(空間的にも時間的にも)効率の良いdequeを提供しています
4930 (@ref{Ring buffer}参照)。また、変更不可な両端キュー@code{data.ideque}
4931 もあります(@ref{Immutable deques}参照)。
4932
4933 また、@code{scheme.list-queue}はポータブルなリストベースのキューのAPIを提供しています
4934 (@ref{R7RS list queues})。
4935 @c COMMON
4936 @end deftp
4937
4938 @deftp {Class} <queue>
4939 @clindex queue
4940 @c MOD data.queue
4941 @c EN
4942 A class of simple queue.
4943 @c JP
4944 シンプルなキューのクラスです。
4945 @c COMMON
4946
4947 @defivar {<queue>} length
4948 @c EN
4949 A read-only slot that returns the number of items in the queue.
4950 @c JP
4951 キュー中の要素の数を返す、読み取り専用のスロットです。
4952 @c COMMON
4953 @end defivar
4954 @end deftp
4955
4956 @deftp {Class} <mtqueue>
4957 @c MOD data.queue
4958 @clindex mtqueue
4959 @c EN
4960 A class of mtqueue. Inherits @code{<queue>}.
4961 @c JP
4962 mtqueueのクラスです。@code{<queue>}を継承しています。
4963 @c COMMON
4964
4965 @defivar {<mtqueue>} max-length
4966 @c EN
4967 The upper bound of the number of items in the queue.
4968 @c JP
4969 キュー中の要素数の上限を示します。
4970 @c COMMON
4971
4972 @c EN
4973 If this slot is zero, the queue cannot hold any items, but
4974 works as a synchronization device.
4975 A writer will block until a reader appears to take the item;
4976 a reader will block until a writer appears to give the item.
4977 @c JP
4978 このスロットが0の場合、キューは要素を中に持つことはできませんが、同期デバイスとして動作します。
4979 書き込みスレッドは、その要素を受け取る読み出しスレッドが現れるまでブロックし、
4980 読み出しスレッドは、要素を渡してくれる書き込みスレッドが現れるまでブロックします。
4981 @c COMMON
4982 @end defivar
4983
4984 @defivar {<mtqueue>} closed
4985 @c EN
4986 A boolean flag, set to @code{#f} initially.
4987 If this is true, the queue no longer accepts a new
4988 data by @code{enqueue!} etc. This slot is read-only and can only
4989 be changed atomically by @code{enqueue/wait!}, @code{queue-push/wait!},
4990 @code{dequeue/wait!} and @code{queue-pop/wait!}.
4991 This is useful when an mtqueue used as a channel is being shutdown.
4992 @c JP
4993 論理値のフラグ。初期値は@code{#f}です。
4994 これが真になると、@code{enqueue!}などによる新たなデータの挿入ができなくなります。
4995 このスロットは読み出し専用で、@code{enqueue/wait!}、@code{queue-push/wait!}、
4996 @code{dequeue/wait!}、@code{queue-pop/wait!}によってアトミックにセットすることが
4997 できます。
4998 これは、mtqueueをチャネルとして使っていて、シャットダウンする場合に有用です。
4999 @c COMMON
5000 @end defivar
5001
5002 @end deftp
5003
5004 @defun make-queue
5005 @c MOD data.queue
5006 @c EN
5007 Creates and returns an empty simple queue.
5008 @c JP
5009 空のシンプルなキューを作って返します。
5010 @c COMMON
5011 @end defun
5012
5013 @defun make-mtqueue :key max-length
5014 @c MOD data.queue
5015 @c EN
5016 Creates and returns an empty mtqueue. When an integer is given
5017 to the keyword argument @var{max-length}, it is used to
5018 initialize the @code{max-length} slot.
5019 @c JP
5020 空のmtqueueを作って返します。整数が@var{max-length}に与えられた場合は、
5021 それが@code{max-length}スロットの値となります。
5022 @c COMMON
5023 @end defun
5024
5025 @defun queue? obj
5026 @c MOD data.queue
5027 @c EN
5028 Returns @code{#t} if @var{obj} is a queue (either a simple queue
5029 or an mtqueue).
5030 @c JP
5031 @var{obj}がキューであれば(シンプルなキューでもmtqueueでも)@code{#t}を返します。
5032 @c COMMON
5033 @end defun
5034
5035 @defun mtqueue? obj
5036 @c MOD data.queue
5037 @c EN
5038 Returns @code{#t} if @var{obj} is an mtqueue.
5039 @c JP
5040 @var{obj}がmtqueueであれば@code{#t}を返します。
5041 @c COMMON
5042 @end defun
5043
5044 @defun queue-empty? queue
5045 @c MOD data.queue
5046 @c EN
5047 Returns @code{#t} if @var{obj} is an empty queue.
5048 @c JP
5049 @var{obj}が空のキューであれば@code{#t}を返します。
5050 @c COMMON
5051 @end defun
5052
5053 @defun queue-length queue
5054 @c MOD data.queue
5055 @c EN
5056 Returns the number of the items in the queue.
5057 @c JP
5058 キューの中にある要素の数を返します。
5059 @c COMMON
5060 @end defun
5061
5062 @defun mtqueue-max-length mtqueue
5063 @c MOD data.queue
5064 @c EN
5065 Returns the maximum number of items the mtqueue can hold.
5066 If the queue doesn't have a limit, @code{#f} is returned.
5067 @c JP
5068 キューが保持できる要素の最大数を返します。限度がない場合は@code{#f}が返ります。
5069 @c COMMON
5070 @end defun
5071
5072 @defun mtqueue-room mtqueue
5073 @c MOD data.queue
5074 @c EN
5075 Returns the number of elements the mtqueue can accept at this moment
5076 before it hits its maximum length. For example, if the queue
5077 already has the maximum number of elements, 0 is returned.
5078 If the queue doesn't have the limit, @code{+inf.0} is returned.
5079 @c JP
5080 保持できる最大容量に達するまであといくつ要素を受け入れることができるかを
5081 示す整数を返します。例えば、既にキューがいっぱいであれば0が返ります。
5082 キューに最大容量が設定されていなければ@code{+inf.0}が返ります。
5083 @c COMMON
5084
5085 @c EN
5086 Note that even if this returns a non-zero finite value, subsequent
5087 @code{enqueue!} may throw an error because of the queue being full.
5088 It's because another thread may put an item to the queue
5089 between this procedure call and @code{enqueue!}. To avoid
5090 this situation, use @code{enqueue/wait!} to insert item
5091 to mtqueue with finite max-length.
5092 @c JP
5093 この手続きが0以外有限値を返した場合でも、続く@code{enqueue!}の呼び出し時点で
5094 キューがいっぱいになっている可能性があることに注意してください。
5095 この手続きの呼び出しと@code{enqueue!}の
5096 呼び出しの間に、他のスレッドがキューに要素を入れるかもしれないからです。
5097 有限長のmtqueueに確実に要素を挿入したい場合は@code{enqueue/wait!}を使ってください。
5098 @c COMMON
5099 @end defun
5100
5101 @defun mtqueue-num-waiting-readers mtqueue
5102 @c MOD data.queue
5103 @c EN
5104 Returns the number of threads waiting on the mtqueue to read
5105 at this moment.
5106 The return value is always a nonnegative exact integer.
5107
5108 Note that the value might change between this procedure's returning
5109 the value and your checking it, if some other thread inserts
5110 an element into the queue. To use the value reliably, you need
5111 another mutex to restrict putting items in the queue.
5112 @c JP
5113 @var{mtqueue}からの読み出しで待っているスレッドの数を返します。
5114 返り値は常に非負の正確な整数です。
5115
5116 この手続きが値を返してからその値を使うまでの間に、別のスレッドが
5117 キューに要素を挿入したら、待っているスレッドの数は変わってしまうことに
5118 注意してください。この手続きの返り値を安全に使うには、
5119 キューに値を挿入する部分を別に排他制御する必要があります。
5120 @c COMMON
5121
5122 @example
5123 (define q (make-mtqueue))
5124
5125 (thread-start! (make-thread (^[] (dequeue/wait! q))))
5126
5127 (mtqueue-num-waiting-readers q) @result{} 1
5128
5129 (enqueue! q 'a)
5130
5131 (mtqueue-num-waiting-readers q) @result{} 0
5132 @end example
5133 @end defun
5134
5135 @defun copy-queue queue
5136 @c MOD data.queue
5137 @c EN
5138 Returns a copy of the queue.
5139 @c JP
5140 キューqueueのコピーを返します。
5141 @c COMMON
5142 @end defun
5143
5144 @defun enqueue! queue obj :optional more-objs @dots{}
5145 @c MOD data.queue
5146 @c EN
5147 Add @var{obj} to the end of @var{queue}. You may give more than
5148 one object, and each of them are enqueued in order.
5149 @c JP
5150 @var{obj}をキュー@var{queue}の末尾に追加します。
5151 一つ以上の@var{obj}を与えることができ、その場合はそれらが順にenqueueされます。
5152 @c COMMON
5153
5154 @c EN
5155 If @var{queue} is an mtqueue, all the objects are enqueued
5156 atomically; no other objects from other threads can be inserted
5157 between the objects given to a single @code{enqueue!} call.
5158 Besides, if the value of its @code{max-length} slot
5159 has a positive finite value, and adding @var{obj}s makes the number of
5160 elements in @var{queue} exceeds @code{max-length},
5161 an error is signaled and @var{queue} won't be modified.
5162 (If @code{max-length} is zero, this procedure always fail.
5163 Use @code{enqueue/wait!} below.)
5164 @c JP
5165 @var{queue}がmtqueueの場合、渡されたオブジェクト全ての追加は
5166 アトミックに行われます。すなわち、途中に別スレッドが要素を挿入する
5167 ことはありません。さらに、@code{max-length}スロットが正の有限値を
5168 持っており、この@code{enqueue!}の実行によってキューの要素数が
5169 @code{max-length}を越えることになる場合は、@var{queue}は
5170 変更されずエラーとなります。
5171 (@code{max-length}がゼロの場合、この手続きは常にエラーとなります。
5172 下に説明する@code{enqueue/wait!}を使ってください。)
5173 @c COMMON
5174
5175 @c EN
5176 If @var{queue} is an mtqueue and it is closed, no change is made
5177 to it and an error is thrown.
5178 @c JP
5179 @var{queue}がmtqueueで既にクローズされていた場合は、キューは変更されず
5180 エラーが投げられます。
5181 @c COMMON
5182 @end defun
5183
5184 @defun queue-push! queue obj :optional more-objs @dots{}
5185 @c MOD data.queue
5186 @c EN
5187 Add @var{obj} in front of @var{queue}. You may give more than
5188 one object, and each of them are pushed in order.
5189
5190 Like @code{enqueue!}, when @var{queue} is an mtqueue,
5191 all objects are added atomically, and the value of
5192 @code{max-length} slot is checked. See @code{enqueue!} above
5193 for the details.
5194 @c JP
5195 @var{obj}をキュー@var{queue}の先頭に追加します。
5196 一つ以上の@var{obj}を与えることができ、その場合はそれらが順にpushされます。
5197
5198 @code{enqueue!}と同様に、@var{queue}がmtqueueの場合は
5199 全てのオブジェクトはアトミックに追加され、また@code{max-length}と@code{closed}の値も
5200 チェックされます。詳しくは上の@code{enqueue!}の説明を参照してください。
5201 @c COMMON
5202 @end defun
5203
5204 @defun enqueue-unique! queue eq-proc obj :optional more-objs @dots{}
5205 @defunx queue-push-unique! queue eq-proc obj :optional more-objs @dots{}
5206 @c MOD data.queue
5207 @c EN
5208 Like @code{enqueue!} and @code{queue-push!}, respectively, except that these
5209 don't modify @var{queue} if it already contains @var{obj}
5210 (elements are compared by two-argument procedure @var{eq-proc}).
5211
5212 When @var{queue} is an mtqueue, all objects are added atomically,
5213 and the value of
5214 @code{max-length} slot is checked. See @code{enqueue!} above
5215 for the details.
5216 @c JP
5217 @var{obj}が既に@var{queue}の中に含まれている場合には@var{queue}を
5218 変更しないことを以外には、@code{enqueue!}および@code{queue-push!}と同じ
5219 動作をします。@var{obj}が含まれているかどうかの検査は
5220 2引数の関数@var{eq-proc}で行います。
5221
5222 @var{queue}がmtqueueの場合は
5223 全てのオブジェクトはアトミックに追加され、また@code{max-length}と@code{closed}の値も
5224 チェックされます。詳しくは上の@code{enqueue!}の説明を参照してください。
5225 @c COMMON
5226 @end defun
5227
5228 @defun dequeue! queue :optional fallback
5229 @defunx queue-pop! queue :optional fallback
5230 @c MOD data.queue
5231 @c EN
5232 Take one object from the front of the queue @var{queue} and returns it.
5233 Both function works the same, but @code{queue-pop!} may be used to
5234 emphasize it works with @code{queue-push!}.
5235
5236 If @var{queue} is empty, @var{fallback} is returned if given,
5237 otherwise an error is signaled.
5238
5239 If @var{queue} is an mtqueue and its @code{max-length} is zero,
5240 the queue is always empty. Use @code{dequeue/wait!} to use
5241 such a queue as an synchronization device.
5242 @c JP
5243 キュー@var{queue}の先頭からひとつ要素を取って返します。
5244 二つの手続きは全く同じ動作をします。@code{queue-pop!}は@code{queue-push!}と
5245 ペアで使われていることを強調したいときに使うと良いでしょう。
5246
5247 キューが空の場合は、@var{fallback}が与えられていればそれが返され、
5248 そうでなければエラーが報告されます。
5249
5250 キューがmtqueueでその@code{max-length}がゼロの場合、
5251 キューは常に空であるとみなされます。ゼロ長のキューを同期デバイスとして
5252 使う場合は@code{dequeue/wait!}を使ってください。
5253 @c COMMON
5254 @end defun
5255
5256 @defun dequeue-all! queue
5257 @c MOD data.queue
5258 @c EN
5259 Returns the whole content of the queue by a list, with emptying
5260 @var{queue}. If @var{queue} is already empty, returns an empty list.
5261 See also @code{queue->list} below.
5262 @c JP
5263 キューの全ての内容をリストにして返します。キューそのものは空になります。
5264 キューが既に空の場合は空リストが返されます。
5265 下の@code{queue->list}も参照してください。
5266 @c COMMON
5267 @end defun
5268
5269 @defun queue-front queue :optional fallback
5270 @defunx queue-rear queue :optional fallback
5271 @c MOD data.queue
5272 @c EN
5273 Peek the head or the tail of the queue and returns the object, respectively.
5274 The queue itself is not modified.
5275 If @var{queue} is empty, @var{fallback} is returned if it is given,
5276 otherwise an error is signaled.
5277 @c JP
5278 キュー@var{queue}の先頭もしくは末尾の要素を返します。キューそのものは変更されません。
5279 キューが空の場合、@var{fallback}が与えられていればその値を返し、
5280 そうでなければエラーを報告します。
5281 @c COMMON
5282 @end defun
5283
5284 @defun list->queue list :optional class :rest initargs
5285 @c MOD data.queue
5286 @c EN
5287 Returns a new queue whose content is the elements in @var{list},
5288 in the given order.
5289
5290 By default the created queue is a simple queue, but you
5291 can create mtqueue or instances of other subclasses of @code{<queue>}
5292 by giving the class to the optional @var{class} arguments.
5293 The optional @var{initargs} arguments are passed to the constructor
5294 of @var{class}.
5295 @c JP
5296 与えられたリスト@var{list}の各要素をその順で持つようなキューを作成して返します。
5297
5298 デフォルトではシンプルキューが作られますが、@var{class}に@code{<class>}の
5299 サブクラスを渡すことで他のキュークラスのインスタンスを作ることができます。
5300 @var{initargs}は@var{class}のコンストラクタに渡されます。
5301 @c COMMON
5302 @end defun
5303
5304 @defun queue->list queue
5305 @c MOD data.queue
5306 @c EN
5307 Returns a list whose content is the items in the queue in order.
5308 Unlike @code{dequeue-all!}, the content of @var{queue} remains intact.
5309
5310 In Gauche, @code{queue->list} copies the content of the queue to a
5311 freshly allocated list, while @code{dequeue-all!} doesn't copy but
5312 directly returns the queue's internal list. There are some Scheme
5313 systems that has @code{queue->list} but doesn't guarantee the content
5314 is copied, so if you're planning to share the code among these
5315 implementations, it's better not to rely on the fact that
5316 @code{queue->list} copies the content.
5317 @c JP
5318 キュー@var{queue}の内容をリストにして返します。
5319 @code{dequeue-all!}と異なり、キューそのものの内容は変化しません。
5320
5321 Gaucheでは@code{queue->list}は新しいリストをアロケートしてキューの
5322 内容をコピーします (@code{dequeue-all!}はコピーをせずにキューの内部の
5323 リストをそのまま返します)。組込みで@code{queue->list}を持っているScheme
5324 実装がいくつかありますが、その中には@code{queue->list}がキューの
5325 内容をコピーすることを保証していないものがあるので、それらの処理系と
5326 共有するコードでは@code{queue->list}がリストをコピーすることを
5327 あてにしない方が良いでしょう。
5328 @c COMMON
5329 @end defun
5330
5331 @defun queue-internal-list queue
5332 @c MOD data.queue
5333 @c EN
5334 Like @code{queue->list}, returns a list whose content is the items
5335 in the queue in order, but the returned list @emph{may} share the
5336 internal storage of @var{queue}. The returned list can be modified
5337 by subsequent operations of @var{queue}, and any modification on the
5338 list can make @var{queue} inconsistent.
5339
5340 Because of this danger, we don't allow @code{<mtqueue>} to be
5341 passed to this procedure; it would signal an error if you do so.
5342
5343 If you just want to extract the accumulated result in @var{queue} without
5344 copying, consider @code{dequeue-all!}, which is safe because it atomically
5345 resets the queue. Use this procedure only when you absolutely need
5346 to access the contents of the queue without taking them out.
5347 @c JP
5348 @code{queue->list}と同じように、@var{queue}の内容をリストとして返しますが、
5349 そのリストは@var{queue}の内部構造と共有されているかもしれません。
5350 つまり、返されたリストは続く@var{queue}への操作によって変更される可能性があり、
5351 また返されたリストを変更すると@var{queue}の一貫性は失われるでしょう。
5352
5353 この危険性のため、@code{<mtqueue>}をこの手続きに渡すことは禁じられています。
5354 もしそうしたらエラーとなります。
5355
5356 @var{queue}に蓄積されたデータをコピーせずに取り出したいというだけなら、
5357 @code{dequeue-all!}を使ってください。それは取り出すのとキューを空にする
5358 操作をアトミックに行うので安全です。この手続きは、キューの中身を取り出すこと無く
5359 内部にアクセスしたいという場合にだけ使って下さい。
5360 @c COMMON
5361 @end defun
5362
5363 @defun find-in-queue pred queue
5364 @c MOD data.queue
5365 @c EN
5366 Returns the first item in @var{queue} that satisfies a
5367 predicate @var{pred}. The order of arguments follows
5368 @code{find} (@pxref{Other list procedures}).
5369 @c JP
5370 キュー内の要素のうち述語@var{pred}を満たす最初の要素を返します。
5371 引数の順序は@code{find}に揃えました (@ref{Other list procedures}参照)。
5372 @c COMMON
5373 @end defun
5374
5375 @defun any-in-queue pred queue
5376 @c MOD data.queue
5377 @c EN
5378 Like @code{any} in SRFI-1, apply @var{pred} on each item
5379 in @var{queue} until it evaluates true, and returns that
5380 true value (doesn't necessarily be @code{#t}). If no
5381 items in the queue satisfies @var{pred}, @code{#f} is returned.
5382 @c JP
5383 SRFI-1の@code{any}のように、@var{queue}中の各要素に
5384 順に@var{pred}を適用し、それが真の値 (@code{#t}である必要はありません) に
5385 評価されたらその値を返します。@var{pred}を満たす要素が無ければ@code{#f}が
5386 返ります。
5387 @c COMMON
5388 @end defun
5389
5390 @defun every-in-queue pred queue
5391 @c MOD data.queue
5392 @c EN
5393 Like @code{every} in SRFI-1, apply @var{pred} on each item
5394 in @var{queue}. If @var{pred} returns @code{#f}, stops
5395 iteration and returns @code{#f} immediately.
5396 Otherwise, returns the result of the application of
5397 @var{pred} on the last item of the queue. If the queue
5398 is empty, @code{#t} is returned.
5399 @c JP
5400 SRFI-1の@code{every}のように、@var{queue}中の各要素に
5401 順に@var{pred}を適用し、それが@code{#f}を返したらすぐ@code{#f}を返します。
5402 @var{pred}に対し@code{#f}を返す要素が無ければ、最後の要素に@var{pred}を
5403 適用した結果が返ります。キューが空なら@code{#f}が返ります。
5404 @c COMMON
5405 @end defun
5406
5407 @defun remove-from-queue! pred queue
5408 @c MOD data.queue
5409 @c EN
5410 Removes all items in the queue that satisfies @var{pred}.
5411 Returns @code{#t} if any item is removed. Otherwise returns @code{#f}.
5412 The order of arguments follows
5413 @code{remove} in @code{scheme.list}
5414 (@pxref{R7RS lists}).
5415 @c JP
5416 キューから、述語@var{pred}を満たす要素を全て取り除きます。
5417 要素が削除された場合は@code{#t}が、そうでなければ@code{#f}が返されます。
5418 引数の順序は@code{scheme.list}
5419 の@code{remove}に揃えました (@ref{R7RS lists}参照)。
5420 @c COMMON
5421 @end defun
5422
5423 @c EN
5424 Note on portability:
5425 Scheme48 has @code{delete-from-queue!}, which takes object to remove
5426 rather than predicate, and also takes arguments in reversed order
5427 (i.e. queue comes first). Avoid conflicting with that I intentionally
5428 left out @code{delete-from-queue!}; it's easy to write one in either
5429 Scheme48 compatible way or consistent to SRFI-1 argument order.
5430 @c JP
5431 移植性に関する註:Scheme48には、述語ではなく削除するオブジェクトそのものを取る
5432 @code{delete-from-queue!}がありますが、引数の順序が逆(キューが先)になっています。
5433 まぎらわしい衝突を避けるため、敢えて@code{delete-from-queue!}は
5434 提供しませんでした。@code{remove-from-queue!}を使えば、Scheme48互換の方法でも、
5435 あるいはSRFI-1と一貫性のある方法でも@code{delete-from-queue!}を簡単に書けるでしょう。
5436 @c COMMON
5437
5438 @defun enqueue/wait! mtqueue obj :optional timeout timeout-val close
5439 @defunx queue-push/wait! mtqueue obj :optional timeout timeout-val close
5440 @defunx dequeue/wait! mtqueue :optional timeout timeout-val close
5441 @defunx queue-pop/wait! mtqueue :optional timeout timeout-val close
5442 @c MOD data.queue
5443 @c EN
5444 These synchronizing variants allows an mtqueue to be used
5445 as a ``channel'', which communicates producer thread(s) and
5446 consumer thread(s).
5447
5448 The caller thread would block if the mtqueue has reached
5449 its maximum length (for @code{enqueue/wait!} and @code{queue-push/wait!}),
5450 or the mtqueue is empty (for @code{dequeue/wait!} and
5451 @code{queue-pop/wait!}). The blocked caller thread is unblocked
5452 either when the blocking condition is resolved, or the timeout
5453 condition is met.
5454
5455 The optional @var{timeout} argument specifies the timeout condition.
5456 If it is @code{#f}, those procedures wait indefinitely.
5457 If it is a real number, they wait at least the given number of
5458 seconds. If it is a @code{<time>} object (@pxref{Time}),
5459 they wait until the absolute point of time the argument specifies.
5460
5461 In case the call is blocked then timed out, the value of
5462 @var{timeout-val} is returned, which defaults to @code{#f}.
5463
5464 When @code{enqueue/wait!} and @code{queue-push/wait!} succeeds
5465 without hitting timeout, they return @code{#t}.
5466 @c JP
5467 これらの同期的手続きで、@var{mtqueue}を、生産者スレッドと消費者スレッドの間に立つ
5468 「チャネル」として使うことができます。
5469
5470 @code{enqueue/wait!}と@code{queue-push/wait!}は、
5471 キューの要素数が@var{max-length}を越える場合に、キューに空きができるまで、
5472 @code{dequeue/wait!}と@code{queue-pop/wait!}は、
5473 キューが空の場合に、キューに要素が追加されるまで、
5474 呼び出しスレッドをブロックします。
5475
5476 @var{timeout}引数で、ブロックされたスレッドのタイムアウトを指定することができます。
5477 @code{#f}は指定しなかった場合と同じで、キューの状態が変化するまで
5478 無期限に待ちます。実数が渡された場合はそれが秒数と解釈され、最低限
5479 その時間経過するまでは待ちます。渡されたのが@code{<time>}オブジェクト
5480 (@ref{Time}参照)である場合は、そのオブジェクトが指定する絶対時刻を
5481 経過するまで待ちます。
5482
5483 タイムアウトによりブロックが解かれた場合は、@var{timeout-val}で
5484 指定した値が返されます。@var{timeout-val}の省略時値は@code{#f}です。
5485
5486 @code{enqueue/wait!}と@code{queue-push/wait!}は、
5487 タイムアウトせずに操作が成功した場合は@code{#t}を返します。
5488 @c COMMON
5489
5490 @c EN
5491 If @var{mtqueue} is already closed, @code{enqueue/wait!} and
5492 @code{queue-push/wait!} raise an error, without modifying the queue.
5493 The check and queue insertion is done atomically, to eliminate
5494 the possibility that other thread tries to enqueue between the
5495 check and insetion. You can use @code{dequeue/wait!} and
5496 @code{queue-pop/wait!} on a closed mtqueue.
5497 @c JP
5498 もし@var{mtqueue}が既にクローズされていたら、@code{enqueue/wait!} and
5499 @code{queue-push/wait!}はキューを変更せずにエラーを投げます。
5500 フラグのチェックとキューへの挿入はアトミックに行われるので、
5501 チェックと挿入の間に他のスレッドがenqueueしてしまうことはありません。
5502 @code{dequeue/wait!}と@code{queue-push/wait!}はクローズ済みのmtqueueに
5503 対しても使えます。
5504 @c COMMON
5505
5506 @c EN
5507 The last optinoal argument, @code{close}, closes the queue if it is given
5508 and true. The close operation is done atomically, and if you're calling
5509 @code{enqueue/wait!} or @code{queue-push/wait!}, @var{obj} is guaranteed
5510 to be the last item put in the queue. It effectively ``shut down''
5511 the channel.
5512 @c JP
5513 最後の省略可能引数@code{close}は、もし真の値が与えられれば、キューをクローズします。
5514 クローズはアトミックに行われるので、
5515 @code{enqueue/wait!}や@code{queue-push/wait!}を呼び出したのであれば、
5516 @var{obj}が最後にキューに追加されるデータであることが保証されます。
5517 これはチャネルの「シャットダウン」操作と考えることができます。
5518 @c COMMON
5519 @end defun
5520
5521 @c ----------------------------------------------------------------------
5522 @node Random data generators, Range, Queue, Library modules - Utilities
5523 @section @code{data.random} - Random data generators
5524 @c NODE ランダムデータの生成, @code{data.random} - ランダムデータの生成
5525
5526 @deftp {Module} data.random
5527 @mdindex data.random
5528 @c EN
5529 This module defines a set of generators and generator makers
5530 that yield random data of specific type and distribution.
5531 @c JP
5532 このモジュールは、特定のデータ型や、特定の値の分布を持つランダムなデータを
5533 生成するジェネレータ、およびそういったジェネレータを作り出すジェネレータ構築器を
5534 提供します。
5535 @c COMMON
5536
5537 @c EN
5538 A part of the functionality of this module is turned into
5539 SRFI-194, but it gives different names/API for the consistency of other SRFIs
5540 (@pxref{Random data generators (SRFI)}).
5541 @c JP
5542 このモジュールの一部の機能はSRFI-194になりましたが、
5543 同SRFIでは他のSRFIとの一貫性から異なる名前/APIを採用しています
5544 (@ref{Random data generators (SRFI)}参照)。
5545 @c COMMON
5546 @end deftp
5547
5548 @c EN
5549 A naming convention: Procedures that takes parameters and returns
5550 a generator is suffixed by @code{$} (e.g. @code{integer$}).
5551 Procedures that are generators themselves are not (e.g. @code{fixnums}).
5552 Procedures that are combinators, that is, the ones that take
5553 one or more generators and returns a generator, generally ends
5554 with a preposition (e.g. @code{list-of}).
5555 @c JP
5556 名前付けの規則:パラメータを受け取り、それにそったジェネレータを返す
5557 手続きにはサフィックス@code{$}がついています (例: @code{integer$})。
5558 それ自体がジェネレータである手続きにはサフィックスがつきません (例: @code{fixnums})。
5559 コンビネータ、つまり複数のジェネレータを取ってジェネレータを返す手続きの名前は、
5560 通常前置詞で終わります (例: @code{list-of})。
5561 @c COMMON
5562
5563 @c EN
5564 @subheading Random source
5565 @c JP
5566 @subheading 乱数源
5567 @c COMMON
5568
5569 @deffn {Parameter} random-data-random-source
5570 @c MOD data.random
5571 @c EN
5572 Its value must be a SRFI-27 random source (@pxref{Sources of random bits}).
5573 The initial value is SRFI-27's @code{default-random-source}.
5574
5575 When generators are created with the utilities of this module, it captures
5576 the dynamic value of this parameter, from which the random values are
5577 generated. Changing the parameter value after generators are created
5578 won't affect their behavior.
5579 @c JP
5580 このパラメータの値はSRFI-27の乱数発生源でなければなりません
5581 (@ref{Sources of random bits}参照)。初期値はSRFI-27の
5582 @code{default-random-source}です。
5583
5584 このモジュールのユーティリティでジェネレータを作った場合、その作成時の
5585 パラメータの動的な値が捕獲され、ジェネレータはそれを使って乱数を生成します。
5586 ジェネレータの作成後にこのパラメータの値を変えてもジェネレータの動作には影響しません。
5587 @c COMMON
5588 @end deffn
5589
5590 @c EN
5591 Note: Up to 0.9.13, generators created with this module refers to the
5592 dynamic value of the current random source every time it generates
5593 a random value, so that prebuilt network of random values can be affected
5594 by modifying the current random source. However it incurs overhead for
5595 each random number generation, and generally it is cheaper to reconstruct
5596 a new generators with the different random source.
5597 The current behavior is consistent with SRFI-194.
5598
5599 The following two procedures are to swap current random source. They
5600 are still supported but no longer effective.
5601 @c JP
5602 註: 0.9.13まで、このモジュールで作られるジェネレータは乱数生成の度に現在の乱数源を
5603 参照していました。これにより、一度構築した乱数生成のネットワークのふるまいを、
5604 現在の乱数源をいじることで変えられますが、乱数発生の度に若干のオーバヘッドも生じます。
5605 一般に、異なる乱数源を使いたければそれを現在の乱数源として新にジェネレータを
5606 作成した方が安価でしょう。それに、現在のふるまいはSRFI-194と一貫性があります。
5607
5608 以下のふたつの手続きは現在の乱数源を置き換えるために提供されていましたが、
5609 今では効果がありません。
5610 @c COMMON
5611
5612 @example
5613 random-data-seed with-random-data-seed
5614 @end example
5615
5616
5617 @c EN
5618 @subheading Generators of primitive data types
5619 @c JP
5620 @subheading プリミティブデータ型のジェネレータ
5621 @c COMMON
5622
5623 @c EN
5624 Those generators generate uniformly distributed data.
5625 @c JP
5626 以下のジェネレータは特に断りが無い限り、一様分布するデータを生成します。
5627 @c COMMON
5628
5629 @c EN
5630 In the following examples, we use @code{generator->list} to show
5631 some concrete data from the generators. It is provided
5632 in @code{gauche.generator} module. @xref{Generators}, for more
5633 utilities work on generators.
5634 @c JP
5635 例の中では、生成された値を具体的に示すために
5636 @code{gauche.generator}モジュールの@code{generator->list}を
5637 使っています。ジェネレータを扱うユーティリティについては
5638 @ref{Generators}を参照してください。
5639 @c COMMON
5640
5641 @defun integers$ size :optional (start 0)
5642 @defunx integers-between$ lower-bound upper-bound
5643 @c MOD data.random
5644 @c EN
5645 Create exact integer generators. The first one, @code{integers$}, creates
5646 a generator that generates integers from start (inclusive) below
5647 start+size (exclusive) uniformly. The second one, @code{integers-between$},
5648 creates a generator that generates integers between
5649 @var{lower-bound} and @var{upper-bound} (both inclusive) uniformly.
5650 @c JP
5651 正確な整数のジェネレータを作成します。
5652 @code{integer$}が返すジェネレータは、
5653 @var{start} 以上 @var{start} + @var{size} 未満の整数を一様に発生させます。
5654 @code{integers-between$}はが返すジェネレータは、@var{lower-bound}以上、
5655 @var{upper-bound}以下の整数を一様に発生させます。
5656 @c COMMON
5657
5658 @example
5659 @c EN
5660 ;; A dice roller
5661 @c JP
5662 ;; サイコロ
5663 @c COMMON
5664 (define dice (integers$ 6 1))
5665
5666 @c EN
5667 ;; Roll the dice 10 times
5668 @c JP
5669 ;; サイコロを10回振ってみる
5670 @c COMMON
5671 (generator->list dice 10)
5672 @result{} (6 6 2 4 2 5 5 1 2 2)
5673 @end example
5674 @end defun
5675
5676 @defun fixnums$
5677 @defunx int8s$
5678 @defunx uint8s$
5679 @defunx int16s$
5680 @defunx uint16s$
5681 @defunx int32s$
5682 @defunx uint32s$
5683 @defunx int64s$
5684 @defunx uint64s$
5685 @c MOD data.random
5686 @c EN
5687 Creates and returns uniform integer generators.
5688 Each generates integers in fixnum range, and
5689 8/16/32/64bit signed and unsigned integers, respectively.
5690 @c JP
5691 固定範囲の一様整数ジェネレータを作って返します。
5692 作られたジェネレータはそれぞれ、
5693 fixnumおよび8/16/32/64ビットの符号つき/符号無し整数を生成します。
5694 @c COMMON
5695
5696 @example
5697 (generator->list (int8s$) 10)
5698 @result{} (20 -101 50 -99 -111 -28 -19 -61 39 110)
5699 @end example
5700 @end defun
5701
5702 @defun booleans$
5703 @c MOD data.random
5704 @c EN
5705 Creates and returns a generator of
5706 boolean values (@code{#f} and @code{#t}) in equal probability.
5707 @c JP
5708 真偽値(@code{#f}と@code{#t})を等確率で生成するジェネレータを作って返します。
5709 @c COMMON
5710
5711 @example
5712 (generator->list (booleans$) 10)
5713 @result{} (#f #f #t #f #f #t #f #f #f #f)
5714 @end example
5715 @end defun
5716
5717 @defun fixnums
5718 @defunx int8s
5719 @defunx uint8s
5720 @defunx int16s
5721 @defunx uint16s
5722 @defunx int32s
5723 @defunx uint32s
5724 @defunx int64s
5725 @defunx uint64s
5726 @defunx booleans
5727 @c MOD data.random
5728 @c EN
5729 These are preconstructed generators by @code{fixnum$} etc. Provided
5730 for the convenience, but note that the random source they use is
5731 fixed to @code{default-random-source}.
5732 @c JP
5733 これらは@code{fixnum$}などを使ってあらかじめ作られたジェネレータです。
5734 簡便のために提供されています。ただ、乱数発生源は@code{default-random-source}
5735 に固定であることに注意してください。
5736 @c COMMON
5737 @end defun
5738
5739 @defun chars$ :optional char-set
5740 @c MOD data.random
5741 @c EN
5742 Creates a generator that generates characters in @var{char-set} uniformly.
5743 The default @var{char-set} is @code{#[A-Za-z0-9]}.
5744 @c JP
5745 @var{char-set}にある文字を一様分布で生成するジェネレータを作ります。
5746 @var{char-set}が省略された場合は@code{#[A-Za-z0-9]}が使われます。
5747 @c COMMON
5748
5749 @example
5750 (define alphanumeric-chars (chars$))
5751
5752 (generator->list alphanumeric-chars 10)
5753 @result{} (#\f #\m #\3 #\S #\z #\m #\x #\S #\l #\y)
5754 @end example
5755 @end defun
5756
5757 @defun reals$ :optional size start
5758 @defunx reals-between$ lower-bound upper-bound
5759 @c MOD data.random
5760 @c EN
5761 Create a generator that generates real numbers uniformly with given range.
5762 The first procedure, @code{reals$}, returns reals between start
5763 and start+size, inclusively. The default of size is 1.0 and start is 0.0.
5764 The second procedure, @code{reals-between$}, returns reals between
5765 lower-bound and upper-bound, inclusively.
5766 @c JP
5767 与えられた範囲の実数値を一様に生成するジェネレータを返します。
5768 @code{reals$}の返すジェネレータは、
5769 @var{start} 以上 @var{start} + @var{size} 以下の実数値を生成します。
5770 @var{size}のデフォルト値は@code{1.0}、@var{start}のデフォルト値は@code{0.0}です。
5771 @code{reals-between$}の返すジェネレータは、
5772 @var{lower-bound}以上@var{upper-bound}以下の実数値を生成します。
5773 @c COMMON
5774
5775 @example
5776 (define uniform-100 (reals$ 100))
5777
5778 (generator->list uniform-100 10)
5779 @result{} (81.67965004942268 81.84927577572596 53.02443813660833)
5780 @end example
5781
5782 @c EN
5783 Note that a generator from @code{reals$} can generate the upper-bound
5784 value start+size, as opposed to @code{integers$}. If you need to exclude
5785 the bound value, just discard the bound value; @code{gfilter} may come
5786 handy.
5787 @c JP
5788 @code{reals$}の返すジェネレータは、@code{integer$}と違って
5789 上限の値を生成し得ることに注意してください。限界値を除外したい場合は、
5790 @code{gfilter}等を使ってその値を棄却します。
5791 @c COMMON
5792
5793 @example
5794 (define generate-from-0-below-1
5795 (gfilter (^r (not (= r 1.0))) (reals$ 1.0 0.0)))
5796 @end example
5797
5798 @c EN
5799 Note also that floating point numbers are not uniformly distributed
5800 within the given real number range. When you uniformly sample
5801 from a certain real number range, the returned flonums would very likely
5802 have the same or closer exponent of the bounds of the range.
5803 If that's what you want, it's ok. If you want a sample uniformly from
5804 a valid flonum values, see @code{finite-flonums$} below.
5805 @c JP
5806 また、浮動小数点数は与えられた実数範囲の中で一様に分布していないことに注意してください。
5807 ある実数範囲から一様にサンプリングした場合、得られるほとんどの実数の指数部は、
5808 範囲の上下限の指数と同じかそれに近いものになります。それが必要なものでしたら良いのですが、
5809 有効な浮動小数点数から一様にサンプリングしたい場合は、下の@code{finite-flonums$}
5810 を見てください。
5811 @c COMMON
5812 @end defun
5813
5814 @defun finite-flonums$
5815 @c EN
5816 Returns a flonum generator that samples uniformly from all possible
5817 finite flonums. It is not the same as uniformly sampling real numbers,
5818 since floating-point numbers are not distributed evenly.
5819 This is more useful if you want feed random flonums for testing,
5820 than uniformly distributed real numbers, for the latter has
5821 rather skewed distribution of exponents.
5822 @c JP
5823 可能な全ての有限の浮動小数点数から一様にサンプリングする浮動小数点数ジェネレータ
5824 を返します。これは実数を一様にサンプリングするのとは異なります。
5825 浮動小数点数は実数空間で一様に分布していないからです。
5826 これは、テスト用途でランダムな浮動小数点数を使いたい場合に便利です。
5827 実数範囲で一様サンプリングすると、得られる数値の指数部は非常に偏ったものになるからです。
5828 @c COMMON
5829 @end defun
5830
5831 @defun complexes-rectangular$ re-lb re-ub im-lb im-ub
5832 @defunx complexes-polar$ [origin] mag-lb mag-ub :optional ang-lb ang-ub
5833 @c EN
5834 Returns a fresh generator of complex numbers uniformly.
5835 All the @var{*-lb} and @var{*-ub} arguments must be real numbers, and each
5836 @var{*-ub} argument must be greater than or equal to the corresponding
5837 @var{*-lb} argument. The @var{origin} argument is a complex number.
5838
5839 Generators returned by
5840 @code{complexes-rectangular$} sample a rectangular area
5841 where its real value is between @var{re-lb} and @var{re-ub} inclusive,
5842 and its imaginary value is between @var{im-lb} and @var{im-ub} inclusive.
5843
5844 Generators returned by
5845 @code{complexes-rectangular$} samples an annulus whose origin is
5846 @var{origin}, whose magnitude is between @var{mag-lb} and @var{mag-ub}
5847 inclusive, and whose angle is between @var{ang-lb} and @var{ang-ub}
5848 radians inclusive. If @var{origin}, @var{ang-lb}, and/or @var{ang-ub}
5849 are omitted, they're defaulted to 0+0i, 0, and 2π.
5850 @c JP
5851 複素数を一様に生成する新たなジェネレータを作って返します。
5852 全ての@var{*-lb}および@var{*-ub}引数は実数でなければならず、@var{*-ub}は
5853 @var{*-lb}以上でなければなりません。@var{origin}は複素数です。
5854
5855 @code{complexes-rectangular$}が返すジェネレータは、
5856 実部が@var{re-lb}と@var{re-ub}の間にあり、
5857 虚部が@var{im-lb}と@var{im-ub}の間にある矩形領域中の複素数を生成します。
5858 境界は含まれます。
5859
5860 @code{complexes-rectangular$}が返すジェネレータは、
5861 @var{origin}を中心とし、半径が@var{mag-lb}と@var{mag-ub}、
5862 切り取り角が@var{ang-lb}と@var{ang-ub}の間にある部分環状領域の中にある
5863 複素数を生成します。境界は含まれます。
5864 @var{origin}、@var{ang-lb}、@var{ang-ub}が
5865 省略された場合は、それぞれ0+0i, 0, 2πが使われます。
5866 @c COMMON
5867 @end defun
5868
5869
5870 @defun samples$ collection
5871 @c MOD data.random
5872 @c EN
5873 Creates a generator that returns randomly chosen item in @var{collection}
5874 at a time.
5875
5876 Do not confuse this with @code{samples-from} below, which is to combine
5877 multiple generators for sampling.
5878 @c JP
5879 コレクション@var{collection}から毎回ランダムにひとつ要素を選んで返すジェネレータを
5880 作成します。
5881
5882 下で説明する@code{samples-from}と混同しないようにしてください。@code{samples-from}
5883 は複数のジェネレータを組み合わせてサンプリングするものです。
5884 @c COMMON
5885
5886 @example
5887 (define coin-toss (samples$ '(head tail)))
5888
5889 (generator->list coin-toss 5)
5890 @result{} (head tail tail head tail)
5891 @end example
5892 @end defun
5893
5894 @defun regular-string$ regexp
5895 @c MOD data.random
5896 @c EN
5897 Creates an infinite
5898 generator that generates random strings each of which matches the given
5899 @var{regexp}. The @var{regexp} shouldn't include conditional patterns
5900 and lookahead/behind assertions.
5901
5902 Note: It is hard to define how the distribution of the generated strings
5903 should look like. For now, we build an NFA from regexp and put the
5904 same probability when there are multiple choices, but that may not be
5905 really useful for typical use cases (e.g. generate test data).
5906 Please assume the current implementation strategy a provisional one.
5907 @c JP
5908 与えられた@var{regexp}にマッチするランダムな文字列を生成し続けるジェネレータを
5909 作って返します。@var{regexp}には条件付きパターン、lookahead/lookbehindアサーションを
5910 含めないでください。
5911
5912 註: 生成される文字列の分布をどうすべきかというのは難しい問題です。
5913 現在の実装は単純に、内部で正規表現からNFAを生成し、複数の選択肢がある場合は
5914 等しい重みでランダムに選択していますが、それが目的(例えばテストデータの生成)に
5915 ふさわしいかどうかはまだわかりません。
5916 現在の実装は暫定的なものと考えてください。
5917 @c COMMON
5918 @end defun
5919
5920 @c EN
5921 @subheading Nonuniform distributions
5922 @c JP
5923 @subheading 非一様分布
5924 @c COMMON
5925
5926 @defun reals-normal$ :optional mean deviation
5927 @c MOD data.random
5928 @c EN
5929 Creates a generator that yields real numbers from normal distribution
5930 with @var{mean} and @var{deviation}. The default of @var{mean} is 0.0
5931 and @var{deviation} is 1.0.
5932 @c JP
5933 期待値@var{mean}、標準偏差@var{deviation}の正規分布に従って実数値を生成する
5934 ジェネレータを作ります。省略時は@var{mean}が0.0、@var{deviation}が
5935 1.0になります。
5936 @c COMMON
5937 @end defun
5938
5939 @defun reals-exponential$ mean
5940 @c MOD data.random
5941 @c EN
5942 Creates a generator that yields real numbers from exponential distribution
5943 with @var{mean}.
5944 @c JP
5945 期待値@var{mean}の指数分布に従って実数値を生成するジェネレータを作ります。
5946 @c COMMON
5947
5948 @c EN
5949 NB: The probability density function p(x) is
5950 @code{(* (/ mean) (exp (- (/ x mean))))}. Some definition of exponential
5951 distribution uses a decay parameter λ such that p(x) is
5952 @code{(* λ (exp (- (* x λ))))}. That is, @i{λ} = 1/@i{mean}.
5953 @c JP
5954 註: 確率密度関数 p(x) は@code{(* (/ mean) (exp (- (/ x mean))))} です。
5955 指数分布の定義では、期待値のかわりに、減衰パラメータ λ を使って確率密度関数を
5956 @code{(* λ (exp (- (* x λ))))}とする流儀もあります。
5957 この場合、@i{λ} = 1/@i{mean}です。
5958 @c COMMON
5959 @end defun
5960
5961 @defun reals-power-law$ xmin power
5962 @c MOD data.random
5963 @c EN
5964 Creates a generator that yields finite positive real numbers greater
5965 than or equal
5966 to @var{xmin}, and follows the power-law probability density function
5967 p(x) = (α-1)/xmin (x/xmin)^@{-α@}, where x >= xmin and α > 1.
5968 The @var{power} argument specifies α.
5969
5970 The @var{xmin} argument must be a positive real numebr, and @var{power}
5971 must be a real number greater than 1.
5972 @c JP
5973 冪乗則に従った確率で有限の正実数を生成するジェネレータを作って返します。
5974 確率密度関数p(x)は(α-1)/xmin (x/xmin)^@{-α@}と表せます。ここでx ≧ xmin、α > 1 です。
5975 @var{power}引数がαを指定します。
5976
5977 @var{xmin}は正の実数、@var{power}は1より大きい実数でなければなりません。
5978 @c COMMON
5979 @end defun
5980
5981 @defun integers-geometric$ p
5982 @c MOD data.random
5983 @c EN
5984 Creates a generator that yields integers from geometric distribution
5985 with success probability @var{p} (0 <= p <= 1). The mean is @code{1/p} and
5986 variance is @code{(1-p)/p^2}.
5987 @c JP
5988 成功確率@var{p} (0 ≦ p ≦ 1) である幾何分布に従って
5989 非負整数値を生成するジェネレータを作ります。
5990 期待値は@code{1/p}、分散は@code{(1-p)/p^2}になります。
5991 @c COMMON
5992 @end defun
5993
5994 @defun integers-poisson$ L
5995 @c MOD data.random
5996 @c EN
5997 Creates a generator that yields integers from poisson distribution with
5998 mean @var{L}, variance @var{L}.
5999 @c JP
6000 期待値@var{L}のポアソン分布に従う非負整数値を生成するジェネレータを作ります。
6001 分散も@var{L}になります。
6002 @c COMMON
6003 @end defun
6004
6005 @c EN
6006 @subheading Aggregate data generators
6007 @c JP
6008 @subheading 複合データ型のジェネレータ
6009 @c COMMON
6010
6011 @defun samples-from generators
6012 @c MOD data.random
6013 @c EN
6014 Takes a finite sequence of generators
6015 (sequence in the sense of @code{gauche.sequence}),
6016 and returns a generator. Every time the resulting generator is called,
6017 it picks one of the input generators in equal probability, then
6018 calls it to get a value.
6019 @c JP
6020 ジェネレータの有限シーケンス (ここでは@code{gauche.sequence}がシーケンスとして
6021 扱うもの) を取り、新たなジェネレータを返します。
6022 返されたジェネレータは、値を必要とする度に、
6023 入力となるジェネレータのどれかを等確率で選んで、その入力ジェネレータから値を取ります。
6024 @c COMMON
6025
6026 @c EN
6027 The resulting generator is exhausted when all the input generators are exhausted.
6028 @c JP
6029 返されるジェネレータは、全ての入力ジェネレータが終端に達した時に終わりとなります。
6030 @c COMMON
6031
6032 @example
6033 (define g (samples-from (list uint8s (chars$ #[a-z]))))
6034
6035 (generator->list g 10)
6036 @result{} (207 107 #\m #\f 199 #\o #\b 57 #\j #\e)
6037 @end example
6038
6039 @c EN
6040 NB: To create a generator that samples from a fixed collection of items,
6041 use @code{samples$} described above.
6042 @c JP
6043 註: 固定した要素の集まりからサンプルするジェネレータを作るには、
6044 上の方で説明した@code{samples$}を使ってください。
6045 @c COMMON
6046 @end defun
6047
6048 @defun weighted-samples-from weight&gens
6049 @c MOD data.random
6050 @c EN
6051 The argument is a list of pairs of a nonnegative real number and a generator.
6052 The real number determines the weight, or the relative probability
6053 that the generator is chosen. The sum of weight doesn't need to
6054 be 1.0.
6055 @c JP
6056 引数は、非負の実数値とジェネレータのペアのリストです。
6057 実数値が「重み」、すなわちペアとなっているジェネレータが選ばれる相対確率を決定します。
6058 重みの総和が1.0である必要はありません。
6059 @c COMMON
6060
6061 @c EN
6062 The following example chooses the uint8 generator four times frequently
6063 than the character generator.
6064 @c JP
6065 次の例では、@code{uint8}ジェネレータは文字ジェネレータより4倍頻繁に使われます。
6066 @c COMMON
6067
6068 @example
6069 (define g (weighted-samples-from
6070 `((4.0 . ,uint8s)
6071 (1.0 . ,(chars$)))))
6072
6073 (generator->list g 10)
6074 @result{} (195 97 #\j #\W #\5 72 49 143 19 164)
6075 @end example
6076 @end defun
6077
6078 @defun pairs-of car-gen cdr-gen
6079 @c MOD data.random
6080 @c EN
6081 Returns a generator that yields pairs,
6082 whose car is generated from @var{car-gen}
6083 and whose cdr is generated from @var{cdr-gen}.
6084 @c JP
6085 ペアを生成するジェネレータを作ります。
6086 各ペアのcarはジェネレータ@var{car-gen}、
6087 cdrはジェネレータ@var{cdr-gen}によって生成されます。
6088 @c COMMON
6089
6090 @example
6091 (define g (pairs-of int8s booleans))
6092
6093 (generator->list g 10)
6094 @result{} ((113 . #t) (101 . #f) (12 . #t) (68 . #f) (-55 . #f))
6095 @end example
6096 @end defun
6097
6098 @defun tuples-of gen @dots{}
6099 @c MOD data.random
6100 @c EN
6101 Returns a generator that yields lists,
6102 whose i-th element is generated from the i-th argument.
6103 @c JP
6104 リストを生成するジェネレータを作ります。
6105 各リストのi番目の要素はi番目の引数のジェネレータによって生成されます。
6106 @c COMMON
6107
6108 @example
6109 (define g (tuples-of int8s booleans (char$)))
6110
6111 (generator->list g 3)
6112 @result{} ((-43 #f #\8) (53 #f #\1) (-114 #f #\i))
6113 @end example
6114 @end defun
6115
6116 @defun permutations-of seq
6117 @c MOD data.random
6118 @c EN
6119 Returns a generator that yields a random permutations of @var{seq}.
6120
6121 The type of @var{seq} should be a sequence with a builder
6122 (@pxref{Sequence framework}). The type of generated objects
6123 will be the same as @var{seq}.
6124 @c JP
6125 シーケンス@var{seq}の要素をランダムに並べ替えたシーケンスを生成する
6126 ジェネレータを作ります。
6127
6128 @var{seq}の型は、ビルダーを持つシーケンスである必要があります
6129 (@ref{Sequence framework}参照)。生成されるオブジェクトは
6130 @var{seq}と同じ型になります。
6131 @c COMMON
6132
6133 @example
6134 (generator->list (permutations-of '(1 2 3)) 3)
6135 @result{} ((1 2 3) (2 3 1) (3 2 1))
6136
6137 (generator->list (permutations-of "abc") 3)
6138 @result{} ("cba" "cba" "cab")
6139 @end example
6140 @end defun
6141
6142 @defun combinations-of size seq
6143 @c MOD data.random
6144 @c EN
6145 Returns a generator that yields a sequence of @var{size} elements
6146 randomly picked from @var{seq}.
6147
6148 The type of @var{seq} should be a sequence with a builder
6149 (@pxref{Sequence framework}). The type of generated objects
6150 will be the same as @var{seq}.
6151 @c JP
6152 シーケンス@var{seq}からランダムに@var{size}個の要素を取り出して
6153 並べたシーケンスを生成するジェネレータを作ります。
6154
6155 @var{seq}の型は、ビルダーを持つシーケンスである必要があります
6156 (@ref{Sequence framework}参照)。生成されるオブジェクトは
6157 @var{seq}と同じ型になります。
6158 @c COMMON
6159
6160 @example
6161 (generator->list (combinations-of 2 '(a b c)) 5)
6162 @result{} ((a c) (a b) (a c) (b a) (a c))
6163
6164 (generator->list (combinations-of 2 '#(a b c)) 5)
6165 @result{} (#(a c) #(b c) #(c b) #(b a) #(b c))
6166 @end example
6167 @end defun
6168
6169 @c EN
6170 The following procedures takes optional @var{sizer} argument, which can
6171 be either a nonnegative integer or a generator of nonnegative integers.
6172 The value of the sizer determines the length of the result data.
6173 @c JP
6174 以下の手続きは、省略可能な@var{sizer}引数を取ります。
6175 @var{sizer}引数は非負整数か、非負整数を生成するジェネレータで、
6176 その値(もしくは生成された値)が、最終的に生成されるデータの長さを決定します。
6177 @c COMMON
6178
6179 @c EN
6180 Unlike most of Gauche procedures, @var{sizer} argument comes before
6181 the last argument when it is not omitted.
6182 We couldn't resist the temptation to
6183 write something like @code{(lists-of 3 booleans)}.
6184 @c JP
6185 Gaucheの他のほとんどの手続きと違って、@var{sizer}引数は省略されない時は
6186 最後の引数よりも前に来ます。これは統一性を損ないますが、
6187 @code{(lists-of 3 booleans)} のように書ける、という誘惑に勝てませんでした。
6188 @c COMMON
6189
6190 @c EN
6191 If @var{sizer} is omitted, the default value is taken from
6192 the parameter @code{default-sizer}. The default of @code{default-sizer}
6193 is @code{(integers-poisson$ 4)}.
6194 @c JP
6195 @var{sizer}引数が省略された場合、パラメータ@code{default-sizer}の値が
6196 使われます。@code{default-sizer}のデフォルトは
6197 @code{(integers-poisson$ 4)}で作られるジェネレータです。
6198 @c COMMON
6199
6200 @defun lists-of item-gen
6201 @defunx lists-of sizer item-gen
6202 @defunx vectors-of item-gen
6203 @defunx vectors-of sizer item-gen
6204 @defunx strings-of
6205 @defunx strings-of item-gen
6206 @defunx strings-of sizer item-gen
6207 @c MOD data.random
6208 @c EN
6209 Creates a generator that generates lists, vectors or strings of values from @var{item-gen}, respectively. The size of each datum is determined by
6210 @var{sizer}.
6211 @c JP
6212 それぞれ、リスト、ベクタ、文字列を生成するジェネレータを作ります。
6213 作られるデータの各要素はジェネレータ@var{item-gen}から取られます。
6214 各データの長さは@var{sizer}により決定されます。
6215 @c COMMON
6216
6217 @c EN
6218 You can also omit @var{item-gen} for @code{strings-of}. In that case,
6219 a generator created by @code{(chars$)} is used.
6220 @c JP
6221 @code{strings-of}の場合は@var{item-gen}も省略することができます。
6222 その場合は、@code{(chars$)}で作られるジェネレータが使われます。
6223 @c COMMON
6224
6225 @example
6226 (generator->list (lists-of 3 uint8s) 4)
6227 @result{} ((254 46 0) (77 158 46) (1 134 156) (74 5 110))
6228
6229 @c EN
6230 ;; using the default sizer
6231 @c JP
6232 ;; デフォルトのsizerを使う
6233 @c COMMON
6234 (generator->list (lists-of uint8s) 4)
6235 @result{} ((93 249) (131 97) (98 206 144 247 241) (126 156 31))
6236
6237 @c EN
6238 ;; using a generator for the sizer
6239 @c JP
6240 ;; sizerにジェネレータを使う
6241 @c COMMON
6242 (generator->list (strings-of (integers$ 8) (chars$)) 5)
6243 @result{} ("dTJYVhu" "F" "PXkC" "w" "")
6244 @end example
6245 @end defun
6246
6247 @defun sequences-of class item-gen
6248 @defunx sequences-of class sizer item-gen
6249 @c MOD data.random
6250 @c EN
6251 Creates a generator that yields sequences of class @var{class},
6252 whose items are generated by @var{item-gen}. The size of each
6253 sequence is determined by @var{sizer}, or the value of @code{default-sizer}
6254 if omitted; the sizer can be a nonnegative integer, or a generator
6255 that yields nonnegative integers.
6256
6257 The class @var{class} must be a subclass of @code{<sequence>} and
6258 implement the builder interface.
6259 @c JP
6260 クラス@var{class}のインスタンスであるシーケンスを生成するジェネレータを作ります。
6261 シーケンスの要素は@var{item-gen}により生成されます。
6262 各シーケンスの長さは@var{sizer}引数 (省略時は@code{default-sizer}の値)
6263 によって決められます。@var{sizer}は非負整数か、非負整数を生成するジェネレータです。
6264
6265 @var{class}は@code{<sequence>}のサブクラスであり、
6266 ビルダーインタフェースを実装していなければなりません。
6267 @c COMMON
6268
6269 @example
6270 (generator->list (sequences-of <u8vector> 4 uint8s) 3)
6271 @result{} (#u8(95 203 243 46) #u8(187 199 153 152) #u8(39 114 39 25))
6272 @end example
6273 @end defun
6274
6275
6276 @deffn {Parameter} default-sizer
6277 @c MOD data.random
6278 @c EN
6279 The sizer used by @code{lists-of}, @code{vectors-of} and @code{strings-of}
6280 when @var{sizer} argument is omitted.
6281
6282 The value must be either an nonnegative integer, or a generator
6283 of nonnegative integers. The default value is @code{(integers-poisson$ 4)}.
6284 @c JP
6285 @code{lists-of}、@code{vectors-of}、@code{strings-of}で
6286 @var{sizer}引数が省略された場合に使われるsizerです。
6287
6288 値は、非負整数か、非負整数を生成するジェネレータでなければなりません。
6289 デフォルトの値は@code{(integers-poisson$ 4)}です。
6290 @c COMMON
6291 @end deffn
6292
6293 @c ----------------------------------------------------------------------
6294 @node Range, Ring buffer, Random data generators, Library modules - Utilities
6295 @section @code{data.range} - Range
6296 @c NODE レンジ, @code{data.range} - レンジ
6297
6298 @deftp {Module} data.range
6299 @mdindex data.range
6300 @c EN
6301 A @emph{range} object is an immutable sequence with O(1) indexed access
6302 to the elements, and each element may be computed procedurally.
6303 For example, a range of intergers between 0 and N can be trivially
6304 realized as a range, where @var{i}-th element is simply computed by
6305 @code{identity}. It is a lot more space-efficient than actually generating
6306 a sequence containing every number.
6307
6308 It also allows certain operations efficient, such as taking subsequence
6309 or appending sequences.
6310
6311 A range object can be used with @code{:range} qualifier in the
6312 SRFI-42 eager comprehension (@pxref{Eager comprehensions}).
6313 @c JP
6314 レンジオブジェクトはO(1)で要素にアクセスでき、
6315 そして各要素が手続き的に計算されるような不変なシーケンスです。
6316 例えば、0からNまでの整数のレンジ、というのは、@var{i}番目の要素を計算する手続きが
6317 @code{identity}であるようなレンジとして簡単に実現できるでしょう。
6318 これは、全ての整数を持つシーケンスを作るよりずっと軽いです。
6319
6320 レンジはまた、一部分だけ取り出したレンジを作ったり、
6321 レンジ同士をつなげたりする操作を効率的に行えます。
6322
6323 レンジオブジェクトはSRFI-42 先行評価的内包表記の@code{:range} qualifierに
6324 渡すこともできます (@ref{Eager comprehensions}参照)。
6325 @c COMMON
6326
6327 @c EN
6328 A portable range object interface is defined in @code{srfi.196}.
6329 We implement the range object as a @code{<sequence>}, so that all
6330 sequence framework interface can be used on the ranges
6331 (@pxref{Sequence framework}). We also provide some additional
6332 procedures that are not in SRFI-196.
6333 @c JP
6334 ポータブルなレンジオブジェクトのインタフェースは@code{srfi.196}で
6335 規定されています。Gaucheではレンジオブジェクトを@code{<sequence>}として
6336 実装し、シーケンスプロトコルも使えるようにしています
6337 (@ref{Sequence framework}参照)。またこのモジュールでは@code{srfi.196}にない
6338 手続きも提供されます。
6339 @c COMMON
6340 @end deftp
6341
6342 @c EN
6343 @subheading Classes
6344 @c JP
6345 @subheading クラス
6346 @c COMMON
6347
6348 @deftp {Class} <range>
6349 @clindex range
6350 @c EN
6351 Range object class. Internally we use several subclasses
6352 according to the nature of the range, but externally all
6353 ranges can be treated as an instance of @code{<range>}.
6354 @c JP
6355 レンジオブジェクトのクラスです。内部的には、異なるレンジの性質に合わせて
6356 いくつかのサブクラスを使っていますが、外部的には全てのレンジを
6357 @code{<range>}クラスのインスタンスとして扱って構いません。
6358 @c COMMON
6359 @end deftp
6360
6361 @deftp {Class} <range-meta>
6362 @clindex range-meta
6363 @c EN
6364 The metaclass of @code{<range>} class.
6365 @c JP
6366 @code{<range>}クラスのメタクラスです。
6367 @c COMMON
6368 @end deftp
6369
6370 @c EN
6371 @subheading Constructors
6372 @c JP
6373 @subheading コンストラクタ
6374 @c COMMON
6375
6376 @defun range length indexer
6377 [SRFI-196]
6378 @c MOD data.range
6379 @c EN
6380 Creates and returns a range of length @var{length},
6381 whose @var{i}-th element (0 <= @code{i} < @var{length}))
6382 is determined by a procedure @var{indexer}, which takes @var{i}
6383 as the sole argument and returns the corresponding element.
6384 @c JP
6385 長さが@var{length}で、@var{i}番目の要素(0 <= @code{i} < @var{length}))
6386 が@code{(@var{indexer} @var{i})}で計算されるようなレンジを作って返します。
6387 @c COMMON
6388
6389 @c EN
6390 Note that @var{indexer} must run in O(1) time, and must be
6391 referentially transparent. The impelemntation may ``expand''
6392 the range, that is, computes the element values into a flat
6393 vector internally.
6394 @c JP
6395 手続き@var{indexer}はO(1)の時間オーダーで動作し、参照透過でなければなりません。
6396 実装によっては、内部で要素の値をフラットベクタにキャッシュすることもありえます。
6397 @c COMMON
6398
6399 @example
6400 (range->list (range 5 (^i (+ i 10))))
6401 @result{} (10 11 12 13 14)
6402 @end example
6403 @end defun
6404
6405 @defun numeric-range start end :optional step
6406 [SRFI-196]
6407 @c MOD data.range
6408 @c EN
6409 Creates and returns a range of numbers starting from @var{start} (inclusive)
6410 and ending below @var{end} (exclusive), increasing with @var{step}.
6411 The default value of @var{step} is 1.
6412 @c JP
6413 @var{start}から始まり、@var{step}ごとに増加し、@var{end}未満で終わる数値のレンジを
6414 作って返します。@var{step}が省略された場合は1が使われます。
6415 @c COMMON
6416
6417 @example
6418 (range->list (numeric-range 2 6))
6419 @result{} (2 3 4 5)
6420
6421 (range->list (numeric-range 0 5 2/3))
6422 @result{} (0 2/3 4/3 2 8/3 10/3 4 14/3)
6423 @end example
6424 @end defun
6425
6426 @defun iota-range length :optional start step
6427 [SRFI-196]
6428 @c MOD data.range
6429 @c EN
6430 Creates and returns a range of numbers. Total length of the range
6431 is @var{length}. The range starts from @var{start} (default 0),
6432 and increased with @var{step} (default 1).
6433 @c JP
6434 長さが@var{length}で、@var{start}から始まり@var{step}ごとに増加する
6435 数値のレンジを作って返します。@var{start}、@var{step}の省略時の値は
6436 それぞれ0と1です。
6437 @c COMMON
6438
6439 @example
6440 (range->list (iota-range 5))
6441 @result{} (0 1 2 3 4)
6442
6443 (range->list (iota-range 7 1 -1/7))
6444 @result{} (1 6/7 5/7 4/7 3/7 2/7 1/7)
6445 @end example
6446 @end defun
6447
6448 @defun vector-range vec :optional start end
6449 [SRFI-196+]
6450 @c MOD data.range
6451 @c EN
6452 Returns a range over the given vector @var{vec}.
6453 The vector is kept in the range, so you shouldn't mutate @var{vec}.
6454 See also @code{vector->range} below.
6455 @c JP
6456 ベクタ@var{vec}にアクセスするレンジを作って返します。
6457 ベクタはそのままレンジのデータ元として使われるので、
6458 この後で@var{vec}を変更してはなりません。
6459 下の@code{vector->range}も参照。
6460 @c COMMON
6461
6462 @c EN
6463 The optional @var{start} and @var{end} arguments limits the
6464 range of the vector to be used.
6465 They are Gauche's extension and not in SRFI-196.
6466 @c JP
6467 省略可能引数@var{start}と@var{end}はベクタの使う範囲のインデックスを制限します。
6468 これらの引数はGaucheの独自拡張で、SRFI-196にはありません。
6469 @c COMMON
6470
6471 @example
6472 (range->list (vector-range '#(a b c)))
6473 @result{} (a b c)
6474
6475 (range->list (vector-range '#(a b c d e) 1 4))
6476 @result{} (b c d)
6477
6478 (range-ref (vector-range '#(a b c d e) 2) 0)n
6479 @result{} c
6480 @end example
6481 @end defun
6482
6483 @defun uvector-range uvec :optional start end
6484 @c MOD data.range
6485 @c EN
6486 Returns a range over the given uniform vector @var{uvec}.
6487 The uniform vector is kept in the range, so you shouldn't mutate @var{uvec}.
6488
6489 The optional @var{start} and @var{end} arguments limits the
6490 range of the uniorm vector to be used.
6491 @c JP
6492 ユニフォームベクタ@var{uvec}にアクセスするレンジを作って返します。
6493 ユニフォームベクタはそのままレンジのデータ元として使われるので、
6494 この後で@var{uvec}を変更してはなりません。
6495
6496 省略可能引数@var{start}と@var{end}はベクタの使う範囲のインデックスを制限します。
6497 @c COMMON
6498 @end defun
6499
6500 @defun bitvector/bool-range bvec :optional start end
6501 @defunx bitvector/int-range bvec :optional start end
6502 @c MOD data.range
6503 Returns a range over the given bitvector @var{bvec}.
6504 @code{Bitvector/bool-range} regards @var{bvec} as a boolean vector,
6505 while @code{bitvector/int-range} regards it as a vector of 0 and 1.
6506 @xref{Bitvectors}, for the details of bitvectors.
6507 Note that @var{bvec} is kept in the range, so you shouldn't mutate @var{uvec}.
6508
6509 The optional @var{start} and @var{end} arguments limits the
6510 range of the uniorm vector to be used.
6511 @end defun
6512
6513 @defun string-range str :optional start end
6514 [SRFI-196]
6515 @c MOD data.range
6516 Returns a range over each character in the given string @var{str}.
6517 The string is kept in the range, so you shouldn't mutate @var{str}.
6518
6519 The optional @var{start} and @var{end} arguments limits the
6520 range of the vector to be used.
6521 They are Gauche's extension and not in SRFI-196.
6522
6523 @example
6524 (range->list (string-range "abc"))
6525 @result{} (#\a #\b #\c)
6526
6527 (range->list (string-range "abcde" 1 4))
6528 @result{} (#\b #\c #\d)
6529 @end example
6530 @end defun
6531
6532 @defun range-append range @dots{}
6533 [SRFI-196]
6534 @c MOD data.range
6535 Returns a new range that walks over concatenation of the given ranges.
6536 @end defun
6537
6538 @defun range-reverse range :optional start end
6539 [SRFI-196+]
6540 @c MOD data.range
6541 Returns a new range that walks over the elements of @var{range}, but
6542 in reverse order.
6543
6544 The optional @var{start} and @var{end} arguments limits the
6545 range of the vector to be used.
6546 They are Gauche's extension and not in SRFI-196.
6547
6548 @example
6549 (range->list (range-reverse (string-range "abc")))
6550 @result{} (#\c #\b #\a)
6551
6552 (range->list (range-reverse (string-range "abcdef" 1 4)))
6553 @result{} (#\d #\c #\b)
6554 @end example
6555 @end defun
6556
6557 @subheading Predicates
6558
6559 @defun range? obj
6560 [SRFI-196]
6561 @c MOD data.range
6562 Returns true iff @var{obj} is a range.
6563 @end defun
6564
6565 @defun range=? elt= range @dots{}
6566 [SRFI-196]
6567 @c MOD data.range
6568 Returns true iff all ranges have the same length, and any pair
6569 of corresponding elements in the given ranges are equal in terms of
6570 @code{elt=} predicate.
6571
6572 As edge cases, when zero or one range is given, @code{#t} is returned.
6573
6574 @example
6575 (range=? eqv? (numeric-range 0 5)
6576 (iota-range 5)
6577 (vector-range '#(0 1 2 3 4)))
6578 @result{} #t
6579 @end example
6580 @end defun
6581
6582 @subheading Accessors
6583
6584 @defun range-length range
6585 [SRFI-196]
6586 @c MOD data.range
6587 Returns the length of @var{range}.
6588 @end defun
6589
6590 @defun range-ref range i :optional fallback
6591 [SRFI-196+]
6592 @c MOD data.range
6593 Returns the @var{i}-th element of @var{range}. The index
6594 @var{i} must be an exact integer.
6595
6596 If @var{i} is negative, or greater than or equal to the length of @var{range},
6597 @var{fallback} is returned if given, or an error is signaled.
6598 The @var{fallback} argument is Gauche's extension and not in SRFI-196.
6599 @end defun
6600
6601 @defun range-first range :optional fallback
6602 [SRFI-196+]
6603 @c MOD data.range
6604 Returns the first element of @var{range}.
6605
6606 If the range is empty,
6607 @var{fallback} is returned if given, or an error is signaled.
6608 The @var{fallback} argument is Gauche's extension and not in SRFI-196.
6609 @end defun
6610
6611 @defun range-last range :optional fallback
6612 [SRFI-196+]
6613 @c MOD data.range
6614 Returns the last element of @var{range}.
6615
6616 If the range is empty,
6617 @var{fallback} is returned if given, or an error is signaled.
6618 The @var{fallback} argument is Gauche's extension and not in SRFI-196.
6619 @end defun
6620
6621 @subheading Iteration
6622
6623 @defun range-split-at range k
6624 [SRFI-196]
6625 @c MOD data.range
6626 Returns two ranges, the first one with elements before @var{k}-th
6627 elements of @var{range},
6628 and the second one with @var{k}-th elements and after of @var{range}.
6629 @end defun
6630
6631 @defun subrange range start end
6632 [SRFI-196]
6633 @c MOD data.range
6634 Returns a new range that contains @var{start}-th (inclusive)
6635 to @var{end}-th (exclusive) elements of @var{range}.
6636 @end defun
6637
6638 @defun range-segment range len
6639 [SRFI-196]
6640 @c MOD data.range
6641 Split @var{range} into subranges of length @var{len}. The last range
6642 may be shorter than @var{len}.
6643
6644 @example
6645 (map range->list (range-segment (numeric-range 0 11) 4))
6646 @result{} ((0 1 2 3) (4 5 6 7) (8 9 10))
6647 @end example
6648 @end defun
6649
6650 @defun range-take range count
6651 @defunx range-take-right range count
6652 [SRFI-196]
6653 @c MOD data.range
6654 Returns a new range containing initial @var{count} elements or last @var{count}
6655 elements from @var{range}, respectively
6656 @end defun
6657
6658 @defun range-drop range count
6659 @defunx range-drop-range range count
6660 [SRFI-196]
6661 @c MOD data.range
6662 Returns a new range containing elements of @var{range}
6663 except initial @var{count} elements or last @var{count} elements, respectively.
6664 @end defun
6665
6666 @defun range-count pred range range2 @dots{}
6667 [SRFI-196]
6668 @c MOD data.range
6669 A procedure @var{pred} must take as many arguments as the given ranges.
6670 It is called on each corresponding element of
6671 @var{range}, @var{range2} @dots{}, and the procedure returns
6672 the number of times @var{pred} returned true.
6673
6674 If more than one ranges are given and not all ranges are of the same length,
6675 iteration terminates at the end of the shortest range.
6676 @end defun
6677
6678 @defun range-any pred range range2 @dots{}
6679 [SRFI-196]
6680 @c MOD data.range
6681 A procedure @var{pred} must take as many arguments as the given ranges.
6682 It is called on each first element of
6683 @var{range}, @var{range2} @dots{}, then each second element, and so on.
6684 As soon as @var{pred} returns a true value, the iteration stops
6685 and the value @var{pred} returns becomes the result of @code{range-any}.
6686 If @var{pred} never returns a true value, @code{#f} is returned.
6687
6688 If more than one ranges are given and not all ranges are of the same length,
6689 iteration terminates at the end of the shortest range.
6690 @end defun
6691
6692 @defun range-every pred range range2 @dots{}
6693 [SRFI-196]
6694 @c MOD data.range
6695 A procedure @var{pred} must take as many arguments as the given ranges.
6696 It is called on each first element of
6697 @var{range}, @var{range2} @dots{}, then each second element, and so on.
6698 As soon as @var{pred} returns a false value, the iteration stops
6699 and @code{range-any} returns @code{#f}.
6700 If all @var{pred} returns a true value, the last value is returned.
6701
6702 If more than one ranges are given and not all ranges are of the same length,
6703 iteration terminates at the end of the shortest range.
6704 @end defun
6705
6706
6707 @defun range-map proc range range2 @dots{}
6708 @defunx range-map->list proc range range2 @dots{}
6709 @defunx range-map->vector proc range range2 @dots{}
6710 [SRFI-196]
6711 @c MOD data.range
6712 Mapping over ranges.
6713 A procedure @var{proc} must take as many arguments as the given ranges,
6714 and is called on each corresponding element of
6715 @var{range}, @var{range2} @dots{}. The results are collected and returned
6716 as a range (@code{range-map}), a list (@code{range-map->list},
6717 or a vector (@code{range-map->vector}. The dynamic order of
6718 in which @var{proc} is invoked is not specified. Note that
6719 @code{range-map} computes all elements before returning the result range.
6720
6721 If more than one ranges are given and not all ranges are of the same length,
6722 iteration terminates at the end of the shortest range.
6723 @end defun
6724
6725 @defun range-for-each proc range range2 @dots{}
6726 [SRFI-196]
6727 @c MOD data.range
6728 A procedure @var{proc} must take as many arguments as the given ranges.
6729 It is invoked with the first elements of each range,
6730 and then with the second elements of them, and so on,
6731 until the shortest range is exhausted. The result of @var{proc} is
6732 discarded.
6733
6734 Returns an undefined value.
6735 @end defun
6736
6737 @defun range-filter pred range
6738 @defunx range-filter->list pred range
6739 @defunx range-remove pred range
6740 @defunx range-remove->list pred range
6741 @defunx range-filter-map pred range range2 @dots{}
6742 @defunx range-filter-map->list pred range range2 @dots{}
6743 [SRFI-196]
6744 @c MOD data.range
6745 A procedure @var{pred} must take as many arguments as the given ranges.
6746 These are range version of @code{filter}, @code{remove}, and
6747 @code{filter-map} (@pxref{Walking over lists}).
6748
6749 The procedures without @code{->list} returns the result as a range,
6750 while the ones with @code{->list} returns the result as a list.
6751
6752 The iteration stops when the shortest range is exhausted.
6753 The result is eagerly computed.
6754
6755 @example
6756 (range->list (range-filter odd? (iota-range 10)))
6757 @result{} (1 3 5 7 9)
6758 (range-remove->list odd? (iota-range 10))
6759 @result{} (0 2 4 6 8)
6760 (range->list (range-filter-map (every-pred odd? square) (iota-range 10)))
6761 @result{} (1 9 25 49 81)
6762 @end example
6763 @end defun
6764
6765 @defun range-fold kons knil range range2 @dots{}
6766 @defunx range-fold-right kons knil range range2 @dots{}
6767 [SRFI-196]
6768 @c MOD data.range
6769 These are range version of @code{fold} and @code{fold-right}
6770 (@pxref{Walking over lists}).
6771 The iteration stops when the shortest range is exhausted.
6772 @end defun
6773
6774 @subheading Searching
6775
6776 @defun range-index pred range range2 @dots{}
6777 @defunx range-index-right pred range range2 @dots{}
6778 [SRFI-196]
6779 @c MOD data.range
6780 Returns the first or the last index of the element in the input range
6781 that satisfies a predicate @var{pred}. If there are more than one
6782 ranges, @var{pred} must take as many arguments as the number of input
6783 ranges, and applied on each corresponding elements of the input range.
6784
6785 @example
6786 (range-index > (vector-range '#(1 5 3 2 4))
6787 (vector-range '#(4 3 0 4 6)))
6788 @result{} 1
6789 (range-index-right > (vector-range '#(1 5 3 2 4))
6790 (vector-range '#(4 3 0 4 6)))
6791 @result{} 2
6792 @end example
6793 @end defun
6794
6795 @defun range-take-while pred range
6796 @defunx range-take-while-right pred range
6797 @defunx range-drop-while pred range
6798 @defunx range-drop-while-right pred range
6799 [SRFI-196]
6800 @c MOD data.range
6801 Same as @code{take-while}, @code{take-while-right}, @code{drop-while},
6802 and @code{drop-while-right}, except those operate on an range
6803 and return an range, instead of a list (@pxref{R7RS lists}).
6804 @end defun
6805
6806 @subheading Conversion
6807
6808 @defun range->list range
6809 @defunx range->vector range
6810 @defunx range->string range
6811 [SRFI-196]
6812 @c MOD data.range
6813 Convert a range to a list, a vector ro a string, respectively.
6814 For @code{range->string}, the argument must be a range consists solely
6815 of characters.
6816 @end defun
6817
6818
6819 @defun vector->range vec :optional start end
6820 [SRFI-196]
6821 @c MOD data.range
6822 Returns a range whose elements are those of a vector @var{vec}.
6823 Unlike @code{vector-range}, the content of @var{vec} is copied into
6824 the range, so mutating @var{vec} won't alter the resulting range.
6825
6826 The optional @var{start} and @var{end} arguments limit the portion
6827 to be used for the result.
6828 @end defun
6829
6830 @defun range->generator range :optional start end
6831 [SRFI-196]
6832 @c MOD data.range
6833 Returns a generator that yields each element of @var{range},
6834 between @var{start} (inclusive) and @var{end} (exclusive) indexes.
6835 When omitted, @var{start} is 0 and @var{end} is the size of the range.
6836 @end defun
6837
6838 @c ----------------------------------------------------------------------
6839 @node Ring buffer, Skew binary random-access lists, Range, Library modules - Utilities
6840 @section @code{data.ring-buffer} - Ring buffer
6841 @c NODE リングバッファ, @code{data.ring-buffer} - リングバッファ
6842
6843 @deftp {Module} data.ring-buffer
6844 @mdindex data.ring-buffer
6845 @c EN
6846 A ring buffer is an array with two fill pointers; in a typical usage,
6847 a producer adds new data to one end while a consumer removes data
6848 from the other end; if fill pointer reaches at the end of the array,
6849 it wraps around to the beginning, hence the name.
6850 @c JP
6851 リングバッファは、両端を指す二つのポインタを持つ配列と考えられます。良くある使い方は、
6852 生産者が配列の一方の端にデータを追加してゆき、消費者がもう一方の端から
6853 データを取り出してゆくというものです。もし端を示すポインタが配列の
6854 終端に達したら、それはもう一方の端につながっているように振る舞います。
6855 「リング」バッファと呼ばれるのはそのためです。
6856 @c COMMON
6857
6858 @c EN
6859 The ring buffer of this module allows adding and removing elements
6860 from both ends, hence functionally it is a double-ended queue,
6861 or deque. It also allows O(1) indexed access to the contents,
6862 and customized handling for the case when the buffer gets full.
6863 @c JP
6864 このモジュールの提供するリングバッファは、どちらの端にもデータを追加し、
6865 どちらの端からもデータを取り出すことができます。したがって機能的には
6866 両端キュー(double-ended queue, deque)の一種とも考えられます。
6867 また、O(1)で要素にアクセス可能で、
6868 さらにバッファが一杯になった時の振る舞いをカスタマイズできます。
6869 @c COMMON
6870
6871 @c EN
6872 You can use an ordinary vector or a uniform vector as the backing
6873 storage of a ring buffer.
6874 @c JP
6875 リングバッファがデータを格納するバッキングストレージとして、
6876 通常のベクタかユニフォームベクタを使えます。
6877 @c COMMON
6878 @end deftp
6879
6880 @defun make-ring-buffer :optional initial-storage :key overflow-handler initial-head-index initial-tail-index
6881 @c MOD data.ring-buffer
6882 @c EN
6883 Creates a ring buffer. By default, a fresh vector is allocated
6884 for the backing storage. You can pass a vector or a uvector to
6885 @var{initial-storage} to be used instead. The passed storage must
6886 be mutable, and will
6887 be modified by the ring buffer; the caller shouldn't modify it,
6888 nor make assumption about its content.
6889 @c JP
6890 リングバッファを作成します。デフォルトでは、データ格納のための領域として
6891 新たなベクタがアロケートされます。かわりに、呼び出し側でベクタかユニフォームベクタ
6892 を用意して@var{initial-storage}に渡すこともできます。その場合、
6893 渡すベクタやユニフォームベクタは変更可能でなければなりません。以降、
6894 リングバッファがそのベクタを変更するので、呼び出し側でベクタを変更
6895 したりベクタの内容が保存されることを期待してはいけません。
6896 @c COMMON
6897
6898 @c EN
6899 By default, the storage you pass as @var{initial-storage} is assumed to
6900 be an empty buffer. You can also pass a pre-filled storage, by
6901 specifing valid range of existing data with
6902 @var{initial-head-index} and @var{initial-tail-index} arguments
6903 (both are defaulted to 0). For example, the following code returns
6904 a ring buffer of initial capacity 8, with the first 4 items are
6905 already filled.
6906 @c JP
6907 デフォルトでは、@var{initial-storage}に渡されたストレージは空のバッファとみなされます。
6908 しかし、あらかじめ一部に有効なデータを入れて渡すこともできます。その場合は、
6909 @var{initial-head-index}と@var{initial-tail-index}引数で有効なデータの
6910 インデックスの範囲を指定してください(これらの引数のデフォルトは0です)。
6911 例えば次のコードは、初期容量8のリングバッファのうち、最初の4要素が既に埋められているような
6912 リングバッファを作って返します。
6913 @c COMMON
6914
6915 @example
6916 (make-ring-buffer (vector 'a 'b 'c 'd #f #f #f #f)
6917 :initial-tail-index 4)
6918 @end example
6919
6920
6921 @c EN
6922 The @var{overflow-handler} keyword argument specifies what to do when
6923 a new element is about to be added to the full buffer.
6924 It must be a procedure, or a symbol @code{error}
6925 or @code{overwrite}.
6926 @c JP
6927 @var{overflow-handler}キーワード引数は、バッファがフルの状態で
6928 新たな要素が追加されようとした時の振る舞いを指定します。
6929 引数は手続きか、シンボル@code{error}か@code{overwrite}のいずれかでなければなりません。
6930 @c COMMON
6931
6932 @c EN
6933 If it is a procedure, it will be called with a ring buffer and
6934 a backing storage (vector or uvector) when it is filled. The procedure
6935 must either (1) allocate and return a larger vector/uvector of the same
6936 type of the passed backing storage, (2) return a symbol @code{error},
6937 or (3) return a symbol @code{overwrite}. If it returns a vector/uvector,
6938 it will be used as the new backing storage. The returned vector doesn't need
6939 to be initialized; the ring buffer routine takes care of copying the
6940 necessary data.
6941 If it returns @code{error},
6942 an error (``buffer is full'') is thrown. If it returns @code{overwrite},
6943 the new element overwrites the existing element (as if one element
6944 from the other end is popped and discarded.)
6945 @c JP
6946 引数が手続きの場合、リングバッファと(一杯になった)バッキングストレージ
6947 が引数として渡されます。この手続きは以下の3つのアクションのうちひとつを
6948 実行しなければなりません。(1)渡されたバッキングストレージ(ベクタか
6949 ユニフォームベクタ)と同じ型で、より大きなベクタまたはユニフォームベクタをアロケートして
6950 返す。(2)シンボル@code{error}を返す。(3)シンボル@code{overwrite}を返す。
6951 手続きがベクタもしくはユニフォームベクタを返した場合は、それが
6952 新たなバッキングストレージとして使われます。
6953 返すベクタの内容を設定する必要はありません。リングバッファが適切に内容のコピーや
6954 必要な初期化を行います。手続きが@code{error}を返した場合は、
6955 ``buffer is full''のエラーが投げられます。
6956 手続きが@code{overwrite}を返した場合は、
6957 新たな要素で古い要素を上書きします(つまり、
6958 あたかも別の端から1要素がポップされて捨てられ、その後で新たな要素が
6959 追加されたかのように振る舞います)。
6960 @c COMMON
6961
6962 @c EN
6963 Passing a symbol @code{error} or @code{overwrite} to @var{overflow-handler}
6964 is a shorthand of passing a procedure that unconditionally returns
6965 @code{error} or @code{overwrite}, respectively.
6966 @c JP
6967 @var{overflow-handler}引数にシンボル@code{error}か@code{overwrite}
6968 を渡した場合は、あたかもそれらのシンボルを無条件に返すoverflow handlerが
6969 指定されたかのように振る舞います。
6970 @c COMMON
6971
6972 @c EN
6973 The default behavior on overflow is to double the size of backing
6974 storage. You can use @code{make-overflow-doubler} below to create
6975 the customized overflow handler easily.
6976 @c JP
6977 @var{overflow-handler}が指定されない場合のデフォルトの動作は、
6978 元のバッキングストレージの倍の容量をアロケートして返すことです。
6979 下の@code{make-overflow-doubler}を使うと、カスタマイズした
6980 オーバフローハンドラを簡単に作ることができます。
6981 @c COMMON
6982 @end defun
6983
6984 @defun make-overflow-doubler :key max-increase max-capacity
6985 @c MOD data.ring-buffer
6986 @c EN
6987 Returns a procedure suitable to be passed to the @var{overflow-handler}
6988 keyword argument of @code{make-ring-buffer}.
6989
6990 The returned procedure takes a ring buffer and its backing storage,
6991 and behaves as follows.
6992 @c JP
6993 @code{make-ring-buffer}の@var{overflow-handler}キーワード引数に
6994 渡せる手続きを作って返します。
6995
6996 返される手続きは、リングバッファとバッキングストレージを引数に取り、
6997 以下のとおり振る舞います。
6998 @c COMMON
6999
7000 @itemize
7001 @item
7002 @c EN
7003 If the size of current backing storage is equal to or greater than
7004 @var{max-capacity}, returns @code{error}.
7005 @c JP
7006 現在のバッキングストレージの大きさが@var{max-capacity}以上であれば、
7007 @code{error}を返す。
7008 @c COMMON
7009 @item
7010 @c EN
7011 Otherwise, if the size of current backing storage is equal to or
7012 greater than @var{max-increase}, allocates a vector/uvector of
7013 the same type of the current backing storage, with the size
7014 @code{(+ max-increase size-of-current-storage)}.
7015 @c JP
7016 そうではなく、現在のバッキングストレージの大きさが@var{max-increase}以上で
7017 あれば、@code{(+ max-increase 現在の大きさ)}の大きさを持つ
7018 ベクタもしくはユニフォームベクタをアロケートして返す。
7019 @c COMMON
7020 @item
7021 @c EN
7022 Otherwise, allocates a vector/uvector of
7023 the same type of the current backing storage with the size
7024 @code{(* 2 size-of-current-storage)}.
7025 @c JP
7026 そうでない場合は、@code{(* 2 現在の大きさ)} の大きさを持つ
7027 ベクタもしくはユニフォームベクタをアロケートして返す。
7028 @c COMMON
7029 @end itemize
7030
7031 @c EN
7032 The default value of @var{max-increase} and @var{max-capacity} is
7033 @code{+inf.0}.
7034 @c JP
7035 @var{max-increase}と@var{max-capacity}のデフォルト値はどちらも
7036 @code{+inf.0}です。
7037 @c COMMON
7038 @end defun
7039
7040 @defun ring-buffer-empty? rb
7041 @c MOD data.ring-buffer
7042 @c EN
7043 Returns @code{#t} if the ring buffer @var{rb} is empty,
7044 @code{#f} if not.
7045 @c JP
7046 リングバッファ@var{rb}が空なら@code{#t}を、そうでなければ@code{#f}を返します。
7047 @c COMMON
7048 @end defun
7049
7050 @defun ring-buffer-full? rb
7051 @c MOD data.ring-buffer
7052 @c EN
7053 Returns @code{#t} if the ring buffer @var{rb} is full,
7054 @code{#f} if not.
7055 @c JP
7056 リングバッファ@var{rb}がフルなら@code{#t}を、そうでなければ@code{#f}を返します。
7057 @c COMMON
7058 @end defun
7059
7060 @defun ring-buffer-num-entries rb
7061 @c MOD data.ring-buffer
7062 @c EN
7063 Returns the number of current elements in the ring buffer @var{rb}.
7064 @c JP
7065 リングバッファ@var{rb}が格納している要素数を返します。
7066 @c COMMON
7067 @end defun
7068
7069 @defun ring-buffer-capacity rb
7070 @c MOD data.ring-buffer
7071 @c EN
7072 Returns the size of the current backing storage of the ring buffer @var{rb}.
7073 @c JP
7074 リングバッファの現在のバッキングストレージの容量(格納可能な要素数)を返します。
7075 @c COMMON
7076 @end defun
7077
7078 @defun ring-buffer-front rb
7079 @defunx ring-buffer-back rb
7080 @c MOD data.ring-buffer
7081 @c EN
7082 Returns the element in the front or back of the ring buffer @var{rb},
7083 respectively.
7084 If the buffer is empty, an error is signaled.
7085 @c JP
7086 リングバッファ@var{rb}の先頭あるいは末尾の要素をそれぞれ返します。
7087 バッファが空の場合はエラーが投げられます。
7088 @c COMMON
7089 @end defun
7090
7091 @defun ring-buffer-add-front! rb elt
7092 @defunx ring-buffer-add-back! rb elt
7093 @c MOD data.ring-buffer
7094 @c EN
7095 Add an element to the front or back of the ring buffer @var{rb},
7096 respectively. If @var{rb} is full, the behavior is determined by
7097 the buffer's overflow handler, as described in @code{make-ring-buffer}.
7098 @c JP
7099 リングバッファ@var{rb}の先頭もしくは末尾にそれぞれ要素を追加します。
7100 @var{rb}がフルの場合の振る舞いは、バッファのオーバーフローハンドラによって
7101 決定されます。詳しくは@code{make-ring-buffer}のエントリを参照してください。
7102 @c COMMON
7103 @end defun
7104
7105 @defun ring-buffer-remove-front! rb
7106 @defunx ring-buffer-remove-back! rb
7107 @c MOD data.ring-buffer
7108 @c EN
7109 Remove an element from the front or back of the ring buffer @var{rb},
7110 and returns the removed element, respectively.
7111 If the buffer is empty, an error is signaled.
7112 @c JP
7113 リングバッファ@var{rb}の先頭もしくは末尾から要素をひとつ取り、取った要素を
7114 返します。
7115 バッファが空の場合はエラーが投げられます。
7116 @c COMMON
7117 @end defun
7118
7119 @defun ring-buffer-ref rb index :optional fallback
7120 @c MOD data.ring-buffer
7121 @c EN
7122 Returns @var{index}-th element in the ring buffer @var{rb}.
7123 The elements are counted from the front; thus, if a new element
7124 is added to the front, the indexes of existing elements will shift.
7125
7126 If the index out of bounds of the existing content,
7127 @var{fallback} will be returned; if @var{fallback} is not
7128 provided, an error is signaled.
7129 @c JP
7130 リングバッファ@var{rb}の@var{index}番目の要素を返します。
7131 要素は先頭から数えられます。したがって、新たな要素が先頭に付け加えられた場合、
7132 既存の要素のインデックスはひとつづつずれます。
7133
7134 @var{index}が@var{rb}の持つ要素の範囲外の場合、@var{fallback}が与えられていれば
7135 それを返し、そうでなければエラーが投げられます。
7136 @c COMMON
7137 @end defun
7138
7139 @defun ring-buffer-set! rb index value
7140 @c MOD data.ring-buffer
7141 @c EN
7142 Sets @var{index}-th element of the ring buffer @var{rb} to @var{value}.
7143 The elements are counted from the front; thus, if a new element
7144 is added to the front, the indexes of existing elements will shift.
7145
7146 An error is signaled if the index is out of bounds.
7147 @c JP
7148 リングバッファ@var{rb}の@var{index}番目の要素に@var{value}をセットします。
7149 要素は先頭から数えられます。したがって、新たな要素が先頭に付け加えられた場合、
7150 既存の要素のインデックスはひとつづつずれます。
7151
7152 @var{index}が@var{rb}の持つ要素の範囲外の場合はエラーが投げられます。
7153 @c COMMON
7154 @end defun
7155
7156
7157 @defun ring-buffer->flat-vector rb :optional start end
7158 @c MOD data.ring-buffer
7159 @c EN
7160 Returns the current valid content of the ring buffer @var{rb}
7161 as a fresh flat vector
7162 of the same type as @var{rb}'s storage. If the optional @var{start}/@var{end}
7163 indexes are given, the content between those indexes are taken.
7164 @c JP
7165 リングバッファ@var{rb}の現在の有効な範囲の内容を、新たにアロケートされる
7166 @var{rb}のストレージと同じ型のベクタとして返します。
7167 @var{start}/@var{end}インデックスを指定した場合はそのインデックスの範囲内の
7168 内容だけが取り出されます。
7169 @c COMMON
7170
7171 @example
7172 (define rb (make-ring-buffer (make-vector 4)))
7173
7174 (ring-buffer->flat-vector rb) @result{} #()
7175
7176 (ring-buffer-add-back! rb 'a)
7177 (ring-buffer-add-back! rb 'b)
7178 (ring-buffer-add-front! rb 'z)
7179 (ring-buffer-add-front! rb 'y)
7180
7181 (ring-buffer->flat-vector rb) @result{} #(y z a b)
7182 (ring-buffer->flat-vector rb 1 3) @result{} #(z a)
7183 @end example
7184 @end defun
7185
7186
7187 @c ----------------------------------------------------------------------
7188 @node Skew binary random-access lists, Sparse data containers, Ring buffer, Library modules - Utilities
7189 @section @code{data.skew-list} - Skew binary random-access lists
7190 @c NODE Skew binary random-access lists, @code{data.sparse} - Skew binary random-access lists
7191
7192 @deftp {Module} data.skew-list
7193 @mdindex data.skew-list
7194 @c EN
7195 This module implements skew binary random-access list (we call it skew-list
7196 for short). It's an immutable
7197 data structure that has properties of both list and vector; constant
7198 time to take the first element (car) and append an element in front
7199 of existing one (cons), O(log n) to take the rest of
7200 the elements (cdr), and O(log n) for indexed access, wher n is
7201 the number of elements.
7202 @c JP
7203 このモジュールは、Skew binary random-access list
7204 (以降は短くskew-listと表記します)を提供します。
7205 skew-listは変更不可なデータ構造で、リストとベクタの中間のような
7206 性質を持っています:要素数をnとするとき
7207 最初の要素を取り出したり(car)、最初に要素を追加する(cons)のはO(1)、
7208 最初以外の要素を返す(cdr)のはO(log n)、
7209 そして整数インデックスにより任意の要素にアクセスするのもO(log n)です。
7210 @c COMMON
7211
7212 @c EN
7213 A skew-list is always 'proper'; that is, it is either an empty
7214 skew-list (@code{skew-list-null}), or an object appended in front
7215 of a skew-list.
7216 @c JP
7217 skew-listは常に「properなリスト」です。すなわち、それは
7218 空のskew-list (@code{skew-list-null})か、
7219 skew-listの前に要素を付け足したもの、です。
7220 @c COMMON
7221 @end deftp
7222
7223 @deftp {Class} <skew-list>
7224 @clindex skew-list
7225 @c MOD data.skew-list
7226 @c EN
7227 The class for skew-lists.
7228
7229 It inherits @code{<sequence>} and implements the sequence protocol
7230 (@pxref{Sequence framework}).
7231 @c JP
7232 skew-listのクラスです。
7233
7234 @code{<sequence>}を継承していて、シーケンスプロトコルを実装しています
7235 (@ref{Sequence framework}参照)。
7236 @c COMMON
7237 @end deftp
7238
7239 @defun skew-list? obj
7240 @c MOD data.skew-list
7241 @c EN
7242 Returns @code{#t} iff @var{obj} is a skew-list.
7243 @c JP
7244 @var{obj}がskew-listなら@code{#t}を、そうでなければ@code{#f}を返します。
7245 @c COMMON
7246 @end defun
7247
7248 @defun skew-list-empty? sl
7249 @c MOD data.skew-list
7250 @c EN
7251 The argument must be a skew list. Returns @code{#t} iff @var{sl}
7252 is an empty skew list.
7253 @c JP
7254 引数はskew listでなければなりません。
7255 @var{sl}が空のskew listなら@code{#t}を、そうでなければ@code{#f}を返します。
7256 @c COMMON
7257 @end defun
7258
7259 @defvar skew-list-null
7260 @c MOD data.skew-list
7261 @c EN
7262 An empty skew list.
7263 @c JP
7264 空のskew listに束縛されています。
7265 @c COMMON
7266 @end defvar
7267
7268 @defun skew-list-cons obj sl
7269 @c MOD data.skew-list
7270 @c EN
7271 Returns a new skew-list which has @var{obj} prepended to
7272 a skew-list @var{sl}. O(1) operation.
7273 @c JP
7274 skew list @var{sl}の先頭に@var{obj}を追加した新たなskew listを作って返します。
7275 O(1)の操作です。
7276 @c COMMON
7277 @end defun
7278
7279 @defun skew-list-car sl
7280 @c MOD data.skew-list
7281 @c EN
7282 Returns the first element of a skew-list @var{sl}. O(1) operation.
7283 An error is raised when @var{sl} is empty.
7284 @c JP
7285 skew list @var{sl}の先頭要素を返します。O(1)の操作です。
7286 @var{sl}が空であればエラーが投げられます。
7287 @c COMMON
7288 @end defun
7289
7290 @defun skew-list-cdr sl
7291 @c MOD data.skew-list
7292 @c EN
7293 Returns a new skew-list that containts elements in @var{sl} but
7294 the first one. O(log n) operation.
7295 An error is raised when @var{sl} is empty.
7296 @c JP
7297 skew list @var{sl}の、最初の要素を取り除いたskew listを返します。
7298 O(log n)の操作です。
7299 @var{sl}が空であればエラーが投げられます。
7300 @c COMMON
7301 @end defun
7302
7303 @defun skew-list-ref sl k :optional fallback
7304 @c MOD data.skew-list
7305 @c EN
7306 Returns the @var{k}-th element of a skew-list @var{sl}. O(log n) operation.
7307 If @var{k}
7308 points past the range of @var{sl}, @var{fallback} is returned if it
7309 is given, or an error is signaled.
7310 @c JP
7311 skew list @var{sl}の@var{k}番目の要素を返します。O(log n)の操作です。
7312 @var{k}が@var{sl}の範囲外を指している場合、@var{fallback}が与えられていればそれが
7313 返され、与えられていなければエラーが投げられます。
7314 @c COMMON
7315
7316 @c EN
7317 Sicne a skew-list is also a sequence, you can use generic @code{ref} as well
7318 (@pxref{Sequence framework}).
7319 @c JP
7320 skew listはシーケンスでもあるので、@code{ref}でアクセスすることもできます
7321 (@ref{Sequence framework}参照)。
7322
7323 @c COMMON
7324 @end defun
7325
7326 @defun skew-list-set sl k obj
7327 @c MOD data.skew-list
7328 @c EN
7329 Returns a new skew-list which is the same as @var{sl} except the @var{k}-th
7330 element is replaced with @var{obj}. The argument @var{sl} remains intact.
7331 O(log n) operation.
7332 @c JP
7333 skew list @var{sl}の、@var{k}番目の要素を@var{obj}に変えた新たなskew listを
7334 作って返します。元の@var{sl}は変更されません。
7335 O(log n)の操作です。
7336 @c COMMON
7337
7338 @c EN
7339 It is an error if @var{k} points beyond the last element of @var{sl}.
7340 @c JP
7341 @var{k}が@var{sl}の範囲外を指していた場合はエラーが投げられます。
7342 @c COMMON
7343 @end defun
7344
7345 @defun skew-list-length sl
7346 @c MOD data.skew-list
7347 @c EN
7348 Returns an integer length of a skew-list @var{sl}. O(log n) operation.
7349 @c JP
7350 skew list @var{sl}の長さを返します。O(log n)の操作です。
7351 @c COMMON
7352
7353 @c EN
7354 Sicne a skew-list is also a sequence, you can use generic @code{size-of} as well
7355 (@pxref{Sequence framework}).
7356 @c JP
7357 skew listはシーケンスでもあるので、@code{size-of}も使えます
7358 (@ref{Sequence framework}参照)。
7359 @c COMMON
7360 @end defun
7361
7362 @defun skew-list-length<=? sl n
7363 @c MOD data.skew-list
7364 @c EN
7365 Returns @code{#t} iff the length of a skew-list @var{sl} is less than
7366 or equal to @var{n}. It is more efficient than calculating
7367 the total length and compares with @var{n}.
7368 @c JP
7369 skew list @var{sl}の長さが@var{n}以下であれば@code{#t}を、そうでなければ
7370 @code{#f}を返します。@var{sl}の全長を求めて@var{n}と比較するより効率的です。
7371 @c COMMON
7372 @end defun
7373
7374 @defun list->skew-list lis
7375 @c MOD data.skew-list
7376 @c EN
7377 Returns a new skew-list which contains elements in @var{lis}, with the
7378 same order. It is an error if @var{lis} is not a proper list.
7379 @c JP
7380 リスト@var{lis}と同じ要素を同じ並びで持つskew listを作って返します。
7381 @var{lis}が正式なリストでなければエラーが投げられます。
7382 @c COMMON
7383
7384 @c EN
7385 Sicne a skew-list is also a sequence, you can use generic @code{coerce-to}
7386 as well (@pxref{Sequence framework}).
7387 @c JP
7388 skew listはシーケンスでもあるので、@code{coerce-to}を使うこともできます
7389 (@ref{Sequence framework}参照)。
7390 @c COMMON
7391 @end defun
7392
7393 @defun list*->skew-list lis
7394 @c MOD data.skew-list
7395 @c EN
7396 The argument @var{lis} may be a dotted list (but can't be circular).
7397 Returns two values: a new skew-list which contains elements
7398 in @var{lis} except the last cdr of it, and the last cdr of @var{lis}.
7399 @c JP
7400 @var{lis}は正式なリストまたはドットリストです (循環リストであってはいけません)。
7401 二つの値を返します。@var{lis}の最後のcdrを除いた要素をその並びで持つ新たな
7402 skew listと、@var{lis}の最後のcdrの値です。
7403 @c COMMON
7404 @end defun
7405
7406 @defun skew-list->list sl
7407 @c MOD data.skew-list
7408 @c EN
7409 Returns a new list that contains all the elements in a skew-list @var{sl},
7410 with the same order.
7411
7412 Sicne a skew-list is also a sequence, you can use generic @code{coerce-to}
7413 as well (@pxref{Sequence framework}.
7414 @c JP
7415 skew list @var{sl}の各要素を同じ並びで持つリストを作って返します。
7416
7417 skew listはシーケンスでもあるので、@code{coerce-to}を使うこともできます
7418 (@ref{Sequence framework}参照)。
7419 @c COMMON
7420 @end defun
7421
7422 @defun skew-list->generator sl
7423 @c MOD data.skew-list
7424 @c EN
7425 Returns a new generator that traverses a skew-list @var{sl}.
7426 @c JP
7427 skew list @var{sl}の要素を順に生成するジェネレータを作って返します。
7428 @c COMMON
7429 @end defun
7430
7431 @defun skew-list->lseq sl
7432 @c MOD data.skew-list
7433 @c EN
7434 Converts a skew-list @var{sl} to a lazy sequence.
7435 @c JP
7436 skew list @var{sl}を遅延シーケンスに変換します。
7437 @c COMMON
7438 @end defun
7439
7440 @defun skew-list-take sl k
7441 @defunx skew-list-drop sl k
7442 @c MOD data.skew-list
7443 @c EN
7444 Returns a new skew-list of the first @var{k} elements and the elements
7445 except the first @var{k} elements, respectively.
7446 @c JP
7447 skew list @var{sl}の、最初の@var{k}要素だけのskew list、
7448 あるいは最初の@var{k}要素を取り除いた残りのskew listを返します。
7449 @c COMMON
7450 @end defun
7451
7452 @defun skew-list-split-at sl k
7453 @c MOD data.skew-list
7454 @c EN
7455 Returns two values, the result of @code{(skew-list-take sl k)}
7456 and @code{(skew-list-drop sl k)}, but more efficiently.
7457 @c JP
7458 @code{(skew-list-take sl k)}と@code{(skew-list-drop sl k)}の結果を
7459 2つの値として返しますが、より効率が良いです。
7460 @c COMMON
7461 @end defun
7462
7463 @defun skew-list-append sl sl2 @dots{}
7464 @c MOD data.skew-list
7465 @c EN
7466 Returns a skew-list which is a concatenation of all the given skew-lists.
7467 @c JP
7468 2つのskew listをつなげたskew listを返します。
7469 @c COMMON
7470 @end defun
7471
7472 @defun skew-list-fold sl kons knil
7473 @c MOD data.skew-list
7474 @c EN
7475 Like @var{fold} on a list.
7476
7477 Sicne a skew-list is also a sequence, you can use generic @code{fold}
7478 as well (@pxref{Sequence framework}.
7479 @c JP
7480 skew list @var{sl}に対して、リストに対する@var{fold}と同じような動作をします。
7481
7482 skew listはシーケンスでもあるので、ジェネリックな@code{fold}を使うこともできます
7483 (@ref{Sequence framework}参照)。
7484 @c COMMON
7485 @end defun
7486
7487 @defun skew-list-map sl proc
7488 @c MOD data.skew-list
7489 @c EN
7490 Returns a skew list, each element of which is the result of
7491 applying @var{proc} on the element of @var{sl}.
7492 The order of application of @var{proc} is not specified.
7493
7494 NB: If you want to map over multiple skew-lists, you can use generic
7495 @code{map} (@pxref{Sequence framework}). The @code{skew-list-map} employs
7496 optimization that's specific to one-argument case.
7497 @c JP
7498 skew list @var{sl}の各要素に@var{proc}を適用した結果を集めた新たなskew listを
7499 作って返します。@var{proc}が適用される順序は決められていません。
7500
7501 複数のskew listに対して@code{map}したい場合は、
7502 ジェネリックの@code{map}が使えます (@ref{Sequence framework})。
7503 @code{skew-list-map}は単一引数の場合に使える最適化を施してあります。
7504 @c COMMON
7505 @end defun
7506
7507
7508 @c ----------------------------------------------------------------------
7509 @node Sparse data containers, Trie, Skew binary random-access lists, Library modules - Utilities
7510 @section @code{data.sparse} - Sparse data containers
7511 @c NODE 疎なデータコンテナ, @code{data.sparse} - 疎なデータコンテナ
7512
7513 @deftp {Module} data.sparse
7514 @mdindex data.sparse
7515 @c EN
7516 This module provides a @emph{sparse vector} and @emph{sparse matrix},
7517 a space efficient data container indexed by nonnegative integer(s), and
7518 a @emph{sparse table}, a hash table using a sparse vector
7519 as a backing storage.
7520 @c JP
7521 このモジュールは、非負整数でインデックスされる空間効率の良いデータ構造である
7522 @emph{疎ベクタ} (@emph{sparse vector})と
7523 @emph{疎行列} (@emph{sparse matrix})、
7524 および
7525 疎ベクタを格納領域に用いるハッシュテーブルである@emph{疎テーブル} (@emph{sparse table})
7526 を提供します。
7527 @c COMMON
7528 @end deftp
7529
7530 @c EN
7531 A sparse vector associates a nonnegative integer index
7532 to a value. It has @emph{vector} in its name since it is indexed
7533 by an integer, but it isn't like a flat array on contiguous memory;
7534 it's more like an associative array. (Internally, the current
7535 implementation uses compact trie structure.)
7536 It is guaranteed that you can store a value with index at least
7537 up to @code{2^32-1}; the actual maximum bits of indexes can
7538 be queried by @code{sparse-vector-max-index-bits}.
7539 (We have a plan to remove the maximum bits limitation in future).
7540 @c JP
7541 疎ベクタは非負整数のインデックスと値を関連付けます。
7542 整数でインデックスされるので名前に@emph{ベクタ}がついていますが、
7543 連続するメモリに置かれる配列ではなく、むしろ連想配列のようなものです。
7544 (内部的には、現在の実装はコンパクトなトライを使っています)。
7545 少なくとも@code{2^32-1}までのインデックスが使えることは保証されています。
7546 実装が許す最大のインデックスのビット長は
7547 @code{sparse-vector-max-index-bits}で得ることができます。
7548 (将来的にはこの制限を無くす計画です)。
7549 @c COMMON
7550
7551 @c EN
7552 Unlike ordinary vectors, you don't need to specify the size
7553 of a sparse vector when you create one. You can just set
7554 a value to any index in the supported range.
7555 @c JP
7556 通常のベクタと違い、疎ベクタは作る時に大きさを指定する必要がありません。
7557 サポートされている範囲内ならどんなインデックスにでも単に値を格納できます。
7558 @c COMMON
7559
7560 @example
7561 (define v (make-sparse-vector))
7562
7563 (sparse-vector-set! v 0 'a)
7564 (sparse-vector-ref v 0) @result{} a
7565
7566 (sparse-vector-set! v 100000000 'b)
7567 (sparse-vector-ref v 100000000) @result{} b
7568
7569 ;; set! also work
7570 (set! (sparse-vector-ref v 100) 'c)
7571 (sparse-vector-ref v 100) @result{} c
7572 @end example
7573
7574 @c EN
7575 If you try to access an element that hasn't been set,
7576 an error is signaled by default. You can set
7577 a default value for each vector, or give a
7578 fallback value to @code{sparse-vector-ref}, to suppress the error.
7579 @c JP
7580 値がセットされていない要素にアクセスすると、デフォルトではエラーが通知されます。
7581 ベクタごとに既定値を設定したり、
7582 @code{sparse-vector-ref}の省略可能引数にフォールバック値を
7583 渡すことでエラーを回避できます。
7584 @c COMMON
7585
7586 @example
7587 (sparse-vector-ref v 1) @result{} @r{error}
7588 (sparse-vector-ref v 1 'noval) @result{} noval
7589
7590 (let1 w (make-sparse-vector #f :default 'x)
7591 (sparse-vector-ref w 1)) @result{} x
7592 @end example
7593
7594 @c EN
7595 A sparse matrix is like a sparse vector, except it can be indexed
7596 by a pair of integers.
7597 @c JP
7598 疎行列は、二つの整数でインデックスされるという点以外は疎なベクタと同じです。
7599 @c COMMON
7600
7601 @c EN
7602 A sparse table works just like a hash table, but it uses
7603 a sparse vector to store the values using hashed number of the keys.
7604 @c JP
7605 疎テーブルはハッシュテーブルと同じように動作しますが、キーのハッシュ値を
7606 インデックスとして値を疎ベクタに格納しています。
7607 @c COMMON
7608
7609 @c EN
7610 The main reason of these sparse data containers are for
7611 memory efficiency. If you want to store values in a vector
7612 but knows you'll use only some entries sparsely, obviously it
7613 is waste to allocate a large vector and to leave many entries unused.
7614 But it is worse than that; Gauche's GC doesn't like a large
7615 contiguous region of memory. Using lots of large vectors adds
7616 GC overhead quickly. It becomes especially visible when you
7617 store large number of entries (like >100,000) into hash tables,
7618 since Gauche's builtin hash tables use a flat vector as a backing
7619 storage. You'll see the heap size grows quickly and
7620 GC runs more frequently and longer.
7621 On the other hand, sparse table works pretty stable with
7622 large number of entries.
7623 @c JP
7624 これらの疎なデータコンテナの主な目的は、メモリ効率です。
7625 ベクタに値を入れておきたいけれどごく一部のインデックスしか使わないことが
7626 分かっている、と言った場合に、巨大なベクタをアロケートしてその大部分を
7627 使わないでおくのは明らかに無駄でしょう。ただそれだけではありません。
7628 Gaucheのガベージコレクタは、一続きの巨大なメモリ領域を確保するのとあまり
7629 相性が良くありません。大きなベクタを大量に使うとGCのオーバヘッドが急速に増えます。
7630 Gaucheの組み込みハッシュテーブルは
7631 データストアに通常のベクタを使っているのですが、
7632 大量のデータを詰め込むとその効果が目に見えてきます。ヒープサイズが急に増え、
7633 GCはより頻繁に走り、しかも一回一回に要する時間は長くなるでしょう。
7634 一方で、疎テーブルは大量のデータに対してもかなり安定に動作します。
7635 @c COMMON
7636
7637 @c EN
7638 Sparse data containers does have overhead on access speed.
7639 They are a bit slower than the ordinary hash tables,
7640 and much slower than ordinary vectors. We should note, however,
7641 as the number of entries grow, access time on ordinary hash
7642 tables grows quicker than sparse tables and eventually two become
7643 comparable.
7644 @c JP
7645 疎なデータコンテナは、単純なデータコンテナに比べるとアクセスにオーバヘッドはあります。
7646 通常のハッシュテーブルより若干遅いですし、通常のベクタと比べるとかなり遅いです。
7647 けれども、テーブル内のデータ数が大きくなる領域では、通常のハッシュテーブルの
7648 アクセス時間の方が急速に悪化するため、いずれ二つのアクセス時間は
7649 そこそこ同じになります。
7650 @c COMMON
7651
7652 @c EN
7653 It depends on your application which you should use, and
7654 if you're not sure, you need to benchmark.
7655 As a rule of thumb, if you use more than several hashtables
7656 each of which contains more than a few tens of thousands of
7657 entries, sparse tables may work better.
7658 If you see GC Warnings telling ``repeated allocation of large
7659 blocks'', you should definitely consider sparse tables.
7660 @c JP
7661 どちらを使うべきかはアプリケーションに依存します。良く分からないのであれば、
7662 ベンチマークを取りましょう。簡単な基準としては、数万以上のエントリを持つ
7663 ハッシュテーブルを数個以上作るなら、疎テーブルの方が良くなるかもしれません。
7664 実行中に``repeated allocation of large blocks''というGCからの
7665 警告を目にしたなら、疎テーブルへの切り替えを考えてみましょう。
7666 @c COMMON
7667
7668 @menu
7669 * Sparse vectors::
7670 * Sparse matrixes::
7671 * Sparse tables::
7672 @end menu
7673
7674 @node Sparse vectors, Sparse matrixes, Sparse data containers, Sparse data containers
7675 @subsection Sparse vectors
7676 @c NODE 疎なベクタ
7677
7678 @deftp {Class} <sparse-vector-base>
7679 @clindex sparse-vector-base
7680 @c MOD data.sparse
7681 @c EN
7682 An abstract base class of sparse vectors.
7683 Inherits @code{<dictionary>} and @code{<collection>}.
7684 Note that sparse vectors are @emph{not} @code{<sequence>}; even
7685 they can be indexable by integers, they don't have
7686 means of @emph{ordered} access.
7687
7688 Sparse vector may be a general vector
7689 that can contain any Scheme objects (like @code{<vector>}),
7690 or a specialized vector that can contain only certain
7691 types of numbers (like @code{<s8vector>} etc.).
7692
7693 All of these sparse vectors can be accessed by the same API.
7694
7695 Sparse vectors also implements the Collection API
7696 (@pxref{Collection framework}) and the Dictionary API
7697 (@pxref{Dictionary framework}).
7698 @c JP
7699 疎なベクタの抽象ベースクラスです。@code{<dictionary>}と@code{<collection>}を
7700 継承しています。@code{<sequence>}は継承していないことに注意してください。
7701 疎なベクタは整数でインデクス可能ですが、インデクスの順番に要素にアクセスする手段を
7702 持っていません。
7703
7704 疎なベクタは、@code{<vector>}と同様、任意のSchemeオブジェクトを格納可能である
7705 ものもあれば、@code{<s8vector>}等と同様に特定の範囲の数値のみ格納可能なものもあります。
7706 全ての疎なベクタは同一セットのAPIで利用可能です。
7707
7708 疎なベクタはまた、コレクションAPIとディクショナリAPIを実装しています。これらについては
7709 @ref{Collection framework}および@ref{Dictionary framework}を
7710 参照してください。
7711 @c COMMON
7712 @end deftp
7713
7714 @deftp {Class} <sparse-vector>
7715 @deftpx {Class} <sparse-@@vector>
7716 @clindex sparse-vector
7717 @clindex sparse-s8vector
7718 @clindex sparse-u8vector
7719 @clindex sparse-s16vector
7720 @clindex sparse-u16vector
7721 @clindex sparse-s32vector
7722 @clindex sparse-u32vector
7723 @clindex sparse-s64vector
7724 @clindex sparse-u64vector
7725 @clindex sparse-f16vector
7726 @clindex sparse-f32vector
7727 @clindex sparse-f64vector
7728 @c MOD data.sparse
7729 @c EN
7730 The actual sparse vector classes. Inherits @code{<sparse-vector-base>}.
7731 An instance of @code{<sparse-vector>} can contain any Scheme objects.
7732
7733 @code{@@} is either one of @code{s8}, @code{u8},
7734 @code{s16}, @code{u16}, @code{s32}, @code{u32},
7735 @code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
7736 The range of values an instance of those classes can hold
7737 is the same as the corresponding @code{<@@vector>} class
7738 in @code{gauche.uvector} (@pxref{Uniform vectors}). That is,
7739 @code{<sparse-u8vector>} can have exact integer values
7740 between 0 and 255.
7741 @c JP
7742 疎なベクタの具体クラスです。それぞれ@code{<sparse-vector-base>}を継承します。
7743
7744 @code{<sparse-vector>}のインスタンスは任意のSchemeオブジェクトを格納できます。
7745
7746 @code{@@}は @code{s8}, @code{u8},
7747 @code{s16}, @code{u16}, @code{s32}, @code{u32},
7748 @code{s64}, @code{u64}, @code{f16}, @code{f32}, @code{f64}のいずれかで、
7749 それぞれの疎なベクタの格納可能な値は、@code{gauche.uvector}の
7750 対応する@code{<@@vector>}に準じます(@ref{Uniform vectors}参照)。
7751 つまり、@code{<sparse-u8vector>}の要素には0以上255以下の正確な整数を
7752 格納できます。
7753 @c COMMON
7754 @end deftp
7755
7756 @defun make-sparse-vector :optional type :key default
7757 @c MOD data.sparse
7758 @c EN
7759 Creates an empty sparse vector. The @var{type} argument can be
7760 @code{#f} (default), one of subclasses of @code{<sparse-vector-base>},
7761 or a symbol of either one of @code{s8}, @code{u8},
7762 @code{s16}, @code{u16}, @code{s32}, @code{u32},
7763 @code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
7764
7765 If @var{type} is omitted or @code{#f}, a @code{<sparse-vector>} is
7766 created. If it is a class, an instance of the class is created
7767 (It is an error to pass a class that is not a subclass of
7768 @code{<sparse-vector-base>}.)
7769 If it is a symbol, an instance of corresponding @code{<sparse-@@vector>}
7770 is created.
7771 @c JP
7772 空の疎なベクタを作成して返します。@var{type}引数は@code{#f}(デフォルト)か、
7773 @code{<sparse-vector-base>}のサブクラスのどれか、
7774 あるいはシンボル@code{s8}, @code{u8},
7775 @code{s16}, @code{u16}, @code{s32}, @code{u32},
7776 @code{s64}, @code{u64}, @code{f16}, @code{f32}, @code{f64}のいずれかを
7777 指定できます。
7778
7779 @var{type}が省略されるか@code{#f}の場合は@code{<sparse-vector>}のインスタンスが
7780 作られます。@var{type}がクラスであればそのインスタンスが、またシンボルであれば、
7781 対応する@code{<sparse-@@vector>}のインスタンスが作られます。
7782 @c COMMON
7783
7784 @c EN
7785 You can specify the default value of the vector by @var{default}
7786 keyword argument. If given, the vector behaves as if it is filled
7787 with the default value (but the vector iterator only picks
7788 the values explicitly set).
7789
7790 Note that you have to give the optional argument as well
7791 to specify the keyword argument.
7792 @c JP
7793 キーワード引数@var{default}によって、作成するベクタの要素既定値を指定できます。
7794 この引数が与えられると、ベクタは全てあらかじめその値で埋められているかのように
7795 振る舞います (ただしイテレータは陽にセットされた値のみ取り出します)。
7796
7797 キーワード引数を与える場合、それに先立って省略可能引数も与える必要が
7798 あることに注意してください。
7799 @c COMMON
7800
7801 @example
7802 (define v (make-sparse-vector 'u8 :default 128))
7803
7804 (sparse-vector-ref v 0) @result{} 128
7805 @end example
7806 @end defun
7807
7808 @defun sparse-vector-max-index-bits
7809 @c MOD data.sparse
7810 @c EN
7811 Returns maximum number of bits of allowed integer. If this
7812 returns 32, the index up to @code{(expt 2 32)} is supported.
7813 It is guaranteed that this is at least 32.
7814 @c JP
7815 実装が利用できる、疎なベクタのインデックスの最大のビット数を返します。
7816 例えばこれが32を返したなら、インデックスとして@code{(expt 2 32)}まで
7817 使えるということです。この値は最低でも32であることが保証されています。
7818 @c COMMON
7819 @end defun
7820
7821 @c EN
7822 In the following entries, the argument @var{sv} denotes
7823 an instance of sparse vector; an error is signaled if other
7824 object is passed.
7825 @c JP
7826 以下のエントリにおいて、引数@var{sv}は疎なベクタのインスタンスです。
7827 他のオブジェクトが渡された場合はエラーが報告されます。
7828 @c COMMON
7829
7830 @defun sparse-vector-copy sv
7831 @c MOD data.sparse
7832 @c EN
7833 Returns a copy of a sparse vector @var{sv}.
7834 @c JP
7835 疎なベクタ@var{sv}のコピーを返します。
7836 @c COMMON
7837 @end defun
7838
7839 @defun sparse-vector-ref sv k :optional fallback
7840 @c MOD data.sparse
7841 @c EN
7842 Returns @var{k}-th element of a sparse vector @var{sv}, where
7843 @var{k} must an exact integer.
7844
7845 If the sparse vector doesn't have a value for @var{k}, it
7846 behaves as follows:
7847
7848 @itemize @bullet
7849 @item
7850 If @var{fallback} is given, it is returned.
7851 @item
7852 Otherwise, if the vector has the default value, it is returned.
7853 @item
7854 Otherwise, an error is signaled.
7855 @end itemize
7856 @c JP
7857 疎なベクタ@var{sv}のインデックス@var{k}にある要素を返します。
7858 @var{k}は正確な整数でなければなりません。
7859
7860 @var{k}に対応する要素がない場合は、次のように振る舞います。
7861
7862 @itemize @bullet
7863 @item
7864 @var{fallback}引数が与えられていればそれを返します。
7865 @item
7866 そうでなく、ベクタが既定値を持っていれば、それを返します。
7867 @item
7868 そうでなければ、エラーが報告されます。
7869 @end itemize
7870 @c COMMON
7871 @end defun
7872
7873 @defun sparse-vector-set! sv k value
7874 @c MOD data.sparse
7875 @c EN
7876 Sets @var{value} for @var{k}-th element of a sparse vector @var{sv}.
7877 @var{K} must be a nonnegative exact integer, and below the maximum
7878 allowed index.
7879
7880 If @var{sv} is a numeric sparse vector, @var{value} must also be
7881 within the allowed range, or an error is signaled.
7882 @c JP
7883 疎なベクタ@var{sv}の@var{k}番めの要素に@var{value}を設定します。
7884 @var{k}は非負の正確な整数で、許される最大のインデックス以下でなければなりません。
7885 @c COMMON
7886 @end defun
7887
7888 @defun sparse-vector-num-entries sv
7889 @c MOD data.sparse
7890 @c EN
7891 Returns the number of entries in @var{sv}.
7892 @c JP
7893 @var{sv}の持つ要素数を返します。
7894 @c COMMON
7895 @end defun
7896
7897 @defun sparse-vector-exists? sv k
7898 @c MOD data.sparse
7899 @c EN
7900 Returns @code{#t} if @var{sv} has an entry for index @var{k},
7901 @code{#f} otherwise.
7902 @c JP
7903 @var{sv}の@var{k}番目のエントリが値を持っていれば@code{#t}を、
7904 そうでなければ@code{#f}を返します。
7905 @code{#t}
7906 @c COMMON
7907 @end defun
7908
7909 @defun sparse-vector-delete! sv k
7910 @c MOD data.sparse
7911 @c EN
7912 Deletes the @var{k}-th entry of @var{sv}. If @var{sv} had the entry ,
7913 returns @code{#t}. If @var{sv} didn't have the entry, returns @code{#f}.
7914 @c JP
7915 @var{sv}の@var{k}番目のエントリが値を持っていれば、それを消去して
7916 @code{#t}を返します。
7917 そうでなければ何もせずに@code{#f}を返します。
7918 @c COMMON
7919 @end defun
7920
7921 @defun sparse-vector-clear! sv
7922 @c MOD data.sparse
7923 @c EN
7924 Empties a sparse vector.
7925 @c JP
7926 疎なベクタを空にします。
7927 @c COMMON
7928 @end defun
7929
7930 @defun sparse-vector-inc! sv k delta :optional (fallback 0)
7931 @c MOD data.sparse
7932 @c EN
7933 @c EN
7934 This is a shortcut of the following. It is especially efficient
7935 for numeric sparse vectors.
7936
7937 @example
7938 (sparse-vector-set! sv k (+ (sparse-vector-ref sv k fallback) delta))
7939 @end example
7940
7941 If the result of addition exceeds the allowed value range of @var{sv},
7942 an error is signaled. In future we'll allow an option to clamp
7943 the result value within the range.
7944 @c JP
7945 これは次のコードと同じ動作をしますが、数値を格納する疎ベクタでは特に
7946 効率よく動作します。
7947
7948 @example
7949 (sparse-vector-set! sv k (+ (sparse-vector-ref sv k fallback) delta))
7950 @end example
7951
7952 もし加算の結果が@var{sv}に許される数値の範囲を越えた場合は、
7953 エラーが投げられます。将来はそういった場合に値をクランプするオプションも
7954 用意する予定です。
7955 @c COMMON
7956 @end defun
7957
7958 @defun sparse-vector-update! sv k proc :optional fallback
7959 @defunx sparse-vector-push! sv k val
7960 @defunx sparse-vector-pop! sv k :optional fallback
7961 @c MOD data.sparse
7962 @c EN
7963 Convenience routines to fetch-and-update an entry of
7964 a sparse vector. Works just like @code{hash-table-update!},
7965 @code{hash-table-push!} and @code{hash-table-pop!};
7966 (@pxref{Hashtables}).
7967 @c JP
7968 疎なベクタのエントリの値を取り出してアップデートするパターンを
7969 簡単に書くためのルーチンです。それぞれ、@code{hash-table-update!}、
7970 @code{hash-table-push!}、@code{hash-table-pop!}と
7971 同じように動作します。(@ref{Hashtables}参照)。
7972 @c COMMON
7973 @end defun
7974
7975 @c EN
7976 The following procedures traverses a sparse vector.
7977 Note that elements are not visited in the order of index;
7978 it's just like hash table traversers.
7979 @c JP
7980 以下の手続きは疎なベクタの要素を横断します。
7981 要素は必ずしもインデックスの順に訪問されるわけではないことに注意してください。
7982 その点ではハッシュテーブルの横断と似ています。
7983 @c COMMON
7984
7985 @c EN
7986 At this moment, if you want to walk a sparse vector with
7987 increasing/decreasing index order, you have to get a list
7988 of keys by @code{sparse-vector-keys}, sort it, then use
7989 it to retrieve values.
7990 We may add an option in future to @code{make-sparse-vector} so that
7991 those walk operation will be more convenient.
7992 @c JP
7993 今のところ、疎なベクタをインデックスの昇順/降順に処理したい場合は、
7994 @code{sparse-vector-keys}で全てのキーを得て、
7995 それをソートしたもので順に値を取り出してゆくしかありません。
7996 将来は、@code{make-sparse-vector}にオプションをつけて
7997 インデックスの順番による横断を簡単にするかもしれません。
7998 @c COMMON
7999
8000 @defun sparse-vector-fold sv proc seed
8001 @c MOD data.sparse
8002 @c EN
8003 For each entry in @var{sv}, calls @var{proc} as
8004 @code{(proc @var{k_n} @var{v_n} @var{seed_n})}, where
8005 @var{k_n} is an index and @var{v_n} is a value for it,
8006 and @var{seed_n} is the returned value of the previous
8007 call to @var{proc} if @var{n} @code{>=} 1, and @var{seed} if @var{n} = 0.
8008 Returns the value of the last call of @var{proc}.
8009 @c JP
8010 @var{sv}の各エントリに対し、手続き@var{proc}を
8011 @code{(proc @var{k_n} @var{v_n} @var{seed_n})}のように呼び出してゆきます。
8012 ここで@var{seed_n}は@var{n} @code{>=} 1の時は直前の@var{proc}の戻り値、
8013 @var{n} = 0の時は引数@var{seed}です。
8014 最後の@var{proc}の戻り値を返します。
8015 @c COMMON
8016 @end defun
8017
8018 @defun sparse-vector-for-each sv proc
8019 @defunx sparse-vector-map sv proc
8020 @c MOD data.sparse
8021 Calls @code{proc} with index and value, e.g. @code{(proc k value)},
8022 for each element of @var{sv}.
8023
8024 The results of @var{proc} are discarded by @code{sparse-vector-for-each},
8025 and gathered to a list and returned by @code{sparse-vector-map}.
8026 @end defun
8027
8028 @defun sparse-vector-keys sv
8029 @defunx sparse-vector-values sv
8030 @c MOD data.sparse
8031 @c EN
8032 Returns a list of all keys and all values in @var{sv}, respectively.
8033 @c JP
8034 それぞれ、@var{sv}中の全てのキー、または全ての値をリストにして返します。
8035 @c COMMON
8036 @end defun
8037
8038 @node Sparse matrixes, Sparse tables, Sparse vectors, Sparse data containers
8039 @subsection Sparse matrixes
8040 @c NODE 疎行列
8041
8042 @c EN
8043 A sparse matrix is like a sparse vector, except it can be indexed
8044 by two nonnegative integers.
8045 @c JP
8046 疎行列は要素が2つの非負整数でインデックスされること以外は疎なベクタと同じです。
8047 @c COMMON
8048
8049 @c EN
8050 Note: This implementation of sparse matrixes aims at a reasonable
8051 space efficiency for sparse matrixes without knowing its structure
8052 beforehand (imagine, for example, a 2D map with some scattered landmarks).
8053 If what you want is a sparse matrix implementation for efficient numeric
8054 calculations, with certain particular structures,
8055 probably the access speed of this module isn't suitable.
8056 @c JP
8057 註:この疎行列の実装は、事前に構造が分かっていない疎な行列をそれなりに空間効率良く
8058 扱うことを目的としています(例えば、2Dのマップにランドマークを記録してゆく、
8059 といったイメージです)。もし探しているものが、数値計算用に特定の構造を持つ疎行列の
8060 実装でしたら、このモジュールは速度的に十分ではないでしょう。
8061 @c COMMON
8062
8063 @c EN
8064 Currently, each index can have half of bits of
8065 @code{sparse-vector-max-index-bits}. We'll remove
8066 this limitation in future.
8067 @c JP
8068 現在の実装では、それぞれのインデックスの最大ビット数が
8069 @code{sparse-vector-max-index-bits}の半分までという制限があります。
8070 将来はこの制限をなくす予定です。
8071 @c COMMON
8072
8073
8074 @deftp {Class} <sparse-matrix-base>
8075 @clindex sparse-matrix-base
8076 @c MOD data.sparse
8077 An abstract base class of sparse matrixes. Inherits @code{<collection>}.
8078
8079 Like sparse vectors, a sparse matrix can be of type that
8080 can store any Scheme objects, or that can store only
8081 certain types of numbers.
8082
8083 All of these sparse matrix subtypes can be accessed by the same API.
8084 @end deftp
8085
8086 @deftp {Class} <sparse-matrix>
8087 @deftpx {Class} <sparse-@@matrix>
8088 @clindex sparse-matrix
8089 @clindex sparse-s8matrix
8090 @clindex sparse-u8matrix
8091 @clindex sparse-s16matrix
8092 @clindex sparse-u16matrix
8093 @clindex sparse-s32matrix
8094 @clindex sparse-u32matrix
8095 @clindex sparse-s64matrix
8096 @clindex sparse-u64matrix
8097 @clindex sparse-f16matrix
8098 @clindex sparse-f32matrix
8099 @clindex sparse-f64matrix
8100 @c MOD data.sparse
8101 The actual sparse matrix classes. Inherits @code{<sparse-matrix-base>}.
8102 An instance of @code{<sparse-matrix>} can contain any Scheme objects.
8103
8104 @code{@@} is either one of @code{s8}, @code{u8},
8105 @code{s16}, @code{u16}, @code{s32}, @code{u32},
8106 @code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
8107 The range of values an instance of those classes can hold
8108 is the same as the corresponding @code{<@@vector>} class
8109 in @code{gauche.uvector} (@pxref{Uniform vectors}). That is,
8110 @code{<sparse-u8matrix>} can have exact integer values
8111 between 0 and 255.
8112 @end deftp
8113
8114 @defun make-sparse-matrix :optional type :key default
8115 @c MOD data.sparse
8116 Creates an empty sparse matrix. The @var{type} argument can be
8117 @code{#f} (default), one of subclasses of @code{<sparse-matrix-base>},
8118 or a symbol of either one of @code{s8}, @code{u8},
8119 @code{s16}, @code{u16}, @code{s32}, @code{u32},
8120 @code{s64}, @code{u64}, @code{f16}, @code{f32}, or @code{f64}.
8121
8122 If @var{type} is omitted or @code{#f}, a @code{<sparse-matrix>} is
8123 created. If it is a class, an instance of the class is created
8124 (It is an error to pass a class that is not a subclass of
8125 @code{<sparse-matrix-base>}.)
8126 If it is a symbol, an instance of corresponding @code{<sparse-@@matrix>}
8127 is created.
8128
8129 You can specify the default value of the matrix by @var{default}
8130 keyword argument. If given, the vector behaves as if it is filled
8131 with the default value (but the matrix iterator only picks
8132 the values explicitly set).
8133
8134 Note that you have to give the optional argument as well
8135 to specify the keyword argument.
8136 @end defun
8137
8138 @defun sparse-matrix-num-entries mat
8139 @c MOD data.sparse
8140 Returns the number of entries explicitly set in a sparse matrix @var{mat}.
8141 @end defun
8142
8143 @defun sparse-matrix-ref mat x y :optional fallback
8144 @c MOD data.sparse
8145 Returns an element indexed by (@var{x}, @var{y}) in a sparse matrix @var{mat}.
8146 If the indexed element isn't set, @var{fallback} is returned if provided;
8147 otherwise, if the matrix has the default value, it is returned; otherwise,
8148 an error is raised.
8149 @end defun
8150
8151 @defun sparse-matrix-set! mat x y value
8152 @c MOD data.sparse
8153 Set @var{value} to the sparse matrix @var{mat} at the location
8154 (@var{x}, @var{y}).
8155 @end defun
8156
8157 @defun sparse-matrix-exists? mat x y
8158 @c MOD data.sparse
8159 Returns @code{#t} iff the sparse matrix @var{mat} has a value at
8160 (@var{x}, @var{y}).
8161 @end defun
8162
8163 @defun sparse-matrix-clear! mat
8164 @c MOD data.sparse
8165 Empties the sparse matrix @var{mat}.
8166 @end defun
8167
8168 @defun sparse-matrix-delete! mat x y
8169 @c MOD data.sparse
8170 Remove the value at (@var{x}, @var{y}) from the sparse matrix @var{mat}.
8171 @end defun
8172
8173 @defun sparse-matrix-copy mat
8174 @c MOD data.sparse
8175 Returns a fresh copy of @var{mat}.
8176 @end defun
8177
8178 @defun sparse-matrix-update! mat x y proc :optional fallback
8179 @c MOD data.sparse
8180 Call @var{proc} with the value at (@var{x}, @var{y}) of the sparse matrix,
8181 and sets the result of @var{proc} as the new value of the location.
8182
8183 The optional @var{fallback} argument works just like @code{sparse-matrix-ref};
8184 if provided, it is passed to @var{proc} in case the
8185 matrix doesn't have a value at (@var{x}, @var{y}).
8186 If @var{fallback} isn't provided and the matrix doesn't have a value
8187 at the location, the default value of the matrix is used if it has one.
8188 Otherwise, an error is signalled.
8189 @end defun
8190
8191 @defun sparse-matrix-inc! mat x y delta :optional fallback
8192 @c MOD data.sparse
8193 @example
8194 (sparse-matrix-update! mat x y (cut + <> delta) fallback)
8195 @end example
8196 @end defun
8197
8198 @defun sparse-matrix-push! mat x y val
8199 @c MOD data.sparse
8200 @example
8201 (sparse-matrix-update! mat x y (cut cons val <>) '())
8202 @end example
8203 @end defun
8204
8205 @defun sparse-matrix-pop! mat x y
8206 @c MOD data.sparse
8207 @example
8208 (rlet1 r #f
8209 (sparse-matrix-update! mat x y (^p (set! r (car p)) (cdr p))))
8210 @end example
8211 @end defun
8212
8213 @defun sparse-matrix-fold mat proc seed
8214 @c MOD data.sparse
8215 Loop over values in the sparse matrix @var{mat}. The procedure
8216 @var{proc} is called with four arguments, @var{x}, @var{y}, @var{val}
8217 and @var{seed}, for each index (@var{x}, @var{y}) which has the value
8218 @var{val}. The initial value of @var{seed} is the one given to
8219 @code{sparse-matrix-fold}, and the result of @var{proc} is passed
8220 as the next seed value. The last result of @var{proc} is returned
8221 from @code{sparse-matrix-fold}.
8222
8223 The procedure @var{proc} is only called on the entries that's actually
8224 has a value, and the order of which the procedure is called is undefined.
8225 @end defun
8226
8227 @defun sparse-matrix-map mat proc
8228 @c MOD data.sparse
8229 @example
8230 (sparse-matrix-fold sv (^[x y v s] (cons (proc x y v) s)) '()))
8231 @end example
8232 @end defun
8233
8234 @defun sparse-matrix-for-each mat proc
8235 @c MOD data.sparse
8236 @example
8237 (sparse-matrix-fold sv (^[x y v _] (proc x y v)) #f))
8238 @end example
8239 @end defun
8240
8241 @defun sparse-matrix-keys mat
8242 @c MOD data.sparse
8243 @example
8244 (sparse-matrix-fold sv (^[x y _ s] (cons (list x y) s)) '())
8245 @end example
8246 @end defun
8247
8248 @defun sparse-matrix-values mat
8249 @c MOD data.sparse
8250 @example
8251 (sparse-matrix-fold sv (^[x y v s] (cons v s)) '())
8252 @end example
8253 @end defun
8254
8255 @node Sparse tables, , Sparse matrixes, Sparse data containers
8256 @subsection Sparse tables
8257 @c NODE 疎なテーブル
8258
8259 @deftp {Class} <sparse-table>
8260 @clindex sparse-table
8261 @c MOD data.sparse
8262 A class for sparse table. Inherits @code{<dictionary>} and
8263 @code{<collection>}.
8264
8265 Operationally sparse tables are the same as hash tables, but
8266 the former consumes less memory in trade of slight slower access.
8267 (Roughly x1.5 to x2 access time when the table is small.
8268 As the table gets larger the difference becomes smaller.)
8269 @end deftp
8270
8271 @defun make-sparse-table comparator
8272 @c MOD data.sparse
8273 Creates and returns an empty sparse table.
8274 The @var{comparator} argument specifies how to compare and hash keys;
8275 it must be either a comparator (@pxref{Basic comparators}),
8276 or one of the symbols @code{eq?}, @code{eqv?}, @code{equal?} and
8277 @code{string=?}, like hash tables (@pxref{Hashtables}). If it is a symbol,
8278 @code{eq-comparator}, @code{eqv-comparator}, @code{equal-comparator} or
8279 @code{string-comparator} are used, respectively.
8280 @end defun
8281
8282 @defun sparse-table-comparator st
8283 @c MOD data.sparse
8284 Returns the comparator used in the sparse table @var{st}.
8285 @end defun
8286
8287 @defun sparse-table-copy st
8288 @c MOD data.sparse
8289 Returns a copy of a sparse table @var{st}.
8290 @end defun
8291
8292 @defun sparse-table-num-entries st
8293 @c MOD data.sparse
8294 Returns the number of entries in a sparse table @var{st}.
8295 @end defun
8296
8297 @defun sparse-table-ref st key :optional fallback
8298 @c MOD data.sparse
8299 Retrieves a value associated to the @var{key} in @var{st}.
8300 If no entry with @var{key} exists, @var{fallback} is returned
8301 when it is provided, or an error is signaled otherwise.
8302 @end defun
8303
8304 @defun sparse-table-set! st key value
8305 @c MOD data.sparse
8306 Sets @var{value} with @var{key} in @var{st}.
8307 @end defun
8308
8309 @defun sparse-table-exists? st key
8310 @c MOD data.sparse
8311 Returns @code{#t} if an entry with @var{key} exists in @var{st},
8312 @code{#f} otherwise.
8313 @end defun
8314
8315 @defun sparse-table-delete! st key
8316 @c MOD data.sparse
8317 Deletes an entry with @var{key} in @var{st} if it exists.
8318 Returns @code{#t} if an entry is actually deleted, or @code{#f}
8319 if there hasn't been an entry with @var{key}.
8320 @end defun
8321
8322 @defun sparse-table-clear! st
8323 @c MOD data.sparse
8324 Empties @var{st}.
8325 @end defun
8326
8327 @defun sparse-table-update! st key proc :optional fallback
8328 @defunx sparse-table-push! st key val
8329 @defunx sparse-table-pop! st key :optional fallback
8330 @c MOD data.sparse
8331 @end defun
8332
8333 @defun sparse-table-fold st proc seed
8334 @defunx sparse-table-for-each st proc
8335 @defunx sparse-table-map st proc
8336 @c MOD data.sparse
8337 @end defun
8338
8339 @defun sparse-table-keys st
8340 @defunx sparse-table-values st
8341 @c MOD data.sparse
8342 @end defun
8343
8344 @c ----------------------------------------------------------------------
8345 @node Trie, Universally unique lexicographically sortable identifier, Sparse data containers, Library modules - Utilities
8346 @section @code{data.trie} - Trie
8347 @c NODE Trie, @code{data.trie} - Trie
8348
8349 @deftp {Module} data.trie
8350 @mdindex data.trie
8351 @c EN
8352 This module provides @emph{Trie}, a dictionary-like data
8353 structure that maps keys to values, where a key is an arbitrary sequence.
8354 Internally it stores the data as a tree where each node corresponds
8355 to each element in the key sequence.
8356 Key lookup is O(n) where n is the length of the key, and not affected
8357 much by the number of total entries.
8358 Also it is easy to find a set of values whose keys share a common prefix.
8359 @c JP
8360 このモジュールは@emph{Trie}を提供します。@emph{Trie}はディレクトリに似
8361 たデータ構造で、キーを値に写像します。また、キーは任意のシーケンスです。
8362 内部的にはデータはツリーとして保持されます。このとき各ノードがキーシー
8363 ケンスの各要素に対応します。キーの検索は O(n) で、n はキーの長さです。
8364 したがって、全体のエントリ数には余り影響を受けません。また、キーが共通
8365 の接頭辞をもつような値の集合を簡単にみつけられます。
8366 @c COMMON
8367
8368 @c EN
8369 The following example may give you the idea.
8370 @c JP
8371 以下のサンプルを見れば考え方が理解できると思います。
8372 @c COMMON
8373
8374 @example
8375 (define t (make-trie)) ;; create a trie
8376
8377 (trie-put! t "pho" 3) ;; populate the trie
8378 (trie-put! t "phone" 5)
8379 (trie-put! t "phrase" 6)
8380
8381 (trie-get t "phone") @result{} 5 ;; lookup
8382
8383 (trie-common-prefix t "pho") ;; common prefix search
8384 @result{} (("phone" . 5) ("pho" . 3))
8385 (trie-common-prefix-keys t "ph")
8386 @result{} ("phone" "pho" "phrase")
8387 @end example
8388
8389 @c EN
8390 Tries are frequently used with string keys, but you are not
8391 limited to do so; any sequence (@pxref{Sequence framework}) can be
8392 a key. If the types of keys differ, they are treated as different
8393 keys:
8394 @c JP
8395 Trieでは文字列キーを使うことが多いですが、それに限定される必要はありま
8396 せん。あらゆるシーケンス(@pxref{Sequence framework})をキーにすることが
8397 できます。キーの型が違えば、別のキーとして扱われます。
8398 @c COMMON
8399
8400 @example
8401 (trie-put! t '(#\p #\h #\o) 8) ;; different key from "pho"
8402 @end example
8403
8404 @c EN
8405 Trie inherits @code{<collection>} and implements collection framework
8406 including the builder. So you can apply generic collection
8407 operations on a trie (@pxref{Collection framework}).
8408 When iterated, each element of a trie appears as a pair of a key
8409 and a value.
8410 @c JP
8411 Trieは@code{<collection>}を継承しており、コレクションフレームワークを
8412 ビルダも含めて実装しています。それゆえ、ジェネリックなコレクション操作
8413 をTrieに適用することが可能です(@ref{Collection framework}参照)。
8414 反復するとTrieの各要素がキーと値の対として現れます。
8415 @c COMMON
8416 @end deftp
8417
8418 @deftp {Class} <trie>
8419 @clindex trie
8420 @c MOD data.trie
8421 @c EN
8422 A class for Trie. No slots are intended for public.
8423 Use the following procedures to operate on tries.
8424 @c JP
8425 Trieクラス。パブリックなスロットはありません。trieを操作するには以下の
8426 手続きを使ってください。
8427 @c COMMON
8428
8429 @c EN
8430 This class also implements the dictionary interface
8431 (@pxref{Generic functions for dictionaries}).
8432 @c JP
8433 このクラスはまた、ディクショナリインタフェースを実装しています
8434 (@ref{Generic functions for dictionaries}参照)。
8435 @c COMMON
8436 @end deftp
8437
8438 @defun make-trie :optional tab-make tab-get tab-put! tab-fold tab-empty?
8439 @c MOD data.trie
8440 @c EN
8441 Creates and returns an empty trie. The optional arguments
8442 are procedures to customize how the nodes of the internal
8443 tree are managed.
8444 @c JP
8445 空のtrieを生成し返します。オプション引数は、
8446 内部木のノードをどのようにマージするかをカスタマイズする手続きです。
8447 @c COMMON
8448
8449 @c EN
8450 Each node can have a table to store its child nodes, indexed
8451 by an element of the key sequence (e.g. if the trie uses strings
8452 as keys, a node's table is indexed by characters).
8453 @c JP
8454 それぞれのノードは子のノードを格納するテーブルを持つことができます。
8455 キーシーケンスの要素でインデックスできます。(たとえば、trieがキーとし
8456 え文字列を使っているとすると、ノードのテーブルは文字でインデックスされ
8457 ています。)
8458 @c COMMON
8459
8460 @c EN
8461 @table @code
8462 @item tab-make
8463 A procedure with no arguments. When called, creates and
8464 returns an empty table for a node.
8465 @item tab-get @var{tab} @var{elt}
8466 Returns a child node indexed by @var{elt}, or returns @code{#f}
8467 if the table doesn't have a child for @var{elt}.
8468 @item tab-put! @var{tab} @var{elt} @var{child-node}
8469 If @var{child-node} isn't @code{#f},
8470 stores a @var{child-node} with index @var{elt}.
8471 If @var{child-node} is @code{#f},
8472 removes the entry with index @var{elt}.
8473 In both cases, this procedure should return the updated table.
8474 @item tab-fold @var{tab} @var{proc} @var{seed}
8475 Calls @var{proc} for every index and node in @var{tab}, while
8476 passing a seed value, whose initial value is @var{seed}.
8477 That is, @var{proc} has a type of @code{(index, node, seed) -> seed}.
8478 Should return the last result of @var{proc}.
8479 @item tab-empty? @var{tab}
8480 Returns @code{#t} if @var{tab} is empty, @code{#f} otherwise.
8481 You can omit or pass @code{#f} to this procedure; then we use
8482 @code{tab-fold} to check if @var{tab} is empty, which can be expensive.
8483 @end table
8484 @c JP
8485 @table @code
8486 @item tab-make
8487 引数なしの手続き。呼ばれるとノード用の空テーブルを生成し返します。
8488 @item tab-get @var{tab} @var{elt}
8489 @var{elt}でインデックスされた子ノードを返すか、あるいは@var{elt}に対応
8490 する子がテーブルにない場合には @code{#f}を返します。
8491 @item tab-put! @var{tab} @var{elt} @var{child-node}
8492 @var{child-node}が@code{#f}でなければ、@var{child-node}に@var{elt}とい
8493 うインデックスをつけて保存します。@var{child-node}が@code{#f}なら
8494 @var{elt}のインデックスをもつエントリを削除します。どちらの場合にも
8495 この手続きは更新されたテーブルを返します。
8496 @item tab-fold @var{tab} @var{proc} @var{seed}
8497 @var{tab}内の各インデックスと要素ごとに@var{proc}を呼びます。シード値
8498 が順に渡されていきます。シード値の初期値は@var{seed}です。すなわち、
8499 @var{proc}の型は@code{(index, node, seed) -> seed} のような型というこ
8500 とになります。返り値は最後の@var{proc}の適用結果です。
8501 @item tab-empty? @var{tab}
8502 @var{tab}が空なら@code{#t}を、そうでなければ@code{#f}を返す手続きです。
8503 この手続きは省略するか@code{#f}を渡すことができます。その場合は空かどうかを
8504 チェックするのに@code{tab-fold}手続きが使われますが、少々重くなるかもしれません。
8505 @end table
8506 @c COMMON
8507
8508 @c EN
8509 The default assumes @code{eqv?}-hashtables, i.e. the
8510 following procedures are used.
8511 @c JP
8512 デフォルトでは@code{eqv?}-ハッシュ可能であることが仮定されます。すなわ
8513 ち、以下の手続きが使われます。
8514 @c COMMON
8515
8516 @example
8517 tab-make: (lambda () (make-hash-table 'eqv?))
8518
8519 tab-get: (lambda (tab k) (hash-table-get tab k #f))
8520
8521 tab-put!: (lambda (tab k v)
8522 (if v
8523 (hash-table-put! tab k v)
8524 (hash-table-delete! tab k))
8525 tab)
8526
8527 tab-fold: hash-table-fold
8528
8529 tab-empty?: (lambda (tab) (zero? (hash-table-num-entries tab)))
8530 @end example
8531
8532 @c EN
8533 The following example creates a trie using
8534 assoc list to manage children, while comparing
8535 string keys with case-insensitive way:
8536 @c JP
8537 以下の例では子を管理するのに連想リストを用いるtrieを作成しています。
8538 文字列キーの比較は大文字小文字を無視する方法で行っています。
8539 @c COMMON
8540
8541 @example
8542 (make-trie list
8543 (cut assoc-ref <> <> #f char-ci=?)
8544 (lambda (t k v)
8545 (if v
8546 (assoc-set! t k v char-ci=?)
8547 (alist-delete! k t char-ci=?)))
8548 (lambda (t f s) (fold f s t))
8549 null?)
8550 @end example
8551
8552 @c EN
8553 It is important that @code{tab-put!} must return an updated
8554 table---by that, you can replace the table structure on the fly.
8555 For example, you may design a table which uses assoc list when
8556 the number of children are small, and then switches to a vector
8557 (indexed by character code) once the number of children grows over
8558 a certain threshold.
8559 @c JP
8560 @code{tab-put!}が更新されたテーブルを返すというのは重要で、これのおか
8561 げで、テーブル構造を実行中に置き換えることができます。たとえば、
8562 子の数が少い場合にはテーブルに連想リストを使い、いったん子の数がある閾
8563 値を越えたら、(文字コードでインデックスされた)ベクタを使うように設計す
8564 ることができます。
8565 @c COMMON
8566 @end defun
8567
8568 @defun trie params kv @dots{}
8569 @c MOD data.trie
8570 @c EN
8571 Construct a trie with the initial contents
8572 @var{kv} @dots{}, where each @var{kv} is a pair of a key and a value.
8573 @var{Params} are a list of arguments
8574 which will be given to @code{make-trie} to create the trie.
8575 The following example creates a trie with two entries
8576 and the default table procedures.
8577 @c JP
8578 初期の内容が@var{kv} @dots{} であるようなtrieを構成します。ここで、
8579 @var{kv}はキーと値の対です。@var{params}はtrieを生成するときに
8580 @code{make-trie}に渡される引数のリストです。以下の例は2つのエントリ
8581 とデフォルトのテーブル手続をもつtrieを生成します。
8582 @c COMMON
8583
8584 @example
8585 (trie '() '("foo" . a) '("bar" . b))
8586 @end example
8587 @end defun
8588
8589 @defun trie-with-keys params key @dots{}
8590 @c MOD data.trie
8591 @c EN
8592 A convenient version of @code{trie} when you only concern
8593 the keys. Each value is the same as its key.
8594 The following example creates a trie with two entries
8595 and the default table procedures.
8596 @c JP
8597 キーにだけ関心がある場合には便利な@code{trie}。各値はキーと同じ。以下
8598 の例では2つのエントリとデフォルトのテーブル手続をもつtrieを生成します。
8599 @c COMMON
8600
8601 @example
8602 (trie-with-keys '() "foo" "bar")
8603 @end example
8604 @end defun
8605
8606 @defun trie? obj
8607 @c MOD data.trie
8608 @c EN
8609 Returns @code{#t} if @var{obj} is a trie, or @code{#f} otherwise.
8610 @c JP
8611 @var{obj}がtrieなら@code{#t}を返し、さもなければ@code{#f}を返します。
8612 @c COMMON
8613 @end defun
8614
8615 @defun trie-num-entries trie
8616 @c MOD data.trie
8617 @c EN
8618 Returns the number of entries in @var{trie}.
8619 @c JP
8620 @var{trie}中のエントリの数を返します。
8621 @c COMMON
8622 @end defun
8623
8624 @defun trie-exists? trie key
8625 @c MOD data.trie
8626 @c EN
8627 Returns @code{#t} if @var{trie} contains an entry with @var{key},
8628 or returns @code{#f} otherwise.
8629 @c JP
8630 @var{trie}が@var{key}というキーのエントリを含む場合には@code{#t}を返し、
8631 さもなければ、@code{#f}を返します。
8632 @c COMMON
8633
8634 @example
8635 (let1 t (trie '() '("foo" . ok))
8636 (list (trie-exists? t "foo")
8637 (trie-exists? t "fo")
8638 (trie-exists? t "bar")))
8639 @result{} '(#t #f #f)
8640 @end example
8641 @end defun
8642
8643 @defun trie-partial-key? trie seq
8644 @c MOD data.trie
8645 @c EN
8646 Returns @code{#t} if there's at least one key in @var{trie} that is
8647 not equal to @var{seq} but @var{seq} matches its prefix. Note that
8648 @var{seq} may or may not a key of @var{trie}; see the example below.
8649 @c JP
8650 @var{trie}の中に少なくともひとつ、@var{seq}と同じではないが@var{seq}を
8651 プリフィクスとするようなキーがあれば@code{#t}を返します。
8652 @var{seq}と一致するキーが他にあるかないかは結果には影響を及ぼしません。
8653 下の例を見てください。
8654 @c COMMON
8655
8656 @example
8657 (define t (trie '() '("foo" . ok) '("fo" . ok)))
8658
8659 (trie-partial-key? t "f") @result{} #t
8660 (trie-partial-key? t "fo") @result{} #t
8661 (trie-partial-key? t "foo") @result{} #f
8662 (trie-partial-key? t "bar") @result{} #f
8663 @end example
8664 @end defun
8665
8666
8667 @defun trie-get trie key :optional fallback
8668 @c MOD data.trie
8669 @c EN
8670 Returns the value associated with @var{key} in @var{trie}, if
8671 such an entry exists. When there's no entry for @var{key},
8672 if @var{fallback} is given, it is returned; otherwise,
8673 an error is signaled.
8674 @c JP
8675 @var{trie}中の@var{key}をもつエントリがあれば、それにむすびついている
8676 値を返します。そのようなエントリがない場合、@var{fallback}が与えられて
8677 いればそれを返し、さもなければ、エラーシグナルがあがります。
8678 @c COMMON
8679 @end defun
8680
8681 @defun trie-put! trie key value
8682 @c MOD data.trie
8683 @c EN
8684 Puts @var{value} associated to @var{key} into @var{trie}.
8685 @c JP
8686 @var{key}に結びついた@var{value}を@var{trie}に挿入します。
8687 @c COMMON
8688 @end defun
8689
8690 @defun trie-update! trie key proc :optional fallback
8691 @c MOD data.trie
8692 @c EN
8693 Works like the following code, except that the
8694 lookup of entry in @var{trie} is done only once.
8695 @c JP
8696 @var{trie}中のエントリの検索が一度きりしか起らないことをのぞけば以下の
8697 コードのように動きます。
8698 @c COMMON
8699
8700 @example
8701 (let ((val (trie-get trie key fallback)))
8702 (trie-put! trie key (proc val)))
8703 @end example
8704 @end defun
8705
8706 @defun trie-delete! trie key
8707 @c MOD data.trie
8708 @c EN
8709 Removes an entry associated with @var{key} from @var{trie}.
8710 If there's no such entry, this procedure does nothing.
8711 @c JP
8712 @var{trie}から@var{key}に関連するエントリを削除します。
8713 そのようなエントリがない場合にはこの手続きはなにもしません。
8714 @c COMMON
8715 @end defun
8716
8717 @defun trie->list trie
8718 @c MOD data.trie
8719 @c EN
8720 Makes each entry in @var{trie} to a pair @code{(@var{key} . @var{value})}
8721 and returns a list of pairs of all entries. The order of entries
8722 are undefined.
8723 @c JP
8724 @var{trie}の各エントリを@code{(@var{key} . @var{value})}という対にして
8725 すべてのエントリの対のリストを返します。エントリの順序は未定義です。
8726 @c COMMON
8727 @end defun
8728
8729 @defun trie-keys trie
8730 @defunx trie-values trie
8731 @c MOD data.trie
8732 @c EN
8733 Returns a list of all keys and values in @var{trie}, respectively.
8734 The order of keys/values are undefined.
8735 @c JP
8736 それぞれ、@var{trie}のすべてのキーのリスト、すべての値のリストを返しま
8737 す。順序は未定義です。
8738 @c COMMON
8739 @end defun
8740
8741 @defun trie->hash-table trie ht-type
8742 @c MOD data.trie
8743 @c EN
8744 Creates a hash table with type @var{ht-type} (see @ref{Hashtables},
8745 about hash table types), and populates it with every key and value
8746 pair in @var{trie}.
8747 @c JP
8748 @var{ht-type}タイプのハッシュテーブル(ハッシュテーブルのタイプについて
8749 は@ref{Hashtables}を参照)を作成し、@var{trie}のすべてのキーと値の対を
8750 セットします。
8751 @c COMMON
8752 @end defun
8753
8754 @defun trie-longest-match trie seq :optional fallback
8755 @c MOD data.trie
8756 @c EN
8757 Returns a pair of the key and its value, where the key is the
8758 longest prefix of @var{seq}. If no such key is found, @var{fallback}
8759 is returned if it is provided, or an error is thrown.
8760
8761 Do not confuse this with @code{trie-common-prefix-*} procedures below;
8762 In this procedure, the key is the prefix of the given argument.
8763 In @code{trie-common-prefix-*} procedures, the given argument is
8764 the prefix of the keys.
8765 @c JP
8766 @var{seq}のプレフィクスになっているキーのうちもっとも長いものを見つけて、
8767 そのキーと値のペアを返します。そういったキーが見つからなかった場合は、
8768 @var{fallback}が与えられればそれを返し、なければエラーが通知されます。
8769
8770 この手続きと以下の@code{trie-common-prefix-*}手続きを混同しないようにしてください。
8771 この手続きでは、キーが引数のプレフィクスです。
8772 @code{trie-common-prefix-*}手続きでは、引数がキーのプレフィクスです。
8773 @c COMMON
8774
8775 @example
8776 (let1 t (make-trie)
8777 (trie-put! t "a" 'a)
8778 (trie-put! t "ab" 'ab)
8779
8780 (trie-longest-match t "abc") @result{} ("ab" . ab)
8781 (trie-longest-match t "acd") @result{} ("a" . a)
8782 (trie-longest-match t "ab") @result{} ("ab" . ab)
8783 (trie-longest-match t "zy") @result{} error
8784 )
8785 @end example
8786 @end defun
8787
8788
8789 @defun trie-common-prefix trie prefix
8790 @defunx trie-common-prefix-keys trie prefix
8791 @defunx trie-common-prefix-values trie prefix
8792 @c MOD data.trie
8793 @c EN
8794 Gathers all entries whose keys begin with @var{prefix};
8795 @code{trie-common-prefix} returns those entries in a list of
8796 pairs @code{(key . value)}; @code{trie-common-prefix-keys} returns
8797 a list of keys; and @code{trie-common-prefix-values} returns a list
8798 of values. The order of entries in a returned list is undefined.
8799 If @var{trie} contains no entry whose key has @var{prefix}, an
8800 empty list is returned.
8801 @c JP
8802 @var{prefix}ではじまるキーをもつエントリをすべて集め、
8803 @code{trie-common-prefix}はその各エントリを@code{(key . value)}の対にし
8804 たリストを返します。@code{trie-common-prefix-keys}は、キーのリストを
8805 @code{trie-common-prefix-values}は値のリストを返します。返されるリスト
8806 のエントリの順序は未定義です。
8807 @var{trie}に指定した@var{prefix}をもつキーのエントリがなければ、
8808 空リストが返されます。
8809 @c COMMON
8810
8811 @c EN
8812 Note that prefix matching doesn't consider the type of sequence;
8813 if @var{trie} has entries for @code{"foo"} and @code{(#\f #\o #\o)},
8814 @code{(trie-common-prefix trie "foo")} will return both entries.
8815 @c JP
8816 接頭辞照合ではシーケンスの型を考慮しないことに注意してください。
8817 @var{trie}のなかに@code{"foo"}と@code{(#\f #\o #\o)}に対応するエントリ
8818 があれば、@code{(trie-common-prefix trie "foo")}はその両方を返します。
8819 @c COMMON
8820 @end defun
8821
8822 @defun trie-common-prefix-fold trie prefix proc seed
8823 @c MOD data.trie
8824 @c EN
8825 For each entry whose key begins with @var{prefix},
8826 calls @var{proc} with three arguments, the entry's key,
8827 its value, and the current seed value. @var{Seed} is
8828 used for the first seed value, and the value @var{proc}
8829 returns is used for the seed value of the next call of @var{proc}.
8830 The last returned value from @var{proc} is returned from
8831 @code{trie-common-prefix-fold}.
8832 The order of entries on which @var{proc} is called is undefined.
8833 If @var{trie} contains no entry whose key has @var{prefix},
8834 @var{proc} is never called and @var{seed} is returned.
8835 @c JP
8836 @var{prefix}ではじまるキーをもつ各エントリに対して、@var{proc}を3つの
8837 引数、エントリのキー、値、現在のシード値で呼びます。@var{seed}は最初の
8838 シード値として使われ、@var{proc}が返す値は次の@var{proc}の呼び出しのシー
8839 ド値として使われます。@var{proc}が返した最後の値が
8840 @code{trie-common-prefix-fold}から返ります。
8841 @var{proc}が適用される順序は未定義です。@var{trie}が@var{prefix}を持つ
8842 キーのエントリを含まない場合には@var{proc}が呼ばれることはなく、
8843 @var{seed}が返ります。
8844 @c COMMON
8845 @end defun
8846
8847 @defun trie-common-prefix-map trie prefix proc
8848 @defunx trie-common-prefix-for-each trie prefix proc
8849 @c MOD data.trie
8850 @c EN
8851 These are to @var{trie-common-prefix-fold} as @code{map} and @code{for-each}
8852 are to @code{fold}; @code{trie-common-prefix-map} calls
8853 @var{proc} with key and value for matching entries and
8854 gathers its result to a list; @code{trie-common-prefix-for-each}
8855 also applies @var{proc}, but discards its results.
8856 @c JP
8857 @code{map}や@code{for-each}を@code{fold}を合せたのと同じように、
8858 @var{trie-common-prefix-fold}に合せたものです。
8859 @code{trie-common-prefix-map}は@var{proc}をマッチするエントリのキーと
8860 値に適用し結果をリストにあつめます。
8861 @code{trie-common-prefix-for-each}も同じく@var{proc}を適用しますが
8862 結果は捨てます。
8863 @c COMMON
8864 @end defun
8865
8866 @defun trie-fold trie proc seed
8867 @defunx trie-map trie proc
8868 @defunx trie-for-each trie proc
8869 @c MOD data.trie
8870 @c EN
8871 These procedures are like their common-prefix versions, but
8872 traverse entire @var{trie} instead.
8873 @c JP
8874 これらの手続きはcommon-prefix版とおなじような働きをしますが、
8875 @var{trie}全体をトラバースします。
8876 @c COMMON
8877 @end defun
8878
8879 @c ----------------------------------------------------------------------
8880 @node Universally unique lexicographically sortable identifier, Database independent access layer, Trie, Library modules - Utilities
8881 @section @code{data.ulid} - Universally unique lexicographically sortable identifier
8882 @c NODE 一意で辞書順ソート可能な識別子, @code{data.ulid} - 一意で辞書順ソート可能な識別子
8883
8884 @deftp {Module} data.ulid
8885 @mdindex data.ulid
8886 @c EN
8887 This module implements ULID (@url{https://github.com/ulid/spec}), a UUID-like
8888 unique identifier that can be sortable in chronological order and
8889 has slightly more compact string representation.
8890 @c JP
8891 このモジュールは、@url{https://github.com/ulid/spec}
8892 で定義されているULIDを実装します。
8893 これはUUIDに似た一位な識別子ですが、生成順序と辞書順序が一致します。
8894 また、UUIDよりもコンパクトな文字列表現を持ちます。
8895 @c COMMON
8896
8897 @example
8898 (define gen-ulid (make-ulid-generator))
8899
8900 (gen-ulid) @result{} #<ulid 01G70P3EWJT28VPQ12NTFFDSZ1>
8901
8902 (ulid->string (gen-ulid)) @result{} "01G70P3Y72TQ1HYY90G8TJSY07"
8903 @end example
8904
8905 @c EN
8906 NB: The new version of UUID RFC (RFC9562) contains a UUID version 7 which
8907 has similar monotonic property of ULID, except the compact notation.
8908 @xref{UUID}, for the details.
8909 @c JP
8910 註: 新しいUUID RFC (RFC9562)には、ULIDと同様の単調増加属性を持つUUID version 7
8911 が含まれています。詳しくは@ref{UUID}を参照のこと。
8912 @c COMMON
8913 @end deftp
8914
8915 @defun make-ulid-generator :optional random-source
8916 @mdindex data.ulid
8917 @c EN
8918 Creates and returns a generator that yields a fresh ULID object
8919 every time it is called. The optional @var{random-source} argument
8920 is a SRFI-27 random source (@pxref{Sources of random bits})
8921 to be used for the random part of ULID. When omitted,
8922 an internal random source is used.
8923 @c JP
8924 呼ばれるたびに新たなULIDオブジェクトを返すジェネレータを作って返します。
8925 省略可能な@var{random-source}引数はSRFI-27の乱数源で、ULIDの乱数部を生成するのに
8926 使われます (@ref{Sources of random bits}参照)。
8927 省略された場合は内部の乱数源が使われます。
8928 @c COMMON
8929
8930 @c EN
8931 To guarantee uniqueness and monotonicity, a ULID generator needs to
8932 keep internal state. If you want to share the generator among multiple threads,
8933 you need to manage your own lock. Keeping the generator private in one
8934 thread eliminates the need of mutex (however, monotonicity is only guaranteed
8935 within each generator).
8936 @c JP
8937 一意性と単調増加特性を保証するために、ULIDジェネレータは内部に状態を保持しています。
8938 作られたジェネレータを複数のスレッドで共有する場合は、呼び出し側で排他制御してください。
8939 ジェネレータをひとつのスレッド内で使う限りにおいては排他制御のオーバヘッドを避けることができます
8940 (ただ、単調増加特性はジェネレータごとにしか保証されません)。
8941 @c COMMON
8942
8943 @c EN
8944 A ULID consists of 48bit timestamp field (milliseconds since Unix epoch)
8945 and 80bit randomness field. The randomness field are generated randomly if
8946 it is the first ULID within the timestamp. If more than one ULID needs
8947 to be generated in a millisecond window, the subsequent ULID gets randomness
8948 field incremented from the previous ULID, so that the chronological order
8949 is maintained.
8950 @c JP
8951 ULIDは48ビットのタイムスタンプ(Unixエポックからのミリ秒)と、80ビットのランダムネスフィールド
8952 から成ります。ランダムネスフィールドはそのミリ秒の時刻で初めてULIDが生成される場合は
8953 ランダムに埋められ、同じミリ秒内で2個め以降のULIDが生成される場合は前回の
8954 ランダムネスフィールドをインクリメントしたものが使われます。
8955 これによって生成順序と辞書順序が一致します。
8956 @c COMMON
8957
8958 @c EN
8959 The ULID spec says if the randomness field overflows because so many
8960 ULIDs are generated within a millisecond, it is an error. Such scenario
8961 is very unlikely but can occur. In our implementation, however, we wait for the
8962 next millisecond boundary in case we ran out randomness field, so the generator
8963 never yields an error.
8964 @c JP
8965 ULID仕様では、同じミリ秒内で多数のULIDが生成されたためにランダムネスフィールドがオーバーフロー
8966 した場合はエラーとしています。それが起きる可能性は極めて小さいですが、起き得ることです。
8967 Gaucheの実装では、ランダムネスフィールドがオーバーフローした場合は次のミリ秒まで待つことで、
8968 エラーにならないようにしています。
8969 @c COMMON
8970 @end defun
8971
8972 @defun ulid? obj
8973 @mdindex data.ulid
8974 @c EN
8975 Returns @code{#t} iff @var{obj} is an ULID object.
8976 @c JP
8977 @var{obj}がULIDオブジェクトなら@code{#t}を、そうでなければ@code{#f}を返します。
8978 @c COMMON
8979 @end defun
8980
8981 @defun ulid-timestamp ulid
8982 @mdindex data.ulid
8983 @c EN
8984 Returns the timestamp part of @var{ulid} (48bits) as an exact integer.
8985 @c JP
8986 @var{ulid}のタイムスタンプ部(48bit)を正確な整数で返します。
8987 @c COMMON
8988 @end defun
8989
8990 @defun ulid-randomness ulid
8991 @mdindex data.ulid
8992 @c EN
8993 Returns the randomess part of @var{ulid} (80bits) as an exact integer.
8994 @c JP
8995 @var{ulid}のランダムネス部(80bit)を正確な整数で返します。
8996 @c COMMON
8997 @end defun
8998
8999 @defun ulid=? ulid1 ulid2
9000 @mdindex data.ulid
9001 @c EN
9002 Returns true if two ULIDs are equivalent.
9003 @c JP
9004 二つのULIDが等価であれば@code{#t}を、そうでなければ@code{#f}を返します。
9005 @c COMMON
9006 @end defun
9007
9008 @defun ulid<? ulid1 ulid2
9009 @mdindex data.ulid
9010 @c EN
9011 Returns true if @var{ulid1} precedes @var{ulid2}. If both ULIDs are
9012 created from the same generator, this means @var{ulid1} is created
9013 chronologically before @var{ulid2}. If they are created from different
9014 generators, the chronological order is not guaranteed, but the discrepancy
9015 only occurs when two ULIDs are created at the same timestamp in
9016 millisecond resolution.
9017 @c JP
9018 辞書順比較で@var{ulid1}が@var{ulid2}よりも小さければ@code{#t}を、
9019 そうでなければ@code{#f}を返します。二つのULIDが同じジェネレータで
9020 生成されていたなら、これは@var{ulid1}が@var{ulid2}より前に生成されたことを意味します。
9021 二つが異なるジェネレータで生成されていた場合は、ミリ秒より小さな間隔において
9022 生成順が辞書順とは異なっている可能性があります。
9023 @c COMMON
9024 @end defun
9025
9026 @defun ulid-hash ulid
9027 @mdindex data.ulid
9028 @c EN
9029 Returns a hash value of @var{ulid} in a nonnegative exact integer.
9030 @c JP
9031 @var{ulid}のハッシュ値を非負の正確な整数で返します。
9032 @c COMMON
9033 @end defun
9034
9035 @defvar ulid-comparator
9036 @mdindex data.ulid
9037 @c EN
9038 Bound to a comparator suitable to compare and hash ULIDs.
9039 @c JP
9040 ULIDの比較およびハッシュに使える比較器です。
9041 @c COMMON
9042 @end defvar
9043
9044 @defun ulid->bytevector ulid
9045 @defunx bytevector->ulid uv
9046 @mdindex data.ulid
9047 @c EN
9048 Covvert between @var{ulid} and a u8vector of length 16. Bits are packed
9049 in big-endian order (first 8 bits of timestamp to first byte, and
9050 so on).
9051 @c JP
9052 @var{ulid}と長さ16のu8vector間の変換手続きです。
9053 ビットはビッグエンディアンで格納されます(タイムスタンプの先頭8ビットが最初のバイト、等)。
9054 @c COMMON
9055 @end defun
9056
9057 @defun ulid->integer ulid
9058 @defunx integer->ulid n
9059 @mdindex data.ulid
9060 @c EN
9061 Convert between @var{ulid} and an exact nonnegative integer up to 128bit.
9062 @c JP
9063 @var{ulid}と非負の正確な128ビット整数との間の変換手続きです。
9064 @c COMMON
9065 @end defun
9066
9067 @defun ulid->string ulid
9068 @defunx string->ulid str
9069 @mdindex data.ulid
9070 @c EN
9071 Convert @var{ulid} to a string of Base32 representation; the
9072 digits are @code{0123456789ABCDEFGHJKMNPQRSTVWXYZ} (@code{I}, @code{L},
9073 @code{O}, and @code{U} are excluded to avoid confusion). Length of
9074 the string is always 26.
9075 @c JP
9076 @var{ulid}とそのBase32文字列表現との間の変換手続きです。
9077 エンコードディジットには@code{0123456789ABCDEFGHJKMNPQRSTVWXYZ}が使われます
9078 (@code{I}、@code{L}、@code{O}、@code{U}は混乱を避けるために使われません)。
9079 文字列の長さは常に26です。
9080 @c COMMON
9081
9082 @c EN
9083 @code{ulid->string} always use uppercase characters; on the other hand,
9084 @code{string->ulid} allows both lowercase and uppercase characters.
9085 @c JP
9086 @code{ulid->string}は常に大文字を使います。
9087 一方、@code{string->ulid}は小文字も大文字も受け付けます。
9088 @c COMMON
9089 @end defun
9090
9091 @c ----------------------------------------------------------------------
9092
9093 @node Database independent access layer, Generic DBM interface, Universally unique lexicographically sortable identifier, Library modules - Utilities
9094 @section @code{dbi} - Database independent access layer
9095 @c NODE データベース非依存アクセス層, @code{dbi} - データベース非依存アクセス層
9096
9097 @deftp {Module} dbi
9098 @mdindex dbi
9099 @c EN
9100 This module provides the unified interface to access various
9101 relational database systems (RDBMS). The operations specific
9102 to individual database systems are packaged
9103 in database driver (DBD) modules, which is usually loaded
9104 implicitly by DBI layer.
9105 @c JP
9106 このモジュールはさまざまなリレーショナルデータベースシステム(RDBMS)に
9107 アクセスするための統一されたインタフェースを提供します。個々のデータベー
9108 スシステムに特有の操作についてはデータベースドライバ(DBD)モジュールに
9109 パッケージされています。DBDのモジュールは通常暗黙裏にDBIの層からロード
9110 されます。
9111 @c COMMON
9112
9113 @c EN
9114 The module is strongly influenced by Perl's DBI/DBD architecture.
9115 If you have used Perl DBI, it would be easy to use this module.
9116 @c JP
9117 このモジュールは Perl の DBI/DBD アーキテクチャに強く影響を受けていま
9118 す。Perl DBIを使った経験があるなら、このモジュールを使うのはたやすいで
9119 しょう。
9120 @c COMMON
9121 @end deftp
9122
9123 @c EN
9124 It's better to look at the example. This is a simple outline
9125 of accessing a database by @code{dbi} module:
9126 @c JP
9127 まず例を見るほうがよいでしょう。以下は@code{dbi}モジュールを使ったデー
9128 タベースアクセス例の概要です。
9129 @c COMMON
9130
9131 @example
9132 (use dbi)
9133 (use gauche.collection) ; to make 'map' work on the query result
9134
9135 (guard (e ((<dbi-error> e)
9136 ;; handle error
9137 ))
9138 (let* ((conn (dbi-connect "dbi:mysql:test;host=dbhost"))
9139 (query (dbi-prepare conn
9140 "SELECT id, name FROM users WHERE department = ?"))
9141 (result (dbi-execute query "R&D"))
9142 (getter (relation-accessor result)))
9143 (map (lambda (row)
9144 (list (getter row "id")
9145 (getter row "name")))
9146 result)))
9147 @end example
9148
9149 @c EN
9150 There's nothing specific to the underlying database system
9151 except the argument @code{"dbi:mysql:test;host=dbhost"}
9152 passed to @code{dbi-connect}, from which @code{dbi} module
9153 figures out that it is an access to @code{mysql} database,
9154 loads @code{dbd.mysql} module, and let it handle the mysql-specific
9155 stuff. If you want to use whatever database system, you can just
9156 pass @code{"dbi:@var{whatever}:@var{parameter}"} to @code{dbi-connect}
9157 instead, and everything stays the same as far as you have
9158 @code{dbd.whatever} installed in your system.
9159 @c JP
9160 @code{dbi-connect}にわたす、@code{"dbi:mysql:test;host=dbhost"}引数以
9161 外は使用するデータベースシステムに依存する部分はありません。この引数に
9162 より、@code{dbi}モジュールはこのアクセスが@code{mysql}データベースに対
9163 するものであると判断します。そして、mysql-特有の手続を扱うようにします。
9164 別のデータベースシステムwhateverを使いたいのであれば、単に
9165 @code{"dbi:@var{whatever}:@var{parameter}"}を@code{dbi-connect}に渡せ
9166 ばよく、@code{dbd.whatever}がシステムにインストールされていれば同じよ
9167 うにできます。
9168 @c COMMON
9169
9170 @c EN
9171 A query to the database can be created by @code{dbi-prepare}.
9172 You can issue the query by @code{dbi-execute}. This two-phase
9173 approach allows you to create a prepared query, which is a kind of
9174 parameterized SQL statement. In the above example the query
9175 takes one parameter, denoted as @code{'?'} in the SQL.
9176 The actual value is given in @code{dbi-execute}. When you
9177 issue similar queries a lot, creating a prepared query and
9178 execute it with different parameters may give you performance gain.
9179 Also the parameter is automatically quoted.
9180 @c JP
9181 データベースに対するクエリは@code{dbi-prepare}を使って作成します。
9182 クエリの発行は@code{dbi-execute}で行います。このような2つのフェーズを
9183 使うことで、パラメータ化されたSQL文の一種であるプリペアドクエリを
9184 作ることができます。上の例ではクエリはSQL文の中で@code{'?'}で表現され
9185 ている部分に、ひとつの引数をわりあてます。実引数の値は
9186 @code{dbi-execute}で設定されます。類似のクエリを大量に発行するような場
9187 合にはプリペアドクエリをひとつ生成し、それにさまざまなパラメータを渡し
9188 て実行するとパフォーマンスがかせげます。このパラメータは自動的にクォー
9189 トされます。
9190 @c COMMON
9191
9192 @c EN
9193 When the query is a @code{SELECT} statement,
9194 its result is returned as a collection that implements
9195 the relation protocol. See @ref{Collection framework}
9196 and @ref{Relation framework} for the details.
9197 @c JP
9198 クエリが@code{SELECT}文の場合、その結果は関係プロトコルを実装するコレ
9199 クションとして返されます。詳細は@ref{Collection framework}および
9200 @ref{Relation framework}を見てください。
9201 @c COMMON
9202
9203 @c EN
9204 The outermost @code{guard} is to catch errors. The @code{dbi} related
9205 errors are supposed to inherit @code{<dbi-error>} condition.
9206 There are a few specific errors defined in @code{dbi} module.
9207 A specific @code{dbd} layer may define more specific errors.
9208 @c JP
9209 いちばん外側にある@code{guard}はエラーを捕捉するためのものです。
9210 @code{dbi}に関連したエラーは@code{<dbi-error>}コンディションを継承して
9211 いるものと見なされます。いくつかの特有のエラーは@code{dbi}モジュールで
9212 定義されています。特定の@code{dbd}層はさらに固有のエラーを定義していま
9213 す。
9214 @c COMMON
9215
9216 @c EN
9217 In the next section we describe user-level API, that is,
9218 the procedures you need to concern when you're using @code{dbi}.
9219 The following section is for the driver API, which you need to use
9220 to write a specific @code{dbd} driver to make it work with @code{dbi}
9221 framework.
9222 @c JP
9223 次節ではユーザレベルのAPIについて説明します。すなわち、@code{dbi}を使
9224 う際に必要となる手続に関する説明です。そのあとのセクションではドライバ
9225 APIを説明をします。すなわち特定の@code{dbd}ドライバを@code{dbi}フレー
9226 ムワークで使えるようにするために使うAPIの説明です。
9227 @c COMMON
9228
9229 @menu
9230 * DBI user API::
9231 * Writing drivers for DBI::
9232 @end menu
9233
9234 @node DBI user API, Writing drivers for DBI, Database independent access layer, Database independent access layer
9235 @subsection DBI user API
9236 @c NODE DBIのユーザAPI
9237
9238 @c EN
9239 @subsubheading DBI Conditions
9240 @c JP
9241 @subsubheading DBIのコンディション
9242 @c COMMON
9243
9244 @c EN
9245 There are several predefined conditions @code{dbi} API may throw.
9246 See @ref{Exceptions} for the details of conditions.
9247 @c JP
9248 @code{dbi} API が投げる可能性のあるコンディションがいくつか定義されて
9249 います。コンディションの詳細については@ref{Exceptions}を見てください。
9250 @c COMMON
9251
9252 @deftp {Condition Type} <dbi-error>
9253 @c MOD dbi
9254 @c EN
9255 The base class of @code{dbi}-related conditions. Inherits @code{<error>}.
9256 @c JP
9257 @code{dbi}-関連のコンディションのベースクラス。@code{<error>}を継承し
9258 ています。
9259 @c COMMON
9260 @end deftp
9261
9262 @deftp {Condition Type} <dbi-nonexistent-driver-error>
9263 @c MOD dbi
9264 @c EN
9265 This condition is thrown by @code{dbi-connect} when it cannot
9266 find the specified driver. Inherits @code{<dbi-error>}.
9267 @c JP
9268 @code{dbi-connect}は指定されたドライバが見つからない場合にこのコンディ
9269 ションを投げます。@code{<dbi-error>}を継承しています。
9270 @c COMMON
9271
9272 @defivar <dbi-nonexistent-driver-error> driver-name
9273 @c EN
9274 Holds the requested driver name as a string.
9275 @c JP
9276 要求されたドライバの名前を文字列として保持している。
9277 @c COMMON
9278 @end defivar
9279 @end deftp
9280
9281 @deftp {Condition Type} <dbi-unsupported-error>
9282 @c MOD dbi
9283 @c EN
9284 This condition is thrown when the called method isn't supported
9285 by the underlying driver. Inherits @code{<dbi-error>}.
9286 @c JP
9287 呼び出されたメソッドが基盤となるドライバでサポートされていない場合、こ
9288 のコンディションが投げられます。@code{<dbi-error>}を継承しています。
9289 @c COMMON
9290 @end deftp
9291
9292 @deftp {Condition Type} <dbi-parameter-error>
9293 @c MOD dbi
9294 @c EN
9295 This condition is thrown when the number of parameters given to
9296 the prepared query doesn't match the ones in the prepared statement.
9297 @c JP
9298 プリペアドクエリへ渡されたパラメータの数がプリペアドステートメントの中
9299 のものと一致しないとき、このコンディションが投げられます。
9300 @c COMMON
9301 @end deftp
9302
9303 @c EN
9304 Besides these errors, if a driver relies on @code{dbi} to
9305 parse the prepared SQL statement, @code{<sql-parse-error>} may
9306 be thrown if an invalid SQL statement is passed to @code{dbi-prepare}.
9307 (@pxref{SQL parsing and construction}).
9308 @c JP
9309 上の3つのエラー以外に、@code{dbi}がプリペアドSQL文を構文解析するのにド
9310 ライバを利用す場合、不正なSQL文が@code{dbi-prepare}に渡されると、
9311 @code{<sql-parse-error>}が投げられます
9312 (@ref{SQL parsing and construction}参照)。
9313 @c COMMON
9314
9315 @c EN
9316 @subsubheading Connecting to the database
9317 @c JP
9318 @subsubheading データベースへの接続
9319 @c COMMON
9320
9321 @defun dbi-connect dsn :key username password
9322 @c MOD dbi
9323 @c EN
9324 Connect to a database using a data source specified by @var{dsn}
9325 (data source name). @var{Dsn} is a string with the following syntax:
9326 @c JP
9327 @var{dsn}(データソース名)で指定されたデータソースを使ってデータベース
9328 に接続します。@var{dsn}は以下の構文をもつ文字列です。
9329 @c COMMON
9330 @example
9331 dbi:@var{driver}:@var{options}
9332 @end example
9333
9334 @c EN
9335 @var{Driver} part names a specific driver. You need to have the
9336 corresponding driver module, @code{dbd.@var{driver}}, installed in
9337 your system. For example, if @var{dsn} begins with @code{"dbi:mysql:"},
9338 @code{dbi-connect} tries to load @code{dbd.mysql}.
9339 @c JP
9340 @var{driver}は特定のドライバ名です。対応するドライバモジュールがなけれ
9341 ばなりません。すなわち、@code{dbd.@var{driver}}がシステムにインストー
9342 ルされていなければなりません。たとえば、@var{dsn}が@code{"dbi:mysql:"}
9343 ではじまるとすると、@code{dbi-connect}は@code{dbd.mysql}をロードしよう
9344 とします。
9345 @c COMMON
9346
9347 @c EN
9348 Interpretation of the @var{options} part is up to the driver.
9349 Usually it is in the form of @code{key1=value1;key2=value2;...},
9350 but some driver may interpret it differently. For example,
9351 @code{mysql} driver allows you to specify a database name
9352 at the beginning of @var{options}. You have to check out
9353 the document of each driver for the exact specification of
9354 @var{options}.
9355 @c JP
9356 @var{options}部分の解釈はドライバに依存します。通常この部分のフォーマッ
9357 トは@code{key1=value1;key2=value2;...}のようになっていますが、ドライバ
9358 によっては別の解釈になります。たとえば、@code{mysql}ドライバでは、
9359 @var{options}の最初の部分でデータベース名を指定することができます。
9360 @var{options}の正確な仕様については各ドライバのドキュメントをチェック
9361 してください。
9362 @c COMMON
9363
9364 @c EN
9365 The keyword arguments gives extra information required for
9366 connection. The @var{username} and @var{password} are commonly
9367 supported arguments. The driver may recognize more keyword arguments.
9368 @c JP
9369 接続のために必要な追加情報はキーワード引数であたえます。
9370 @var{username}および@var{password}は共通でサポートされている引数です。
9371 ドライバは他にもキーワード引数を認識します。
9372 @c COMMON
9373
9374 @c EN
9375 If a connection to the database is successfully established,
9376 a connection object (an instance of a subclass of @code{<dbi-connection>})
9377 is returned. Otherwise, an error is signaled.
9378 @c JP
9379 データベースへの接続が成功したら、コネクションオブジェクト
9380 (@code{<dbi-connection>}のサブクラスのインスタンス)が返ります。さもな
9381 ければ、エラーがあがります。
9382 @c COMMON
9383 @end defun
9384
9385 @deftp {Class} <dbi-connection>
9386 @clindex dbi-connection
9387 @c MOD dbi
9388 @c EN
9389 The base class of a connection to a database system.
9390 Each driver defines a subclass of this to keep information about
9391 database-specific connections.
9392 @c JP
9393 データベースシステムへの接続のベースクラス。各ドライバはこのクラスのサ
9394 ブクラスを定義し、これにデータベース特有のコネクションに関する情報を持
9395 たせます。
9396 @c COMMON
9397 @end deftp
9398
9399 @deffn {Method} dbi-open? (c <dbi-connection>)
9400 @c MOD dbi
9401 @c EN
9402 Queries whether a connection to the database is still open (active).
9403 @c JP
9404 データベースへの接続がオープン状態(アクティブ状態)にあるかどうかを確か
9405 めます。
9406 @c COMMON
9407 @end deffn
9408
9409 @deffn {Method} dbi-close (c <dbi-connection>)
9410 @c MOD dbi
9411 @c EN
9412 Closes a connection to the database. This causes releasing resources
9413 related to this connection. Once closed, @var{c} cannot
9414 be used for any dbi operations (except passing to @code{dbi-open?}).
9415 Calling @code{dbi-close} on an already closed connection has no effect.
9416 @c JP
9417 データベースへの接続を閉じます。これによりこの接続に関連付けられたリソー
9418 スが解放されます。いったん閉じた@var{c}に対してはどのようなdbi操作もで
9419 きません。(@code{dbi-open?}だけは例外)。すでに閉じられたコネクションに
9420 対して@code{dbi-close}を呼んでもなにも起りません。
9421 @c COMMON
9422
9423 @c EN
9424 Although a driver usually closes a connection when @code{<dbi-connection>}
9425 object is garbage-collected, it is not a good idea to rely on that,
9426 since the timing of GC is unpredictable. The user program must make
9427 sure that it calls @code{dbi-close} at a proper moment.
9428 @c JP
9429 ドライバは通常@code{<dbi-connection>}がガベージコレクションされたとき
9430 にコネクションを閉じますが、このことを期待したコードを書くのはいただけ
9431 ません。GCのタイミングというのは予測不可能だからです。ユーザプログラム
9432 は適切なタイミングで@code{dbi-close}を呼ぶようにすべきです。
9433 @c COMMON
9434 @end deffn
9435
9436 @defun dbi-list-drivers
9437 @c MOD dbi
9438 @c EN
9439 Returns a list of module names of known drivers.
9440 @c JP
9441 解っているドライバのモジュール名のリストを返します。
9442 @c COMMON
9443 @end defun
9444
9445 @deftp {Class} <dbi-driver>
9446 @clindex dbi-driver
9447 @c MOD dbi
9448 @c EN
9449 The base class of a driver. You usually don't need to see this
9450 as far as you're using the high-level @code{dbi} API.
9451 @c JP
9452 ドライバのベースクラス。高レベルの@code{dbi} APIを使うかぎり、これが必
9453 要になることはありません。
9454 @c COMMON
9455 @end deftp
9456
9457 @defun dbi-make-driver driver-name
9458 @c MOD dbi
9459 @c EN
9460 This is a low-level function called from @code{dbi-connect} method,
9461 and usually a user doesn't need to call it.
9462 @c JP
9463 @code{dbi-connect}から呼ばれる低レベル関数、通常この関数を呼ぶ必要はあ
9464 りません。
9465 @c COMMON
9466
9467 @c EN
9468 Loads a driver module specified by @var{driver-name}, and
9469 instantiate the driver class and returns it.
9470 @c JP
9471 @var{driver-name}で指定されたドライバモジュールをロードし、当該のドラ
9472 イバクラスのインスタンスを生成してそれを返します。
9473 @c COMMON
9474 @end defun
9475
9476 @c EN
9477 @subsubheading Preparing and issuing queries
9478 @c JP
9479 @subsubheading クエリの準備と発行
9480 @c COMMON
9481
9482 @deffn {Method} dbi-prepare conn sql :key pass-through @dots{}
9483 @c MOD dbi
9484 @c EN
9485 From a string representation of SQL statement @var{sql},
9486 creates and returns a query object (an instance of @code{<dbi-query>}
9487 or its subclass) for the database connection @code{conn}
9488 @c JP
9489 SQL文の文字列表現@var{sql}からデータベースコネクション@code{conn}用の
9490 クエリオブジェクト(@code{<dbi-query>}のインスタンスもしくはそのサブク
9491 ラスのインスタンス)を生成してそれを返します。
9492 @c COMMON
9493
9494 @c EN
9495 @var{Sql} may contain parameter slots, denoted by @code{?}.
9496 @c JP
9497 @var{sql}は@code{?}であらわされているパラメータスロットを持ちます。
9498 @c COMMON
9499 @example
9500 (dbi-prepare conn "insert into tab (col1, col2) values (?, ?)")
9501
9502 (dbi-prepare conn "select * from tab where col1 = ?")
9503 @end example
9504
9505 @c EN
9506 They will be filled when you actually issue the query by
9507 @code{dbi-execute}.
9508 There are some advantages of using parameter
9509 slots: (1) The necessary quoting is done automatically.
9510 You don't need to concern about security holes caused by
9511 improper quoting, for example.
9512 (2) Some drivers support a feature to send the template SQL
9513 statement to the server at the preparation stage, and send
9514 only the parameter values at the execution stage. It would be
9515 more efficient if you issue similar queries lots of time.
9516 @c JP
9517 これらのスロットは@code{dbi-execute}を使って実際にクエリを発行したとき
9518 に埋められます。パラメータスロットを使うのは以下の利点があるからです。
9519 (1) クォートが自動的にほどこされます。不適切なクォートによるセキュリティ
9520 ホールを気にする必要はありません。
9521 (2) いくつかのドライバでは準備の段階でサーバへテンプレートSQL文を送る
9522 機能がサポートされていて、実行段階ではパラメータを送るだけで済みます。
9523 これは似たようなクエリを大量に一度に発行するときには効率のよいやりかた
9524 です。
9525 @c COMMON
9526
9527 @c EN
9528 If the backend doesn't support prepared statements (SQL templates
9529 having @code{?} parameters), the driver may use @code{text.sql}
9530 module to parse @var{sql}. It may raise @code{<sql-parse-error>}
9531 condition if the given SQL is not well formed.
9532 @c JP
9533 バックエンドでプリペアド文がサポートされていない場合(でSQLテンプレー
9534 トが@code{?}パラメータを持つ場合)、ドライバは@var{sql}を解析するのに
9535 @code{text.sql}モジュールを使います。与えられたSQL文が正しい構文でなけ
9536 れば、@code{<sql-parse-error>}コンディションが発生します。
9537 @c COMMON
9538
9539 @c EN
9540 You may pass a true value to the keyword argument @var{pass-through}
9541 to suppress interpretation of SQL and pass @var{sql} as-is to the
9542 back end database system. It is useful if the back-end supports
9543 extension of SQL which @code{text.sql} doesn't understand.
9544 @c JP
9545 キーワード引数@var{pass-through}に真の値を渡して、SQLの解釈を抑制し、
9546 @var{sql}をそのままバックエンドのデータベースシステムに渡すことができ
9547 ます。@code{text.sql}で理解できないようなSQLの拡張をバックエンドがサポー
9548 トしている場合に役立ちます。
9549 @c COMMON
9550
9551 @c EN
9552 If the driver lets prepared statement handled in back-end,
9553 without using @code{text.sql}, the @code{pass-through} argument
9554 may be ignored.
9555 The driver may also take other keyword arguments. Check out
9556 the documentation of individual drivers.
9557 @c JP
9558 ドライバがプリペアド文を@code{text.sql}抜きでバックエンドに処理させた
9559 場合、@code{pass-through}引数は無視されます。ドライバは他のキーワード
9560 引数を取ることもあります。詳細はそれぞれのドライバのドキュメントを参照
9561 してください。
9562 @c COMMON
9563
9564 @c EN
9565 @emph{Note:} Case folding of SQL statement
9566 is implementation dependent. Some DBMS may treat table
9567 names and column names in case insensitive way, while
9568 others do in case sensitive way. To write a portable
9569 SQL statement, make them quoted identifiers, that is,
9570 always surround names by double quotes.
9571 @c JP
9572 @emph{注意}:SQL文のケース畳み込みは実装依存です。DBMSのなかにはテーブ
9573 ル名やカラム名は大文字小文字の区別をしないものもあり、一方で区別するも
9574 のもあります。ポータブルなSQL文を書きたいのなら、識別子をクォートしま
9575 しょう。すなわち常に名前をダブルクォートで囲むようにします。
9576 @c COMMON
9577 @end deffn
9578
9579 @deftp {Class} <dbi-query>
9580 @clindex dbi-query
9581 @c MOD dbi
9582 @c EN
9583 Holds information about prepared query, created by @code{dbi-prepare}.
9584 The following slots are defined.
9585 @c JP
9586 @code{dbi-prepare}によって作成されたプリペアドクエリに関する情報を保持
9587 します。以下のスロットが定義されています。
9588 @c COMMON
9589
9590 @defivar <dbi-query> connection
9591 @c EN
9592 Contains the @code{<dbi-connection>} object.
9593 @c JP
9594 @code{<dbi-connection>}オブジェクトを含みます。
9595 @c COMMON
9596 @end defivar
9597
9598 @defivar <dbi-query> prepared
9599 @c EN
9600 If the driver prepares query by itself, this slot may contain
9601 a prepared statement. It is up to each driver how to use
9602 this slot, so the client shouldn't rely on its value.
9603 @c JP
9604 ドライバがクエリを準備する場合、このスロットがプリペアド文を保持します。
9605 このスロットをどのように使うかはおのおののドライバによります。したがっ
9606 て、クライアントはこの値に依存してはいけません。
9607 @c COMMON
9608 @end defivar
9609
9610 @end deftp
9611
9612 @deffn {Method} dbi-open? (q <dbi-query>)
9613 @c MOD dbi
9614 @c EN
9615 Returns @code{#t} iff the query can still be passed to
9616 @code{dbi-execute}.
9617 @c JP
9618 クエリが@code{dbi-execute}に渡せる状態になっているときにのみ、
9619 @code{#t}を返します。
9620 @c COMMON
9621 @end deffn
9622
9623 @deffn {Method} dbi-close (q <dbi-query>)
9624 @c MOD dbi
9625 @c EN
9626 Destroy the query and free resources associated to the query.
9627 After this operation, @code{dbi-open?} returns @code{#f} for @var{q},
9628 and the query can't be used in any other way. Although the resource
9629 may be freed when @var{q} is garbage-collected, it is strongly recommended
9630 that the application closes queries explicitly.
9631 @c JP
9632 クエリを破棄し、当該クエリに関連づけられたリソースを解放します。この操
9633 作を実行後は、@code{dbi-open?}は@var{q}に対して@code{#f}を返します。
9634 そして、当該クエリは他の用途にはつかえません。@var{q}がガベージコレク
9635 ションにより回収された場合、リソースは解放されますが、アプリケーション
9636 が明示的にクエリを閉じるようにすることを強く勧めます。
9637 @c COMMON
9638 @end deffn
9639
9640 @deffn {Method} dbi-execute (q <dbi-query>) parameter @dots{}
9641 @c MOD dbi
9642 @c EN
9643 Executes a query created by @code{dbi-prepare}. You should pass
9644 the same number of @var{parameter}s as the query expects.
9645 @c JP
9646 @code{dbi-prepare}によって作成されたクエリを実行します。当該クエリが期
9647 待するのと同じ数のパラメータを渡す必要があります。
9648 @c COMMON
9649
9650 @c EN
9651 If the issued query is @code{select} statement, @code{dbi-execute}
9652 returns an object represents a @emph{relation}.
9653 A relation encapsulates the values in
9654 rows and columns, as well as meta information like column names.
9655 See "Retrieving query results" below for how to access the result.
9656 @c JP
9657 発行されたクエリが@code{select}文の場合@code{dbi-execute}は
9658 @emph{リレーション}を表わすオブジェクトを返します。リレーションは
9659 行とカラムの値をカプセル化したもので、カラム名のようなメタ情報も同様で
9660 す。結果へアクセスの方法については後述の「クエリの結果を見る」を見てく
9661 ださい。
9662 @c COMMON
9663
9664 @c EN
9665 If the query is other types, such as @code{create}, @code{insert}
9666 or @code{delete}, the return value of the query closure is unspecified.
9667 @c JP
9668 クエリがSELECT以外の@code{create}、@code{insert}、@code{delete}などの
9669 場合、クエリクロージャー返り値は不定です。
9670 @c COMMON
9671 @end deffn
9672
9673 @deffn {Method} dbi-do conn sql :optional options parameter-value @dots{}
9674 @c MOD dbi
9675 @c EN
9676 This is a convenience procedure when you create a query
9677 and immediately execute it. It is equivalent to the following
9678 expression, although the driver may overload this method to avoid
9679 creating intermediate query object to avoid the overhead.
9680 @c JP
9681 この手続はクエリを作成し、すぐに実行したいときに便利です。これは次の式
9682 と同じですが、この場合はドライバはオーバーヘッドを避けるため、中間のク
9683 エリを作らないようにこのメソッドをオーバーロードします。
9684 @c COMMON
9685 @example
9686 (dbi-execute (apply dbi-prepare conn sql options)
9687 parameter-value @dots{})
9688 @end example
9689 @end deffn
9690
9691 @deffn {Method} dbi-escape-sql conn str
9692 @c MOD dbi
9693 @c EN
9694 Returns a string where special characters in @var{str} are escaped.
9695 @c JP
9696 @var{str}中の特殊文字をエスケープした文字列を返します。
9697 @c COMMON
9698
9699 @c EN
9700 The official SQL standard only specify a single quote (@code{'}) as
9701 such character. However, it doesn't specify non-printable characters,
9702 and the database system may use other escaping characters. So
9703 it is necessary to use this method rather than doing escaping
9704 by your own.
9705 @c JP
9706 SQLの公式標準ではこのような文字としてはシングルクォート(@code{'})につ
9707 いてだけ規定しています。しかし、印字可能文字ではない文字については規定
9708 がありません。また、データベースシステムによっては他のエスケープ文字を
9709 使うものもあります。それゆえ、自分でエスケープしようとせずに、このメソッ
9710 ドを使う必要があります。
9711 @c COMMON
9712
9713 @c EN
9714 @example
9715 ;; assumes c is a valid DBI connection
9716 (dbi-escape-sql c "don't know")
9717 @result{} "don''t know"
9718 @end example
9719 @c JP
9720 @example
9721 ;; c を利用可能なDBIコネクションとする
9722 (dbi-escape-sql c "don't know")
9723 @result{} "don''t know"
9724 @end example
9725 @c COMMON
9726 @end deffn
9727
9728 @c EN
9729 @subsubheading Retrieving query results
9730 @c JP
9731 @subsubheading クエリの結果を見る
9732 @c COMMON
9733
9734 @c EN
9735 If the query is a @code{select} statement, it returns an object
9736 of both @code{<collection>} and @code{<relation>}.
9737 It is a collection of rows (that is, it implements @code{<collection>} API),
9738 so you can use @code{map}, @code{for-each} or other generic functions
9739 to access rows. You can also use the relation API to retrieve column
9740 names and accessors from it. See @ref{Relation framework}, for the relation
9741 API, and @ref{Collection framework}, for the collection API.
9742 @c JP
9743 クエリが@code{select}文である場合、@code{<collection>}と
9744 @code{<relation>}の両方のオブジェクトが返ります。行のコレクション
9745 (すなわち、@code{<collection>} APIの実装)ですから、行にアクセスするに
9746 は@code{map}、@code{for-each}、その他のジェネリック関数が使えます。
9747 また、カラム名やアクセサを取り出すにはリレーションAPIが使えます。
9748 リレーションAPIについては@ref{Relation framework}をコレクションAPIにつ
9749 いては@ref{Collection framework}を見てください。
9750 @c COMMON
9751
9752 @c EN
9753 The actual class of the object returned from a query depends on
9754 the driver, but you may use the following method on it.
9755 @c JP
9756 クエリから戻ったオブジェクトの実際のクラスはドライバによりますが、
9757 以下のメソッドを使うことができます。
9758 @c COMMON
9759
9760 @deffn {Method} dbi-open? result
9761 @c MOD dbi
9762 @c EN
9763 Check whether the result of a query is still active.
9764 The result may become inactive when it is explicitly closed
9765 by @code{dbi-close} and/or the connection to the database is
9766 closed.
9767 @c JP
9768 クエリの結果がまだアクティブであるかどうかをチェックします。
9769 結果は@code{dbi-close}によって明示的に閉じられるかデータベースへのコネ
9770 クションが閉じられると非アクティブになります。
9771 @c COMMON
9772 @end deffn
9773
9774 @deffn {Method} dbi-close result
9775 @c MOD dbi
9776 @c EN
9777 Close the result of the query. This may cause releasing resources
9778 related to the result. You can no longer use @var{result} once it is
9779 closed, except passing it to @code{dbi-open?}.
9780 @c JP
9781 クエリの結果を閉じます。結果に関連付けられていたリソースが解放されます。
9782 @var{result}は、いったん閉じると使えなくなります。ただし、
9783 @code{dbi-open?}にだけは渡せます。
9784 @c COMMON
9785
9786 @c EN
9787 Although a driver usually releases resources when the result is
9788 garbage-collected, the application shouldn't rely on that and
9789 is recommended call @code{dbi-close} explicitly when it is done
9790 with the result.
9791 @c JP
9792 ドライバは通常、結果がガベージコレクタによって回収される時にリソースを
9793 解放しますが、アプリケーションはこれに依存してはいけません。結果を使い
9794 おわったら明示的に@code{dbi-close}を呼ぶことをおすすめします。
9795 @c COMMON
9796 @end deffn
9797
9798 @node Writing drivers for DBI, , DBI user API, Database independent access layer
9799 @subsection Writing drivers for DBI
9800 @c NODE DBI用のドライバを書く
9801
9802 @c EN
9803 Writing a driver for a specific database system means implementing
9804 a module @code{dbd.@var{foo}}, where @var{foo} is the name of the driver.
9805 @c JP
9806 特定のデータベースシステムのドライバを書くということは、
9807 @code{dbd.@var{foo}}モジュールを実装することです。ここで@var{foo}はド
9808 ライバの名前になります。
9809 @c COMMON
9810
9811 @c EN
9812 The module have to implement several classes and methods, as explained below.
9813 @c JP
9814 このモジュールは以下に説明するいくつかのクラスとメソッドを実装しなけれ
9815 ばなりません。
9816 @c COMMON
9817
9818 @c EN
9819 @subsubheading DBI classes to implement
9820 @c JP
9821 @subsubheading 実装するDBIクラス
9822 @c COMMON
9823
9824 @c EN
9825 You have to define the following classes.
9826 @c JP
9827 以下のクラスを定義しなければなりません。
9828 @c COMMON
9829
9830 @c EN
9831 @itemize @bullet
9832 @item
9833 Subclass @code{<dbi-driver>}.
9834 The class name @emph{must} be @code{<@var{foo}-driver>}, where
9835 @var{foo} is the name of the driver.
9836 Usually this class produces a singleton instance,
9837 and is only used to dispatch @code{dbi-make-connection}
9838 method below.
9839 @item
9840 Subclass @code{<dbi-connection>}. An instance of this class is created
9841 by @code{dbi-make-connection}. It needs to keep the information about
9842 the actual connections.
9843 @item
9844 Subclass @code{<relation>} and @code{<collection>} to represent
9845 query results suitable for the driver. (In most cases, the order of
9846 the result of SELECT statement is significant, since it may be
9847 sorted by ORDER BY clause. Thus it is more appropriate to
9848 inherit @code{<sequence>}, rather than @code{<collection>}).
9849 @item
9850 Optionally, subclass @code{<dbi-query>} to keep driver-specific
9851 information of prepared queries.
9852 @end itemize
9853 @c JP
9854 @itemize @bullet
9855 @item
9856 @code{<dbi-driver>}のサブクラス。このクラスの名前は@emph{必ず}
9857 @code{<@var{foo}-driver>}でなければなりません。ここで、@var{foo}は
9858 ドライバの名前です。通常このクラスはシングルトンインスタンスを生成し、
9859 後述の@code{dbi-make-connection}メソッドをディスパッチするためにのみ利
9860 用されます。
9861 @item
9862 @code{<dbi-connection>}のサブクラス。このクラスのインスタンスは
9863 @code{dbi-make-connection}によって生成されます。そのためには、実際のコ
9864 ネクションに関する情報を保持する必要があります。
9865 @item
9866 ドライバにあったクエリ結果を表現するための@code{<relation>}および
9867 @code{<collection>}のサブクラス。(ほとんどの場合、SELECT文の結果は順序
9868 が重要です。それは、ORDER BY 節によってソートされる可能性があるからで
9869 す。したがって、@code{<sequence>}を継承するほうが、@code{<collection>}
9870 を継承するよりも適切です。)
9871 @item
9872 オプションとして、プリペアドクエリのドライバ特有の情報を保持するため
9873 @code{<dbi-query>}のサブクラスを実装します。
9874 @end itemize
9875 @c COMMON
9876
9877 @c EN
9878 @subsubheading DBI methods to implement
9879 @c JP
9880 @subsubheading 実装するDBIメソッド
9881 @c COMMON
9882
9883 @c EN
9884 The driver need to implement the following methods.
9885 @c JP
9886 ドライバは以下のメソッドを実装しなければなりません。
9887 @c COMMON
9888
9889 @deffn {Method} dbi-make-connection (d <foo-driver>) (options <string>) (options-alist <list>) :key username password @dots{}
9890 @c MOD dbi
9891 @c EN
9892 This method is called from @code{dbi-connect}, and responsible to
9893 connect to the database and to create a connection object.
9894 It must return a connection object, or raise an @code{<dbi-error>} if
9895 it cannot establish a connection.
9896 @c JP
9897 このメソッドは@code{dbi-connect}から呼ばれ、データベースへの接続を担い、
9898 コネクションオブジェクトを作成します。コネクションオブジェクトを返さな
9899 ければなりません。コネクションが確立できない場合には、
9900 @code{<dbi-error>}をあげなければなりません。
9901 @c COMMON
9902
9903 @c EN
9904 @var{Options} is the option part of the data source name (DSN) given to
9905 @code{dbi-connect}. @var{options-alist} is an assoc list of
9906 the result of parsing @var{options}. Both are provided so that
9907 the driver may interpret @var{options} string in nontrivial way.
9908 @c JP
9909 @var{options}は@code{dbi-connect}に与えられるデータソースネーム(DSN)の
9910 オプションパートです。@var{options-alist}は@var{options}を解析した結果
9911 の連想リストです。両方ともに用意して、ドライバが自明ではない方法で
9912 @var{options}文字列を解釈できるようにします。
9913 @c COMMON
9914
9915 @c EN
9916 For example, given @code{"dbi:foo:myaddressbook;host=dbhost;port=8998"}
9917 as DSN, foo's @code{dbi-make-connection} will receive
9918 @code{"myaddressbook;host=dbhost;port=8998"} as @var{options},
9919 and @code{(("myaddressbook" . #t) ("host" . "dbhost") ("port" . "8998"))}
9920 as @var{options-alist}.
9921 @c JP
9922 たとえば、DSNとして
9923 @code{"dbi:foo:myaddressbook;host=dbhost;port=8998"}が与えられたとする
9924 と、fooの@code{dbi-make-connection}は@var{options}として
9925 @code{"myaddressbook;host=dbhost;port=8998"}を受け取り、
9926 @var{options-alist}として
9927 @code{(("myaddressbook" . #t) ("host" . "dbhost") ("port" . "8998"))}
9928 を受け取ります。
9929 @c COMMON
9930
9931 @c EN
9932 After @var{options-alist}, whatever keyword arguments given to
9933 @code{dbi-connect} are passed. DBI protocol currently
9934 specifies only @var{username} and @var{password}.
9935 The driver may define other keyword arguments.
9936 It is recommended to name the driver-specific keyword arguments
9937 prefixed by the driver name, e.g. for @code{dbd.foo}, it may take
9938 a @code{:foo-whatever} keyword argument.
9939 @c JP
9940 @var{options-alist}の後ろならどのようなキーワード引数でも
9941 @code{dbi-connect}に渡せます。DBIプロトコルは現在のところは
9942 @var{username}および@var{password}のみを指定します。
9943 ドライバはその他のキーワード引数を定義できます。
9944 ドライバ特有のキーワード引数にはドライバ名を接頭辞として付けることをお
9945 勧めします。たとえば、@code{dbd.foo}なら、@code{:foo-whatever}のように
9946 です。
9947 @c COMMON
9948
9949 @c EN
9950 It is up to the driver writer to define what options are available and
9951 the syntax of the options. The basic idea is that the DSN
9952 identifies the source of the data; it's role is like URL in WWW.
9953 So, it may include the hostname and port number of the database,
9954 and/or the name of the database, etc. However, it shouldn't include
9955 information related to authentication, such as username and password.
9956 That's why those are passed via keyword arguments.
9957 @c JP
9958 どのようなオプションを使えるようにするか、あるいはオプションの構文をど
9959 うするかはドライバを書く人しだいです。基本的な考え方は、DSN はデータの
9960 ソースを識別するためのものであり、その役割りはWWWにおけるURLのようなも
9961 のだということです。それゆえ、データベースのホスト名、ポート番号、それ
9962 にデータベース名などが含まれることになるでしょう。しかし、ユーザ名やパ
9963 スワードのような認証に関する情報を含めてはいけません。というわけで、そ
9964 の手の情報はキーワード引数で渡すのです。
9965 @c COMMON
9966 @end deffn
9967
9968 @deffn {Method} dbi-prepare (c <foo-connection>) (sql <string>) :key pass-through @dots{}
9969 @c MOD dbi
9970 @c EN
9971 This method should create and return a prepared query object,
9972 which is an instance of @code{<dbi-query>} or its subclass.
9973 The query specified by @var{sql} is issued to the database system
9974 when the prepared query object is passed to @code{dbi-execute}.
9975 @c JP
9976 このメソッドは@code{<dbi-query>}あるいはそのサブクラスのインスタンスで
9977 あるプリペアドクエリオブジェクトを生成し、それを返すものでなくてはなり
9978 ません。@var{sql}によるクエリがデータベースに発行されるのは、プリペア
9979 ドクエリオブジェクトが@code{dbi-execute}に渡されたときです。
9980 @c COMMON
9981
9982 @c EN
9983 The method must set @var{c} to the @code{connection} slot of
9984 the returned query object.
9985 @c JP
9986 このメソッドは返されるクエリオブジェクトの@code{connection}スロットに
9987 @var{c}を設定しなけばなりません。
9988 @c COMMON
9989
9990 @c EN
9991 @var{Sql} is an SQL statement. It may contain placeholders represented
9992 by @code{'?'}. The query closure should take the same number of arguments
9993 as of the placeholders. It is up to the driver whether it parses
9994 @var{sql} internally and construct a complete SQL statement when
9995 the query closure is called, or it passes @var{sql} to the back-end
9996 server to prepare the statement and let the query closure just send
9997 parameters.
9998 @c JP
9999 @var{sql}はSQL文です。これには@code{'?'}で表現されたプレイスホルダが含
10000 まれることがあります。クエリクロージャはこのプレイスホルダと同じ数の引
10001 数をとらなければなりません。内部的に@var{sql}をどのようにパーズするか、
10002 クエリクロージャが呼ばれたとき完全なSQL文を構築するか、@var{sql}をバッ
10003 クエンドのサーバに送って文を準備し、クエリクロージャはパラメータだけを
10004 送るようにするかなどはドライバに依存します。
10005 @c COMMON
10006
10007 @c EN
10008 If the driver parses SQL statement internally, it should recognize
10009 a keyword argument @code{pass-through}. If a true value is given,
10010 the driver must treat @code{sql} opaque and pass it as is when
10011 the query closure is called.
10012 @c JP
10013 ドライバがSQL文を内部的にわたす場合、キーワード引数@code{pass-through}
10014 を認識しなければいけません。もし、真の値が与えられたら、ドライバは
10015 @code{sql}を不透明なものとして扱い、これをそのままクエリクロージャが呼
10016 ばれた際に渡さなければなりません。
10017 @c COMMON
10018
10019 @c EN
10020 The driver may define other keyword arguments.
10021 It is recommended to name the driver-specific keyword arguments
10022 prefixed by the driver name, e.g. for @code{dbd.foo}, it may take
10023 a @code{:foo-whatever} keyword argument.
10024 @c JP
10025 ドライバがその他のキーワード引数を定義することもできます。
10026 その場合、ドライバ特有のキーワード引数にはドライバ名を接頭辞として付け
10027 ることをお勧めします。たとえば、@code{dbd.foo}なら、
10028 @code{:foo-whatever}のようにです。
10029 @c COMMON
10030 @end deffn
10031
10032 @deffn {Method} dbi-execute-using-connection (c <foo-connection>) (q <dbi-query>) (params <list>)
10033 @c MOD dbi
10034 @c EN
10035 This method is called from @code{dbi-execute}.
10036 It must issue the query kept in @var{q}. If the query is parameterized,
10037 the actual parameters given to @var{dbi-execute} are passed to
10038 @var{params} argument.
10039 @c JP
10040 このメソッドは@code{dbi-execute}から呼ばれます。@var{q}が保持するクエ
10041 リを発行しなければなりません。クエリがパラメータ化されている場合、
10042 @var{dbi-execute}に与えられた実際のパラメータは@var{params}引数に渡さ
10043 れます。
10044 @c COMMON
10045
10046 @c EN
10047 If @var{q} is a @code{select}-type query, this method must return
10048 an appropriate relation object.
10049 @c JP
10050 @var{q}が@code{select}-型のクエリの場合は、このメソッドは適切なリレー
10051 ションオブジェクトを返さなければなりません。
10052 @c COMMON
10053 @end deffn
10054
10055 @deffn {Method} dbi-escape-sql (c <foo-connection>) str
10056 @c MOD dbi
10057 @c EN
10058 If the default escape method isn't enough, the driver may
10059 overload this method to implement a specific escaping.
10060 For example, MySQL treats backslash characters specially
10061 as well as single quotes, so it has its @code{dbi-escape-sql}
10062 method.
10063 @c JP
10064 デフォルトのエスケープメソッドでは十分でないとき、ドライバは特別のエス
10065 ケープを行うためにこのメソッドをオーバーロードすることができます。たと
10066 えば、MySQLではバックスラッシュ文字はシングルクォートと同様に特別あつ
10067 かいしますので、@code{dbi-escape-sql}メソッドを持っています。
10068 @c COMMON
10069 @end deffn
10070
10071 @deffn {Method} dbi-open? (c <foo-connection>)
10072 @deffnx {Method} dbi-open? (q <foo-query>)
10073 @deffnx {Method} dbi-open? (r <foo-result>)
10074 @deffnx {Method} dbi-close (c <foo-connection>)
10075 @deffnx {Method} dbi-close (q <foo-query>)
10076 @deffnx {Method} dbi-close (r <foo-result>)
10077 @c MOD dbi
10078 @c EN
10079 Queries open/close status of a connection and a result, and
10080 closes a connection and a result. The close methods should cause
10081 releasing resources used by connection/result. The driver
10082 has to allow @code{dbi-close} to be called on a connection or a
10083 result which has already been closed.
10084 @c JP
10085 これらのメソッドでコネクションおよび結果の状態を調べ、コネクションおよ
10086 び結果を閉じます。closeメソッドはコネクションや結果が利用しているリソー
10087 スを解放しなければなりません。ドライバは@code{dbi-close}がすでに閉じら
10088 れたコネクションや結果に対しても適用できるようにしておかなければなりま
10089 せん。
10090 @c COMMON
10091 @end deffn
10092
10093 @deffn {Method} dbi-do (c <foo-connection>) (sql <string>) :optional options parameter-value @dots{}
10094 @c MOD dbi
10095 @c EN
10096 The default method uses @code{dbi-prepare} and @code{dbi-execute}
10097 to implement the function. It just works,
10098 but the driver may overload this method in order to skip
10099 creating intermediate query object for efficiency.
10100 @c JP
10101 この機能を実装するのにデフォルトメソッドは@code{dbi-prepare}および
10102 @code{dbi-execute}を使っています。これだけでも動きますが、
10103 ドライバは効率のために中間のクエリオブジェクトの生成をスキップするため
10104 にこのメソッドをオーバーロードできます。
10105 @c COMMON
10106 @end deffn
10107
10108 @c EN
10109 @subsubheading DBI utility functions
10110 @c JP
10111 @subsubheading DBIのユーティリティ関数
10112 @c COMMON
10113
10114 @c EN
10115 The following functions are low-level utilities which you may
10116 use to implement the above methods.
10117 @c JP
10118 以下の関数は上述のメソッドを実装するための低レベルのユーティリティです。
10119 @c COMMON
10120
10121 @defun dbi-parse-dsn data-source-name
10122 @c MOD dbi
10123 @c EN
10124 Parse the data source name (DSN) string given to @code{dbi-connect},
10125 and returns tree values: (1) The driver name in a string. (2)
10126 'options' part of DSN as a string. (3) parsed options in an assoc
10127 list. This may raise @code{<dbi-error>} if the given string doesn't
10128 conform DSN syntax.
10129 @c JP
10130 @code{dbi-connect}に与えられたデータソースネーム(DSN)文字列を解析し、
10131 以下の3つの値を返す。(1) ドライバ名(文字列) (2) DSNのオプション部分(文
10132 字列) (3) 解析済オプション(連想リスト)。与えられた文字列がDSN構文に準
10133 拠していない場合には@code{<dbi-error>}があがります。
10134 @c COMMON
10135
10136 @c EN
10137 You don't need to use this to write a typical driver, for the
10138 parsing is done before @code{dbi-make-connection} is called.
10139 This method may be useful if you're writing a kind of meta-driver,
10140 such as a proxy.
10141 @c JP
10142 典型的なドライバを書く場合には必要ありません。構文解析は
10143 @code{dbi-make-connection}を呼ぶ前にすんでいるからです。このメソッドは
10144 プロキシのようなメタドライバという類のものを書くときに便利です。
10145 @c COMMON
10146 @end defun
10147
10148 @defun dbi-prepare-sql connection sql
10149 @c MOD dbi
10150 @c EN
10151 Parses an SQL statement @var{sql} which may contain placeholders,
10152 and returns a closure, which generates a complete SQL statement when
10153 called with actual values for the parameters. If the back-end
10154 doesn't support prepared statements, you may use this function
10155 to prepare queries in the driver.
10156 @c JP
10157 プレイスホルダを含むSQL文 @var{sql} をパーズし、実際の値をパラメータと
10158 して渡されたときに完全なSQLを生成するクロージャを作成します。
10159 バックエンドがプリペアド文をサポートしていない場合は、ドライバ中でクエ
10160 リを準備するのにこの関数を使うことになります。
10161 @c COMMON
10162
10163 @c EN
10164 @var{Connection} is a DBI connection to the database. It is required
10165 to escape values within SQL properly (see @code{dbi-escape-sql} above).
10166 @c JP
10167 @var{connection}はデータベースへのDBIコネクションです。SQL中の値は適切
10168 にエスケープされている必要があります(上述の@code{dbi-escape-sql}をみて
10169 ください)。
10170 @c COMMON
10171
10172 @c EN
10173 @example
10174 ;; assume c contains a valid dbi connection
10175 ((dbi-prepare-sql c "select * from table where id=?") "foo'bar")
10176 => "select * from table where id='foo''bar'"
10177 @end example
10178 @c JP
10179 @example
10180 ;; c は正しいdbiコネクションを持っているとする
10181 ((dbi-prepare-sql c "select * from table where id=?") "foo'bar")
10182 => "select * from table where id='foo''bar'"
10183 @end example
10184 @c COMMON
10185 @end defun
10186
10187 @c ----------------------------------------------------------------------
10188
10189 @node Generic DBM interface, File-system dbm, Database independent access layer, Library modules - Utilities
10190 @section @code{dbm} - Generic DBM interface
10191 @c NODE 汎用DBMインタフェース, @code{dbm} - 汎用DBMインタフェース
10192
10193 @deftp {Module} dbm
10194 @mdindex dbm
10195 @c EN
10196 DBM-like libraries provides an easy way to store values to a file,
10197 indexed by keys. You can think it as a persistent associative memory.
10198 @c JP
10199 DBM系のライブラリはキーでインデックスされた値をファイルに格納する簡単な方法を
10200 提供します。一種の永続的な連想記憶と言えるでしょう。
10201 @c COMMON
10202
10203 @c EN
10204 This modules defines @code{<dbm>} abstract class, which has
10205 a common interface to use various DBM-type database packages.
10206 As far as you operate on the already opened database,
10207 importing @code{dbm} module is enough.
10208 @c JP
10209 このモジュールが定義する抽象クラス@code{<dbm>}は、DBM系ライブラリへの
10210 統一されたインタフェースを提供します。@code{dbm}モジュールだけをインポートすれば、
10211 既にオープンされたデータベースを操作することができます。
10212 @c COMMON
10213
10214 @c EN
10215 To create or open a database, you need a concrete implementation
10216 of the database. With the default build-time configuration,
10217 the following implementations are included in Gauche.
10218 Bindings to various other dbm-like libraries are
10219 available as extension packages.
10220 Each module defines its own low-level accessing functions
10221 as well as the common interface.
10222 Note that your system may not have one or more of those DBM libraries;
10223 Gauche defines only what the system provides.
10224 @c JP
10225 データベースをオープンしたり作成したりするには、dbmインタフェースを実装した
10226 モジュールが必要になります。デフォルトのビルド時コンフィグレーションでは、
10227 以下の実装がGaucheに含まれます。他の様々なdbmライブラリへのバインディングが
10228 拡張パッケージとして提供されています。
10229 それぞれのモジュールは、dbmインタフェース共通の手続きの他に、
10230 直接実装を操作できる低レベルの手続きも提供します。
10231 システムによっては以下のインタフェースの全てが実装されているわけではないことに
10232 注意してください。Gaucheではシステムが提供する実装のみを定義します。
10233 @c COMMON
10234
10235 @table @code
10236 @item dbm.fsdbm
10237 @c EN
10238 file-system dbm (@pxref{File-system dbm}).
10239 @c JP
10240 ファイルシステムdbm (@ref{File-system dbm}参照).
10241 @c COMMON
10242
10243 @item dbm.gdbm
10244 @c EN
10245 GDBM library (@pxref{GDBM interface}).
10246 @c JP
10247 GDBMライブラリ (@ref{GDBM interface}参照).
10248 @c COMMON
10249
10250 @item dbm.ndbm
10251 @c EN
10252 NDBM library (@pxref{NDBM interface}).
10253 @c JP
10254 NDBMライブラリ (@ref{NDBM interface}参照).
10255 @c COMMON
10256
10257 @item dbm.odbm
10258 @c EN
10259 DBM library (@pxref{Original DBM interface}).
10260 @c JP
10261 DBMライブラリ (@ref{Original DBM interface}参照).
10262 @c COMMON
10263 @end table
10264 @end deftp
10265
10266 @c EN
10267 The following code shows a typical usage of the database.
10268 @c JP
10269 以下にdbmデータベースの使用例を示します。
10270 @c COMMON
10271
10272 @example
10273 (use dbm) ; @r{dbm abstract interface}
10274 (use dbm.gdbm) ; @r{dbm concrete interface}
10275
10276 ; @r{open the database}
10277 (define *db* (dbm-open <gdbm> :path "mydb" :rw-mode :write))
10278
10279 ; @r{put the value to the database}
10280 (dbm-put! *db* "key1" "value1")
10281
10282 ; @r{get the value from the database}
10283 (define val (dbm-get *db* "key1"))
10284
10285 ; @r{iterate over the database}
10286 (dbm-for-each *db* (lambda (key val) (foo key val)))
10287
10288 ; @r{close the database}
10289 (dbm-close *db*)
10290 @end example
10291
10292 @c EN
10293 The @code{<dbm>} abstract class implements collection
10294 and dictionary framework. (See @ref{Collection framework}
10295 and @ref{Dictionary framework}, respectively).
10296 @c JP
10297 @var{<dbm>}抽象クラスは、コレクションフレームワークと
10298 ディクショナリフレームワークを実装しています。
10299 (それぞれ@ref{Collection framework}と@ref{Dictionary framework}参照。)
10300 @c COMMON
10301
10302 @menu
10303 * Opening and closing a dbm database::
10304 * Accessing a dbm database::
10305 * Iterating on a database::
10306 * Managing dbm database instance::
10307 * Dumping and restoring dbm database::
10308 * Writing a dbm implementation::
10309 @end menu
10310
10311 @node Opening and closing a dbm database, Accessing a dbm database, Generic DBM interface, Generic DBM interface
10312 @subsection Opening and closing a dbm database
10313 @c NODE DBMデータベースのオープンとクローズ
10314
10315 @deftp {Class} <dbm>
10316 @clindex dbm
10317 @c MOD dbm
10318 @c EN
10319 An abstract class for dbm-style database. Inherits
10320 @code{<dictionary>} (@pxref{Dictionary framework}).
10321 Defines the common
10322 database operations. This class has the following instance slots.
10323 They must be set before the database is actually opened by
10324 @code{dbm-open}.
10325
10326 The concrete class may add more slots for finer control on the database,
10327 such as locking.
10328 @c JP
10329 DBM系のデータベースのための抽象クラスです。
10330 @code{<dictionary>}クラスを継承します (@ref{Dictionary framework}参照)。
10331 データベースへの共通のオペレーションを
10332 定義します。以下のインスタンススロットを持ちます。これらのスロットの値は
10333 @code{dbm-open}によってデータベースがオープンされる前にセットされて
10334 いなければなりません。
10335
10336 具体クラスは、データベースの操作をより細かく行うための追加のスロット(例えばロックを
10337 行うかどうか)を持つかもしれません。
10338 @c COMMON
10339
10340 @defivar <dbm> path
10341 @c EN
10342 Pathname of the dbm database. Some dbm implementation may append
10343 suffixes to this.
10344 @c JP
10345 データベースファイルのパス名。dbmの実装によっては、このパスにサフィックスが追加されます。
10346 @c COMMON
10347 @end defivar
10348
10349 @defivar <dbm> rw-mode
10350 @c EN
10351 Specifies read/write mode. Can be either one of the following keywords:
10352 @table @code
10353 @item :read
10354 The database will be opened in read-only mode. The database file must
10355 exist when @code{dbm-open} is called.
10356 @item :write
10357 The database will be opened in Read-write mode.
10358 If the database file does not exist, @code{dbm-open} creates one.
10359 @item :create
10360 The database will be created and opened in Read-write mode.
10361 If the database file exists, @code{dbm-open} truncates it.
10362 @end table
10363 @c JP
10364 読み書きのモードを指定します。以下の値のいずれかを取ります。
10365 @table @code
10366 @item :read
10367 データベースは@code{dbm-open}によって読みだし専用モードでオープンされます。
10368 オープンされる時点でデータベースは存在していなければなりません。
10369 @item :write
10370 データベースは@code{dbm-open}によって読み書き可能なモードでオープンされます。
10371 データベースが存在しなければ、@code{dbm-open}は新しいデータベースを作成します。
10372 @item :create
10373 @code{dbm-open}によって新しいデータベースが作成され、読み書き可能なモードでオープンされます。
10374 既にデータベースが存在していた場合、その内容はクリアされます。
10375 @end table
10376 @c COMMON
10377 @end defivar
10378
10379 @defivar <dbm> file-mode
10380 @c EN
10381 Specifies the file permissions (as @code{sys-chmod}) to create the
10382 database. The default value is @code{#o664}.
10383 @c JP
10384 データベースが作成されるときのファイルパーミッションを指定します。
10385 デフォルトは@code{#o664}です。
10386 @c COMMON
10387 @end defivar
10388
10389 @defivar <dbm> key-convert
10390 @defivarx <dbm> value-convert
10391 @c EN
10392 By default, you can use only strings for both key and values. With this
10393 option, however, you can specify how to convert other Scheme values to/from
10394 string to be stored in the database. The possible values are the
10395 followings:
10396 @table @asis
10397 @item @code{#f}
10398 The default value. Keys (values) are not converted. They must be
10399 a string.
10400 @item @code{#t}
10401 Keys (values) are converted to its string representation, using
10402 @code{write}, to store in the database, and converted
10403 back to Scheme values, using @code{read}, to retrieve from the database.
10404 The data must have an external representation that can be read back.
10405 (But it is not checked when the data is written; you'll get an error
10406 when you read the data). The key comparison is done in the string
10407 level, so the external representation of the same key must match.
10408 @item a list of two procedures
10409 Both procedure must take a single argument. The first procedure must
10410 receive a Scheme object and returns a string. It is used to convert
10411 the keys (values) to store in the database. The second procedure
10412 must receive a string and returns a Scheme object. It is used to
10413 convert the stored data in the database to a Scheme object.
10414 The key comparison is done in the string
10415 level, so the external representation of the same key must match.
10416 @end table
10417 @c JP
10418 デフォルトでは、dbmデータベースはキーにも値にも文字列しか使うことはできません。
10419 これらのスロットによって、それ以外のSchemeオブジェクトを取り扱う方法を指定することが
10420 できます。以下の値のいずれかが可能です。
10421 @table @asis
10422 @item @code{#f}
10423 デフォルトの値です。キーあるいは値は変換されません。それらは文字列でなければなりません。
10424 @item @code{#t}
10425 キーあるいは値は@code{write}を使って文字列に変換されデータベースに格納されます。
10426 そして@code{read}を使って文字列からSchemeオブジェクトへと変換されます。
10427 後で@code{read}で読みこめるようなキーあるいは値のみを扱うことができます。
10428 (但し、dbmライブラリは書き込み時にそれが後で読み込めるかどうかのチェックは行いません)。
10429 キーの比較は文字列に変換された後で行われるので、同じ値となるキーは同じ文字列表現を
10430 持つ必要があります。
10431 @item 二つの手続きのリスト
10432 どちらの手続きも一つの引数を取ります。最初の手続きはSchemeオブジェクトを受け取り、
10433 文字列を返します。キーあるいは値をデータベースに格納する時に呼ばれます。
10434 二つ目の手続きは文字列を受け取りSchemeオブジェクトを返します。データベースから
10435 キーあるいは値を取り出す時に呼ばれます。
10436 キーの比較は文字列に変換された後で行われるので、同じ値となるキーは同じ文字列に
10437 変換される必要があります。
10438 @end table
10439 @c COMMON
10440 @end defivar
10441 @end deftp
10442
10443 @deftp {Metaclass} <dbm-meta>
10444 @clindex dbm-meta
10445 @c MOD dbm
10446 @c EN
10447 A metaclass of @code{<dbm>} and its subclasses.
10448 @c JP
10449 @var{<dbm>}クラス及びそのサブクラスのメタクラスです。
10450 @c COMMON
10451 @end deftp
10452
10453 @deffn {Method} dbm-open (dbm <dbm>)
10454 @c MOD dbm
10455 @c EN
10456 Opens a dbm database. @var{dbm} must be an instance of
10457 one of the concrete classes that derived from the @code{<dbm>} class,
10458 and its slots must be set appropriately. On success, it returns
10459 the @var{dbm} itself. On failure, it signals an error.
10460 @c JP
10461 DBMデータベースをオープンします。@var{dbm}は、@code{<dbm>}クラスを継承した
10462 具体クラスのインスタンスでなければなりません。また、そのスロットには適切な値が
10463 セットされている必要があります。オープンに成功したら@var{dbm}自身が返されます。
10464 失敗した場合はエラーが報告されます。
10465 @c COMMON
10466 @end deffn
10467
10468 @deffn {Method} dbm-open (dbm-class <dbm-meta>) options @dots{}
10469 @c MOD dbm
10470 @c EN
10471 A convenient method that creates dbm instance and opens it.
10472 It is defined as follows.
10473 @c JP
10474 DBMインスタンスを作成してオープンするための便利なメソッドです。
10475 次のように定義されます。
10476 @c COMMON
10477 @example
10478 (define-method dbm-open ((class <class>) . initargs)
10479 (dbm-open (apply make class initargs)))
10480 @end example
10481 @end deffn
10482
10483 @c EN
10484 Database file is closed when it is garbage collected.
10485 However, to ensure the modification is properly synchronized,
10486 you should close the database explicitly.
10487 @c JP
10488 データベースファイルはガベージコレクトされる際にクローズされますが、
10489 変更を正しくデータベースに反映するには、明示的にクローズした方が良いでしょう。
10490 @c COMMON
10491
10492 @deffn {Method} dbm-close (dbm @code{<dbm>})
10493 @c MOD dbm
10494 @c EN
10495 Closes a database @var{dbm}. Once the database is closed, any
10496 operation to access the database content raises an error.
10497 @c JP
10498 データベース@var{dbm}をクローズします。データベースがクローズされると、
10499 それ以降のアクセスオペレーションはエラーとなります。
10500 @c COMMON
10501 @end deffn
10502
10503 @deffn {Method} dbm-closed? (dbm @code{<dbm>})
10504 @c MOD dbm
10505 @c EN
10506 Returns true if a database @var{dbm} is already closed, false otherwise.
10507 @c JP
10508 データベース@var{dbm}が既にクローズされていたら@code{#t}を返します。
10509 @c COMMON
10510 @end deffn
10511
10512 @defun dbm-type->class dbmtype
10513 @c MOD dbm
10514 Sometimes you don't know which type of dbm implementation you
10515 need to use in your application beforehand, but rather you need to
10516 determine the type according to the information given at run-time.
10517 This procedure fulfills the need.
10518
10519 The @var{dbmtype} argument is a symbol that names the type
10520 of dbm implementation; for example, @code{gdbm} for @code{dbm.gdbm},
10521 and @code{fsdbm} for @code{dbm.fsdbm}. We assume that the
10522 dbm implementation of type @code{@var{foo}} is provided as
10523 a module @code{dbm.@var{foo}}, and its class is named
10524 as @code{<@var{foo}>}.
10525
10526 This procedure first checks if the required module has been
10527 loaded, and if not, it tries to load it. If the module
10528 loads successfully, it returns the class object of the
10529 named dbm implementation. If it can't load the module,
10530 or can't find the dbm class, this procedure returns #f.
10531
10532 @example
10533 (use dbm)
10534
10535 (dbm-type->class 'gdbm)
10536 @result{} @code{#<class <gdbm>>}
10537
10538 (dbm-type->class 'nosuchdbm)
10539 @result{} @code{#f}
10540 @end example
10541 @end defun
10542
10543 @node Accessing a dbm database, Iterating on a database, Opening and closing a dbm database, Generic DBM interface
10544 @subsection Accessing a dbm database
10545 @c NODE DBMデータベースのアクセス
10546
10547 @c EN
10548 Once a database is opened, you can use the following methods
10549 to access individual key/value pairs.
10550 @c JP
10551 データベースがオープンされたら、以下のアクセスメソッドが使えます。
10552 @c COMMON
10553
10554 @deffn {Method} dbm-put! (dbm @code{<dbm>}) key value
10555 @c MOD dbm
10556 @c EN
10557 Put a @var{value} with @var{key}.
10558 @c JP
10559 値@var{value}をキー@var{key}と関連付けて保存します。
10560 @c COMMON
10561 @end deffn
10562
10563 @deffn {Method} dbm-get (dbm @code{<dbm>}) key :optional default
10564 @c MOD dbm
10565 @c EN
10566 Get a value associated with @var{key}. If no value exists for @var{key}
10567 and @var{default} is specified, it is returned. If no value exists for
10568 @var{key} and @var{default} is not specified, an error is signaled.
10569 @c JP
10570 キー@var{key}に関連付けられた値を返します。もし値が存在しなければ、@var{default}が
10571 与えられていればそれを返し、そうでなければエラーを報告します。
10572 @c COMMON
10573 @end deffn
10574
10575 @deffn {Method} dbm-exists? (dbm @code{<dbm>}) key
10576 @c MOD dbm
10577 @c EN
10578 Return true if a value exists for @var{key}, false otherwise.
10579 @c JP
10580 キー@var{key}に関連付けられた値が存在すれば@code{#t}を返します。
10581 @c COMMON
10582 @end deffn
10583
10584 @deffn {Method} dbm-delete! (dbm @code{<dbm>}) key
10585 @c MOD dbm
10586 @c EN
10587 Delete a value associated with @var{key}.
10588 @c JP
10589 キー@var{key}に関連付けられた値を消去します。値が存在しない場合は何もしません。
10590 @c COMMON
10591 @end deffn
10592
10593 @node Iterating on a database, Managing dbm database instance, Accessing a dbm database, Generic DBM interface
10594 @subsection Iterating on a dbm database
10595 @c NODE DBMデータベース上の繰り返し処理
10596
10597 @c EN
10598 To walk over the entire database, following methods are provided.
10599 @c JP
10600 全データベースを渡り歩く処理のために、以下のメソッドが用意されています。
10601 @c COMMON
10602
10603 @deffn {Method} dbm-fold (dbm @code{<dbm>}) procedure knil
10604 @c MOD dbm
10605 @c EN
10606 The basic iterator.
10607 For each key/value pair, @var{procedure} is called as
10608 @code{(@var{procedure} @var{key} @var{value} @var{r})},
10609 where @var{r} is @var{knil} for the fist call of @var{procedure},
10610 and the return value of the previous call for subsequent calls.
10611 Returns the result of the last call of @var{procedure}.
10612 If no data is in the database, @var{knil} is returned.
10613
10614 The following method returns the sum of all the integer values.
10615 @c JP
10616 基本的な繰り返し処理です。データベース内の各キー/値のペアに関して、手続き
10617 @var{procedure}が @code{(@var{procedure} @var{key} @var{value} @var{r})},
10618 のように呼ばれます。ここで@var{r}は、最初の@var{procedure}の呼び出しの時には@var{knil}
10619 が、以降の呼び出しの時にはその直前の@var{procedure}が返した値が渡されます。
10620 最後の@var{procedure}の戻り値が@code{dbm-fold}の戻り値となります。
10621 データベース中にデータがひとつもなければ@var{knil}がそのまま返されます。
10622
10623 次の例は、データベース中の整数の値を全て加算します。
10624 @c COMMON
10625 @example
10626 (dbm-fold dbm (lambda (k v r) (if (integer? v) (+ v r) r)) 0)
10627 @end example
10628 @end deffn
10629
10630 @deffn {Method} dbm-for-each (dbm @code{<dbm>}) procedure
10631 @c MOD dbm
10632 @c EN
10633 For each key/value pair in the database @var{dbm}, @var{procedure}
10634 is called. Two arguments are passed to @var{procedure}---a key and
10635 a value. The result of @var{procedure} is discarded.
10636 @c JP
10637 データベース内の各キー/値のペアに関して、手続き@var{procedure}を呼び出します。
10638 @var{procedure}にはキーと値が渡されます。@var{procedure}の戻り値は捨てられます。
10639 @c COMMON
10640 @end deffn
10641
10642 @deffn {Method} dbm-map (dbm @code{<dbm>}) procedure
10643 @c MOD dbm
10644 @c EN
10645 For each key/value pair in the database @var{dbm}, @var{procedure}
10646 is called. Two arguments are passed to @var{procedure}---a key and
10647 a value. The result of @var{procedure} is accumulated to a list
10648 which is returned as a result of @code{dbm-map}.
10649 @c JP
10650 データベース内の各キー/値のペアに関して、手続き@var{procedure}を呼び出します。
10651 @var{procedure}にはキーと値が渡されます。@var{procedure}の戻り値はリストに
10652 集められて@code{dbm-map}の戻り値となります。
10653 @c COMMON
10654 @end deffn
10655
10656 @node Managing dbm database instance, Dumping and restoring dbm database, Iterating on a database, Generic DBM interface
10657 @subsection Managing dbm database instance
10658 @c NODE DBMデータベースインスタンスの管理
10659
10660 @c EN
10661 Each dbm implementation has its own way to store the
10662 database. Legacy dbm uses two files, whose names are
10663 generated by adding @file{.dir} and @file{.pag} to the
10664 value of @var{path} slot. @code{Fsdbm} creates a directory
10665 under @var{path}. If dbm database is backed up by
10666 some database server, @var{path} may be used only as
10667 a key to the database in the server.
10668 @c JP
10669 各DBM実装は、データベースを格納するのに独自の方法を使います。
10670 レガシーなDBMは、@var{path}スロットの値にそれぞれ@file{.dir}と
10671 @file{.pag}を付けた名前の2つのファイルを使います。
10672 @code{fsdbm}は@var{path}の下にディレクトリを作ります。
10673 DBMデータベースが他のデータベースサーバによってバック
10674 アップされる場合は、@var{path}はそのサーバで単なるキーと
10675 して使われるでしょう。
10676
10677 @c EN
10678 The following methods hide such variations and provides
10679 a convenient way to manage a database itself. You have to
10680 pass a class that implements a concrete dbm database to their
10681 first argument.
10682 @c JP
10683 以下のメソッドは、そのようなバリエーションを隠し、
10684 データベースそれ自体を管理する簡易な方法を提供します。
10685 最初の引数に、具体的なDBMデータベースを実装している
10686 クラスを渡す必要があります。
10687 @c COMMON
10688
10689 @deffn {Generic Function} dbm-db-exists? class name
10690 @c MOD dbm
10691 @c EN
10692 Returns @code{#t} if a database of class @var{class}
10693 specified by @var{name} exists.
10694 @c JP
10695 @var{name}で指定された@var{class}クラスのデータベースが
10696 存在する場合は@code{#t}を返します。
10697 @c COMMON
10698
10699 @example
10700 ;; Returns #t if testdb.dir and testdb.pag exist
10701 (dbm-db-exists? <odbm> "testdb")
10702 @end example
10703 @end deffn
10704
10705 @deffn {Generic Function} dbm-db-remove class name
10706 @c MOD dbm
10707 @c EN
10708 Removes an entire database of class @var{class} specified by
10709 @var{name}.
10710 @c JP
10711 @var{name}で指定される@var{class}クラスのデータベース
10712 全体を削除します。
10713 @c COMMON
10714 @end deffn
10715
10716 @deffn {Generic Function} dbm-db-copy class from to
10717 @c MOD dbm
10718 @c EN
10719 Copy a database of class @var{class} specified by
10720 @var{from} to @var{to}. The integrity of @var{from}
10721 is guaranteed if the @var{class}'s dbm implementation supports
10722 locking (i.e. you won't get a corrupted database even if
10723 some other process is trying to write to @var{from}
10724 during copy). If the destination database @var{to} exists,
10725 its content is destroyed. If this function is interrupted,
10726 whether @var{to} is left in incomplete state or not depends
10727 on the dbm implementation. The implementation usually tries
10728 its best to provide transactional behavior, that is,
10729 to recover original @var{to} when the copy fails. However,
10730 for the robust operations the caller have to check the state
10731 of @var{to} if @code{dbm-db-copy} fails.
10732 @c JP
10733 @var{from}で指定された@var{class}クラスのデータベースを
10734 @var{to}へコピーします。
10735 @var{class}のdbm実装がロックをサポートしている限り、@var{from}の一貫性は
10736 保たれます (つまり、コピー中に他のプロセスが@var{from}を
10737 変更しようとした場合であっても、@var{to}が壊れたデータベースになることは
10738 ありません)。 もしコピー先の@var{to}が既に存在するデータベースで
10739 あった場合、@var{to}の元の内容は失われます。
10740 コピーが中断された場合に@var{to}が不完全な状態のままになるかどうかは
10741 dbm実装に依存します。dbm実装の多くはトランザクショナルな振る舞い、
10742 すなわち、コピーが失敗した場合に元の@var{to}を復元することを試みます。
10743 しかし確実な操作のためには、コピーが失敗した場合には呼び出し側で@var{to}の
10744 状態を確認することが必要です。
10745 @c COMMON
10746
10747 @example
10748 (dbm-db-copy <gdbm> "testdb.dbm" "backup.dbm")
10749 @end example
10750 @end deffn
10751
10752 @deffn {Generic Function} dbm-db-move class from to
10753 @c MOD dbm
10754 @c EN
10755 Moves or renames a database of class @var{class} specified by
10756 @var{from} to @var{to}. Like @code{dbm-db-copy}, the database
10757 integrity is guaranteed as far as @var{class}'s dbm implementation
10758 supports locking. If the destination database @var{to} exists,
10759 its content is destroyed.
10760 @c JP
10761 @var{from}で指定された@var{class}クラスのデータベースを
10762 @var{to}へ移動、あるいはリネームします。@code{dbm-db-copy}と同じく、
10763 @var{class}のdbm実装がロックをサポートしていれば
10764 データベースの一貫性は保証されます。移動先の@var{to}が既に
10765 存在していた場合、その元の内容は失われます。
10766 @c COMMON
10767 @end deffn
10768
10769 @node Dumping and restoring dbm database, Writing a dbm implementation, Managing dbm database instance, Generic DBM interface
10770 @subsection Dumping and restoring dbm database
10771 @c NODE DBMデータベースのダンプとリストア
10772
10773 Most dbm implementations use some kind of binary format, and
10774 some of them are architecture dependent.
10775 That makes it difficult to pass around dbm databases
10776 between different machines.
10777 A safe way is to write out the content of a dbm database
10778 into some portable format on the source machine,
10779 and rebuild another dbm database from it on the destination
10780 machine.
10781
10782 The operation is so common that Gauche provides convenience
10783 scripts that does the job. They are installed into the
10784 standard Gauche library directory, so it can be invoked
10785 by @code{gosh <scriptname>}.
10786
10787 To write out the content of a dbm database named by @var{dbm-name},
10788 you can use @code{dbm/dump} script:
10789
10790 @example
10791 $ gosh dbm/dump [-o @var{outfile}][-t @var{type}] @var{dbm-name}
10792 @end example
10793
10794 The @var{outfile} argument names the output file. If omitted,
10795 the output is written out to stdout. The @var{type} argument
10796 specifies the implementation type of the dbm database; e.g.
10797 @code{gdbm} or @code{fsdbm}. The program calls
10798 @code{dbm-type->class} (@pxref{Opening and closing a dbm database})
10799 on the @var{type} argument to load the necessary dbm implementation.
10800
10801 The dumped format is simply a series of S-expressions,
10802 each of which is a dotted pair of string key and string value.
10803 Character encodings are assumed to be the same as
10804 @code{gosh}'s native character encoding.
10805
10806 The dumped output may contain S-expressions other than dotted pair
10807 of strings to include meta information. For now, programs
10808 that deals with dumped output should just ignore S-expressions
10809 other than dotted pairs.
10810
10811 To read back the dumped dbm format, you can use @code{dbm/restore}
10812 script:
10813
10814 @example
10815 $ gosh dbm/restore [-i @var{infile}][-t @var{type}] @var{dbm-name}
10816 @end example
10817
10818 The @var{infile} argument names the dumped file to be read.
10819 If omitted, it reads from stdin. The @var{type} argument
10820 specifies the dbm type, as in @code{dbm/dump} script.
10821 The @var{dbm-name} argument names the dbm database; if the
10822 database already exists, its content is cleared, so be careful.
10823
10824
10825 @node Writing a dbm implementation, , Dumping and restoring dbm database, Generic DBM interface
10826 @subsection Writing a dbm implementation
10827 @c NODE DBM実装を書く
10828
10829 When you write an extension module that behaves like
10830 a persistent hashtable, it is a good idea to adapt it
10831 to the dbm interface, so that the application can use
10832 the module in a generic way.
10833
10834 The minimum procedures to conform the dbm interface
10835 are as follow:
10836
10837 @itemize @bullet
10838 @item
10839 Define a metaclass @code{<@var{foo}-meta>}. It doesn't
10840 need to inherit anything except @code{<class>}.
10841 @item
10842 Define a dbm class @code{<@var{foo}>} that inherits @code{<dbm>}
10843 and whose metaclass is @code{<@var{foo}-meta>}.
10844 @item
10845 Define methods for @code{dbm-open}, @code{dbm-close},
10846 @code{dbm-put!}, @code{dbm-get}, @code{dbm-exists},
10847 @code{dbm-delete!}, @code{dbm-fold}, @code{dbm-closed?},
10848 specialized for @code{<@var{foo}>}.
10849 (The case of @code{dbm-open} for @code{<@var{foo}-meta>} is
10850 handled automatically, so you don't need to define it unless
10851 you want something special).
10852 Also note that the specialized @code{dbm-open} must call
10853 @code{next-method} in it to set up dbm base class internals.
10854 @item
10855 Define methods for @code{dbm-db-exists?} and
10856 @code{dbm-db-remove} on @code{<@var{foo}-meta>}.
10857 @end itemize
10858
10859 Besides above, you may define the following methods.
10860
10861 @itemize @bullet
10862 @item
10863 Methods for @code{dbm-for-each} and @code{dbm-map}.
10864 If you don't define them, a generic implementation
10865 by @code{dbm-fold} is used. There may be an implementation
10866 specific way which is more efficient.
10867 @item
10868 Methods for @code{dbm-db-copy} and @code{dbm-db-move}.
10869 If you don't define them, a fallback method
10870 opens the specified databases and copies elements one by
10871 one, and removes the original if the method is @code{dbm-db-move}.
10872 Note that the fallback method is not only inefficient,
10873 but also it may not copy any implementation-specific
10874 meta information. It is highly recommended for the
10875 dbm implementation to provide these methods as well.
10876 @end itemize
10877
10878 It is generally recommended to name the implementation module
10879 as @code{dbm.@var{foo}}, and the class of the implementation
10880 as @code{<@var{foo}>}. With this convention it is easier to
10881 write an application that dynamically loads and uses
10882 dbm implementation specified at runtime.
10883
10884 @c ----------------------------------------------------------------------
10885 @node File-system dbm, GDBM interface, Generic DBM interface, Library modules - Utilities
10886 @section @code{dbm.fsdbm} - File-system dbm
10887 @c NODE ファイルシステムdbm, @code{dbm.fsdbm} - ファイルシステムdbm
10888
10889 @deftp {Module} dbm.fsdbm
10890 @mdindex dbm.fsdbm
10891 Implements fsdbm. Extends @code{dbm}.
10892 @end deftp
10893
10894 @deftp {Class} <fsdbm>
10895 @clindex fsdbm
10896 @c MOD dbm.fsdbm
10897 @c EN
10898 @code{Fsdbm} is a dbm implementation that directly uses
10899 the filesystem. Basically, it uses file names for keys,
10900 and file content for values. Unlike other dbm implementations,
10901 this doesn't depend on external libraries---it is pure Scheme
10902 implementation---so it is always available, while other dbm
10903 implementations may not.
10904 @c JP
10905 @code{fsdbm}は、直接ファイルシステムを扱うDBM実装です。
10906 基本的には、ファイル名をキー、ファイルの内容を値として使います。
10907 他のDBM実装とは違い、これは他の特別なライブラリに依存しません
10908 (純粋にSchemeのみにより実装されています)。
10909 したがって、他のDBM実装が使えないときでも、いつでも使うことが
10910 できます。
10911
10912 @c EN
10913 Obviously, it is not suitable for the database that has
10914 lots of entries, or has entries deleted and added very frequently.
10915 The advantage is when the number of entries
10916 are relatively small, and the values are relatively large while
10917 keys are small.
10918 @c JP
10919 明らかに、たくさんのエントリを持っていたり、エントリの追加や
10920 削除が頻繁に起こるようなデータベースには向いていません。
10921 エントリの数が相対的に小さく、キーが小さいのに値が大きいような
10922 場合に向いています。
10923
10924 @c EN
10925 The database name given to @code{<fsdbm>} instance
10926 is used as a directory name that stores the data.
10927 @c JP
10928 @code{<fsdbm>}のインスタンスに与えられるデータベース名は、
10929 データを格納するディレクトリの名前として使われます。
10930
10931 @c EN
10932 The data files are stored in subdirectories under @var{path} of
10933 @code{fsdbm} instance, hashed by the key. Non-alphanumeric characters
10934 in the key is encoded like @code{_3a} for '@code{:}', for example.
10935 If a key is too long to be a file name, it is chopped to chunks,
10936 and each chunk but the last one is used as a directory name.
10937 Note that a long key name may still cause a problem, for example,
10938 some of old 'tar' command can't deal with pathnames (not each
10939 pathname components, but the entire pathname) longer than 256
10940 characters.
10941 @c JP
10942 データのファイルは、@code{fsdbm}インスタンスの@var{path}の
10943 サブディレクトリに格納され、キーによりハッシュされます。
10944 キーに英数字でない文字がある場合はエンコードされます。
10945 例えば、'@code{:}'は、@code{_3a}にエンコードされます。
10946 キーがファイル名としては長すぎる場合は、いくつかに
10947 分割され、その最後の文字列片以外はディレクトリ名として
10948 使われます。長いキー名は問題を引き起こすかも知れないことに
10949 注意して下さい。例えば、いくつかの古い'tar'コマンドは、256文字
10950 を越える長いパス名を扱えません(それぞれのパスコンポーネント
10951 ではなく、パス名全体でです)。
10952 @c COMMON
10953 @end deftp
10954
10955 @c EN
10956 Fsdbm implements all of the dbm protocol
10957 (see @ref{Generic DBM interface}).
10958 It doesn't have any fsdbm-specific procedures.
10959 @c JP
10960 fsdbmは、全てのDBMプロトコルを実装しています
10961 (@ref{Generic DBM interface}参照)。
10962 fsdbm特有の手続きというものはありません。
10963 @c COMMON
10964
10965 @c ----------------------------------------------------------------------
10966 @node GDBM interface, NDBM interface, File-system dbm, Library modules - Utilities
10967 @section @code{dbm.gdbm} - GDBM interface
10968 @c NODE GDBMインタフェース, @code{dbm.gdbm} - GDBMインタフェース
10969
10970 @deftp {Module} dbm.gdbm
10971 @mdindex dbm.gdbm
10972 Provides interface to the gdbm library. Extends @code{dbm}.
10973 @end deftp
10974
10975 @deftp {Class} <gdbm>
10976 @clindex gdbm
10977 @c MOD dbm.gdbm
10978 @c EN
10979 Inherits @code{<dbm>}. Provides an implementation for GDBM library.
10980 This module is only installed when your system already has GDBM
10981 (1.8.0 is preferred, but works with older 1.7.x with some limitations).
10982 @c JP
10983 @code{<dbm>} を継承します。GDBM ライブラリのための実装を提供します。
10984 このモジュールは、すでにあなたのシステムにすでに GDBM がある場合にのみ
10985 インストールされます(バージョン 1.8.0 が推奨されますが、いくつかの制限が
10986 あるだけで古い 1.7.x でも動作します)。
10987 @c COMMON
10988
10989 @defivar <gdbm> sync
10990 @end defivar
10991 @defivar <gdbm> nolock
10992 @end defivar
10993 @defivar <gdbm> bsize
10994 @end defivar
10995 @end deftp
10996
10997 @c EN
10998 Besides the unified DBM interface (@pxref{Generic DBM interface}),
10999 this module provides the following low-level functions that provides
11000 direct access to the gdbm API. See gdbm manual for details of these
11001 APIs.
11002 @c JP
11003 統合された DBM インターフェース (@pxref{Generic DBM interface}) の
11004 他に、このモジュールでは GDBM API への直接のアクセスを提供する以下の
11005 低レベルな手続きを提供しています。これらの API の詳細については GDBM の
11006 マニュアルを見て下さい。
11007 @c COMMON
11008
11009 @defun gdbm-open path :optional size rwmode fmode error-callback
11010 @c MOD dbm.gdbm
11011 @end defun
11012
11013 @defvar GDBM_READER
11014 @c MOD dbm.gdbm
11015 @end defvar
11016
11017 @defvar GDBM_WRITER
11018 @c MOD dbm.gdbm
11019 @end defvar
11020
11021 @defvar GDBM_WRCREAT
11022 @c MOD dbm.gdbm
11023 @end defvar
11024
11025 @defvar GDBM_NEWDB
11026 @c MOD dbm.gdbm
11027 @end defvar
11028
11029 @defvar GDBM_FAST
11030 @c MOD dbm.gdbm
11031 @end defvar
11032
11033 @defvar GDBM_SYNC
11034 @c MOD dbm.gdbm
11035 @end defvar
11036
11037 @defvar GDBM_NOLOCK
11038 @c MOD dbm.gdbm
11039 @end defvar
11040
11041 @defun gdbm-close gdbm-object
11042 @c MOD dbm.gdbm
11043 @end defun
11044
11045 @defun gdbm-closed? gdbm-object
11046 @c MOD dbm.gdbm
11047 @end defun
11048
11049 @defun gdbm-store key value :optional flag
11050 @c MOD dbm.gdbm
11051 @end defun
11052
11053 @defvar GDBM_INSERT
11054 @c MOD dbm.gdbm
11055 @end defvar
11056
11057 @defvar GDBM_REPLACE
11058 @c MOD dbm.gdbm
11059 @end defvar
11060
11061
11062 @defun gdbm-fetch gdbm-object key
11063 @c MOD dbm.gdbm
11064 @end defun
11065
11066
11067 @defun gdbm-delete gdbm-object key
11068 @c MOD dbm.gdbm
11069 @end defun
11070
11071
11072 @defun gdbm-firstkey gdbm-object
11073 @c MOD dbm.gdbm
11074 @end defun
11075
11076
11077 @defun gdbm-nextkey gdbm-object key
11078 @c MOD dbm.gdbm
11079 @end defun
11080
11081
11082 @defun gdbm-reorganize gdbm-object
11083 @c MOD dbm.gdbm
11084 @end defun
11085
11086
11087 @defun gdbm-sync gdbm-object
11088 @c MOD dbm.gdbm
11089 @end defun
11090
11091
11092 @defun gdbm-exists? gdbm-object key
11093 @c MOD dbm.gdbm
11094 @end defun
11095
11096
11097 @defun gdbm-strerror errno
11098 @c MOD dbm.gdbm
11099 @end defun
11100
11101
11102 @defun gdbm-setopt gdbm-object option value
11103 @c MOD dbm.gdbm
11104 @end defun
11105
11106 @defvar GDBM_CACHESIZE
11107 @c MOD dbm.gdbm
11108 @end defvar
11109
11110 @defvar GDBM_FASTMODE
11111 @c MOD dbm.gdbm
11112 @end defvar
11113
11114 @defvar GDBM_SYNCMODE
11115 @c MOD dbm.gdbm
11116 @end defvar
11117
11118 @defvar GDBM_CENTFREE
11119 @c MOD dbm.gdbm
11120 @end defvar
11121
11122 @defvar GDBM_COALESCEBLKS
11123 @c MOD dbm.gdbm
11124 @end defvar
11125
11126 @defun gdbm-version
11127 @c MOD dbm.gdbm
11128 @end defun
11129
11130 @defun gdbm-errno
11131 @c MOD dbm.gdbm
11132 @end defun
11133
11134 @c ----------------------------------------------------------------------
11135 @node NDBM interface, Original DBM interface, GDBM interface, Library modules - Utilities
11136 @section @code{dbm.ndbm} - NDBM interface
11137 @c NODE NDBMインタフェース, @code{dbm.ndbm} - NDBMインタフェース
11138
11139 @deftp {Module} dbm.ndbm
11140 @mdindex dbm.ndbm
11141 Provides interface to the 'new' dbm library, a.k.a. ndbm.
11142 Extends @code{dbm}.
11143 @end deftp
11144
11145 @deftp {Class} <ndbm>
11146 @clindex ndbm
11147 @c MOD dbm.ndbm
11148 @c EN
11149 Inherits @code{<dbm>}. Provides an implementation for NDBM library.
11150 This module is only installed when your system already has NDBM.
11151 @c JP
11152 @code{<dbm>} を継承します。NDBM ライブラリのための実装を提供します。
11153 このモジュールはあなたのシステムにすでに NDBM がある場合にのみ
11154 インストールされます。
11155 @c COMMON
11156 @end deftp
11157
11158 @c EN
11159 Besides the unified DBM interface (@pxref{Generic DBM interface}),
11160 this module provides the following low-level functions that provides
11161 direct access to the ndbm API. See ndbm manual for details of these
11162 APIs.
11163 @c JP
11164 統合された DBM インターフェース (@pxref{Generic DBM interface}) の
11165 他に、このモジュールでは NDBM API への直接のアクセスを提供する以下の
11166 低レベルな手続きを提供しています。これらの API の詳細については NDBM の
11167 マニュアルを見て下さい。
11168 @c COMMON
11169
11170 @defun ndbm-open path flags mode
11171 @c MOD dbm.ndbm
11172 @end defun
11173
11174 @defun ndbm-close ndbm-object
11175 @c MOD dbm.ndbm
11176 @end defun
11177
11178 @defun ndbm-closed? ndbm-object
11179 @c MOD dbm.ndbm
11180 @end defun
11181
11182 @defun ndbm-store ndbm-object key content :optional flag
11183 @c MOD dbm.ndbm
11184 @end defun
11185
11186 @defun ndbm-fetch ndbm-object key
11187 @c MOD dbm.ndbm
11188 @end defun
11189
11190 @defun ndbm-delete ndbm-object key
11191 @c MOD dbm.ndbm
11192 @end defun
11193
11194 @defun ndbm-firstkey ndbm-object
11195 @c MOD dbm.ndbm
11196 @end defun
11197
11198 @defun ndbm-nextkey ndbm-object
11199 @c MOD dbm.ndbm
11200 @end defun
11201
11202 @defun ndbm-error ndbm-object
11203 @c MOD dbm.ndbm
11204 @end defun
11205
11206 @defun ndbm-clear-error ndbm-object
11207 @c MOD dbm.ndbm
11208 @end defun
11209
11210 @c ----------------------------------------------------------------------
11211 @node Original DBM interface, Filtering file content, NDBM interface, Library modules - Utilities
11212 @section @code{dbm.odbm} - Original DBM interface
11213 @c NODE オリジナルのDBMインタフェース, @code{dbm.odbm} - オリジナルのDBMインタフェース
11214
11215 @deftp {Module} dbm.odbm
11216 @mdindex dbm.odbm
11217 Provides interface to the legacy dbm library.
11218 Extends @code{dbm}.
11219 @end deftp
11220
11221 @deftp {Class} <odbm>
11222 @clindex odbm
11223 @c MOD dbm.odbm
11224 @c EN
11225 Inherits @code{<dbm>}. Provides an implementation for legacy DBM
11226 library.
11227 This module is only installed when your system already has DBM.
11228
11229 The biggest limitation of the legacy DBM is that you can only open
11230 one database at a time. You can create a multiple @code{<odbm>}
11231 instances, but you can open at most one of it at a time, or
11232 you'll get an error.
11233 @c JP
11234 @code{<dbm>} を継承しています。レガシーな DBM ライブラリのための実装を
11235 提供します。このモジュールは、あなたのシステムにすでに DBM がある場合にのみ
11236 インストールされます。
11237
11238 レガシー DBM の最大の制限は、データベースを一時に一つしか開けないことです。
11239 複数の @code{<odbm>} のインスタンスを作ることができますが、一時に一つしか
11240 開くことが出来ず、一つ以上開こうとするとエラーになります。
11241 @c COMMON
11242 @end deftp
11243
11244 @c EN
11245 Besides the unified DBM interface (@pxref{Generic DBM interface}),
11246 this module provides the following low-level functions that provides
11247 direct access to the dbm API. See dbm manual for details of these
11248 APIs.
11249 @c JP
11250 統合された DBM インターフェース (@pxref{Generic DBM interface}) の
11251 他に、このモジュールでは DBM API への直接のアクセスを提供する以下の
11252 低レベルな手続きを提供しています。これらの API の詳細については DBM の
11253 マニュアルを見て下さい。
11254 @c COMMON
11255
11256 @defun odbm-init path
11257 @c MOD dbm.odbm
11258 @end defun
11259
11260 @defun odbm-close
11261 @c MOD dbm.odbm
11262 @end defun
11263
11264 @defun odbm-store key value
11265 @c MOD dbm.odbm
11266 @end defun
11267
11268 @defun odbm-fetch key
11269 @c MOD dbm.odbm
11270 @end defun
11271
11272 @defun odbm-delete key
11273 @c MOD dbm.odbm
11274 @end defun
11275
11276 @defun odbm-firstkey
11277 @c MOD dbm.odbm
11278 @end defun
11279
11280 @defun odbm-nextkey key
11281 @c MOD dbm.odbm
11282 @end defun
11283
11284
11285 @c ----------------------------------------------------------------------
11286 @c @node Pseudo DBM interface, gauche.charconv - Character code conversion, Original DBM interface, Library modules
11287 @c @section @code{dbm.pdbm} - Pseudo DBM interface
11288
11289 @c ----------------------------------------------------------------------
11290 @node Filtering file content, Filesystem utilities, Original DBM interface, Library modules - Utilities
11291 @section @code{file.filter} - Filtering file content
11292 @c NODE ファイルのフィルタ, @code{file.filter} - ファイルのフィルタ
11293
11294 @deftp {Module} file.filter
11295 @mdindex file.filter
11296 @c EN
11297 This module provides utilities for a common pattern in
11298 filter-type commands, that is, to take an input, to process
11299 the content, and to write the result. The common occurring
11300 pattern is:
11301
11302 @itemize @bullet
11303 @item
11304 Input may be a specified file, or an input port
11305 (the current input port by default).
11306 @item
11307 Output may be a specified file, or an output port
11308 (the current output port by default).
11309 @item
11310 Output may be a temporary file, which will be renamed
11311 upon completion of the processing.
11312 @item
11313 Output file may be removed when an error occurs
11314 in the processing.
11315 @end itemize
11316 @c JP
11317 このモジュールは、フィルター型のコマンド、
11318 すなわち入力を読み込み、処理をして結果を書き出すような場合に
11319 共通するパターンに使えるユーティリティ手続きを提供します。
11320 共通するパターンとは:
11321
11322 @itemize @bullet
11323 @item
11324 入力は指定されたファイルかポートで、デフォルトはカレント入力ポート。
11325 @item
11326 出力は指定されたファイルかポートで、デフォルトはカレント出力ポート。
11327 @item
11328 出力は一時ファイルに書き出すこともできて、
11329 その場合は処理が終了した時点で指定されたファイルにリネーム。
11330 @item
11331 処理途中でエラーが起こった場合に出力ファイルを削除
11332 @end itemize
11333 @c COMMON
11334 @end deftp
11335
11336 @defun file-filter proc :key input output temporary-file keep-output? rename-hook
11337 @c MOD file.filter
11338 @c EN
11339 Calls @var{proc} with two arguments, an input port and
11340 an output port. Returns the result(s) of @var{proc}.
11341 The input port and output port are chosen depending on the keyword arguments.
11342 @c JP
11343 二つの引数、入力ポートと出力ポートを引数として@var{proc}を呼び出し、
11344 その結果を返します。
11345 入力ポートと出力ポートはキーワード引数により決定されます。
11346 @c COMMON
11347
11348 @table @code
11349 @item input
11350 @c EN
11351 The argument must be either an input port or a string
11352 that specifies a file name.
11353 If it's an input port, it is passed to @var{proc} as is.
11354 If it's a string, the named file is opened for input and the resulting
11355 port is passed to @var{proc}, and the port is closed when @var{proc}
11356 returns.
11357 If this argument is omitted, the current input port is passed.
11358 @c JP
11359 この引数は入力ポートかファイル名を示す文字列でなければなりません。
11360 入力ポートの場合、それはそのまま@var{proc}に渡されます。
11361 文字列が渡された場合は、そのファイル名を持つファイルを入力用にオープンし、
11362 そのポートが@var{proc}に渡され、またこのポートは@var{proc}が戻った時に閉じられます。
11363 この引数が省略された場合は、現在の入力ポートが渡されます。
11364 @c COMMON
11365 @item output
11366 @c EN
11367 The argument must be either an output port or a string
11368 that specifies a file name.
11369 If it's an output port, it is passed to @var{proc} as is.
11370 If it's a string, the named file is opened for output
11371 (unless @var{temporary-file} is given, in that case
11372 a temporary file is opened instead), and the resulting port
11373 is passed to @var{proc}. This port is closed when @var{proc} returns.
11374 If this argument is omitted, the current output port is passed.
11375 @c JP
11376 この引数は出力ポートかファイル名を示す文字列でなければなりません。
11377 出力ポートの場合、それはそのまま@var{proc}に渡されます。
11378 文字列が渡された場合は、そのファイル名を持つファイルを出力用にオープンし、
11379 そのポートが@var{proc}に渡されます (但し、@var{temporary-file}
11380 引数が渡された時はそれに指定されるファイルが一時ファイルとしてオープンされます)。
11381 オープンされたポートは@var{proc}が戻った時に閉じられます。
11382 この引数が省略された場合は、現在の出力ポートが渡されます。
11383 @c COMMON
11384 @item temporary-file
11385 @c EN
11386 The value must be a boolean or a string. If a non-false value
11387 is given, and output is a file, then a fresh temporary file is
11388 created and opened for output and passed to @var{proc}.
11389 When @var{proc} returns normally, the file is renamed
11390 to the name given to @var{output} keyword argument.
11391
11392 If @code{#t} is given, a temporary file name is generated
11393 based on the name of the output file.
11394 If a string file name is given to this argument, the name
11395 is used for @code{sys-mkstemp}.
11396
11397 If the given file name begins with characters except @code{"/"}, @code{"./"}
11398 or @code{"../"}, the directory of the file name given to @var{output} argument
11399 is attached before it.
11400
11401 The default value is @code{#f} (do not use a temporary file).
11402 @c JP
11403 値は真偽値か文字列でなければなりません。@code{#f}でない値が渡され、
11404 かつ出力がファイルである場合、新たな一時ファイルが出力用に作成され@var{proc}に
11405 渡されます。
11406 そして@var{proc}が正常に返って来た時点で、一時ファイルは@var{output}に指定された
11407 ファイルへとリネームされます。
11408
11409 この引数が@code{#t}の場合、一時ファイル名は出力ファイル名をもとに作られます。
11410 この引数が文字列の場合はそれが@code{sys-mkstemp}に渡されます。
11411
11412 もし一時ファイル名が@code{"/"}、@code{"./"}、@code{"../"}以外の
11413 文字で始まっていた場合は、@var{output}に与えられたファイル名のディレクトリが
11414 一時ファイルの前に追加されます。
11415
11416 デフォルトの値は@code{#f} (一時ファイルを使わない) です。
11417 @c COMMON
11418 @item keep-output?
11419 @c EN
11420 If a true value is given, the output is not deleted even
11421 when @var{proc} signals an error.
11422 By default, the output (or the temporary file when
11423 @var{temporary-file} is given) will be deleted on error.
11424 @c JP
11425 真の値が与えられた場合、@var{proc}がエラーになった場合でも出力ファイルを削除しません。
11426 デフォルトでは、出力ファイル(もしくは@var{temporary-file}が与えられた場合は
11427 そのファイル)はエラーの場合には削除されます。
11428 @c COMMON
11429 @item leave-unchanged
11430 @c EN
11431 When a temporary file is used, and a true value is given to this argument,
11432 the existing output file is left intact when the generated output in
11433 the temporary file exactly matches the original content of the output
11434 file. It is useful if touching output file may trigger some actions
11435 (e.g. by @code{make}) and you want to avoid invoking unnecessary
11436 actions. The default value is @code{#f} (always replace the output).
11437 @c JP
11438 一時ファイルを使う場合に、この引数に真の値が与えられると、
11439 出力ファイルが既に存在して一時ファイルに生成された内容と全く同じだった場合に、
11440 出力ファイルをそのままにします。これは、出力ファイルに触ることで何らかの
11441 アクションが起きるようになっている場合に(例: @code{make})、
11442 不必要なアクションを起こさないために便利です。
11443 デフォルトの値は@code{#f} (常に出力ファイルを置き換える) です。
11444 @c COMMON
11445 @end table
11446 @end defun
11447
11448 @defun file-filter-fold proc seed :key reader input output temporary-file keep-output? rename-hook
11449 @c MOD file.filter
11450 @c EN
11451 A convenience wrapper of @code{file-filter}.
11452 Call @var{proc} for each item read from input
11453 by @var{reader} (@code{read-line} by default). The argument
11454 @var{proc} receives is the item, the seed value and the output port;
11455 @var{proc} can emit the output, as well as returning some value
11456 that is passed along as the seed value. Other keyword arguments
11457 are passed to @code{file-filter}.
11458
11459 For example, the following code reads each line from @file{file.txt} and
11460 displays lines matching @code{#/regexp/} with line numbers.
11461 @c JP
11462 @file{file-filter}の便利なラッパー手続きです。
11463 入力から@var{reader}によって読まれるデータに対して次々に@var{proc}を
11464 呼び出します。@var{reader}のデフォルトは@code{read-line}です。
11465 @var{proc}の引数は、読まれたデータ、シード値、出力ポートです。
11466 @var{proc}は何かを出力することもできますし、値を返せばそれが
11467 次のシード値として受け渡されてゆきます。他のキーワード引数は
11468 @code{file-filter}にそのまま渡されます。
11469
11470 例えば次のコードは、@file{file.txt}を1行づつ読み、@code{#/regexp/}に
11471 マッチする行を行番号つきで出力します。
11472 @c COMMON
11473
11474 @example
11475 (file-filer-fold
11476 (^[line nc out]
11477 (when (#/regexp/ line) (format out "~3d: ~a\n" nc line))
11478 (+ nc 1))
11479 1 :input "file.txt")
11480 @end example
11481 @end defun
11482
11483 @defun file-filter-map proc :key reader input output temporary-file keep-output? rename-hook
11484 @defunx file-filter-for-each proc :key reader input output temporary-file keep-output? rename-hook
11485 @c MOD file.filter
11486 @c EN
11487 Utilities similar to @code{file-filter-fold},
11488 like @code{map} and @code{for-each} to @code{fold}.
11489
11490 The procedure @var{proc} is called with two arguments,
11491 an item read from the input and an output port.
11492 The results of @var{proc} are collected as a list and returned
11493 by @code{file-filter-map}, and discarded by @code{file-filter-for-each}.
11494
11495 The meaning of keyword arguments are the same as @code{file-filter-fold}.
11496 @c JP
11497 @code{file-filter-fold}に似たユーティリティです。
11498 @code{fold}に対する@code{map}、@code{for-each}に相当します。
11499
11500 手続き@var{proc}は二つの引数、入力から読まれたデータと出力ポートを受けとります。
11501 @var{proc}の結果は、@code{file-filter-map}では集められてリストとして
11502 戻り値となり、@code{file-filter-for-each}では捨てられます。
11503
11504 キーワード引数の意味は@code{file-filter-fold}と同じです。
11505 @c COMMON
11506 @end defun
11507
11508
11509 @c ----------------------------------------------------------------------
11510 @node Filesystem utilities, Mathematical constants, Filtering file content, Library modules - Utilities
11511 @section @code{file.util} - Filesystem utilities
11512 @c NODE ファイルシステムユーティリティ, @code{file.util} - ファイルシステムユーティリティ
11513
11514 @deftp {Module} file.util
11515 @mdindex file.util
11516 @c EN
11517 Provides convenient utility functions handling files and directories.
11518 Those functions are built on top of the primitive system
11519 procedures described in @ref{Filesystems}.
11520 @c JP
11521 ファイルやディレクトリを扱う便利な手続き群を提供します。
11522 これらの手続きは@ref{Filesystems}で述べられたプリミティブなシステム手続きの上に
11523 構築されています。
11524 @c COMMON
11525
11526 @c EN
11527 Many procedures in this module takes a keyword argument @var{follow-link?},
11528 which specifies the behavior when the procedure sees a symbolic link.
11529 If true value is given to @var{follow-link?} (which is the default),
11530 the procedure operates on the file referenced by the link; if false is
11531 given, it operates on the link itself.
11532 @c JP
11533 このモジュール内の多くの手続きは@var{follow-link?}というキーワード引数を取ります。
11534 これは手続きがシンボリックリンクに出会ったときの動作を指定します。@var{follow-link?}が
11535 真であれば、手続きはリンクの指す先のファイルに作用します。これがデフォルトの振舞いです。
11536 @var{follow-link?}に@code{#f}が渡された場合は手続きはリンクそのものに作用します。
11537 @c COMMON
11538 @end deftp
11539
11540 @c EN
11541 Note on the naming convention: Some Scheme implementations "create"
11542 new directories and files, while the others "make" them.
11543 Some implementations "delete" them, while the others "remove" them.
11544 It seems that both conventions are equally popular.
11545 So Gauche provides @emph{both}.
11546 @c JP
11547 名前つけ規則に関する注記:ファイルやディレクトリを
11548 作成するのに@code{"create"}という語を使う処理系と@code{"make"}を
11549 使う処理系があります。ファイルやディレクトリを削除するのにも@code{"remove"}と
11550 @code{"delete"}の流派があります。どちらも同じくらい広く使われているようなので、
11551 Gaucheでは@emph{両方の}名前を提供することにしました。
11552 @c COMMON
11553
11554 @menu
11555 * Directory utilities::
11556 * Pathname utilities::
11557 * File attribute utilities::
11558 * File operations::
11559 * Temporary files and directories::
11560 * Lock files::
11561 @end menu
11562
11563 @node Directory utilities, Pathname utilities, Filesystem utilities, Filesystem utilities
11564 @subsection Directory utilities
11565 @c NODE ディレクトリユーティリティ
11566
11567 @defun current-directory :optional new-directory
11568 @c MOD file.util
11569 @c EN
11570 When called with no argument, this returns the pathname of the current
11571 working directory. When called with a string argument @var{new-directory},
11572 this sets the current working directory of the process to it.
11573 If the process can't change directory to @var{new-directory}, an error is
11574 signaled.
11575
11576 This function is in ChezScheme, MzScheme and some other Scheme
11577 implementations.
11578
11579 SRFI-170 defines @code{current-directory} without arguments, to return
11580 the current working directory.
11581 @c JP
11582 引数無しで呼ばれた場合、カレントディレクトリを返します。
11583 文字列@var{new-directory}が与えられた場合はプロセスのカレントディレクトリを
11584 @var{new-directory}に変更します。変更が出来なかった場合はエラーとなります。
11585
11586 この関数はChezSchemeやMzSchemeなどいくつかのScheme処理系に見られます。
11587
11588 SRFI-170は引数を取らない@code{current-directory}を定義しています。
11589 現在のディレクトリを返すのは一緒です。
11590 @c COMMON
11591 @end defun
11592
11593 @defun home-directory :optional user
11594 @c MOD file.util
11595 @c EN
11596 Returns the home directory of the given @var{user},
11597 which may be a string user name or an integer user id.
11598 If @var{user} is omitted, the current user is assumed.
11599 If the given user cannot be found, or the home directory
11600 of the user cannot be determined, @code{#f} is returned.
11601 @c JP
11602 名前または整数のユーザidで与えられたユーザ@var{user}のホームディレクトリを
11603 返します。@var{user}が省略された場合はカレントユーザが使われます。
11604 与えられたユーザが見付けられないか、ホームディレクトリを決定できなかった場合は
11605 @code{#f}が返されます。
11606 @c COMMON
11607
11608 @c EN
11609 On Windows native platforms, this function is only supported
11610 to query the current user's directory.
11611 @c JP
11612 Windowsネイティブ環境では、この関数はカレントユーザに対してのみ動作します。
11613 @c COMMON
11614 @end defun
11615
11616 @defun directory-list path :key children? add-path? filter filter-add-path?
11617 @c MOD file.util
11618 @c EN
11619 Returns a list of entries in the directory @var{path}.
11620 The result is sorted by dictionary order.
11621
11622 By default, only the basename (the last component) of the entries
11623 returned. If @var{add-path?} is given and true, @var{path} is appended
11624 to each entry. If @var{children?} is given and true, @code{"."} and
11625 @code{".."} are excluded from the result.
11626
11627 If @var{filter} is given, it must be a predicate that takes one argument.
11628 It is called on every element of the directory entry,
11629 and only the entries on which
11630 @var{filter} returns true are included in the result.
11631 The argument passed to @var{filter} is a basename of the directory entry
11632 by default, but when @var{filter-add-path?} is true, @var{path} is
11633 appended to the entry.
11634
11635 If @var{path} is not a directory, an error is signaled.
11636 @c JP
11637 ディレクトリ@var{path}中のエントリのリストを返します。
11638 リストは文字列順にソートされます。
11639
11640 デフォルトではエントリのベースネーム(パスの最後のコンポーネント)のみが
11641 返されますが、キーワード引数@var{add-path?}に真の値が与えられた時は
11642 @var{path}が各エントリの前に追加されます。
11643 @var{children?}に真の値が与えられた時は、カレントディレクトリと親ディレクトリが
11644 リストから除かれます。
11645
11646 @var{filter}引数は、もし与えられれば、一つの引数を取る
11647 手続きでなければなりません。ディレクトリ中の各エントリを引数としてその手続きが呼ばれ、
11648 真を返したエントリのみが結果に含まれます。
11649 @var{filter}に与えられるエントリはデフォルトではベース名のみですが、
11650 引数@var{filter-add-path?}が真ならば@var{path}が前に追加された名前となります。
11651
11652 @var{path}がディレクトリでない場合はエラーが報告されます。
11653 @c COMMON
11654
11655 @example
11656 (directory-list "test")
11657 @result{} ("." ".." "test.scm" "test.scm~")
11658
11659 (directory-list "test" :add-path? #t)
11660 @result{} ("test/." "test/.." "test/test.scm" "test/test.scm~")
11661
11662 (directory-list "test" :children? #t)
11663 @result{} ("test.scm" "test.scm~")
11664
11665 (directory-list "test" :children? #t :add-path? #t
11666 :filter (lambda (e) (not (string-suffix? "~" e))))
11667 @result{} ("test/test.scm")
11668 @end example
11669 @end defun
11670
11671 @defun directory-list2 path :key children? add-path? filter follow-link?
11672 @c MOD file.util
11673 @c EN
11674 Like @code{directory-list}, but returns two values; the first one is a list
11675 of subdirectories, and the second one is a list of the rest.
11676 The keyword arguments @var{children?}, @code{add-path?} and @var{filter}
11677 are the same as @code{directory-list}.
11678
11679 Giving false value to @var{follow-link?} makes @code{directory-list2}
11680 not follow the symbolic links; if the @var{path} contains a
11681 symlink to a directory,
11682 it will be included in the first list if @var{follow-link?}
11683 is omitted or true,
11684 while it will be in the second list if @var{follow-link?} is false.
11685 @c JP
11686 @code{directory-list}に似ていますが、ふたつの値を返します。最初の値は
11687 @var{path}内にあるサブディレクトリのリストで、次の値はそれ以外のエントリのリストです。
11688 キーワード引数@var{children?}、@code{add-path?}、@var{filter}は
11689 @code{directory-list}と同じ意味をもちます。
11690
11691 偽の値を@var{follow-link?}に与えると、@var{path}内のシンボリックリンクを
11692 辿りません;すなわち、@var{path}内にディレクトリへのシンボリックリンクがあった場合、
11693 デフォルト、もしくは@var{follow-link?}に真の値が与えられた場合は
11694 それは最初のリスト(サブディレクトリ)に入りますが、@var{follow-link?}
11695 に偽の値が与えられた場合は後者のリスト(その他のエントリ)に入ります。
11696 @c COMMON
11697 @end defun
11698
11699 @defun directory-fold path proc seed :key lister follow-link?
11700 @c MOD file.util
11701 @c EN
11702 A fundamental directory traverser.
11703 Conceptually it works as follows, in recursive way.
11704 @c JP
11705 ディレクトリ探索の最も基本的な手続きです。基本的な動作は以下に示すような再帰的なものです。
11706 @c COMMON
11707
11708 @c EN
11709 @itemize @bullet
11710 @item
11711 If @var{path} is not a directory, calls
11712 @code{(@var{proc} @var{path} @var{seed})} and returns the result.
11713 @item
11714 If @var{path} is a directory, calls
11715 @code{(@var{lister} @var{path} @var{seed})}. The procedure @var{lister}
11716 is expected to return two values: a list of pathnames, and the
11717 next seed value. Then
11718 @code{directory-fold} is called on each returned pathname,
11719 passing the returned seed value to the @var{seed} argument of the
11720 next call of @code{directory-fold}.
11721 Returns the result of the last seed value.
11722 @end itemize
11723 @c JP
11724 @itemize @bullet
11725 @item
11726 @var{path}がディレクトリでない場合は@code{(@var{proc} @var{path} @var{seed})} を
11727 評価し、結果を返します。
11728 @item
11729 @var{path}がディレクトリであった場合、まず
11730 @code{(@var{lister} @var{path} @var{seed})} を評価します。
11731 手続き@var{lister}は2つの値、パス名のリストと次のseedとなる値を
11732 返さなければなりません。
11733 続いて、@code{directory-fold}が各パス名に対して再帰的に呼ばれます。
11734 各呼び出しの結果が次の再帰呼び出しの@var{seed}の値に使われます。
11735 @end itemize
11736 @c COMMON
11737
11738 @c EN
11739 The default procedure of @var{lister} is just a call to @code{directory-list},
11740 as follows.
11741 @c JP
11742 デフォルトの@var{lister}は@code{directory-list}を次のように呼び出すものです。
11743 @c COMMON
11744 @example
11745 (lambda (path seed)
11746 (values (directory-list path :add-path? #t :children? #t)
11747 seed))
11748 @end example
11749
11750 @c EN
11751 Note that @var{lister} shouldn't return the given path itself (@code{"."})
11752 nor the parent directory (@code{".."}), or the recursion wouldn't
11753 terminate. Also note @var{lister} is expected to return a path accessible
11754 from the current directory, i.e. if @var{path} is @code{"/usr/lib/foo"} and
11755 it contains @code{"libfoo.a"} and @code{"libfoo.so"}, @var{lister} should
11756 return @code{'("/usr/lib/foo/libfoo.a" "/usr/lib/foo/libfoo.so")}.
11757 @c JP
11758 @var{lister}は@var{path}自身への参照 (@code{"."}) やその親ディレクトリへの参照を
11759 返してはなりません。また、@var{lister}の戻り値は現在のディレクトリからアクセス可能な
11760 パス名でなければなりません。例えば@var{path}が@code{"/usr/lib/foo"}であり、
11761 そのディレクトリが@code{"libfoo.a"}と@code{"libfoo.so"}を含んでいた場合、
11762 @var{lister}は@code{'("/usr/lib/foo/libfoo.a" "/usr/lib/foo/libfoo.so")}
11763 のようなリストを返す必要があります。
11764 @c COMMON
11765
11766 @c EN
11767 The keyword argument @var{follow-link?} is used to determine whether
11768 @var{lister} should be called on a symbolic link pointing to a directory.
11769 When @var{follow-link?} is true (default), @var{lister} is called
11770 with the symbolic link if it points to a directory.
11771 When @var{follow-link?} is false, @var{proc} is not called.
11772 @c JP
11773 キーワード引数@var{follow-link?}はディレクトリを指しているシンボリックリンクに対して
11774 @var{lister}を呼ぶかどうかを決定します。@var{follow-link?}が真(デフォルト値)である
11775 場合はそのようなシンボリックリンクに対しても@var{lister}が呼ばれます。
11776 一方、@var{follow-link?}が偽であればシンボリックリンクに対しては@var{proc}が呼ばれます。
11777 @c COMMON
11778
11779 @c EN
11780 The following example returns a list of pathnames of the emacs backup files
11781 (whose name ends with "~") under the given path.
11782 @c JP
11783 次の例は、与えられたpath以下からemacsのバックアップファイル ("~"で終る名を持つファイル)
11784 のリストを返します。
11785 @c COMMON
11786 @example
11787 (use srfi.13) ;; for string-suffix?
11788 (directory-fold path
11789 (lambda (entry result)
11790 (if (string-suffix? "~" entry)
11791 (cons entry result)
11792 result))
11793 '())
11794 @end example
11795
11796 @c EN
11797 The following example lists all the files and directories under the
11798 given pathname. Note the use of @var{lister} argument to include
11799 the directory path itself in the result.
11800 @c JP
11801 次の例は与えられたpath以下全てのファイルとディレクトリ名をリストにして
11802 返します。@var{lister}引数を使ってディレクトリ名そのものを結果に
11803 含めていることに注目して下さい。
11804 @c COMMON
11805 @example
11806 (directory-fold path cons '()
11807 :lister (lambda (path seed)
11808 (values (directory-list path :add-path? #t :children? #t)
11809 (cons path seed))))
11810 @end example
11811
11812 @end defun
11813
11814 @defun make-directory* name :optional perm
11815 @defunx create-directory* name :optional perm
11816 @c MOD file.util
11817 @c EN
11818 Creates a directory @var{name}. If the intermediate path to the
11819 directory doesn't exist, they are also created
11820 (like @code{mkdir -p} command on Unix). If the directory
11821 @var{name} already exist, these procedure does nothing.
11822 @var{Perm} specifies the integer flag for permission bits of the
11823 directory.
11824 @c JP
11825 ディレクトリ@var{name}を作成します。@var{name}に至るパスが存在しない
11826 場合は必要なディレクトリが作成されます (Unixの@code{mkdir -p}コマンドと
11827 同様です)。ディレクトリ@var{name}が既に存在していた場合は何もしません。
11828 @var{perm}は作成されるディレクトリのパーミッションビットを指定します。
11829 @c COMMON
11830 @end defun
11831
11832
11833 @defun remove-directory* name :key if-does-not-exist
11834 @defunx delete-directory* name :key if-does-not-exist
11835 @c MOD file.util
11836 @c EN
11837 Deletes directory @var{name} and its content recursively
11838 (like @code{rm -r} command on Unix). Symbolic links are not
11839 followed.
11840 @c JP
11841 ディレクトリ@var{name}とその内容を再帰的に消去します
11842 (Unixの@code{rm -r}コマンドと同様です)。シンボリックリンクは辿られません。
11843 @c COMMON
11844
11845 @c EN
11846 The keyword argument @var{if-does-not-exist} must be either
11847 @code{:error} (default) or @code{#f}. If it is @code{:error},
11848 an error is signaled if @var{name} does not exist.
11849 If it is @code{#f}, the procedure just returns in such a case.
11850 @c JP
11851 キーワード引数@var{if-does-not-exist}は、@code{:error} (デフォルト) か
11852 @code{#f} でなければなりません。
11853 @code{:error}の場合、@var{name}が存在しなければエラーが投げられます。
11854 @code{#f}の場合、@var{name}が存在しなければ手続きは何もせずに返ります。
11855 @c COMMON
11856
11857 @c EN
11858 An error is thrown when @var{name} exists but is not a directory.
11859 You can use @code{remove-files} to remove both files and directories.
11860 @c JP
11861 @var{name}が存在し、ディレクトリでない場合はエラーが投げられます。
11862 ディレクトリでもファイルでも削除したい場合は@code{remove-files}が使えます。
11863 @c COMMON
11864 @end defun
11865
11866 @defun copy-directory* src dst :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
11867 @c MOD file.util
11868 @c EN
11869 If @var{src} is a regular file, copies its content to @var{dst}, just like
11870 @code{copy-file} does. If @var{src} is a directory, recursively
11871 descends it and copy the file tree to @var{dst}. Basically
11872 it mimics the behavior of @code{cp -r} command.
11873
11874 If there's any symbolic links under @var{src}, the link itself
11875 is copied instead of the file pointed to by it, unless a true value
11876 is given to the @var{follow-link?} keyword argument,
11877 i.e. the default value of @var{follow-link?} is @code{#f}.
11878 (Note that this is opposite to the @code{copy-file}, in which
11879 @var{follow-link?} is true by default.)
11880 @c JP
11881 @var{src}が通常のファイルであれば、@code{copy-file}と同じように
11882 その内容を@var{dst}にコピーします。しかし@var{src}がディレクトリの場合は、
11883 再帰的にディレクトリを辿り、その全てを@var{dst}へとコピーします。
11884 @code{cp -r}コマンドに相当するものだと考えて良いでしょう。
11885
11886 @var{src}がディレクトリの場合、デフォルトではその下にあるシンボリックリンクは
11887 辿られず、リンクそのものがコピーされます。リンク先の内容をもコピーしたい
11888 場合は@var{follow-link?}キーワード引数に真の値を与えてください。
11889 つまり、@var{follow-link?}キーワード引数のデフォルト値は@code{#f}です。
11890 (このデフォルト値は@code{copy-file}と逆であることに注意してください。
11891 @code{copy-file}では@var{follow-link?}はデフォルトで真であり、
11892 リンクそのものをコピーしたい場合に明示的に@code{#f}を与える必要があります。)
11893 @c COMMON
11894
11895 @c EN
11896 The meanings of the other keyword arguments are the same as
11897 @code{copy-file}. See the entry of @code{copy-file} for the details.
11898 @c JP
11899 他のキーワード引数の意味は@code{copy-file}と同じです。
11900 詳細は@code{copy-file}を参照してください。
11901 @c COMMON
11902 @end defun
11903
11904 @defun create-directory-tree dir spec
11905 @c MOD file.util
11906 @c EN
11907 Creates a directory tree under @var{dir} according to @var{spec}.
11908 This procedure is useful to set up certain directory hierarchy at once.
11909
11910 The @var{spec} argument is an S-expression with the following structure:
11911
11912 @example
11913 <spec> : <name> ; empty file
11914 | (<name> <option> ...) ; empty file
11915 | (<name> <option> ... <string>) ; file with content
11916 | (<name> <option> ... <procedure>) ; file with generated content
11917 | (<name> <option> ... (<spec> ...)) ; directory
11918
11919 <name> : string or symbol
11920
11921 <option> ... : keyword-value alternating list
11922 @end example
11923 @c JP
11924 @var{spec}で指定されるディレクトリツリーを@var{dir}の下に作成します。
11925 特定のディレクトリ構造を一気にセットアップする際に便利です。
11926
11927 @var{spec}引数は次に示される構造をもつS式です。
11928
11929 @example
11930 <spec> : <name> ; 空のファイル
11931 | (<name> <option> ...) ; 空のファイル
11932 | (<name> <option> ... <string>) ; 固定内容のファイル
11933 | (<name> <option> ... <procedure>) ; 内容を生成するファイル
11934 | (<name> <option> ... (<spec> ...)) ; ディレクトリ
11935
11936 <name> : 文字列かシンボル
11937
11938 <option> ... : キーワードと値の交代リスト
11939 @end example
11940 @c COMMON
11941
11942 @c EN
11943 With the first and second form of @var{spec}, an empty file is created
11944 with the given name.
11945 With the third form of @var{spec}, the string becomes the
11946 content of the file.
11947
11948 With the fourth form of @var{spec}, the procedure is called with the
11949 pathname as an argument, and output to the current output
11950 port within the procedure is written to the created file.
11951 The pathname is relative to the @var{dir} argument.
11952 At the time the procedure is called, its parent directory
11953 is already created.
11954
11955 The last form of @var{spec} creates a named directory,
11956 then creates its children recursively according to the specs.
11957 @c JP
11958 @var{spec}の最初と2番目の形式では、名前@var{name}を持つ空のファイルが作られます。
11959 3番目の形式では与えられた文字列がファイルの内容となります。
11960
11961 4番目の形式では、手続きがファイルのパス名を引数として呼び出され、
11962 その手続きがcurrent output portに出力した内容がファイルの内容となります。
11963 引数に渡されるパス名は@var{dir}引数からの相対パスです。
11964 手続きが呼ばれる時、その親ディレクトリは既につくられています。
11965
11966 最後の形式は、名前@var{name}を持つディレクトリを作成し、
11967 その子供として再帰的に指定された@var{spec}によるファイル/ディレクトリを作成します。
11968 @c COMMON
11969
11970 @c EN
11971 With @var{option}s you can control attributes of created files/directories.
11972 Currently the following options are recognized.
11973
11974 @table @code
11975 @item :mode @var{mode}
11976 Takes integer as permission mode bits.
11977 @item :owner @var{uid}
11978 @itemx :group @var{gid}
11979 Takes integer uid/gid of the owner/group of the file/directory.
11980 Calling process may need special privilege to change the owner
11981 and/or group.
11982 @item :symlink @var{path}
11983 This is only valid for file spec, and it causes
11984 @code{create-directory-tree} to create a named symbolic link
11985 whose content is @var{path}.
11986 @end table
11987 @c JP
11988 @var{option}によって、作られるファイル/ディレクトリの属性を細かく指定できます。
11989 今のところ、次のオプションが認識されます。
11990
11991 @table @code
11992 @item :mode @var{mode}
11993 整数@var{mode}でパーミッションのモードビットを指定します。
11994 @item :owner @var{uid}
11995 @itemx :group @var{gid}
11996 整数@var{uid}/@var{gid}で作成されるエントリのオーナー/グループを指定します。
11997 作成されるエントリのオーナー/グループを変更するには、
11998 呼び出すプロセスに特権が必要かもしれません。
11999 @item :symlink @var{path}
12000 ファイルを作成する@var{spec}でのみ有効なオプションで、
12001 @var{path}を指すシンボリックリンクを作成します。
12002 @end table
12003 @c COMMON
12004 @end defun
12005
12006 @defun check-directory-tree dir spec
12007 @c MOD file.util
12008 @c EN
12009 Checks if a directory hierarchy according to @var{spec} exists
12010 under @var{dir}. Returns @code{#t} if it exists, or @code{#f} otherwise.
12011
12012 The format of @var{spec} is the same
12013 as @code{create-directory-tree} described above.
12014
12015 If @var{spec} contains options, the attributes of existing
12016 files/directories are also checked if they match the given options.
12017 @c JP
12018 @var{spec}で記述されるディレクトリ階層が@var{dir}の下に存在するかどうかを
12019 調べ、存在すれば@code{#t}、そうでなければ@code{#f}を返します。
12020
12021 @var{spec}の形式は上で説明した@code{create-directory-tree}と同じです。
12022
12023 @var{spec}がオプションを含んでいる場合、該当するファイル/ディレクトリの
12024 属性もそのオプションに合致するかどうかチェックされます。
12025 @c COMMON
12026 @end defun
12027
12028
12029 @node Pathname utilities, File attribute utilities, Directory utilities, Filesystem utilities
12030 @subsection Pathname utilities
12031 @c NODE パスネームユーティリティ
12032
12033 @defun build-path base-path component @dots{}
12034 @c MOD file.util
12035 @c EN
12036 Appends pathname components @var{component} @dots{} to the @var{base-path}.
12037 This takes care of platform-specific pathname separators.
12038 @c JP
12039 パス名のコンポーネント@var{component} @dots{}を@var{base-path}に追加します。
12040 パスの区切り文字は、プラットフォームに合ったものが選択されます。
12041 @c COMMON
12042
12043 @c EN
12044 @var{Base-path} can be a directory name, @code{#f}, or a symbol @code{cwd} or
12045 @code{cld}. If it is @code{#f}, @code{"."} is used.
12046 If it is @code{cwd}, the current working directory
12047 is used. If it is @code{cld}, the directory of the current loading
12048 file is used
12049 (@code{current-load-path}, @pxref{Loading Scheme file}).
12050 If there's no current loading file (e.g. calling
12051 from REPL), the current working directory is used instead.
12052 @c JP
12053 @var{base-path}には、ディレクトリ名か、@code{#f}、
12054 あるいはシンボル@code{cwd}もしくは@code{cld}を渡すことができます。
12055 @code{#f}は@code{"."}と同じです。
12056 @code{cwd}の場合は現在のディレクトリ(current working directory)
12057 が使われます。@code{cld}の場合は現在のファイルをロードしているディレクトリ
12058 (current loading directory)が使われます。
12059 (@code{current-load-path}, @ref{Loading Scheme file}参照)。
12060 但し、コードがファイルからロードされてたので
12061 ない場合(REPLから呼び出した場合など)は、現在のディレクトリが代わりに使われます。
12062 @c COMMON
12063
12064 @c EN
12065 Note that the current loading directory is looked up at the time
12066 @code{build-path} is called. It may not the directory where the
12067 actual source file is in, if @code{build-path} is called after loading
12068 is completed.
12069 @c JP
12070 現在のロードディレクトリは@code{build-path}が呼ばれた時に調べられることに注意して下さい。
12071 @code{build-path}がロード終了後に呼ばれる場合は、それはそのソースが置かれた
12072 ディレクトリではないかもしれません。
12073 @c COMMON
12074
12075 @c EN
12076 @var{Component} can be a string, @code{#f}, or
12077 a symbol @code{same} or @code{up}. The latter three
12078 are interpreted as @code{"."}, @code{"."}, and @code{".."}, respectively.
12079 They are appended to @var{base-path}.
12080 (The symbol @code{same} and @code{up} are taken from MzScheme).
12081 @c JP
12082 パス名のコンポーネント@var{component}は、文字列、
12083 @code{#f}、あるいはシンボル@code{same}または@code{up}です。
12084 後3者はそれぞれ@code{"."}、@code{"."}、@code{".."}と解釈されます。
12085 @var{components}は@var{base-path}の後に追加されます。
12086 (@code{same}と@code{up}はMzSchemeから採られました)。
12087 @c COMMON
12088 @end defun
12089
12090 @defun absolute-path? path
12091 @defunx relative-path? path
12092 @c MOD file.util
12093 @c EN
12094 Returns @code{#t} if @var{path} is absolute or relative, respectively.
12095 @c JP
12096 @var{path}がそれぞれ絶対パスまたは相対パスならば@code{#t}を返します。
12097 @c COMMON
12098 @end defun
12099
12100 @defun expand-path path
12101 @c MOD file.util
12102 @c EN
12103 Expands tilda-notation of @var{path} if it contains one.
12104 Otherwise, @var{path} is returned. This function does not
12105 check if @var{path} exists and/or readable.
12106 @c JP
12107 @var{path}がチルダ表記を含んでいたらそれを展開したものを返します。
12108 そうでなければ@var{path}そのものを返します。この手続きは@var{path}が
12109 存在しアクセス可能であるかどうかはチェックしません。
12110 @c COMMON
12111 @end defun
12112
12113 @defun resolve-path path
12114 @c MOD file.util
12115 @c EN
12116 Expands @var{path} like @code{expand-path},
12117 then resolve symbolic links for every components
12118 of the path. If @var{path} does not exist, or contains dangling link,
12119 or contains unreadable directory, an error is signaled.
12120 @c JP
12121 @var{path}を@code{expand-path}と同様に展開し、
12122 続いて@var{path}の各コンポーネントに対してそれがシンボリックリンクであればリンク先の
12123 ものに置き換えてゆきます。@var{path}が存在しないパスを指していたり、
12124 シンボリックリンクの先が存在しなかったり、読み出せないディレクトリがあった場合は
12125 エラーとなります。
12126 @c COMMON
12127 @end defun
12128
12129 @defun simplify-path path
12130 @c MOD file.util
12131 @c EN
12132 Remove 'up' (@code{".."}) components and 'same' (@code{"."}) components
12133 from @var{path} as much as possible.
12134 This function does not access the filesystem.
12135 @c JP
12136 @var{path}から、親ディレクトリへの参照(@code{".."})と自分自身への参照(@code{"."})を
12137 出来る限り取り除きます。この手続きはファイルシステムへはアクセスしません。
12138 @c COMMON
12139 @end defun
12140
12141 @defun decompose-path path
12142 @c MOD file.util
12143 @c EN
12144 Returns three values; the directory part of @var{path},
12145 the basename without extension of @var{path}, and
12146 the extension of @var{path}. If the pathname doesn't have an extension,
12147 the third value is @code{#f}. If the pathname ends with a directory
12148 separator, the second and third values are @code{#f}. (Note: This treatment
12149 of the trailing directory separator differs from
12150 @code{sys-dirname}/@code{sys-basename}; those follow popular shell's
12151 convention, which ignores trailing slashes.)
12152 @c JP
12153 パス名@var{path}のディレクトリ部、拡張子を除いたファイル名、
12154 そして拡張子の3つの値を返します。パス名が拡張子を持たない場合、
12155 最後の値は@code{#f}になります。パス名がディレクトリセパレータで
12156 終わっている場合は2番目と3番目の値が@code{#f}になります。
12157 (後置されたディレクトリセパレータに関するこの取扱いは、
12158 @code{sys-dirname}/@code{sys-basename}と異なることに注意して下さい。
12159 @code{sys-dirname}等は後置されたディレクトリセパレータを無視するという
12160 シェル等の慣習に従っています。)
12161 @c COMMON
12162 @example
12163 (decompose-path "/foo/bar/baz.scm")
12164 @result{} "/foo/bar", "baz", "scm"
12165 (decompose-path "/foo/bar/baz")
12166 @result{} "/foo/bar", "baz", #f
12167
12168 (decompose-path "baz.scm")
12169 @result{} ".", "baz", "scm"
12170 (decompose-path "/baz.scm")
12171 @result{} "/", "baz", "scm"
12172
12173 ;; Boundary cases
12174 (decompose-path "/foo/bar/baz.")
12175 @result{} "/foo/bar", "baz", ""
12176 (decompose-path "/foo/bar/.baz")
12177 @result{} "/foo/bar", ".baz", #f
12178 (decompose-path "/foo/bar.baz/")
12179 @result{} "/foo/bar.baz", #f, #f
12180 @end example
12181 @end defun
12182
12183 @defun path-extension path
12184 @defunx path-sans-extension path
12185 @c MOD file.util
12186 @c EN
12187 Returns an extension of @var{path},
12188 and a pathname of @var{path} without extension, respectively.
12189 If @var{path} doesn't have an extension, @code{#f} and @var{path}
12190 is returned respectively.
12191 @c JP
12192 それぞれ、@var{path}の拡張子と、@var{path}から拡張子を除いたものを返します。
12193 @var{path}が拡張子を持っていない場合はそれぞれ@code{#f}と@var{path}が返されます。
12194 @c COMMON
12195
12196 @example
12197 (path-extension "/foo/bar.c") @result{} "c"
12198 (path-sans-extension "/foo/bar.c") @result{} "/foo/bar"
12199
12200 (path-extension "/foo/bar") @result{} #f
12201 (path-sans-extension "/foo/bar") @result{} "/foo/bar"
12202 @end example
12203 @end defun
12204
12205 @defun path-swap-extension path newext
12206 @c MOD file.util
12207 @c EN
12208 Returns a pathname in which the extension of @var{path} is replaced
12209 by @var{newext}. If @var{path} doesn't have an extension,
12210 "." and @var{newext} is appended to @var{path}.
12211
12212 If @var{newext} is @code{#f}, it returns @var{path} without extension.
12213 @c JP
12214 @var{path}の拡張子が@var{newext}に置換されたものが返されます。@code{path}が
12215 拡張子を持たない場合は、@var{path}に "." と@var{newext}が追加されます。
12216
12217 @var{newext}が@code{#f}の場合は、@var{path}の拡張子が除かれたものが
12218 返されます。
12219 @c COMMON
12220
12221 @example
12222 (path-swap-extension "/foo/bar.c" "o") @result{} "/foo/bar.o"
12223 (path-swap-extension "/foo/bar.c" "") @result{} "/foo/bar."
12224 (path-swap-extension "/foo/bar.c" #f) @result{} "/foo/bar"
12225
12226 (path-swap-extension "/foo/bar" "o") @result{} "/foo/bar.o"
12227 (path-swap-extension "/foo/bar" "") @result{} "/foo/bar."
12228 (path-swap-extension "/foo/bar" #f) @result{} "/foo/bar"
12229 @end example
12230 @end defun
12231
12232 @defun find-file-in-paths name :key paths pred extensions
12233 @c MOD file.util
12234 @c EN
12235 Looks for a file that has name @var{name} in the given list of pathnames
12236 @var{paths} and that satisfies a predicate @var{pred}. If found,
12237 the absolute pathname of the file is returned. Otherwise, @code{#f}
12238 is returned.
12239
12240 If @var{name} is an absolute path, only the existence of @var{name}
12241 and whether it satisfies @var{pred} are checked.
12242
12243 The default value of @var{paths} is taken from the environment variable
12244 @code{PATH}, and the default value of @var{pred} is @code{file-is-executable?}
12245 (@pxref{File attribute utilities}). That is, @code{find-file-in-paths}
12246 searches the named executable file in the command search paths
12247 by default.
12248 @c JP
12249 名前@var{name}を持ち、述語@var{pred}を満たすファイルをパス名のリスト@var{paths}
12250 から探します。見つかった場合はファイルの絶対パス名を、見つからなかった場合は
12251 @code{#f}を返します。
12252
12253 @var{name}が絶対パス名で与えられた場合はそれが存在するかどうかと
12254 @var{pred}を満たすかどうかのみがチェックされます。
12255
12256 @var{paths}のデフォルト値は環境変数@code{PATH}から取られます。また、
12257 @var{pred}のデフォルト値は@code{file-is-executable?}
12258 (@ref{File attribute utilities}参照)です。すなわち、デフォルトでは
12259 この手続きはコマンドサーチパスから実行可能ファイルを探すのに使えます。
12260 @c COMMON
12261
12262 @example
12263 (find-file-in-paths "ls")
12264 @result{} "/bin/ls"
12265
12266 @c EN
12267 ;; @r{example of searching user preference file of my application}
12268 @c JP
12269 ;; @r{アプリケーション"myapp"のユーザプレファレンスファイルを探す例}
12270 @c COMMON
12271 (find-file-in-paths "userpref"
12272 :paths `(,(expand-path "~/.myapp")
12273 "/usr/local/share/myapp"
12274 "/usr/share/myapp")
12275 :pred file-is-readable?)
12276 @end example
12277
12278 @c EN
12279 The @var{extensions} keyword argument may list alternative extensions
12280 added to @var{name}. For example, the following example searches
12281 not only @file{notepad}, but also @file{notepad.exe} and @file{notepad.com},
12282 in the PATH. If an alternate name is found,
12283 the returned pathname contains the extension.
12284 @c JP
12285 @var{extensions}キーワード引数には、@var{name}に追加して探すべき拡張子の
12286 リストを指定できます。例えば次の例では、@file{notepad}に加え
12287 @file{notepad.exe}と@file{notepad.com}がPATHから探されます。
12288 拡張子つきの名前が見つかった場合、返されるパスは拡張子を含んだものとなります。
12289 @c COMMON
12290
12291 @example
12292 (find-file-in-paths "notepad" :extensions '("exe" "com"))
12293 @end example
12294
12295 @c EN
12296 For each path, the name and the alternative names are checked in order.
12297 That is,
12298 if there are @file{/bin/b.com} and @file{/usr/bin/b.exe} and @var{paths}
12299 is @code{("/bin" "/usr/bin")}, you'll get @file{/bin/b.com} when you
12300 search @file{b} with extensions @code{("exe" "com")}.
12301 @c JP
12302 各パスについて、@var{name}および拡張子つきの名前が順にチェックされます。
12303 すなわち、@file{/bin/b.com}と@file{/usr/bin/b.exe}があって
12304 @var{paths}が@code{("/bin" "/usr/bin")}である場合、
12305 @var{extensions}に@code{("exe" "com")}を与えて@file{b}を探すと、
12306 @file{/bin/b.com}が返ります。
12307 @c COMMON
12308 @end defun
12309
12310 @defun null-device
12311 @c MOD file.util
12312 @c EN
12313 Returns a name of the @emph{null} device.
12314 On unix platforms (including cygwin) it returns @code{"/dev/null"},
12315 and on Windows native platforms (including mingw) it returns @code{"NUL"}.
12316 @c JP
12317 nullデバイス名を返します。cygwinを含むunixプラットフォームでは
12318 @code{"/dev/null"}、mingwを含むWindowsネイティブプラットフォームでは
12319 @code{"NUL"}が返されます。
12320 @c COMMON
12321 @end defun
12322
12323 @defun console-device
12324 @c MOD file.util
12325 @c EN
12326 Returns a name of the console device.
12327 On unix platforms (including cygwin) it returns @code{"/dev/tty"},
12328 and on Windows native platforms (including mingw) it returns @code{"CON"}.
12329
12330 This function does not guarantee the device is actually available
12331 to the calling process.
12332 @c JP
12333 コンソールデバイス名を返します。cygwinを含むunixプラットフォームでは
12334 @code{"/dev/tty"}、mingwを含むWindowsネイティブプラットフォームでは
12335 @code{"CON"}が返されます。
12336
12337 そのデバイスが実際に現在のプロセスから利用可能であるかどうかはチェックされません。
12338 @c COMMON
12339 @end defun
12340
12341
12342 @node File attribute utilities, File operations, Pathname utilities, Filesystem utilities
12343 @subsection File attribute utilities
12344 @c NODE ファイル属性ユーティリティ
12345
12346 @defun file-type path :key follow-link?
12347 @defunx file-perm path :key follow-link?
12348 @defunx file-mode path :key follow-link?
12349 @defunx file-ino path :key follow-link?
12350 @defunx file-dev path :key follow-link?
12351 @defunx file-rdev path :key follow-link?
12352 @defunx file-nlink path :key follow-link?
12353 @defunx file-uid path :key follow-link?
12354 @defunx file-gid path :key follow-link?
12355 @defunx file-size path :key follow-link?
12356 @defunx file-atime path :key follow-link?
12357 @defunx file-mtime path :key follow-link?
12358 @defunx file-ctime path :key follow-link?
12359 @c MOD file.util
12360 @c EN
12361 These functions return the attribute of file/directory specified by
12362 @var{path}. The attribute name corresponds to the slot name of
12363 @code{<sys-stat>} class (@pxref{File stats}).
12364 If the named path doesn't exist, @code{#f} is returned.
12365
12366 If @var{path} is a symbolic link, these functions queries the
12367 attributes of the file pointed by the link, unless
12368 an optional argument @var{follow-link?} is given and false.
12369
12370 MzScheme and Chicken have @code{file-size}. Chicken also has
12371 @code{file-modification-time}, which is @code{file-mtime}.
12372 @c JP
12373 これらの手続きは@var{path}で示されるファイルやディレクトリのアトリビュートを
12374 返します。アトリビュート名は@code{<sys-stat>}のスロット名に対応しています。
12375 @ref{File stats}を参照して下さい。@var{path}で示されるファイルが
12376 存在しなければ@code{#f}が返されます。
12377
12378 @var{path}がシンボリックリンクだった場合、オプショナルな引数
12379 @var{follow-link?} に偽の値が与えられていない限り、これらの手続きは
12380 リンクの指す先のファイルに関する情報を返します。
12381
12382 MzSchemeとChickenには@code{file-size}があります。
12383 Chickenには@code{file-modification-time}があり、これは@code{file-mtime}と
12384 同じです。
12385 @c COMMON
12386 @end defun
12387
12388 @defun file-is-readable? path
12389 @defunx file-is-writable? path
12390 @defunx file-is-executable? path
12391 @c MOD file.util
12392 @c EN
12393 Returns @code{#t} if @var{path} exists and readable/writable/executable
12394 by the current effective user, respectively.
12395 This API is taken from STk.
12396 @c JP
12397 @var{path}が存在して、現在の実効ユーザがそれぞれ読み取り/書き込み/実行可能なら@code{#t}を
12398 返します。
12399 このAPIはSTkから取られました。
12400 @c COMMON
12401 @end defun
12402
12403 @defun file-is-symlink? path
12404 @c MOD file.util
12405 @c EN
12406 Returns @code{#t} if @var{path} exists and a symbolic link.
12407 See also @code{file-is-regular?} and @code{file-is-directory?} in
12408 @ref{File stats}.
12409 @c JP
12410 @var{path}が存在して、それがシンボリックリンクなら@code{#t}を返します。
12411 (参照:@ref{File stats}の@code{file-is-regular?}, @code{file-is-directory?}).
12412 @c COMMON
12413 @end defun
12414
12415 @defun file-eq? path1 path2
12416 @defunx file-eqv? path1 path2
12417 @defunx file-equal? path1 path2
12418 @c MOD file.util
12419 @c EN
12420 Compares two files specified by @var{path1} and @var{path2}.
12421 @code{file-eq?} and @code{file-eqv?} checks if @var{path1} and @var{path2}
12422 refers to the identical file, that is, whether they are on the same
12423 device and have the identical inode number. The only difference is
12424 when the last component of @var{path1} and/or @var{path2} is a symbolic
12425 link, @code{file-eq?} doesn't resolve the link (so compares the links
12426 themselves) while @var{file-eqv?} resolves the link and compares the
12427 files referred by the link(s).
12428 @c JP
12429 @var{path1}と@var{path2}で示されるファイルを比較します。
12430 @code{file-eq?}と@code{file-eqv?}は@var{path1}と@var{path2}が
12431 全く同一のファイルを参照しているかどうか、すなわち、同じデバイス上にあり同じ
12432 inode番号を持つかどうかをチェックします。二つの手続きの違いは、
12433 @code{path1}や@var{path2}の最後のコンポーネントがシンボリックリンクで
12434 あった場合に、@var{file-eq?}はリンクそのものの比較をするが
12435 @code{file-eqv?}はリンクを辿った先のファイルの比較をする、という点です。
12436 @c COMMON
12437
12438 @c EN
12439 @code{file-equal?} compares @var{path1} and @var{path2} considering their
12440 content, that is, when two are not the identical file in the sense of
12441 @code{file-eqv?}, @code{file-equal?} compares their content and returns
12442 @code{#t} if all the bytes match.
12443 @c JP
12444 @code{file-equal?}は@var{path1}と@var{path2}をその内容まで考慮して比較します。
12445 すなわち、二つのファイルが@code{file-eqv?}の意味で同一でなかった場合、
12446 @code{file-equal?}はファイルの内容を比較し、全てが一致した場合に@code{#t}を返します。
12447 @c COMMON
12448
12449 @c EN
12450 The behavior of @code{file-equal?} is undefined
12451 when @var{path1} and @var{path2} are both directories.
12452 Later, it may be extended to scan the directory contents.
12453 @c JP
12454 @var{path1}と@var{path2}ともにディレクトリが与えられた場合の
12455 @code{file-equal?}の動作は未定義です。将来、ディレクトリ内容を
12456 スキャンするような拡張が加えられるかもしれません。
12457 @c COMMON
12458 @end defun
12459
12460 @deffn {Generic Function} file-mtime=? f1 f2
12461 @deffnx {Generic Function} file-mtime<? f1 f2
12462 @deffnx {Generic Function} file-mtime<=? f1 f2
12463 @deffnx {Generic Function} file-mtime>? f1 f2
12464 @deffnx {Generic Function} file-mtime>=? f1 f2
12465 @c MOD file.util
12466 @c EN
12467 Compares file modification time stamps. There are a bunch of methods defined,
12468 so each argument can be either one of the followings.
12469
12470 @itemize @bullet
12471 @item
12472 String pathname. The mtime of the specified path is used.
12473 @item
12474 @code{<sys-stat>} object (@pxref{File stats}).
12475 The mtime is taken from the stat structure.
12476 @item
12477 @code{<time>} object. The time is used as the mtime.
12478 @item
12479 Number. It is considered as the number of seconds since Unix Epoch, and
12480 used as mtime.
12481 @end itemize
12482 @c JP
12483 二つのファイルの変更時間を比較します。それぞれの引数に対して、
12484 次のような型のオブジェクトが渡せるようなメソッドが定義されています。
12485
12486 @itemize @bullet
12487 @item
12488 文字列のパス名。そのパス名で示されるファイルから変更時間が取られます。
12489 @item
12490 @code{<sys-stat>}オブジェクト (@pxref{File stats})。
12491 stat構造体から変更時間が取られます。
12492 @item
12493 @code{<time>}オブジェクト。その示す時間が変更時間と考えられます。
12494 @item
12495 数値。変更時間をUnix Epochからの秒数で表したものと見なされます。
12496 @end itemize
12497 @c COMMON
12498
12499 @example
12500 @c EN
12501 ;; @r{compare "foo.c" is newer than "foo.o"}
12502 @c JP
12503 ;; @r{"foo.c" より "foo.o" が新しいかどうか調べる}
12504 @c COMMON
12505 (file-mtime>? "foo.c" "foo.o")
12506
12507 @c EN
12508 ;; @r{see if "foo.log" is updated within last 24 hours}
12509 @c JP
12510 ;; @r{"foo.log"が過去24時間以内に更新されたかどうかを調べる}
12511 @c COMMON
12512 (file-mtime>? "foo.c" (- (sys-time) 86400))
12513 @end example
12514 @end deffn
12515
12516 @deffn {Generic Function} file-ctime=? f1 f2
12517 @deffnx {Generic Function} file-atime=? f1 f2
12518 @findex file-ctime<?
12519 @findex file-ctime<=?
12520 @findex file-ctime>?
12521 @findex file-ctime>=?
12522 @findex file-atime<?
12523 @findex file-atime<=?
12524 @findex file-atime>?
12525 @findex file-atime>=?
12526 @c MOD file.util
12527 @c EN
12528 Same as @code{file-mtime=?}, except these checks file's change time
12529 and access time, respectively.
12530 All the variants of @code{<}, @code{<=}, @code{>}, @code{>=} are also
12531 defined.
12532 @c JP
12533 @code{file-mtime=?}と同じですが、ファイルの属性変更時間とアクセス時間に
12534 関して比較します。
12535 @code{<}, @code{<=}, @code{>}, @code{>=}を使う関数も同様に定義されています。
12536 @c COMMON
12537 @end deffn
12538
12539 @node File operations, Temporary files and directories, File attribute utilities, Filesystem utilities
12540 @subsection File operations
12541 @c NODE ファイル操作
12542
12543 @defun touch-file path :key (time #f) (type #f) (create #t)
12544 @defunx touch-files paths :key (time #f) (type #f) (create #t)
12545 @c MOD file.util
12546 @c EN
12547 Updates timestamp of @var{path}, or each path in the list @var{paths},
12548 to the current time. If the specified path
12549 doesn't exist, a new file with size zero is created, unless
12550 the keyword argument @var{create} is @code{#f}.
12551
12552 If the keyword argument @var{time} is given and not @code{#f}, it
12553 must be a nonnegative real number. It is used as the timestamp value
12554 instead of the current time.
12555
12556 The keyword argument @var{type} can be @code{#f} (default), a symbol
12557 @code{atime} or @code{mtime}. If it is a symbol, only the access time
12558 or modification time is updated.
12559
12560 Note: @code{touch-files} processes one file at a time, so the timestamp
12561 of each file may not be exactly the same.
12562
12563 These procedures are built on top of the system call
12564 @code{sys-utime} (@pxref{File stats}).
12565 @c JP
12566 @var{path}もしくはリスト@var{paths}中の各パスの
12567 タイムスタンプを現在の時刻に更新します。
12568 指定されたパスが存在しなかった場合、キーワード引数@var{create}が@code{#f}でなければ、
12569 その名前で大きさゼロのファイルが作成されます。
12570
12571 キーワード引数@var{time}が与えられて@code{#f}でない場合、それは
12572 非負の実数でなければなりません。現在の時刻のかわりにその値がタイムスタンプとして使われます。
12573
12574 キーワード引数@var{type}は@code{#f}(デフォルト)か、シンボル@code{atime}もしくは
12575 @code{mtime}です。シンボルの場合は、それぞれアクセス時刻か変更時刻のみが更新されます。
12576
12577 註:@code{touch-files}はファイルをひとつづつ処理するので、各ファイルの
12578 タイムスタンプが完全に同一にはならない可能性があります。
12579
12580 これらの手続きはシステムコール@code{sys-utime}を使って作られています
12581 (@ref{File stats}参照)。
12582 @c COMMON
12583 @end defun
12584
12585 @defun copy-file src dst :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
12586 @c MOD file.util
12587 @c EN
12588 Copies file from @var{src} to @var{dst}. The source file @var{src} must exist.
12589 The behavior when the destination @var{dst} exists varies by the keyword
12590 argument @var{if-exists};
12591
12592 @table @code
12593 @item :error
12594 (Default) Signals an error when @var{dst} exists.
12595 @item :supersede
12596 Replaces @var{dst} to the copy of @var{src}.
12597 @item :backup
12598 Keeps @var{dst} by renaming it.
12599 @item :append
12600 Append the @var{src}'s content to the end of @var{dst}.
12601 @item #f
12602 Doesn't copy and returns @code{#f} when @var{dst} exists.
12603 @end table
12604 @c JP
12605 ファイル@var{src}を@var{dst}へコピーします。コピー元ファイル@var{src}は
12606 存在していなければなりません。コピー先ファイル@var{dst}が存在していた場合の
12607 ふるまいはキーワード引数@var{if-exists}によって以下のように指定されます。
12608
12609 @table @code
12610 @item :error
12611 (デフォルト) @var{dst}が存在していたらエラーを通知する。
12612 @item :supersede
12613 @var{dst}を@var{src}のコピーで置き換える。
12614 @item :backup
12615 @var{dst}の名前を変えてキープする。
12616 @item :append
12617 @var{dst}の末尾に@var{src}の内容を追加する。
12618 @item #f
12619 @var{dst}が存在していたらコピーをせず@code{#f}を返す。
12620 @end table
12621 @c COMMON
12622
12623 @c EN
12624 @code{Copy-file} returns @code{#t} after completion.
12625 @c JP
12626 @code{copy-file}はコピーが完了したら@code{#t}を返します。
12627 @c COMMON
12628
12629 @c EN
12630 If @var{src} is a symbolic link, @code{copy-file} follows the
12631 symlink and copies the actual content by default. An error
12632 is raised if @var{src} is a dangling symlink.
12633
12634 Giving @code{#f} to the keyword argument @var{follow-link?}
12635 makes @code{copy-file} to copy the link itself.
12636 It is possible that @var{src} is a dangling
12637 symlink in this case.
12638 @c JP
12639 @var{src}がシンボリックリンクであった場合、@code{copy-file}は
12640 デフォルトでリンクを辿ります。つまり、ファイルの実体がコピーされます。
12641 @var{src}が存在しないパスを指すシンボリックリンクであった場合は
12642 エラーが通知されます。
12643
12644 キーワード引数@var{follow-link?}に@code{#f}を与えることで、
12645 @code{copy-link}にシンボリックリンクそのものをコピーさせることも
12646 できます。この場合、@var{src}が存在しないパスを指すシンボリックリンクで
12647 あっても構いません。
12648 @c COMMON
12649
12650 @c EN
12651 If @var{if-exists} is @code{:backup}, the keyword argument @var{backup-suffix}
12652 specifies the suffix attached to the @var{dst} to be renamed.
12653 The default value is @code{".orig"}.
12654 @c JP
12655 @var{if-exists}が@code{:backup}である場合、
12656 @var{dst}がリネームされる名前は
12657 @var{dst}にキーワード引数@var{backup-suffix}で指定されるサフィックスを
12658 付けたものとなります。デフォルト値は@code{".orig"}です。
12659 @c COMMON
12660
12661 @c EN
12662 By default, @code{copy-file} starts copying to @var{dst} directly.
12663 However, if the keyword argument @var{safe} is a true value,
12664 it copies the file to a temporary file in the same directory of @var{dst},
12665 then renames it to @var{dst} when copy is completed.
12666 (When @var{safe} is true and @var{if-exists} is @code{:append},
12667 we first copy the content of @var{dst} to a temporary file if @var{dst}
12668 exists, appends the content of @var{src}, then renames the result to @var{dst}).
12669 If copy is interrupted for some reason, the filesystem is "rolled back"
12670 properly.
12671
12672 @c JP
12673 デフォルトでは@code{copy-file}は直接@var{dst}にコピーを行いますが、
12674 キーワード引数@var{safe}に真の値が与えられた場合は、@var{dst}と同じディレクトリ
12675 内の一時ファイルにまずコピーし、それが完了した時点で@var{dst}へとリネームします。
12676 (@var{safe}が真でかつ@var{if-exists}が@code{:append}であった場合は、
12677 @var{dst}があればまずその内容を一時ファイルにコピーし、そこに@var{src}の内容を
12678 追加し、最後にそれを@var{dst}へリネームします。)
12679 コピーが何らかの理由で中断された場合、ファイルシステムはコピー前の状態へと
12680 「ロールバック」されます。
12681 @c COMMON
12682
12683 @c EN
12684 If the keyword argument @var{keep-timestamp} is true, @code{copy-file}
12685 sets the destination's timestamp to the same as the source's timestamp
12686 after copying.
12687 @c JP
12688 キーワード引数@var{keep-timestamp}に真の値が与えられた場合は、
12689 @code{copy-file}はコピー後にコピー先のファイルのタイムスタンプを
12690 コピー元のタイムスタンプに合わせます。
12691 @c COMMON
12692
12693 @c EN
12694 If the keyword argument @var{keep-mode} is true, the destination file's
12695 permission bits are set to the same as the source file's. If it is false
12696 (default), the destination file's permission remains the same if
12697 the destination already exists and the @var{safe} argument is false,
12698 otherwise it becomes @code{#o666} masked by umask settings.
12699 @c JP
12700 キーワード引数@var{keep-mode}に真の値が与えられた場合は、
12701 コピー先のファイルのパーミッションビットはコピー元のそれに合わせられます。
12702 @var{keep-mode}が偽の場合(デフォルト)は、コピー先が既に存在して
12703 @var{safe}引数が偽の場合にコピー先のもとのパーミッションが保持され、
12704 そうでなければ@code{#o666}がumaskセッティングによってマスクされた
12705 値となります。
12706 @c COMMON
12707 @end defun
12708
12709 @c @defun copy-files files dstdir :key if-exists backup-suffix safe keep-timestamp keep-mode follow-link?
12710 @c @c EN
12711 @c Copies each file in a list @var{files} to the destination @var{dstdir}, which
12712 @c must be an existing directory. The keyword arguments are passed
12713 @c to @code{copy-file}.
12714 @c @c JP
12715 @c リスト@var{files}中の各ファイルをディレクトリに@var{dstdir}にコピーします。
12716 @c @var{dstdir}は既に存在しなければなりません。
12717 @c キーワード引数はそのまま@code{copy-file}に渡されます。
12718 @c @c COMMON
12719 @c @end defun
12720
12721 @defun move-file src dst :key if-exists backup-suffix
12722 @c MOD file.util
12723 @c EN
12724 Moves file @var{src} to @var{dst}. The source @var{src} must exist.
12725 The behavior when @var{dst} exists varies by the keyword argument
12726 @var{if-exists}, as follows.
12727 @table @code
12728 @item :error
12729 (Default) Signals an error when @var{dst} exists.
12730 @item :supersede
12731 Replaces @var{dst} by @code{src}.
12732 @item :backup
12733 Keeps @var{dst} by renaming it.
12734 @item #f
12735 Doesn't move and returns @code{#f} when @var{dst} exists.
12736 @end table
12737 @c JP
12738 ファイル@var{src}を@var{dst}へ移動します。移動元ファイル@var{src}は
12739 存在していなければなりません。移動先ファイル@var{dst}が存在した場合の
12740 ふるまいはキーワード引数@var{if-exists}によって以下のように指定されます。
12741 @table @code
12742 @item :error
12743 (デフォルト) @var{dst}が存在していたらエラーを通知する。
12744 @item :supersede
12745 @var{dst}を@code{src}で置き換える。
12746 @item :backup
12747 @var{dst}の名前を変えてキープする。
12748 @item #f
12749 @var{dst}が存在していたら移動をせず@code{#f}を返す。
12750 @end table
12751 @c COMMON
12752
12753 @c EN
12754 @code{Move-file} returns @code{#t} after completion.
12755 @c JP
12756 @code{move-file}は移動が完了したら@code{#t}を返します。
12757 @c COMMON
12758
12759 @c EN
12760 If @var{if-exists} is @code{:backup}, the keyword argument @var{backup-suffix}
12761 specifies the suffix attached to the @var{dst} to be renamed.
12762 The default value is @code{".orig"}.
12763 @c JP
12764 @var{if-exists}が@code{:backup}である場合、@var{dst}がリネームされる
12765 名前は@var{dst}にキーワード引数@var{backup-suffix}で指定されるサフィックスを
12766 付けたものとなります。デフォルト値は@code{".orig"}です。
12767 @c COMMON
12768
12769 @c EN
12770 The file @var{src} and @var{dst} can be on the different filesystem.
12771 In such a case, @code{move-file} first copies @var{src} to the
12772 temporary file on the same directory as @var{dst}, then renames
12773 it to @var{dst}, then removes @var{src}.
12774 @c JP
12775 ファイル@var{src}と@var{dst}は別のファイルシステム上にあっても構いません。
12776 その場合、@code{move-file}はまず@var{src}を@var{dst}と同じディレクトリの
12777 一時ファイルにコピーし、それを@var{dst}にリネームし、それから
12778 @var{src}を消去します。
12779 @c COMMON
12780 @end defun
12781
12782 @c @defun move-files files dstdir :key if-exists backup-suffix
12783 @c @c EN
12784 @c Moves each file in a list @var{files} to @var{dstdir},
12785 @c which must be an existing directory. Keyword arguments
12786 @c are passed to @code{move-file}.
12787 @c @c JP
12788 @c リスト@var{files}中の各ファイルをディレクトリ@var{dstdir}に移動します。
12789 @c @var{dstdir}は既に存在しなければなりません。
12790 @c キーワード引数はそのまま@code{move-file}に渡されます。
12791 @c @c COMMON
12792 @c @end defun
12793
12794 @defun remove-file filename
12795 @defunx delete-file filename
12796 [R7RS file]
12797 @c MOD file.util
12798 @c EN
12799 Removes the named file. An error is signalled if @var{filename}
12800 does not exist, is a directory, or cannot be deleted with other
12801 reasons such as permissions.
12802 R7RS defines @code{delete-file}.
12803
12804 Compare with @code{sys-unlink} (@pxref{Directory manipulation}),
12805 which doesn't raise an error when the named file doesn't exist.
12806 @c JP
12807 指定された名前のファイルを消去します。ファイルが存在しなかったり、ディレクトリであったり、
12808 パーミッションがなく消去できなかった場合等にはエラーが報告されます。
12809 @code{delete-file}はR7RSで定義されています。
12810
12811 @code{sys-unlink}と似ていますが、@code{sys-unlink}はファイルが無かった場合に
12812 エラーをあげず@code{#f}を返すことに注意。(@ref{Directory manipulation}参照。)
12813 @c COMMON
12814 @end defun
12815
12816 @defun remove-files paths
12817 @defunx delete-files paths
12818 @c MOD file.util
12819 @c EN
12820 Removes each path in a list @var{paths}. If the path is
12821 a file, it is @code{unlink}ed. If it is a directory,
12822 its contents are recursively removed by @code{remove-directory*}.
12823 If the path doesn't exist, it is simply ignored.
12824
12825 @code{delete-files} is just an alias of @code{remove-files}.
12826 @c JP
12827 リスト@var{paths}中の各パスを削除します。パスがファイルの場合は
12828 @code{unlink}し、ディレクトリの場合は@code{remove-directory*}を
12829 使って再帰的にその内容を消去します。存在しないパスは単に無視されます。
12830
12831 @code{delete-files}は@code{remove-files}の別名です。
12832 @c COMMON
12833 @end defun
12834
12835
12836 @defun file->string filename options @dots{}
12837 @defunx file->list reader filename options @dots{}
12838 @defunx file->string-list filename options @dots{}
12839 @defunx file->sexp-list filename options @dots{}
12840 @c MOD file.util
12841 @c EN
12842 Convenience procedures to read from a file @var{filename}.
12843 They first open the named file, then call @code{port->string},
12844 @code{port->list}, @code{port->string-list} and @code{port->sexp-list}
12845 on the opened file, respectively. (@pxref{Input utility functions}).
12846 The file is closed if all the content is read or an error is
12847 signaled during reading.
12848 @c JP
12849 ファイル @var{filename} から読み込むための便利手続き。
12850 これらの手続きは、まず、指定された名前のファイルをオープンし、その
12851 オープンしたファイルに対してそれぞれ @code{port->string}、
12852 @code{port->list}、@code{port->string-list} および @code{port->sexp-list}
12853 を呼びます(@ref{Input utility functions}参照)。すべての内容が読み込まれる
12854 かまたは読み込み中にエラーシグナルがあがれば、ファイルはクローズされます。
12855 @c COMMON
12856
12857 @c EN
12858 Those procedures take the same keyword arguments as
12859 @code{call-with-input-file}.
12860 When the named file doesn't exist, the behavior depends on
12861 @var{:if-does-not-exist} keyword argument---an error is signaled
12862 if it is @code{:error}, and @code{#f} is returned if the argument is
12863 @code{#f}.
12864 @c JP
12865 これらの手続きは@code{call-with-input-file}と同じキーワード引数を取ります。
12866 ファイルが見つからなかった場合の振舞いは
12867 キーワード引数@code{:if-does-not-exist}によって指定できます。
12868 それが@code{:error}ならエラーが報告され、
12869 @code{#f}なら@code{#f}が返されます。
12870 @c COMMON
12871 @end defun
12872
12873 @defun string->file filename string options @dots{}
12874 @defunx list->file writer filename lis options @dots{}
12875 @defunx string-list->file filename lis options @dots{}
12876 @defunx sexp-list->file filenme lis options @dots{}
12877 @c MOD file.util
12878 @c EN
12879 Opposite of @code{file->string} etc. They are convenient
12880 to quickly write out things into a file.
12881
12882 NB: The name @code{string->file} etc. might suggest they would take the
12883 object to be written as the first argument. We decided to put @var{filename}
12884 first, since in the situations where these procedures are used,
12885 it is more likely that one want to write literal data, which would be
12886 bigger than the filename itself.
12887
12888 The options part is passed to @code{call-with-output-file} as is.
12889 For example, the following code appends the text when @file{foo.txt}
12890 already exists:
12891 @c JP
12892 @code{file->string}等の逆を行う手続きです。
12893 手軽にファイルに何かを書き出したい時に便利です。
12894
12895 註: @code{string->file}等の名前からして、
12896 書き出されるオブジェクトを第一引数にする方が慣習にあっているかもしれません。
12897 けれども、実際にこれらの手続きが使われる場面では、書き出されるオブジェクトとして
12898 リテラルデータが来る場合も多く、だとするとより短いファイル名を先にした方が
12899 読み書きしやすいだろうと考え、@var{filename}を先に持ってきてあります。
12900
12901 @var{options} @dots{}部分はそのまま@code{call-with-output-file}に
12902 渡されます。次の例は@file{foo.txt}が存在していればそれにデータを書き足します。
12903 @c COMMON
12904
12905 @example
12906 (string->file "foo.txt" "New text to append\n"
12907 :if-exists :append)
12908 @end example
12909
12910 @c EN
12911 The @code{list->file} takes @var{writer} argument, which is a procedure
12912 that receives two arguments, an element from the list @var{lis}, and an
12913 output port. It should write out the element to the port in a suitable
12914 way. The @code{string-list->file} and @code{sexp-list->file} are
12915 specialized versions of @code{list->file}, where @code{string-list->file}
12916 uses @code{(^[s p] (display s p) (newline p))} as @var{writer},
12917 and @code{sexp-list->file} uses
12918 @code{(^[s p] (write s p) (newline p))} as @var{writer}.
12919 @c JP
12920 @code{list->file}が取る@var{writer}引数は、リスト@var{lis}からのひとつの要素と
12921 出力ポートの二つの引数を取る手続きで、適切な形式で要素をポートに書き出します。
12922 @code{string-list->file}と@code{sexp-list->file}は
12923 @code{list->file}の特化したバージョンで、
12924 @code{string-list->file}はwriterとして@code{(^[s p] (display s p) (newline p))}を、
12925 @code{sexp-list->file}はwriterとして@code{(^[s p] (write s p) (newline p))}を
12926 使います。
12927 @c COMMON
12928 @end defun
12929
12930
12931 @node Temporary files and directories, Lock files, File operations, Filesystem utilities
12932 @subsection Temporary files and directories
12933 @c NODE 一時ファイルとディレクトリ
12934
12935 @deffn {Parameter} temporary-directory
12936 @c MOD file.util
12937 @c EN
12938 A parameter that keeps the name of the directory that can be used
12939 to create a temporary files. The default value is
12940 the one returned from @code{sys-tmpdir} (@pxref{Pathnames}).
12941 The difference of @code{sys-tmpdir} is that, since this is a parameter,
12942 it can be overridden by application during execution.
12943 Libraries are recommended to use this instead of @code{sys-tmpdir}
12944 for greater flexibility.
12945 @c JP
12946 一時ファイルを作るのに適したディレクトリ名を保持しているパラメータです。
12947 デフォルトの値は@code{sys-tmpdir}の戻り値です (@ref{Pathnames}参照)。
12948 @code{sys-tmpdir}との違いは、これはパラメータなので
12949 アプリケーションが実行時に変更できることです。
12950 ライブラリは柔軟性を高めるためにできるだけ@code{sys-tmpdir}よりは
12951 こちらを利用するのが良いでしょう。
12952 @c COMMON
12953 @end deffn
12954
12955 @defun call-with-temporary-file proc :key directory prefix
12956 @c MOD file.util
12957 @c EN
12958 Creates a temporary file with a unique name and opens it for output,
12959 then calls @var{proc} with the output port and the temporary file's name.
12960 The temporary file is removed after either @var{proc} returns
12961 or raises an uncaught error.
12962 Returns the value(s) @var{proc} returns.
12963
12964 The temporary file is created in the directory @var{directory},
12965 with the name @var{prefix} followed by several random alphanumeric characters.
12966 When omitted, the value of @code{(temporary-directory)} is used
12967 for @var{directory}, and @code{"gtemp"} for @var{prefix}.
12968
12969 The name passed to @var{proc} consists of @var{directory} and
12970 the file's name. So whether the name is absolute or relative pathname
12971 depends on the value of @var{directory}.
12972
12973 @example
12974 (call-with-temporary-file (^[_ name] name)
12975 @result{} @r{Something like "/tmp/gtemp4dSpMh"}
12976 @end example
12977
12978 You can keep the output file by renaming it in @var{proc}. But if doing so,
12979 make sure to specify @var{directory} so that the temporary file
12980 is created in the same directory as the final output; rename
12981 may not work across filesystems.
12982 If you anticipate your code runs on Windows as well, make sure to close
12983 the output port before renaming. Windows does not allow you to rename
12984 an opened file.
12985
12986 Internally, it calls @code{sys-mkstemp} to create a unique file.
12987 @xref{Directory manipulation}, for the details.
12988 @c JP
12989 一意な名前を持つ一時ファイルを作成し、出力用にオープンして、
12990 その出力ポートと名前を引数として@var{proc}を呼びます。
12991 一時ファイルは、@var{proc}から戻った場合でも、@var{proc}がエラーを投げた場合でも、
12992 消去されます。
12993 @var{proc}の返す値(複数可)が@code{call-with-temporary-file}の戻り値となります。
12994
12995 一時ファイルはディレクトリ@var{directory}以下に作られ、
12996 その名前は@var{prefix}の後にいくつかの英数字を付け加えたものになります。
12997 省略された場合、@code{(temporary-directory)}の値が@var{directory}に、
12998 @code{"gtemp"}が@var{prefix}に使われます。
12999
13000 @var{proc}に渡される名前は@var{directory}とファイル名をつなげたパス名です。
13001 絶対パスになるか相対パスになるかは@var{directory}の値によります。
13002
13003 @example
13004 (call-with-temporary-file (^[_ name] name)
13005 @result{} @r{例えば "/tmp/gtemp4dSpMh"}
13006 @end example
13007
13008 出力したファイルを取っておきたい場合は、@var{proc}の中でリネームしてください。
13009 その場合、最終的なファイルと同じディレクトリに一時ファイルを作るように、
13010 @var{directory}引数を指定するのを忘れないように。
13011 ファイルシステムをまたぐリネームはうまくいかない場合があります。
13012 また、コードがWindows上でも使われる可能性がある場合は、
13013 リネームする前に出力ポートを閉じてください。
13014 Windowsではオープンされているファイルはリネームできません。
13015
13016 内部的に、この手続きは@code{sys-mkstemp}を呼んで一意なファイルを作っています。
13017 @code{sys-mkstemp}については@ref{Directory manipulation}参照。
13018 @c COMMON
13019 @end defun
13020
13021 @defun call-with-temporary-directory proc :key directory prefix
13022 @c MOD file.util
13023 @c EN
13024 Creates a temporary directory with unique name,
13025 then calls @var{proc} with the name.
13026 The temporary directory and its contents are removed
13027 after either @var{proc} returns
13028 or raises an uncaught error.
13029 Returns the value(s) @var{proc} returns.
13030
13031 The temporary directory is created in the directory @var{directory},
13032 with the name @var{prefix} followed by several random alphanumeric characters.
13033 When omitted, the value of @code{(temporary-directory)} is used
13034 for @var{directory}, and @code{"gtemp"} for @var{prefix}.
13035
13036 The name passed to @var{proc} consists of @var{directory} and
13037 the directory name. So whether the name is absolute or relative pathname
13038 depends on the value of @var{directory}.
13039
13040 Internally, it calls @code{sys-mkdtemp} to create a unique file.
13041 @xref{Directory manipulation}, for the details.
13042 @c JP
13043 一意な名前を持つ一時ディレクトリを作成し、
13044 その名前を引数として@var{proc}を呼びます。
13045 一時ディレクトリは、@var{proc}から戻った場合でも、@var{proc}がエラーを投げた場合でも、
13046 消去されます。
13047 @var{proc}の返す値(複数可)が@code{call-with-temporary-directory}の戻り値となります。
13048
13049 一時ディレクトリはディレクトリ@var{directory}以下に作られ、
13050 その名前は@var{prefix}の後にいくつかの英数字を付け加えたものになります。
13051 省略された場合、@code{(temporary-directory)}の値が@var{directory}に、
13052 @code{"gtemp"}が@var{prefix}に使われます。
13053
13054 @var{proc}に渡される名前は@var{directory}とファイル名をつなげたパス名です。
13055 絶対パスになるか相対パスになるかは@var{directory}の値によります。
13056
13057 内部的に、この手続きは@code{sys-mkdtemp}を呼んで一意なディレクトリを作っています。
13058 @code{sys-mkstemp}については@ref{Directory manipulation}参照。
13059 @c COMMON
13060 @end defun
13061
13062 @node Lock files, , Temporary files and directories, Filesystem utilities
13063 @subsection Lock files
13064 @c NODE ロックファイル
13065
13066 @c EN
13067 Exclusivity of creating files or directories is often used
13068 for inter-process locking. The following procedure provides
13069 a packaged interface for it.
13070 @c JP
13071 ファイルやディレクトリを作成する排他性は、しばしばプロセス間のロックに
13072 使われます。以下の手続きはパッケージ化されたインタフェースを提供します。
13073 @c COMMON
13074
13075 @defun with-lock-file lock-name thunk :key type retry-interval @
13076 retry-limit secondary-lock-name retry2-interval @
13077 retry2-limit perms abandon-timeout
13078 @c MOD file.util
13079 @c EN
13080 Exclusively creates a file or a directory (@emph{lock file})
13081 with @var{lock-name}, then executes @var{thunk}.
13082 After @var{thunk} returns, or an error is thrown in it,
13083 the lock file is removed. When @var{thunk} returns normally,
13084 its return values become the return values of @code{with-lock-file}.
13085 @c JP
13086 @var{lock-name}という名前を持つファイルもしくはディレクトリ (ここでは
13087 @emph{ロックファイル}と呼びます) を排他的に作成し、
13088 @var{thunk}を実行します。@var{thunk}から戻ってくるか、エラーが投げられたら、
13089 ロックファイルは削除されます。@var{thunk}が正常に戻ってきた場合、
13090 その戻り値が@code{with-lock-file}の戻り値となります。
13091 @c COMMON
13092
13093 @c EN
13094 If the lock file already exists, @code{with-lock-file} waits and retries
13095 getting the lock until timeout reaches. It can be configured by
13096 the keyword arguments.
13097 @c JP
13098 ロックファイルが既に存在していた場合、@code{with-lock-file}はタイムアウトになるまで
13099 少し待ってリトライすることを続けます。細かい動作はキーワード引数で指定できます。
13100 @c COMMON
13101
13102 @c EN
13103 There's a chance that @code{with-lock-file} leaves the lock file
13104 when it gets a serious error situation and doesn't have the opportunity
13105 to clean up. You can allow @code{with-lock-file} to @emph{steal}
13106 the lock if its timestamp is too old; say, if you know that the
13107 applications usually locks just for seconds, and you find the lock
13108 file is 10 minutes old, then it's likely that the previous
13109 process was terminated abruptly and couldn't clean it up.
13110 You can also configure this behavior by the keyword arguments.
13111 @c JP
13112 @code{with-lock-file}実行中に深刻なエラーによって、ロックファイルを消せずに
13113 プロセスが終了してしまう可能性があります。そのため、
13114 @code{with-lock-file}は、ロックファイルのタイムスタンプが非常に古い場合には
13115 ロックを@emph{盗む}ことを許しています。例えば、通常アプリケーションはたかだか数秒しか
13116 ロックしないはずなのに、10分前のタイムスタンプを持つロックファイルを見つけたとしたら、
13117 以前のプロセスがクリーンアップをせずに落ちてしまったことは十分考えられるでしょう。
13118 この振る舞いも、キーワード引数で制御することができます。
13119 @c COMMON
13120
13121 @c EN
13122 Internally, @emph{two} lock files are used to implement this
13123 stealing behavior safely. The creation and removal of the primary
13124 lock file (named by @var{lock-name} argument) are guarded by
13125 the secondary lock file (named by @var{secondary-lock-file} argument,
13126 defaulted by @code{.2} suffix attached to @var{lock-name}).
13127 The secondary lock prevents more than one process steals
13128 the same primary lock file simultaneously.
13129 @c JP
13130 内部的には、安全な「盗ロック」を実現するために、二つのロックファイルが使われています。
13131 主ロックファイル(@var{lock-name}で指定される名前を持つもの)の作成と削除の
13132 操作がそれぞれ、副ロックファイル(@var{secondary-lock-file}で指定される名前を
13133 持つもの。指定が省略された場合は@var{lock-name}にサフィックス@code{.2}をつけたもの)
13134 によって保護されます。
13135 副ロックは、二つ以上のプロセスが主ロックファイルを同時に盗もうとした場合を保護します。
13136 @c COMMON
13137
13138 @c EN
13139 The secondary lock is acquired for a very short period so there's
13140 much less chance to be left behind by abnormal terminations.
13141 If it happens, however, we just give up; we don't steal the
13142 secondary lock.
13143 @c JP
13144 副ロックファイルによるロックはほぼ常に極めて短い期間に
13145 限定されるため、事故により副ロックファイルが残されてしまう可能性は
13146 主ロックファイルに比べ非常に小さいです。それでももし副ロックファイルが
13147 残されてしまった場合は、@code{with-lock-file}は単に諦めます。副ロックファイルまで
13148 盗むことはしません。
13149 @c COMMON
13150
13151 @c EN
13152 If @code{with-lock-file} couldn't get a lock before timeout,
13153 a @code{<lock-file-failure>} condition is thrown.
13154 @c JP
13155 @code{with-lock-file}がタイムアウトまでにロックを獲得できなけば、
13156 @code{<lock-file-failure>}コンディションが投げられます。
13157 @c COMMON
13158
13159 @c EN
13160 Here's a list of keyword arguments.
13161 @c JP
13162 以下のキーワード引数が認識されます。
13163 @c COMMON
13164
13165 @table @var
13166 @item type
13167
13168 @c EN
13169 It can be either one of the symbols @code{file} or @code{directory}.
13170 @c JP
13171 シンボル@code{file}か@code{directory}のどちらか。
13172 @c COMMON
13173
13174 @c EN
13175 If it is @code{file}, we use a lock file, relying on the @code{O_EXCL}
13176 exclusive creation flag of @code{open(2)}.
13177 This is the default value.
13178 It works for most platforms;
13179 however, some NFS implementation may not implement the exclusive
13180 semantics properly.
13181 @c JP
13182 @code{file}を指定した場合、@code{open(2)}の@code{O_EXCL}フラグを使う
13183 排他的ファイル作成を利用したロックファイルを使います。これがデフォルトの動作です。
13184 ほとんどのプラッフォームで動作しますが、NFSの実装の一部に、
13185 排他的ファイル作成のセマンティクスが正しく実装されていない場合があります。
13186 @c COMMON
13187
13188 @c EN
13189 If it is @code{directory}, we use a lock directory, relying on the
13190 atomicity of @code{mkdir(2)}. It should work for any platforms,
13191 but it may be slower than @code{file}.
13192 @c JP
13193 @code{directory}を指定した場合は、@code{mkdir(2)}の排他性を利用した
13194 ロックディレクトリを使います。これはどんなプラットフォームでも動作する
13195 はずですが、@code{file}を指定した場合より遅いかもしれません。
13196 @c COMMON
13197
13198 @item retry-interval
13199 @itemx retry-limit
13200
13201 @c EN
13202 Accepts a nonnegative real number that specifies either
13203 the interval to attempt to acquire the primary lock, or the maximum
13204 time we should keep retrying, respectively, in seconds.
13205 The default value is 1 second interval and 10 second limit.
13206 To prevent retrying, give 0 to @var{retry-limit}.
13207 @c JP
13208 時間を秒で指定する非負の実数を取ります。前者は主ロック獲得を再試行する
13209 時間間隔、後者は再試行を繰り返す総時間を指定します。
13210 デフォルトはそれぞれ、1秒と10秒です。再試行をしないようにするには、
13211 @var{retry-limit}に0を渡してください。
13212 @c COMMON
13213
13214 @item secondary-lock-name
13215
13216 @c EN
13217 The name of the secondary lock file (or directory). If omitted,
13218 @var{lock-name} with a suffix @code{.2} attached is used.
13219 Note: The secondary lock name must be agreed on all programs that
13220 locks the same (primary) lock file. I recommend to leave this
13221 to the default unless there's a good reason to do otherwise.
13222 @c JP
13223 副ロックファイル(もしくはディレクトリ)の名前を指定します。
13224 省略された場合は、@var{lock-name}にサフィックス@code{.2}をつけたものが使われます。
13225 副ロックファイルの名前は、同じ(主)ロックファイルを使うプログラム全てで
13226 一致していなければなりません。
13227 特に変える必要が無ければデフォルトのままにするのが良いでしょう。
13228 @c COMMON
13229
13230 @item retry2-interval
13231 @itemx retry2-limit
13232
13233 @c EN
13234 Like @var{retry-interval} and @var{retry-limit}, but these specify
13235 interval and timeout for the secondary lock file. The possibility
13236 of secondary lock file collision is usually pretty low, so
13237 you would hardly need to tweak these. The default values are
13238 1 second interval and 10 second limit.
13239 @c JP
13240 @var{retry-interval}と@var{retry-limit}に似ていますが、
13241 こちらは副ロックファイルの再試行間隔と最長再試行時間を指定します。
13242 副ロックが衝突する確率は通常極めて低いので、これらのパラメータを
13243 調整する必要は滅多に無いでしょう。デフォルトの値はそれぞれ
13244 1秒と10秒です。
13245 @c COMMON
13246
13247 @item perms
13248
13249 @c EN
13250 Specify the permission bitmask of the lock file or directory,
13251 in a nonnegative exact integer. The default is @code{#o644} for
13252 a lock file and @code{#o755} for a lock directory.
13253
13254 Note that to control who can acquire/release/steal the lock,
13255 what matters is
13256 the permission of the directory in which the lock file/directory,
13257 not the permission of the lock file/directory itself.
13258 @c JP
13259 ロックファイルもしくはディレクトリのパーミッションを、非負正確整数の
13260 ビットマスクで指定します。デフォルトは、ロックファイルに対して@code{#o644}、
13261 ロックディレクトリに対しては@code{#o755}です。
13262
13263 ロックを獲得/解放したり盗んだりするには、ロックファイル自身のパーミッションではなく、
13264 ロックファイルが置かれるディレクトリのパーミッションが関係することに注意してください。
13265 @c COMMON
13266
13267 @item abandon-timeout
13268
13269 @c EN
13270 Specifies the period in seconds in a nonnegative real number.
13271 If the primary lock file is
13272 older than that, @code{with-lock-file} steals the lock.
13273 To prevent stealing, give @code{#f} to this argument.
13274 The default value is 600 seconds.
13275 @c JP
13276 時間の長さ(秒)を非負の実数で指定します。
13277 @code{with-lock-file}がロックファイルを見つけて、そのタイムスタンプが
13278 現在の時刻マイナスこの時間よりも古いものだった場合、ロックを盗みます。
13279 ロックを盗むことを禁止したければこの引数に@code{#f}を渡してください。
13280 デフォルトは600秒です。
13281 @c COMMON
13282
13283 @end table
13284
13285 @end defun
13286
13287 @deftp {Condition type} <lock-file-failure>
13288 @c MOD file.util
13289 @c EN
13290 A condition indicating that @code{with-lock-file} couldn't
13291 obtain the lock. Inherits @code{<error>}.
13292 @c JP
13293 @code{with-lock-file}がロックを獲得できなかった場合に投げられる
13294 コンディションです。@code{<error>}を継承します。
13295 @c COMMON
13296
13297 @defivar <lock-file-failure> lock-file-name
13298 @c EN
13299 The primary lock file name.
13300 @c JP
13301 獲得しようとした主ロックファイルの名前です。
13302 @c COMMON
13303 @end defivar
13304 @end deftp
13305
13306 @c EN
13307 Gauche also provides OS-supported file locking feature,
13308 @code{fcntl} lock, via @code{gauche.fcntl} module.
13309 Whether you want to use @code{fcntl} lock or @code{with-lock-file}
13310 will depend on your application.
13311 @c JP
13312 Gaucheは、OSによりサポートされる@code{fcntl}ロックの機能も、
13313 @code{gauche.fcntl}モジュールによって提供しています。
13314 @code{fcntl}ロックを使うべきか@code{with-lock-file}を使うべきかは、
13315 アプリケーションによります。
13316 @c COMMON
13317
13318 @c EN
13319 These are the advantages of the @code{fcntl} lock:
13320 @c JP
13321 @code{fcntl}ロックの利点は次の通りです。
13322 @c COMMON
13323
13324 @itemize
13325 @item
13326 @c EN
13327 The lock is removed when the process dies without explicitly unlocking it.
13328 @c JP
13329 プロセスが死んだ時に、ロックは自動的に解除される
13330 @c COMMON
13331 @item
13332 @c EN
13333 You can directly lock the file you're touching.
13334 @c JP
13335 作業するファイルそのものをロックできる。
13336 @c COMMON
13337 @item
13338 @c EN
13339 You can lock a part of a file.
13340 @c JP
13341 ファイルの一部だけをロックできる。
13342 @c COMMON
13343 @item
13344 @c EN
13345 You can have shared (read) and exclusive (write) locks.
13346 @c JP
13347 共有(読み出し)ロックと排他(書き込み)ロックが使える。
13348 @c COMMON
13349 @end itemize
13350
13351 @c EN
13352 In common situations, probably the most handy property is the
13353 first one; you don't need to worry about leaving lock behind
13354 unexpected process termination.
13355 @c JP
13356 多くの場合、最も便利なのは最初の性質でしょう。プロセスが予想外に落ちてしまった
13357 場合でも、ロックが残されてしまうことを心配しないで済みます。
13358 @c COMMON
13359
13360 @c EN
13361 However, there are a couple of shortcomings in @code{fcntl} locks.
13362 @c JP
13363 けれども、@code{fcntl}ロックには欠点もあります。
13364 @c COMMON
13365
13366 @itemize
13367 @item
13368 @c EN
13369 It is not guaranteed to work across different platforms,
13370 and/or NFS-mounted filesystems.
13371 @c JP
13372 異なるプラットフォームや、NFSマウントされたファイルシステム間で
13373 確実に動作する保証がない。
13374 @c COMMON
13375 @item
13376 @c EN
13377 The lock is per-process, per-file, and non-recursive.
13378 If you have a lock in a file,
13379 then calls a library that also locks the file, the lock always
13380 succeeds. Worse, if the library unlocks the file,
13381 the lock is completely removed, while the caller doesn't know
13382 about it. It also means that, in order to prevent multiple threads
13383 in a process from accessing the same file, you have to use
13384 mutex along the fcntl lock.
13385 @c JP
13386 ロックはプロセス単位、ファイル単位でかつ非再帰的である。
13387 例えば、既にプロセスがロックしているファイルに対して、呼び出したライブラリ内でまたロックを
13388 獲得しようとすると、それは常に成功する。さらに悪いことに、そのライブラリが
13389 ロックを解放した時点で、元からロックがかかっていたかどうかに関わらず、プロセス全体が
13390 ロックを手放してしまう。このことはまた、複数のスレッド間で排他的にファイルに
13391 アクセスしたい場合は、fcntlロックと一緒にmutexも使う必要があるということでもある。
13392 @c COMMON
13393 @end itemize
13394
13395 @c EN
13396 Especially because of the second point, it is very difficult
13397 to use @code{fcntl} lock unless you have total control over and knowledge
13398 of the entire application.
13399 It is ok to use the @code{fcntl} lock by the application code to lock
13400 the application-specific file.
13401 Library developers have difficulty, however, to make sure any potential
13402 user of the library won't try to lock the same file as the library tries
13403 to lock (usually it's impossible).
13404 @c JP
13405 二番目の欠点のせいで、アプリケーション全体を知っていてコードを好きにできる場合でなければ、
13406 @code{fcntl}ロックを安全に使うことが非常に難しくなっています。
13407 アプリケーションコードが、そのアプリケーションで使うためだけのファイルをロックするのに
13408 @code{fcntl}ロックを使うのは何も問題ありません。
13409 しかしライブラリ開発者は、ライブラリ内で@code{fcntl}ロックを使うなら、
13410 そのライブラリのユーザや他のライブラリが将来に渡って同じファイルを決してロックしない
13411 ということを保証しなければなりません(通常、そんなことは不可能です)。
13412 @c COMMON
13413
13414 @c ----------------------------------------------------------------------
13415 @node Mathematical constants, Mersenne-Twister random number generator, Filesystem utilities, Library modules - Utilities
13416 @section @code{math.const} - Mathematical constants
13417 @c NODE 定数, @code{math.const} - 定数
13418
13419 @deftp {Module} math.const
13420 @mdindex math.const
13421 @c EN
13422 This module defines several commonly-used mathematic constants.
13423 @c JP
13424 いくつかの一般的に用いられる数学定数を定義しています。
13425 @c COMMON
13426 @end deftp
13427
13428 @defvr {Constant} pi
13429 @defvrx {Constant} π
13430 @defvrx {Constant} 2pi
13431 @defvrx {Constant} 2π
13432 @defvrx {Constant} pi/2
13433 @defvrx {Constant} π/2
13434 @defvrx {Constant} pi/4
13435 @defvrx {Constant} π/4
13436 @defvrx {Constant} pi/180
13437 @defvrx {Constant} π/180
13438 @defvrx {Constant} 1/pi
13439 @defvrx {Constant} 1/π
13440 @defvrx {Constant} 180/pi
13441 @defvrx {Constant} 180/π
13442 @c MOD math.const
13443 @c EN
13444 Bound to constants computed with π.
13445 @c JP
13446 πから計算される定数値に束縛されています。
13447 @c COMMON
13448 @end defvr
13449
13450 @defvr {Constant} e
13451 @c MOD math.const
13452 Napier's constant.
13453 @end defvr
13454
13455 @c ----------------------------------------------------------------------
13456 @node Mersenne-Twister random number generator, Prime numbers, Mathematical constants, Library modules - Utilities
13457 @section @code{math.mt-random} - Mersenne Twister Random number generator
13458 @c NODE Mersenne Twister乱数発生器, @code{math.mt-random} - Mersenne Twister乱数発生器
13459
13460 @deftp {Module} math.mt-random
13461 @mdindex math.mt-random
13462 @c EN
13463 Provides a pseudo random number generator (RNG) based on
13464 "Mersenne Twister" algorithm developed by Makoto Matsumoto and
13465 Takuji Nishimura. It is fast, and has huge period of 2^19937-1.
13466 See @url{https://dl.acm.org/citation.cfm?id=272995}, for details about the algorithm.
13467 @c JP
13468 Makoto MatsumotoとTakuji Nishimuraにより開発された、
13469 ``Mersenne Twister''アルゴリズムに基づく、
13470 仮想的な乱数発生器(RNG)を提供します。
13471 高速で、2^19937-1という極めて長大な周期を持ちます。
13472 アルゴリズムの詳細については、@url{https://dl.acm.org/citation.cfm?id=272995}を参照して下さい。
13473 @c COMMON
13474
13475 @c EN
13476 For typical use cases of random number generators,
13477 we recommend to use @code{srfi.27} which is implemented
13478 on top of this module and provides portable API
13479 (@pxref{Sources of random bits}).
13480 You should use this module directly only when you need
13481 functions that aren't available through @code{srfi.27}.
13482 @c JP
13483 乱数発生器の通常の用途には、@code{srfi.27}を使うことをお勧めします
13484 (@ref{Sources of random bits}参照)。
13485 @code{srfi.27}はこのモジュールの上に実装されていますが、ポータブルなAPIを提供しています。
13486 @code{srfi.27}にない機能が必要な時のみこのモジュールを直接使うようにしてください。
13487 @c COMMON
13488 @end deftp
13489
13490 @deftp {Class} <mersenne-twister>
13491 @clindex mersenne-twister
13492 @c MOD math.mt-random
13493 @c EN
13494 A class to encapsulate the state of Mersenne Twister RNG.
13495 Each instance of this class has its own state, and can be used
13496 as an independent source of random bits if initialized
13497 by individual seed.
13498 @c JP
13499 Mersenne Twister RNGの状態をカプセル化するクラスです。
13500 このクラスのそれぞれのインスタンスは独自の状態を持ち、
13501 個別のシードで初期化されていれば、それぞれがランダムビットの
13502 独立したソースになり得ます。
13503 @c COMMON
13504 @end deftp
13505
13506 @defun make-mersenne-twister :optional seed private?
13507 @c MOD math.mt-random
13508 @c EN
13509 Creates and returns a new @code{<mersenne-twister>} RNG instance.
13510
13511 If @var{seed} argument is given, it must be either nonnegative exact
13512 integer, u32vector, or @code{#f}. The key can be any length.
13513
13514 If @var{seed} is omitted or @code{#f}, the RNG is initialized to the fixed value,
13515 so that it generates the same sequences of random numbers. If you want
13516 different sequence for each instance, you have to give different seeds
13517 explicitly, or initialize each instance with different seeds using
13518 @code{mt-random-set-seed!} below.
13519 @c JP
13520 新たな@code{<mersenne-twister>}のインスタンスを作って返します。
13521
13522 @var{seed}引数が与えられたなら、それは任意の正確な非負整数か、
13523 @code{u32vctor}でなければなりません。キーの長さに制限はありません。
13524
13525 @var{seed}が省略されるか@code{#f}の場合、RNGは固定の種で初期化されるので、
13526 そのままだと常に同じ乱数列を生成します。
13527 インスタンス毎に異なる乱数列が必要なら、明示的に異なる種を渡すか、
13528 下の@code{mt-random-set-seed!}で種を設定してください。
13529 @c COMMON
13530
13531 @c EN
13532 By default, the created RNG is thread-safe; you can call the generator
13533 from multiple thread without worrying to break its internal state.
13534
13535 However, if you know you only use it in a single thread, or you use
13536 separate mutex and know the generator call is alyways protected, then
13537 you can give a true value to @var{private?} optional argument to avoid
13538 overhead of locking.
13539 @c JP
13540 デフォルトでは、作られるRNGはスレッドセーフです。
13541 すなわち、複数のスレッドからジェネレータを呼んでも内部状態を壊してしまうことはありません。
13542
13543 ただ、RNGを一つのスレッドからしか使わないとか、他のロックで常に排他された環境でしか
13544 呼ばないということがわかっているなら、@var{private?}引数に真の値を渡すことができます。
13545 その場合、RNGはロックを省略します。
13546 @c COMMON
13547
13548 @example
13549 (define m (make-mersenne-twister (sys-time)))
13550
13551 (mt-random-real m) @result{} 0.10284287848537865
13552 (mt-random-real m) @result{} 0.463227748348805
13553 (mt-random-real m) @result{} 0.8628500643709712
13554 @dots{}
13555 @end example
13556 @end defun
13557
13558 @defun mt-random-set-seed! mt seed
13559 @c MOD math.mt-random
13560 @c EN
13561 Sets random seed value @var{seed} to the Mersenne Twister RNG (MTRNG) @var{mt}.
13562 @var{Seed} can be an arbitrary positive exact integer,
13563 or arbitrary length of u32vector (@pxref{Homogeneous vectors}).
13564 @c JP
13565 メルセンヌツイスターRNG @var{mt}にランダムシードの値@var{seed}をセットします。
13566 @var{seed}は任意の正の正確整数か、任意長のu32vector
13567 (@ref{Homogeneous vectors}参照)が使えます。
13568 @c COMMON
13569
13570 @c EN
13571 Internally, MTRNG keeps its state in an array of 624 32-bit integers.
13572 If the given seed is small (e.g. fixnum), it can't create enough
13573 variations. Particularly, if the seed is within 32bits, it can be
13574 computed by sampling a couple of result from MTRNG. If you want the random
13575 sequence harder to predict, prepare your own u32vector seed filled with
13576 high-entroby bits.
13577
13578 Note that Mersenne Twister is never intended for cryptograhpy, you shouldn't
13579 use it for security-sensitive purposes.
13580 @c JP
13581 MTRNGは32ビット整数624個の配列を内部状態として持っています。
13582 シード値が小さい場合(例: fixnum)、充分なバリエーションを作ることができません。
13583 特に、シード値が32ビットに収まる場合、MTRNGの二つの出力だけから
13584 シード値が逆算できてしまいます。
13585 もし乱数列をもっと予測しづらくしたいなら、u32vectorをエントロピーの高いビットで満たして
13586 それをシードとして使ってください。
13587
13588 メルセンヌツイスターは暗号学的に安全であることを意図して作られてはいません。
13589 セキュリティが重要な用途には使わないでください。
13590 @c COMMON
13591
13592 @c EN
13593 NB: Up to 0.9.9, when @var{seed} is a bignum, we roll our own way to
13594 fold it in 32bit integer and then called Mersenne-Twister's initialization
13595 function. It loses the entropy, so we changed it and now all the bits
13596 in the bignum is used for the seed.
13597 @c JP
13598 註: 0.9.9までは、@var{seed}にbignumが渡された場合、そこから独自のアルゴリズムで
13599 32bitの値を生成してメルセンヌツイスタの初期化関数を呼んでいました。
13600 しかしそれだとエントロピーを捨てることになるので、現在は
13601 全てのビットがシード値に使われるように変更されています。
13602 @c COMMON
13603 @end defun
13604
13605 @defun mt-random-get-seed mt
13606 @c MOD math.mt-random
13607 @c EN
13608 Returns the last seed value used to initialize Mersenne Twister RNG @var{mt}.
13609 It is either an exact integer or u32vector.
13610 If @var{mt} has never been initialized, @code{#<undef>} is returned.
13611 @c JP
13612 Mersenne Twister RNG @var{mt}を初期化するのに使われたシード値を返します。
13613 複数回初期化されている場合は、最後に初期化されたものを返します。
13614 シード値は正確な整数かu32vectorです。
13615 初期化されたことがなければ、@code{#<undef>}が返されます。
13616 @c COMMON
13617 @end defun
13618
13619 @defun mt-random-get-state mt
13620 @defunx mt-random-set-state! mt state
13621 @c MOD math.mt-random
13622 @c EN
13623 Retrieves and reinstalls the state of Mersenne Twister RNG @var{mt}.
13624 The state is represented by a u32vector of 625 elements. The state
13625 can be stored elsewhere, and then restored to an instance of
13626 @code{<mersenne-twister>} to continue to generate the pseudo random
13627 sequence.
13628 @c JP
13629 Mersenne Twister RNG @var{mt}を取り出して再インストールします。
13630 状態は、625要素のu32vectorで表現されます。
13631 状態はどこにでも保存することができ、仮想的なランダムシーケンスの
13632 生成を続行するために、@code{<mersenne-twister>}のインスタンスとして
13633 リストアできます。
13634 @c COMMON
13635 @end defun
13636
13637 @defun mt-random-real mt
13638 @defunx mt-random-real0 mt
13639 @c MOD math.mt-random
13640 @c EN
13641 Returns a random real number between 0.0 and 1.0.
13642 1.0 is not included in the range. @code{Mt-random-real} doesn't
13643 include 0.0 either, while @code{mt-random-real0} does.
13644 Excluding 0.0 is from the draft SRFI-27.
13645 @c JP
13646 0.0と1.0の間のランダムな実数を返します。
13647 1.0は範囲に含まれません。
13648 @code{mt-random-real}は、0.0も範囲に含みませんが、
13649 @code{mt-random-real0}は含みます。
13650 0.0を含まないのは、SRFI-27ドラフトに依拠しています。
13651 @c COMMON
13652 @end defun
13653
13654 @defun mt-random-integer mt range
13655 @c MOD math.mt-random
13656 @c EN
13657 Returns a random exact positive integer between 0 and @var{range}-1.
13658 @var{Range} can be any positive exact integer.
13659 @c JP
13660 0から@var{range}-1までの正の正確整数をランダムに返します。
13661 @var{range}はいかなる正の正確整数でも構いません。
13662 @c COMMON
13663 @end defun
13664
13665 @defun mt-random-fill-u32vector! mt u32vector
13666 @defunx mt-random-fill-f32vector! mt f32vector
13667 @defunx mt-random-fill-f64vector! mt f64vector
13668 @c MOD math.mt-random
13669 @c EN
13670 Fills the given uniform vector by the random numbers.
13671 For @code{mt-random-fill-u32vector!}, the elements are filled
13672 by exact positive integers between 0 and 2^32-1.
13673 For @code{mt-random-fill-f32vector!} and
13674 @code{mt-random-fill-f64vector!}, it is filled by an inexact
13675 real number between 0.0 and 1.0, exclusive.
13676
13677 If you need a bunch of random numbers at once, these are much
13678 faster than getting one by one.
13679 @c JP
13680 与えられたユニフォームベクタをランダムな数値で埋めます。
13681 @code{mt-random-fill-u32vector!}では、要素は0と2^32-1の間の
13682 正の正確整数で埋められます。
13683 @code{mt-random-fill-f32vector!}と@code{mt-random-fill-f64vector!}
13684 では、0.0と1.0(含まれない)の間の非正確実数で埋められます。
13685 @c COMMON
13686 @end defun
13687
13688 @c ----------------------------------------------------------------------
13689 @node Prime numbers, Simplex solver, Mersenne-Twister random number generator, Library modules - Utilities
13690 @section @code{math.prime} - Prime numbers
13691 @c NODE 素数, @code{math.prime} - 素数
13692
13693 @deftp {Module} math.prime
13694 @mdindex math.prime
13695 @c EN
13696 This module provides utilities related to prime numbers.
13697 @c JP
13698 このモジュールは、素数を扱うユーティリティ関数を提供します。
13699 @c COMMON
13700 @end deftp
13701
13702 @c EN
13703 @subheading Sequence of prime numbers
13704 @c JP
13705 @subheading 素数のシーケンス
13706 @c COMMON
13707
13708 @defvar *primes*
13709 @c MOD math.prime
13710 @c EN
13711 An infinite lazy sequence of primes.
13712 @c JP
13713 素数の無限遅延シーケンスです。
13714 @c COMMON
13715
13716 @example
13717 ;; show 10 prime numbers from 100-th one.
13718 (take (drop *primes* 100) 10)
13719 @result{} (547 557 563 569 571 577 587 593 599 601)
13720 @end example
13721 @end defvar
13722
13723 @defun reset-primes
13724 @c MOD math.prime
13725 @c EN
13726 Once you take a very large prime out of @code{*primes*}, all primes
13727 before that has been calculated remains in memory, since the
13728 head of sequence is held in @code{*primes*}. Sometimes you know
13729 you need no more prime numbers and you wish those calculated ones
13730 to be garbage-collected. Calling @code{reset-primes} rebinds
13731 @code{*primes*} to unrealized lazy sequence, allowing the previously
13732 realized primes to be GCed.
13733 @c JP
13734 @code{*primes*}から大きな素数を取り出すと、それ以前の素数も全てメモリに
13735 残り続けます。@code{*primes*}変数がシーケンスの頭を抱えているからです。
13736 もう素数を必要としないことがわかっている場合、それらのメモリがガベージコレクト
13737 されることが望ましいかもしれません。@code{reset-primes}手続きは
13738 @code{*primes*}をまだ現実化されていない遅延シーケンスに再束縛し、
13739 次のGCで計算済みの素数シーケンスが回収されるようにします。
13740 @c COMMON
13741 @end defun
13742
13743 @defun primes
13744 @c MOD math.prime
13745 @c EN
13746 Returns a fresh lazy sequence of primes. It is useful when
13747 you need certain primes in a short period of time---if you don't keep
13748 a reference to the head of the returned sequence, it will be garbage
13749 collected after you've done with the primes.
13750 (Note that calculation of a prime number needs the
13751 sequence of primes from the beginning,
13752 so even if your code only keep a reference
13753 in the middle of the sequence, the entire sequence will be kept
13754 in the thunk within the lazy sequence---you have to release all
13755 references in order to make the sequence GCed.)
13756
13757 On the other hand,
13758 each sequence returned by @code{primes} are realized individually,
13759 duplicating calculation.
13760
13761 The rule of thumb is---if you use primes repeatedly throughout
13762 the program, just use @code{*primes*} and you'll save calculation.
13763 If you need primes one-shot, call @code{primes} and abandon it
13764 and you'll save space.
13765 @c JP
13766 新たな素数の遅延シーケンスを返します。
13767 その時だけ素数を使いたい、という時に便利です。返されたシーケンスへの
13768 参照が無くなれば、シーケンスはガベージコレクトされます。
13769 (ある素数の計算には素数のシーケンスが最初から必要なので、
13770 たとえシーケンスの頭ではなく途中への参照だけを持っていたとしても、
13771 遅延シーケンスの中のサンクにはシーケンスの頭への参照が保持されています。
13772 シーケンスがGCされるためには、いかなる部分への参照も残さないようにしなければなりません)。
13773
13774 @code{primes}が返す各シーケンスは独立しているので、素数の計算もそれぞれで
13775 (重複して)行われることになります。
13776
13777 単純なルールとして、プログラム中で何度も素数を使う必要があるのなら
13778 変数@code{*primes*}を利用するのが良いでしょう。各素数の計算は一度しか
13779 行われず、余分な計算を省くことができます。しかしその場だけ素数が欲しいなら、
13780 @code{primes}を呼んで、仕事が済んだらシーケンスを捨ててしまえば、
13781 不要なシーケンスがメモリに残りつづけることを心配しなくても済みます。
13782 @c COMMON
13783 @end defun
13784
13785 @c EN
13786 @subheading Testing primality
13787 @c JP
13788 @subheading 素数かどうかを調べる
13789 @c COMMON
13790
13791 @defun small-prime? n
13792 @c MOD math.prime
13793 @c EN
13794 For relatively small positive integers
13795 (below @code{*small-prime-bound*}, to be specific), this procedure
13796 determines if the input is prime or not, quickly and deterministically.
13797 If @var{n} is on or above the bound, this procedure returns @code{#f}.
13798
13799 This can be used to quickly filter out known primes; it never returns
13800 @code{#t} on composite numbers (while it may return @code{#f} on
13801 large prime numbers).
13802 Miller-Rabin test below can tell if the input is composite for sure,
13803 but it may return @code{#t} on some composite numbers.
13804 @c JP
13805 比較的小さな正整数 (@code{*small-prime-bound*}以下の正整数) に対して、
13806 それが素数であるかどうかを判定し、素数なら@code{#t}を返します。
13807 @var{n}がそれ以上である場合は常に@code{#f}を返します。
13808
13809 この手続きは確実に素数であるとわかるものを素早く判別する時に便利です。
13810 @code{#t}が返れば確実に素数であるとわかるからです (入力が大きな素数の時に
13811 @code{#f}を返すことはありえますが)。
13812 これに対し、下に述べるMiller-Rabin法では、合成数は確実に判別できますが、
13813 素数であるかどうかは確実には言えません。
13814 @c COMMON
13815 @end defun
13816
13817 @defvar *small-prime-bound*
13818 @c MOD math.prime
13819 @c EN
13820 For all positive integers below this value
13821 (slightly above 3.4e14 in the current implementation),
13822 @code{small-prime?} can determines whether it is a prime or not.
13823 @c JP
13824 これより小さな数に対しては、@var{small-prime?}は決定的に
13825 素数かどうかを判別します。現在の実装ではこの数は3.4e14よりちょっと大きな数です。
13826 @c COMMON
13827 @end defvar
13828
13829
13830 @defun miller-rabin-prime? n :key num-tests random-integer
13831 @c MOD math.prime
13832 @c EN
13833 Check if an exact integer @var{n} is a prime number, using
13834 probabilistic Miller-Rabin algorithm (@var{n} must be greater than 1).
13835 If this procedure returns @code{#f},
13836 @var{n} is a composite number. If this procedure returns @code{#t},
13837 @var{n} is @emph{likely} a prime, but there's a small probability
13838 that it is a false positive.
13839 @c JP
13840 2以上の正確な整数@var{n}が素数かどうかを、確率的なMiller-Rabin法を使って判定します。
13841 この手続きが@code{#f}を返したなら、@var{n}は確実に合成数です。
13842 この手続きが@code{#t}を返した場合、@var{n}はおそらく素数ですが、
13843 疑陽性である確率もわずかにあります。
13844 @c COMMON
13845
13846 @c EN
13847 Note that if @var{n} is smaller than a certain number
13848 (@code{*small-prime-bound*}), the algorithm is
13849 deterministic; if it returns @code{#t}, @var{n} is certainly a prime.
13850 @c JP
13851 ただし、@code{n}がある数(@code{*small-prime-bound*})
13852 より小さければ、アルゴリズムは決定的で、@code{#t}が返る@var{n}は確実に素数です。
13853 @c COMMON
13854
13855 @c EN
13856 If @var{n} is greater than or equal to
13857 @code{*small-prime-bound*},
13858 we use a probabilistic test. We choosing random base integer
13859 to perform Miller-Rabin test up to 7 times by default.
13860 You can change the number of tests by the keyword argument
13861 @var{num-tests}. The error probability
13862 (to return @code{#t} for a composite number)
13863 is at most @code{(expt 4 (- num-tests))}.
13864 @c JP
13865 @var{n}が@code{*small-prime-bound*}以上の場合は
13866 確率的テストを用います。デフォルトでは7回、ランダムにベース整数値を選んで
13867 Miller-Rabinテストを適用します。試行回数は@var{num-tests}キーワード引数で
13868 変更可能です。合成数に対して誤って@code{#t}を返してしまう確率は
13869 たかだか@code{(expt 4 (- num-tests))}です。
13870 @c COMMON
13871
13872 @c EN
13873 For a probabilistic test, @code{miller-rabin-prime?} uses
13874 its own fixed random seed by default. We chose fixed seed
13875 so that the behavior can be reproducible. To change the random
13876 sequence, you can provide your own random integer generator
13877 to the @var{random-integer} keyword argument. It must be
13878 a procedure that takes a positive integer @var{k} and returns
13879 a random integer from 0 to @var{k-1}, including.
13880 @c JP
13881 確率的テストでは、@var{miller-rabin-prime?}はデフォルトで
13882 この手続き固有の、固定したランダムシードを使います。固定値なのは再現性を確保するためです。
13883 異なる乱数系列を使いたければ、ランダムな整数生成手続きを
13884 @var{random-integer}キーワード引数に与えてください。
13885 手続きは正整数@var{k}を取り、0から@var{k-1}までのランダムな整数値を
13886 返すものでなければなりません。
13887 @c COMMON
13888 @end defun
13889
13890 @defun bpsw-prime? n
13891 @c MOD math.prime
13892 @c EN
13893 Check if an exact integer @var{n} is a prime number, using
13894 Baillie-PSW primality test
13895 (@url{http://www.trnicely.net/misc/bpsw.html}). It is deterministic,
13896 and returns the definitive answer below 2^64 (around 1.8e19).
13897 For larger integers this can return @code{#t} on a composite number,
13898 although such number hasn't been found yet. This never returns @code{#f}
13899 on a prime number.
13900
13901 This is slower than Miller-Rabin but fast enough for casual use,
13902 so it is handy when you want a definitive answer below the above range.
13903 @c JP
13904 @var{n}が素数かどうかをBaillie-PSW法を用いて判定します
13905 (@url{http://www.trnicely.net/misc/bpsw.html})。
13906 このアルゴリズムは2^64 (約1.8e19) 以下の入力に対しては決定的であり、
13907 正しい答えを返します。入力がそれ以上の場合、合成数に対して@code{#t}が返る可能性が
13908 あります (具体的な数はまだ見つかっていませんが)。素数に対して@code{#f}が返ることは
13909 決してありません。
13910
13911 Miller-Rabin法より遅いですがカジュアルに使う分には十分に速いので、
13912 上記の入力範囲で確実な答えを得たい場合は便利でしょう。
13913 @c COMMON
13914 @end defun
13915
13916 @c EN
13917 @subheading Factorization
13918 @c JP
13919 @subheading 素因数分解
13920 @c COMMON
13921
13922 @defun naive-factorize n :optional divisor-limit
13923 @c MOD math.prime
13924 @c EN
13925 Factorize a positive exact integer @var{n} by trying to divide it with
13926 all primes up to @code{(sqrt n)}. Returns a list of prime factors
13927 (each of which is equal to or greater than 2),
13928 smaller ones first.
13929 @c JP
13930 正整数@var{n}を、@code{(sqrt n)}までの素数で順に割ってみることで
13931 素因数分解します。戻り値は小さい順に並べられた素因数(2以上の整数)のリストです。
13932 @c COMMON
13933
13934 @example
13935 (naive-factorize 142857)
13936 @result{} (3 3 3 11 13 37)
13937 @end example
13938
13939 @c EN
13940 Note that @code{(naive-factorize 1)} is @code{()}.
13941 @c JP
13942 @code{(naive-factorize 1)}は@code{()}を返します。
13943 @c COMMON
13944
13945 @c EN
13946 Although this is pretty naive method, this works well as far as
13947 any of @var{n}'s factors are up to the order of around @code{1e7}.
13948 For example, the following example runs in about 0.4sec on 2.4GHz Core2
13949 machine.
13950 (The first time will take about 1.3sec to realize lazy prime sequences.)
13951 @c JP
13952 この方法は極めてナイーブなものですが、目安としてどの素因数も@code{1e7}程度以下であれば
13953 それなりに使えます。例えば次の例は2.4GHz Core2マシンで0.4秒で答えが返ります
13954 (ただし、初回の実行は遅延素数シーケンスの実現化があるので1.3秒ほどかかりますが)。
13955 @c COMMON
13956
13957 @example
13958 (naive-factorize 3644357367494986671013))
13959 @result{} (10670053 10670053 32010157)
13960 @end example
13961
13962 @c EN
13963 Of course, if @var{n} includes any factors above that order,
13964 the performance becomes abysmal. So it is better to use this
13965 procedure below 1e14 or so.
13966 @c JP
13967 もちろん@var{n}がより大きなオーダーの素因数を含んでいると、性能は急激に
13968 悪化します。安全に使うには@var{n}を1e14程度のオーダーに止めておくのが良いでしょう。
13969 @c COMMON
13970
13971 @c EN
13972 Alternatively, you can give @var{divisor-limit} argument that specifies
13973 the upper bound of the prime number to be tried. If it is given,
13974 @code{naive-factorize} leaves a factor @var{f} as is if it can't be
13975 divided by any primes less than or equal to @var{divisor-limit}.
13976 So, the last element of the returned list may be composite number.
13977 This is handy to exclude trivial factors before applying more sophisticated
13978 factorizing algorithms.
13979 @c JP
13980 オプショナル引数@var{divisor-limit}を与えると、試行する素数の上限を指定
13981 できます。この引数がある場合、@code{naive-factorize}は因数@var{f}が
13982 @var{divisor-limit}以下の素数で割りきれなければ、そこで諦めて@var{f}を
13983 結果に含めます。この場合、結果の最後の要素は合成数であるかもしれないわけです。
13984 これは、より高度な素因数分解アルゴリズムを適用する前にありきたりの素因数を
13985 除外するのに便利です。
13986 @c COMMON
13987
13988 @example
13989 (naive-factorize 825877877739 1000)
13990 @result{} (3 43 6402154091)
13991
13992 ;; whereas
13993 (naive-factorize 825877877739)
13994 @result{} (3 43 4591 1394501)
13995 @end example
13996
13997 @c EN
13998 The procedure also memoizes the results on smaller @var{n} to make
13999 things faster.
14000 @c JP
14001 この手続きは高速化のために小さな@var{n}に対する結果はメモ化しています。
14002 @c COMMON
14003 @end defun
14004
14005 @defun mc-factorize n
14006 @c MOD math.prime
14007 @c EN
14008 Factorize a positive exact integer @var{n} using the algorithm
14009 described in
14010 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}.
14011 @c JP
14012 正整数@var{n}をモンテカルロ素因数分解法
14013 (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})により
14014 素因数分解します。
14015 @c COMMON
14016
14017 @c EN
14018 This one is capable to handle much larger range than
14019 @code{naive-factorize}, somewhere around 1e20 or so.
14020
14021 Since this method is probabilistic, the execution time may vary
14022 on the same @var{n}. But it will always return the definitive
14023 results as far as every prime factor of @var{n} is smaller than 2^64.
14024
14025 At this moment, if @var{n} contains a prime factor greater than
14026 2^64, this routine would keep trying factorizing it forever.
14027 Practical applications should have some means to interrupt the
14028 function and give it up after some time bounds.
14029 This will be addressed once we have deterministic primality test.
14030 @c JP
14031 この手続きは@code{naive-factorize}よりも大きな数に使えます
14032 (目安としては1e20程度まで)。
14033
14034 アルゴリズムは確率的なので、同じ@var{n}に対しても実行時間はばらつきますが、
14035 @var{n}の素因数が全て2^64より小さければ、かならず確定的な答えを返します。
14036
14037 今のところ、@var{n}が2^64以上の素因数を含んでいる場合、この手続きは
14038 永遠にそれを分割しようとしてループしてしまいます。現実的なアプリケーションは
14039 何らかの方法で一定の時間でルーチンを中断して諦めるメカニズムが必要でしょう。
14040 全ての入力に大して確定的な素数判定が実装されれば、この欠陥も修正されます。
14041 @c COMMON
14042 @end defun
14043
14044
14045 @c EN
14046 @subheading Miscellaneous
14047 @c JP
14048 @subheading その他の関数
14049 @c COMMON
14050
14051 @defun jacobi a n
14052 @c MOD math.prime
14053 @c EN
14054 Calculates Jacobi symbol @code{(@var{a}/@var{n})}
14055 (@url{http://en.wikipedia.org/wiki/Jacobi_symbol}).
14056 @c JP
14057 Jacobi symbol @code{(@var{a}/@var{n})} を計算します
14058 (@url{http://en.wikipedia.org/wiki/Jacobi_symbol})。
14059 @c COMMON
14060 @end defun
14061
14062 @defun totient n
14063 @c MOD math.prime
14064 @c EN
14065 Euler's totient function of nonnegative integer @var{n}.
14066
14067 The current implementation relies on @code{mc-factorize} above,
14068 so it may take very long if @var{n} contains large prime factors.
14069 @c JP
14070 オイラーのトーシェント関数です。@var{n}は非負整数です。
14071
14072 現在の実装は上の@code{mc-factorize}を使っており、
14073 @var{n}が大きな素因数を持っている場合は非常に長い時間がかかります。
14074 @c COMMON
14075 @end defun
14076
14077 @c ----------------------------------------------------------------------
14078 @node Simplex solver, Windows support, Prime numbers, Library modules - Utilities
14079 @section @code{math.simplex} - Simplex solver
14080 @c NODE シンプレックスソルバー, @code{math.simplex} - シンプレックスソルバー
14081
14082 @deftp {Module} math.simplex
14083 @mdindex math.simplex
14084 @c EN
14085 Implements the simplex algorithm to solve linear programming problems.
14086 @c JP
14087 線形計画問題をシンプレックス法で解く実装です。
14088 @c COMMON
14089 @end deftp
14090
14091 @defun simplex-solve A b goal c
14092 @c MOD math.simplex
14093 @c EN
14094 @var{A} is an m x n array of numbers, @var{b} is a sequence of
14095 m numbers, @var{c} is a sequence of n numbers,
14096 and @var{goal} is either @code{:maximize} or @code{:minimize}.
14097 Returns an f64vector @var{x} of length n,
14098 such that it maximizes or minimizes
14099 the inner product @var{c} . @var{x}, while satisfying
14100 the constraint @code{A}@var{x} <= @var{b} and @var{x} >= 0.
14101 @c JP
14102 @var{A}は m x n の数値配列、@var{b}は @var{m}個の数値のシーケンス、
14103 @var{c}は@var{n}個の数値のシーケンスで、また@var{goal}は
14104 @code{:maximize}か@code{:minimize}です。
14105 この手続きは次の制約を満たす長さnのf64vectorである@var{x}を返します:
14106 制約条件 @code{A}@var{x} <= @var{b} および @var{x} >= 0 のもとで、
14107 内積 @var{c} . @var{x} が最大値もしくは最小値を取る@var{x}。
14108 @c COMMON
14109
14110 @c EN
14111 The array can be any type of arrays (@pxref{Arrays}) and the
14112 two sequences can be any type of sequence, as far as they only
14113 contain real numbers. Internally it uses @code{f64vector} and
14114 @code{f64array} for calculation.
14115 The arguments aren't mutated during computation.
14116 @c JP
14117 配列と2つのシーケンスは、全ての要素が数値でさえあればどんな型でも渡せます
14118 (配列については@ref{Arrays}参照)。内部的には、@code{f64vector}と
14119 @code{f64array}が計算に使われます。
14120 引数に渡した配列とシーケンスは変更されません。
14121 @c COMMON
14122
14123 @c EN
14124 You can have negative entries in @var{b}; the procedure uses two-phase
14125 simplex method in that case.
14126 @c JP
14127 @var{b}の要素は負であっても構いません。負の数がある場合、この手続きは
14128 2-phaseシンプレックス法を使います。
14129 @c COMMON
14130
14131 @c EN
14132 If you have a '>=' constraint, you can negate both sides to make it a '<='
14133 constraint. If you have an equality in the constraint, you can either
14134 use it to reduce one variable, or add both '>=' and '<=' constraints.
14135 @c JP
14136 制約が「定数項以上」である場合は、両辺の符号を反転して「定数項以下」の制約にしてください。
14137 等しい制約がある場合は、あらかじめその関係を使って変数を減らすか、
14138 「定数項以上」と「定数項以下」の制約を同時に与えることで解けます。
14139 @c COMMON
14140
14141 @c EN
14142 If there can be multiple solutions, the procedure returns one of them.
14143 If there's no solutions, it returns @code{#f}.
14144 @c JP
14145 複数の解がある場合はどれか一つが返されます。
14146 解が無い場合は@code{#f}が返されます。
14147 @c COMMON
14148
14149 @example
14150 ;; Maximize x1 + x2 under constraints of
14151 ;; x1 + 0.5*x2 <= 2.0 and
14152 ;; 3*x1 + 2*x2 <= 12.0
14153
14154 (simplex-solve '#,(<array> (0 2 0 2) 1 0.5 3 2)
14155 '#f64(2.0 12.0)
14156 :maximize '#(1 1))
14157
14158 @result{} #f64(0.0 4.0)
14159 @end example
14160 @end defun
14161
14162 @c ----------------------------------------------------------------------
14163 @node Windows support, PEG parser combinators, Simplex solver, Library modules - Utilities
14164 @section @code{os.windows} - Windows support
14165 @c NODE Windowsのサポート, @code{os.windows} - Windowsのサポート
14166
14167 @deftp {Module} os.windows
14168 @mdindex os.windows
14169 This module is only available on Windows-native Gauche, and
14170 provides Windows-specific procedures.
14171 You can check @code{gauche.os.windows} feature with
14172 @code{cond-expand} macro (@pxref{Feature conditional})
14173 to conditionalize windows-specific code.
14174
14175 @example
14176 (cond-expand
14177 [gauche.os.windows
14178 (use os.windows)
14179 ... Windows-specific code ...]
14180 [else
14181 ... Unix code ...])
14182 @end example
14183
14184 Currently there aren't enough procedures provided here, but
14185 eventually we want to support simple scripting on Windows.
14186
14187 Unless otherwise noted,
14188 when Windows API returns an error value, a @code{<system-error>} condition
14189 is thrown.
14190 @end deftp
14191
14192 @menu
14193 * Windows dialogs::
14194 * Windows console API::
14195 @end menu
14196
14197 @node Windows dialogs, Windows console API, Windows support, Windows support
14198 @subsection Windows dialogs
14199
14200 Currenly we only have MessageBox API.
14201
14202 @defun sys-message-box window message :optional caption flags
14203 @c MOD os.windows
14204 Calls Windows MessageBox API. The @var{window} argument should
14205 be a handle for a window, or @code{#f}; at the moment we don't
14206 provide any API that retrieves window handles, so you should always
14207 pass @code{#f} here. The @var{message} argument takes a string
14208 for the content of the message box. Optional @var{caption}
14209 argument takes a string to be used in the window title.
14210
14211 The @var{flags} argument is an integer; it should be @code{logior}
14212 of values from one or more of the following groups. See the
14213 Windows reference manual for the details.
14214
14215 @table @emph
14216 @item Buttons
14217 @code{MB_ABORTRETRYIGNORE},
14218 @code{MB_CANCELTRYCONTINUE},
14219 @code{MB_HELP},
14220 @code{MB_OK} (default),
14221 @code{MB_OKCANCEL},
14222 @code{MB_RETRYCANCEL},
14223 @code{MB_YESNO},
14224 @code{MB_YESNOCANCEL}
14225 @item Icon
14226 Default is no icon. Possible values:
14227 @code{MB_ICONEXCLAMATION},
14228 @code{MB_ICONWARNING},
14229 @code{MB_ICONINFORMATION},
14230 @code{MB_ICONASTERISK},
14231 @code{MB_ICONQUESTION},
14232 @code{MB_ICONSTOP},
14233 @code{MB_ICONERROR},
14234 @code{MB_ICONHAND}
14235 @item Default button
14236 @code{MB_DEFBUTTON1} (default),
14237 @code{MB_DEFBUTTON2},
14238 @code{MB_DEFBUTTON3},
14239 @code{MB_DEFBUTTON4}
14240 @item Modality
14241 @code{MB_APPLMODAL} (default),
14242 @code{MB_SYSTEMMODAL},
14243 @code{MB_TASKMODAL}
14244 @item Other options
14245 @code{MB_DEFAULT_DESKTOP_ONLY},
14246 @code{MB_RIGHT},
14247 @code{MB_RTLREADING},
14248 @code{MB_SETFOREGROUND},
14249 @code{MB_TOPMOST},
14250 @code{MB_SERVICE_NOTIFICATION}
14251 @end table
14252
14253 Return value is one of the following integer constants,
14254 indicating which button is pressed:
14255 @code{IDABORT},
14256 @code{IDCANCEL},
14257 @code{IDCONTINUE},
14258 @code{IDIGNORE},
14259 @code{IDNO},
14260 @code{IDOK},
14261 @code{IDRETRY},
14262 @code{IDTRYAGAIN}, or
14263 @code{IDYES}
14264 @end defun
14265
14266 @node Windows console API, , Windows dialogs, Windows support
14267 @subsection Windows console API
14268
14269 Most of these procedures corresponds to Windows Console API one-to-one.
14270 See the Windows reference for the detail description of what each API does.
14271
14272 @subsubheading Attaching and detaching
14273
14274 @defun sys-alloc-console
14275 @defunx sys-free-console
14276 [Windows]
14277 @c MOD os.windows
14278 Calls @code{AllocConsole} and @code{FreeConsole}, respectively.
14279 @end defun
14280
14281 @defun sys-generate-console-ctrl-event event pgid
14282 [Windows]
14283 @c MOD os.windows
14284 Calls @code{GenerateConsoleCtrlEvent}. For @var{event} argument,
14285 the constants @code{CTRL_C_EVENT} and @code{CTRL_BREAK_EVENT} are available.
14286 @end defun
14287
14288 @defvr {Constant} CTRL_C_EVENT
14289 @defvrx {Constant} CTRL_BREAK_EVENT
14290 [Windows]
14291 @c MOD os.windows
14292 Constants to be used for @var{event} argument of
14293 @code{sys-generate-console} above.
14294 @end defvr
14295
14296 @subsubheading Console codepage
14297
14298 @defun sys-get-console-cp
14299 @defunx sys-get-console-output-cp
14300 @defunx sys-set-console-cp codepage
14301 @defunx sys-set-console-output-cp codepage
14302 [Windows]
14303 @c MOD os.windows
14304 Call @code{GetConsoleCP}, @code{GetConsoleOutputCP},
14305 @code{SetConsoleCP}, and @code{SetConsoleOutputCP}, respectively.
14306 Setter procedures returns an undefined value.
14307 @end defun
14308
14309 @subsubheading Console cursor
14310
14311 @defun sys-get-console-cursor-info handle
14312 @defunx sys-set-console-cursor-info handle size visible
14313 [Windows]
14314 @c MOD os.windows
14315 Call @code{GetConsoleCursorInfo} and @code{SetConsoleCursorInfo},
14316 respectively. @var{Handle} is a handle to the console screen buffer.
14317 The getter returns two values, size (the integer
14318 percentage of the character cell that is filled by the cursor,
14319 between 1 and 100), and a boolean visible flag.
14320 The setter takes a handle to the console screen buffer,
14321 integer size percentage, and boolean visible flag. It returns
14322 an undefined value.
14323 @end defun
14324
14325 @defun sys-set-console-cursor-position handle x y
14326 [Windows]
14327 @c MOD os.windows
14328 Calls @code{SetConsoleCursorPosition}.
14329 @var{Handle} is a handle to the console screen buffer.
14330 @var{X} and @var{y} are cursor coordinates in character position,
14331 where (0, 0) is the upper-left corner of the console screen buffer.
14332 It returns an undefined value.
14333
14334 To get the current cursor position, you can use
14335 @code{sys-get-console-screen-buffer-info}.
14336 @end defun
14337
14338 @subsubheading Console mode
14339
14340 @defun sys-get-console-mode handle
14341 @defunx sys-set-console-mode handle mode
14342 [Windows]
14343 @c MOD os.windows
14344 @end defun
14345
14346 @defvr {Constant} ENABLE_LINE_INPUT
14347 @defvrx {Constant} ENABLE_ECHO_INPUT
14348 @defvrx {Constant} ENABLE_PROCESSED_INPUT
14349 @defvrx {Constant} ENABLE_WINDOW_INPUT
14350 @defvrx {Constant} ENABLE_MOUSE_INPUT
14351 @defvrx {Constant} ENABLE_PROCESSED_OUTPUT
14352 @defvrx {Constant} ENABLE_WRAP_AT_EOL_OUTPUT
14353 [Windows]
14354 @c MOD os.windows
14355 @end defvr
14356
14357 @subsubheading Screen buffer
14358
14359 @defun sys-create-console-screen-buffer desired-access share-mode inheritable
14360 [Windows]
14361 @c MOD os.windows
14362 @end defun
14363
14364 @defvr {Constant} GENERIC_READ
14365 @defvrx {Constant} GENERIC_WRITE
14366 [Windows]
14367 @c MOD os.windows
14368 @end defvr
14369
14370 @defvr {Constant} FILE_SHARE_READ
14371 @defvrx {Constant} FILE_SHARE_WRITE
14372 [Windows]
14373 @c MOD os.windows
14374 @end defvr
14375
14376 @defun sys-set-console-active-screen-buffer handle
14377 [Windows]
14378 @c MOD os.windows
14379 @end defun
14380
14381 @defun sys-scroll-console-screen-buffer handle scroll-rectangle clip-rectangle x y fill
14382 [Windows]
14383 @c MOD os.windows
14384 @end defun
14385
14386 @deftp {Class} <win:console-screen-buffer-info>
14387 @clindex win:console-screen-buffer-info
14388 [Windows]
14389 @c MOD os.windows
14390
14391 @defivar {<win:console-screen-buffer-info>} size.x
14392 @defivarx {<win:console-screen-buffer-info>} size.y
14393 @end defivar
14394
14395 @defivar {<win:console-screen-buffer-info>} cursor-position.x
14396 @defivarx {<win:console-screen-buffer-info>} cursor-position.y
14397 @end defivar
14398
14399 @defivar {<win:console-screen-buffer-info>} attributes
14400 @end defivar
14401
14402 @defivar {<win:console-screen-buffer-info>} window.left
14403 @defivarx {<win:console-screen-buffer-info>} window.top
14404 @defivarx {<win:console-screen-buffer-info>} window.right
14405 @defivarx {<win:console-screen-buffer-info>} window.bottom
14406 @end defivar
14407
14408 @defivar {<win:console-screen-buffer-info>} maximum-window-size.x
14409 @defivarx {<win:console-screen-buffer-info>} maximum-window-size.y
14410 @end defivar
14411
14412 @end deftp
14413
14414 @defvr {Constant} FOREGROUND_BLUE
14415 @defvrx {Constant} FOREGROUND_GREEN
14416 @defvrx {Constant} FOREGROUND_RED
14417 @defvrx {Constant} FOREGROUND_INTENSITY
14418 @defvrx {Constant} BACKGROUND_BLUE
14419 @defvrx {Constant} BACKGROUND_GREEN
14420 @defvrx {Constant} BACKGROUND_RED
14421 @defvrx {Constant} BACKGROUND_INTENSITY
14422 [Windows]
14423 @c MOD os.windows
14424 @end defvr
14425
14426 @defun sys-get-console-screen-buffer-info handle
14427 [Windows]
14428 @c MOD os.windows
14429 @end defun
14430
14431 @defun sys-get-largest-console-window-size handle
14432 [Windows]
14433 @c MOD os.windows
14434 @end defun
14435
14436 @defun sys-set-screen-buffer-size handle x y
14437 [Windows]
14438 @c MOD os.windows
14439 @end defun
14440
14441 @subsubheading Console input/output
14442
14443 @deftp {Class} <win:input-record>
14444 @clindex win:input-record
14445 [Windows]
14446 @c MOD os.windows
14447
14448 @defivar {<win:input-record>} event-type
14449 @end defivar
14450
14451 @defivar {<win:input-record>} key.down
14452 @defivarx {<win:input-record>} key.repeat-count
14453 @defivarx {<win:input-record>} key.virtual-key-code
14454 @defivarx {<win:input-record>} key.virtual-scan-code
14455 @defivarx {<win:input-record>} key.unicode-char
14456 @defivarx {<win:input-record>} key.ascii-char
14457 @defivarx {<win:input-record>} key.control-key-state
14458 @end defivar
14459
14460 @defivar {<win:input-record>} mouse.x
14461 @defivarx {<win:input-record>} mouse.y
14462 @defivarx {<win:input-record>} mouse.button-state
14463 @defivarx {<win:input-record>} mouse.control-key-state
14464 @defivarx {<win:input-record>} mouse.event-flags
14465 @end defivar
14466
14467 @defivar {<win:input-record>} window-buffer-size.x
14468 @defivarx {<win:input-record>} window-buffer-size.y
14469 @end defivar
14470
14471 @defivar {<win:input-record>} menu.command-id
14472 @end defivar
14473
14474 @defivar {<win:input-record>} focus.set-focus
14475 @end defivar
14476
14477 @end deftp
14478
14479 @defun sys-get-number-of-console-input-events handle
14480 [Windows]
14481 @c MOD os.windows
14482 @end defun
14483
14484 @defun sys-get-number-of-console-mouse-buttons
14485 [Windows]
14486 @c MOD os.windows
14487 @end defun
14488
14489 @defun sys-peek-console-input handle
14490 @defunx sys-read-console-input handle
14491 [Windows]
14492 @c MOD os.windows
14493 @end defun
14494
14495 @defun sys-read-console handle buf
14496 [Windows]
14497 @c MOD os.windows
14498 @end defun
14499
14500 @defun sys-read-console-output handle buf w h x y region
14501 [Windows]
14502 @c MOD os.windows
14503 @end defun
14504
14505 @defun sys-read-console-output-attribute handle buf x y
14506 [Windows]
14507 @c MOD os.windows
14508 @end defun
14509
14510 @defun sys-read-console-output-character handle len x y
14511 [Windows]
14512 @c MOD os.windows
14513 @end defun
14514
14515 @defun sys-set-console-text-attribute handle attr
14516 [Windows]
14517 @c MOD os.windows
14518 @end defun
14519
14520 @defun sys-set-console-window-info handle absolute window
14521 [Windows]
14522 @c MOD os.windows
14523 @end defun
14524
14525 @defun sys-write-console handle string
14526 [Windows]
14527 @c MOD os.windows
14528 @end defun
14529
14530 @defun sys-write-console-output-character handle string x y
14531 [Windows]
14532 @c MOD os.windows
14533 @end defun
14534
14535 @defun sys-fill-console-output-character handle char len x y
14536 [Windows]
14537 @c MOD os.windows
14538 @end defun
14539
14540 @defun sys-fill-console-output-attribute handle attr len x y
14541 [Windows]
14542 @c MOD os.windows
14543 @end defun
14544
14545 @defun sys-flush-console-input-buffer handle
14546 [Windows]
14547 @c MOD os.windows
14548 @end defun
14549
14550 @defun sys-get-console-title
14551 [Windows]
14552 @c MOD os.windows
14553 @end defun
14554
14555 @defun sys-set-console-title string
14556 [Windows]
14557 @c MOD os.windows
14558 @end defun
14559
14560 @subsubheading Standard handles
14561
14562 @defun sys-get-std-handle which
14563 @defunx sys-set-std-handle which handle
14564 [Windows]
14565 @c MOD os.windows
14566 @end defun
14567
14568 @defvr {Constant} STD_INPUT_HANDLE
14569 @defvrx {Constant} STD_OUTPUT_HANDLE
14570 @defvrx {Constant} STD_ERROR_HANDLE
14571 [Windows]
14572 @c MOD os.windows
14573 @end defvr
14574
14575
14576 @c ----------------------------------------------------------------------
14577 @node PEG parser combinators, RFC822 message parsing, Windows support, Library modules - Utilities
14578 @section @code{parser.peg} - PEG parser combinators
14579 @c NODE PEGパーザコンビネータ, @code{parser.peg} - PEGパーザコンビネータ
14580
14581 @deftp {Module} parser.peg
14582 @mdindex parser.peg
14583 @c EN
14584 This module implements a parser combinator library
14585 to build parsers based on Parsing Expression Grammar, or PEG.
14586 @c JP
14587 このモジュールは、Parsing Expression Grammar (PEG)に基づいたパーザを組み立てる
14588 コンビネータライブラリを実装しています。
14589 @c COMMON
14590
14591 @c EN
14592 PEG is a @emph{formal grammar} to define a language, like regular
14593 expressions or context-free grammars.
14594 An interesting characteristic of PEG is that it can
14595 be directly mapped to a recursive decent parser, which is exactly
14596 what this library does---each production rule is a Scheme expression
14597 that takes parsers and returns a combined parser. One advantage of
14598 this approach is that you can freely mix ordinary Scheme code
14599 within the parser, that is, there's no special ``parser description
14600 language'' distinct from the base Scheme language, nor you need to
14601 run separate tools like parser generators to obtain a runnable parser code.
14602 @c JP
14603 PEGは、正規表現や文脈自由文法と同様の@emph{形式言語}です。
14604 PEGが興味深いのは、文法記述がそのまま再帰下降パーザに移し替えられるところで、
14605 このライブラリはまさにそれをやっています。各生成規則は、パーザを受け取って
14606 結合されたパーザを返すScheme式です。
14607 このアプローチの利点は、Schemeコードと文法記述を混ぜて書けることです。
14608 特別な「パーザー記述言語」を別に学ぶ必要も、パーザジェネレータのような別ツールを
14609 使ってソースコードを生成する必要もありません。
14610 @c COMMON
14611
14612 @c EN
14613 Although PEG can directly parse the character string, the parser
14614 combinators are not tied to it. In fact, most of the combinators
14615 work transparently for any
14616 sequence of tokens, where the exact meanings of tokens depend on
14617 the application; you can have separate lexer that generates
14618 token sequence that PEG parser can parse, for example.
14619 @c JP
14620 PEGは文字列を直接パーズすることもできますが、
14621 パーザコンビネータは文字列のパーズ限定ではありません。実際、多くのコンビネータは
14622 「トークン」の列 (具体的なトークンの意味はアプリケーションが決められます) に対して
14623 透過的に動作します。例えば字句解析器を別に作ってトークンの列を生成し、
14624 それをPEGでパーズする、ということもできます。
14625 @c COMMON
14626
14627 @c EN
14628 This library is specifically written to get a good performance
14629 on Gauche. The parser created by @code{parser.peg} is
14630 no slower than the parser written manually from scratch.
14631 However, you have to watch out some traps; see
14632 @ref{PEG performance tips}, for the details.
14633 @c JP
14634 このライブラリは、Gaucheで性能が出るように書かれています。
14635 @code{parser.peg}で作られたパーザは、手書きのパーザと遜色ない性能を持ちます。
14636 但し、いくつか気をつけるべき点はあります。それについては
14637 @ref{PEG performance tips}を参照してください。
14638 @c COMMON
14639 @end deftp
14640
14641 @menu
14642 * PEG Walkthrough::
14643 * PEG parser drivers::
14644 * What is a PEG parser::
14645 * PEG primitive parser builders::
14646 * PEG ropes::
14647 * PEG choice::
14648 * PEG sequencing combinators::
14649 * PEG repetition combinators::
14650 * PEG miscellaneous combinators::
14651 * PEG performance tips::
14652 @end menu
14653
14654 @node PEG Walkthrough, PEG parser drivers, PEG parser combinators, PEG parser combinators
14655 @subsection Walkthrough
14656 @c NODE PEGひとめぐり
14657
14658 @c EN
14659 In this section we cover the basic concepts and tools of @code{parser.peg}.
14660 The code of examples is in @file{examples/pegintro.scm} if you have the
14661 source tree of Gauche.
14662 @c JP
14663 本節では、@code{parser.peg}の基本的なコンセプトと道具を説明します。
14664 例に使ったコードは、Gaucheのソースツリーの@file{examples/pegintro.scm}にあります。
14665 @c COMMON
14666
14667 @c EN
14668 In @code{parser.peg}, a parser is merely a Scheme procedure
14669 that takes a list of tokens as an argument and returns
14670 a result (well, in fact, it returns three values, but we'll go
14671 into the details later.)
14672 @c JP
14673 @code{parser.peg}では、パーザとは単なるSchemeの手続きです。それは
14674 トークンのリストを引数に取り、結果を返します
14675 (実際は3つの値を返します。それについては後で詳しく述べます)。
14676 @c COMMON
14677
14678 @c EN
14679 Typically you don't need to write parser procedures directly.
14680 Instead, you can use procedures that
14681 generates parsers. A parser can be as simple as the
14682 following, which accepts a character @code{#\a}.
14683 @c JP
14684 パーザ手続きを直接書く必要は滅多にありません。
14685 代わりに、パーザを生成する手続きがたくさん用意されているのでそれを使います。
14686 例えば、文字@code{#\a}を受理するパーザはこう書けます。
14687 @c COMMON
14688
14689 @example
14690 ($. #\a) ; @result{} a parser
14691 @end example
14692
14693 @c EN
14694 Here, @emph{accept} means the parser checks if the head of input has
14695 a character @code{#\a}, and if it is, it succeeds, and if not, it fails.
14696 @c JP
14697 ここで@emph{受理する}とは、パーザが入力の先頭をチェックして、
14698 それが文字@code{#\a}ならば成功し、そうでなければ失敗するという意味です。
14699 @c COMMON
14700
14701 @c EN
14702 A parser can be invoked by a @emph{parser driver}. For example,
14703 you can use @code{peg-parse-string} to invoke the above parser
14704 on a string:
14705 @c JP
14706 パーザは@emph{パーザドライバ}によって呼び出せます。例えば
14707 @code{peg-parse-string}を使って、上のパーザで文字列をパーズしてみましょう。
14708 @c COMMON
14709
14710 @example
14711 gosh> (peg-parse-string ($. #\a) "abc")
14712 #\a
14713 @end example
14714
14715 @c EN
14716 The parsing succeeds, and returns the matched value---@code{#\a} in this case.
14717 If the parser can't accept the input, the driver throws an error
14718 @code{<parse-error>}.
14719 @c JP
14720 パーズは成功し、マッチした値 (@code{#\a}) が返りました。
14721 パーザが期待する入力でなかった場合には、ドライバは@code{<parse-error>}を投げます。
14722 @c COMMON
14723
14724 @example
14725 gosh> (peg-parse-string ($char #\a) "xyz")
14726 *** PARSE-ERROR: expecting #\a at 0, but got #\x
14727 @end example
14728
14729 @c EN
14730 A parser can also be constructed by combining simpler parsers,
14731 using @emph{parser combinators}. For example, @code{$seq} takes
14732 zero or more parsers and apply them sequentially, returning
14733 the last result.
14734 @c JP
14735 単純なパーザを@emph{パーザコンビネータ}で組み合わせて、より複雑なパーザを作ることができます。
14736 例えば、@code{$seq}はいくつかのパーザを受け取り、「それらを順に適用して
14737 最後の結果を返すパーザ」を作って返します。
14738 @c COMMON
14739
14740 @example
14741 gosh> (peg-parse-string ($seq ($. #\a) ($. #\b) ($. #\c)) "abc")
14742 #\c
14743 @end example
14744
14745 @c EN
14746 The combinator @code{$many} takes a parser and returns a new parser
14747 that accepts zero or more occurrence of the string the original parser
14748 accepts.
14749 @c JP
14750 コンビネータ@code{$many}はパーザを取ると、それのゼロ回以上の繰り返しを受理する
14751 パーザを作って返します。
14752 @c COMMON
14753
14754 @example
14755 gosh> (peg-parse-string ($many ($. #\a)) "aaaaabc")
14756 (#\a #\a #\a #\a #\a)
14757 gosh> (peg-parse-string ($many ($. #\a)) "xxxxxyz")
14758 ()
14759 @end example
14760
14761 @c EN
14762 A parser is just an ordinary Scheme procedure, so it can be bound
14763 to a variable, then can be used to construct more complex parsers.
14764 @c JP
14765 パーザは通常のSchemeの手続きなので、変数に束縛し、それをより複雑なパーザを作るのに使えます。
14766 @c COMMON
14767
14768 @example
14769 (define digits ($many1 ($. #[\d])))
14770 (define ws ($many_ ($. #[\s])))
14771 (define separator ($seq ws ($. #\,) ws))
14772 @end example
14773
14774 @c EN
14775 I leave explanation of @code{$many1} and
14776 @code{$many_} for the later section,
14777 but you may be able to guess what those parsers do;
14778 @code{digits} accepts a sequence of one or more digits, and
14779 @code{ws} accepts sequence of zero or more whitespaces. The @code{separator}
14780 parser accepts a comma, optionally surrounded by whitespaces.
14781 @c JP
14782 @code{$many1}と@code{$many_}の説明は後回しにしますが、
14783 何となくこれらのパーザの動作は推測できるのではないでしょうか。
14784 @code{digits}は1個以上の数字の並びを、
14785 @code{ws}は0個以上の空白文字の並びを受理するパーザです。
14786 @code{separator}パーザは0個以上の空白で囲まれたコンマを受容します。
14787 @c COMMON
14788
14789 @c EN
14790 The @code{digits} parser returns a list of accepted
14791 characters:
14792 @c JP
14793 @code{digits}は受理した文字のリストを返します。
14794 @c COMMON
14795
14796 @example
14797 gosh> (peg-parse-string digits "12345")
14798 (#\1 #\2 #\3 #\4 #\5)
14799 @end example
14800
14801 @c EN
14802 Can we create a parser that returns an integer as
14803 a parsed result? Yes, we can use the @code{$let} macro.
14804 @c JP
14805 パーズの結果として整数値を返すようにできるでしょうか。
14806 @code{$let}マクロを使えばできます。
14807 @c COMMON
14808
14809 @example
14810 (define integer
14811 ($let ([ds digits])
14812 ($return (x->integer (list->string ds)))))
14813 @end example
14814
14815 @c EN
14816 The @code{$let} works somewhat like @code{and-let*}; it takes
14817 a form of @code{($let ([@var{var} @var{parser}] @dots{}) @var{expr} @dots{})},
14818 applying the @var{parser}s in order, binding the result of each
14819 parser to @var{var}. If any of the @var{parser} fails, the entire
14820 parser created by @code{$let} macro fails. When all the @var{parser} succeeds,
14821 each result is bound to @var{var} and @var{expr} @dots{} are
14822 evaluated. The last @var{expr} must yield a parser.
14823 @c JP
14824 @code{$let}は@code{and-let*}のように動作します。
14825 @code{($let ([@var{var} @var{parser}] @dots{}) @var{expr})}という形式を取り、
14826 @var{parser}を順に入力に適用してゆきます。
14827 @var{parser}のどれかひとつでも失敗したら全体が失敗します。
14828 全ての@var{parser}が成功したら、それぞれの結果が@var{var}に束縛された環境下で
14829 @var{expr} @dots{}が評価されます。最後の@var{expr}はパーザを返さねばなりません。
14830 @c COMMON
14831
14832 @c EN
14833 The @code{$return} procedure creates a parser
14834 that doesn't consume input, always succeeds
14835 and returns the given value. The name is taken from
14836 Haskell's monads. Note that it is just an ordinary procedure
14837 and not like a control-transfer syntax as traditional language's
14838 @code{return}. You may think it just as type conversion
14839 procedure from a Scheme object to a parser.
14840 @c JP
14841 @code{$return}手続きは、入力を消費せず、常に成功し、引数をパーズ結果とする
14842 パーザを作ります。この名前はHaskellのモナドからきました。
14843 他の多くの言語にあるreturnのように制御の流れを変えるのではなく、単なる手続きであることに
14844 注意してください。任意のSchemeオブジェクトをパーザに変える変換手続きと考えても良いでしょう。
14845 @c COMMON
14846
14847 @example
14848 gosh> (peg-parse-string integer "12345")
14849 12345
14850 @end example
14851
14852 @c EN
14853 Now you can combine those parsers to build more complex one, such
14854 as a comma-separated list of integers:
14855 @c JP
14856 これらのパーザを組み合わせて、さらに複雑なパーザを作ることができます。
14857 例えばコンマで区切られた整数のリストです:
14858 @c COMMON
14859
14860 @example
14861 (define integers1 ($seq integer
14862 ($many ($seq separator integer))))
14863
14864 gosh> (peg-parse-string integers1 "123, 456, 789")
14865 (456 789)
14866 @end example
14867
14868 @c EN
14869 Oops, where's 123? Well, remember that
14870 @code{$seq} discards the results but the last one.
14871 We can use @code{$let} again to keep all the results.
14872 @c JP
14873 あれ、最初の123がどっかいっちゃいました。そうそう、
14874 @code{$seq}は最後のパーザの値以外は捨てるのでした。
14875 @code{$let}を使って結果を集めることができます。
14876 @c COMMON
14877
14878 @example
14879 (define integers2 ($let ([n integer]
14880 [ns ($many ($seq separator integer))])
14881 ($return (cons n ns))))
14882
14883 gosh> (peg-parse-string integers2 "123, 456, 789")
14884 (123 456 789)
14885 @end example
14886
14887 @c EN
14888 (Unlike @code{let} where the order of its init expressions are
14889 not defined, @code{$let} guarantees the parsers are applied sequentially.
14890 The reason it is not called @code{$let*} is the scope;
14891 we also have @code{$let*}, which we'll explain shortly.)
14892 @c JP
14893 (@code{let}ではinit式の評価順序は決まっていませんが、
14894 @code{$let}はパーザを書かれた順に適用することを保証しています。
14895 これを@code{$let*}と呼んでいないのはスコープのためです。
14896 すぐ後で@code{$let*}も紹介します。)
14897 @c COMMON
14898
14899 @c EN
14900 Another way to gather the results of parsers is a combinator @code{$lift}.
14901 It is used as @code{($lift proc parser @dots{})}, where @var{proc}
14902 is an ordinary procedure which receives the result of @var{parser} @dots{}
14903 as arguments. The return value of @var{proc} becomes the result of
14904 the entire parser. Unlike @code{$let}, @var{proc} doesn't need to
14905 return a parser.
14906 @c JP
14907 パーザの結果を集めるもうひとつの方法は@code{$lift}コンビネータです。
14908 @code{($lift proc parser @dots{})} のように使います。ここで
14909 @var{proc}は普通の手続きで、@var{parser} @dots{}の結果を引数として受け取り、
14910 @var{proc}の返した結果が全体のパーザの結果になります。
14911 @code{$let}と違って、@var{proc}はパーザを返す必要はありません。
14912 @c COMMON
14913
14914 @example
14915 (define integers3 ($lift cons
14916 integer
14917 ($many ($seq separator integer))))
14918 @end example
14919
14920 @c EN
14921 The parsers so far doesn't handle the case when the list contains no
14922 integers. Using @code{$or} combinator, which represents a choice,
14923 we can modify it to handle zero-element case.
14924 @c JP
14925 これまでのパーザは入力に整数が全く含まれていない場合を考慮していませんでした。
14926 選択を表す@code{$or}コンビネータを使って、整数が無いケースをサポートできます。
14927 @c COMMON
14928
14929 @example
14930 (define integers4 ($or ($let ([n integer]
14931 [ns ($many ($seq separator integer))])
14932 ($return (cons n ns)))
14933 ($return '())))
14934 @end example
14935
14936 @c EN
14937 By the way, ``list of stuff separated by something'' is a very common
14938 pattern, so we can extract the pattern to name it:
14939 @c JP
14940 ところで、「何かで区切られた何かのリスト」というのは頻繁に出てくるので、次のように
14941 パターンを取り出しておくことができます:
14942 @c COMMON
14943
14944 @example
14945 (define (sep-by stuff separator)
14946 ($or ($let ([n stuff]
14947 [ns ($many ($seq separator stuff))])
14948 ($return (cons n ns)))
14949 ($return '())))
14950 @end example
14951
14952 @c EN
14953 Then the list of integers can be written this simple:
14954 @c JP
14955 すると整数のリストのパーザはこんなに簡単になります:
14956 @c COMMON
14957
14958 @example
14959 (define integers5 (sep-by integer separator))
14960 @end example
14961
14962 @c EN
14963 In fact, @code{parser.peg} provides @code{$sep-by} to do the above,
14964 but we've just shown the definition to demonstrate
14965 the power of the combinatorial approach;
14966 you can use ordinary procedural abstraction to factor out common patterns.
14967 @c JP
14968 実は@code{parser.peg}には上と同じことができる@code{$sep-by}というのが
14969 既に用意されているんですが、コンビネータを使う方法の強みを示すために
14970 あえて実装してみました。
14971 共通のパターンに通常の手続きを使った抽象化を使えるのが利点です。
14972 @c COMMON
14973
14974 @c EN
14975 There's one catch in the @code{$or} form.
14976 It tries the next alternative only when the
14977 parser fails @emph{without consuming the input}. Once the input is
14978 consumed, @code{$or} commits to that choice. For example,
14979 the following fails even if the input seems to match the
14980 second alternative:
14981 @c JP
14982 @code{$or}についてはひとつ注意があります。ある選択肢が失敗した時、
14983 @emph{それが入力を消費していない場合に限り}、次の選択肢が試されるということです。
14984 入力が少しでも消費されたら、@code{$or}はその選択肢にコミットし、
14985 その先で失敗しても他の選択肢を試しません。下の例では、
14986 2番目の@code{$seq}が入力にマッチするにもかかわらず、パーズは失敗します。
14987 @c COMMON
14988
14989 @example
14990 (define paren ($. #\())
14991 (define thesis ($. #\)))
14992
14993 (peg-parse-string ($or ($seq paren ($."ab") thesis)
14994 ($seq paren ($."cd") thesis))
14995 "(cd)")
14996 @result{} *** PARSE-ERROR: expecting ab at 1, but got #\c
14997 @end example
14998
14999 @c EN
15000 It's because when @code{$or} tries the first branch, it reads the initial
15001 open paren from the input, so @code{$or} commits to the first branch.
15002 When the branch fails, @code{$or} doesn't bother to try the second branch.
15003 (In other words, @code{$or} does not backtrack.)
15004 @c JP
15005 @code{$or}の最初の選択肢で、先頭の開き括弧はマッチに成功して入力が消費されます。
15006 その後でマッチが失敗するわけですが、既に入力が消費されているので、
15007 @code{$or}は他の選択肢を考慮することなく全体を失敗させます。
15008 (言い換えれば、@code{$or}はバックトラックを行いません。)
15009 @c COMMON
15010
15011 @c EN
15012 You may factor out the common prefix:
15013 @c JP
15014 一つの手は、共通部分を括り出すことです。
15015 @c COMMON
15016
15017 @example
15018 ($seq paren
15019 ($or ($."ab") ($."cd"))
15020 thesis)
15021 @end example
15022
15023
15024 @c EN
15025 But it may complicates the syntax, and it is not always trivial to
15026 factor out like above. The better way is to use the @code{$try}
15027 combinator: @code{($try @var{p})} runs a parser @var{p}, and if
15028 it fails, @code{$try} rolls back the input as if it didn't
15029 consume input at all. Using with @code{$or}, you can do arbitrary
15030 lookahead and backtrack.
15031 @c JP
15032 ただ、これは文法を複雑化させることがありますし、
15033 いつでも簡単にできるとは限りません。よりうまい方法は@code{$try}コンビネータを
15034 使うことです。 @code{($try @var{p})}はパーザ@var{p}を走らせ、それが
15035 失敗したら入力を元の時点まで巻き戻します。@code{$or}と一緒につかえば、
15036 いくらでも先読みとバックトラックができます。
15037 @c COMMON
15038
15039 @example
15040 ($or ($try ($seq paren ($."ab") thesis))
15041 ($seq paren ($."cd") thesis))
15042 @end example
15043
15044 @c EN
15045 Now, let's get back to the integer list example and make
15046 it more interesting.
15047 Suppose the list of integers are surrounded by parentheses,
15048 brackets or curly-braces. Opening one and closing one must correspond.
15049 @c JP
15050 さて整数のリストの例をもうちょっとおもしろくしてみましょう。
15051 リストは小括弧、中括弧、大括弧のどれかで囲まれていて、開き括弧と閉じ括弧は対応
15052 していなければならない、とします。
15053 @c COMMON
15054
15055 @example
15056 (define begin-list
15057 ($seq0 ($. #[\(\[\@{]) ws))
15058
15059 (define (end-list opener)
15060 ($seq ws (case opener
15061 [(#\() ($. #\))]
15062 [(#\[) ($. #\])]
15063 [(#\@{) ($. #\@})])))
15064
15065 (define int-list
15066 ($let* ([opener begin-list] ;*1
15067 [ints ($sep-by integer separator)] ;*2
15068 [ (end-list opener) ]) ;*3
15069 ($return ints)))
15070 @end example
15071
15072 @c EN
15073 The opening bracket is parsed by the parser @code{begin-list}.
15074 The @code{$seq0} combinator is similar to @code{seq}, but returns
15075 the result of the first parser instead of the last one
15076 (it's @code{begin0} to @code{begin}).
15077 @c JP
15078 開き括弧は@code{begin-list}パーザが受理します。@code{$seq0}は
15079 @code{$seq}とほぼ同じですが、最初のパーザの結果を返します。
15080 (@code{begin}に対する@code{begin0}と同じです。)
15081 @c COMMON
15082
15083 @c EN
15084 The closing bracket must match the opening one, so @code{end-list}
15085 is a procedure that takes the opening bracket and returns a suitable
15086 parser to accept the corresponding closing bracket.
15087 @c JP
15088 閉じ括弧は開き括弧と対応しないとならないので、@code{end-list}は
15089 開き括弧を取って適切な閉じ括弧のパーザを返す手続きになっています。
15090 @c COMMON
15091
15092 @c EN
15093 The @code{int-list} first parses the opening bracket by @code{begin-list}
15094 and bind the result to @var{opener} (*1).
15095 Then goes to parse comma-separated integers (*2) and bind the
15096 result list to @var{ints}.
15097 Finally, it parses the matching closing bracket (*3). Note that
15098 the it omits the variable, since we don't need the result of
15099 closing bracket parser.
15100 @c JP
15101 @code{int-list}はまず開き括弧を@code{begin-list}でパーズし、その結果を
15102 @var{opener}に束縛します(*1)。次にコンマ区切りの整数をパーズし、結果のリストを
15103 @var{ints}に束縛します(*2)。最後に開き括弧に対応する閉じ括弧をパーズします(*3)。
15104 最後のパーザは値を使わないので、変数を省略しています。
15105 @c COMMON
15106
15107 @c EN
15108 Since we need to use the value of @var{opener} in the following bindings,
15109 we use @code{$let*} here, instead of @code{$let}. The difference is
15110 the scope of the parser expressions in the binding. Note that, however,
15111 @code{$let} is a lot more easier to optimize, so you want to use
15112 @code{$let} whenever possible.
15113 @c JP
15114 @var{opener}の値を続く束縛フォームの中で使う必要があるので、
15115 ここでは@code{$let}ではなく@code{$let*}を使いました。
15116 この差は@code{let}と@code{let*}の差と同じで、スコープの違いです。
15117 ただ、@code{$let}の方が処理系にはうんと最適化しやすいので、
15118 可能な限り@code{$let}を使う方が良いでしょう。
15119 @c COMMON
15120
15121 @c EN
15122 Let's see it works.
15123 @c JP
15124 走らせてみます。
15125 @c COMMON
15126
15127 @example
15128 gosh> (peg-parse-string int-list "[123, 456, 789]")
15129 (123 456 789)
15130 gosh> (peg-parse-string int-list "@{123, 456, 789@}")
15131 (123 456 789)
15132 gosh> (peg-parse-string int-list "(123, 456, 789@}")
15133 *** PARSE-ERROR: expecting #\) at 14, but got #\@}
15134 @end example
15135
15136 @c EN
15137 The last example shows it rejects unmatched brackets.
15138 @c JP
15139 最後の例は括弧の対応が取れていないと失敗する例です。
15140 @c COMMON
15141
15142 @c EN
15143 What if we want a nested list? In BNF, we could write
15144 something like this:
15145 @c JP
15146 ネストしたリストをパーズするにはどうすればいいでしょう?
15147 BNFならこう書けるでしょう。
15148 @c COMMON
15149
15150 @example
15151 list : begin-list (elem (separator elem)* )? end-list
15152 elem : integer | list
15153 @end example
15154
15155 @c EN
15156 The straight translation would be he following.
15157 @c JP
15158 これをそのまま移し替えると次のようになります。
15159 @c COMMON
15160
15161 @example
15162 ;; First try
15163 (define nested-list
15164 ($let* ([opener begin-list]
15165 [ints ($sep-by elem separator)]
15166 [ (end-list opener) ])
15167 ($return ints)))
15168 (define elem ($or integer nested-list))
15169 @end example
15170
15171 @c EN
15172 Let's load it... Oops.
15173 @c JP
15174 ロードしてみましょう。おっと
15175 @c COMMON
15176
15177 @example
15178 *** ERROR: unbound variable: elem
15179 Stack Trace:
15180 _______________________________________
15181 0 elem
15182 [unknown location]
15183 1 (eval expr env)
15184 at "../lib/gauche/interactive.scm":267
15185 @end example
15186
15187 @c EN
15188 We need the parser @code{elem} to construct @code{nested-list}, but
15189 we need the parser @code{nested-list} to construct @code{elem}.
15190 In lazy languages like Haskell this doesn't matter, but we Schemers
15191 are @emph{eager}!
15192 @c JP
15193 @code{nested-list}の値を計算するのに@code{elem}の値を使いますが、
15194 @code{elem}の値を計算するのに@code{nested-list}の値が必要です。
15195 Haskellのような怠惰な言語ならこれでも構わないんですが、
15196 Schemerは熱心なんです!
15197 @c COMMON
15198
15199 @c EN
15200 The solution is to delay the parser construction until it is
15201 actually used. The @code{$lazy} form does the job:
15202 @c JP
15203 解決策は、パーザの計算を必要になるまで遅らせることです。
15204 @code{$lazy}フォームが必要な遅延を行います。
15205 @c COMMON
15206
15207 @example
15208 (define nested-list
15209 ($lazy
15210 ($let* ([opener begin-list]
15211 [ints ($sep-by elem separator)]
15212 [ (end-list opener) ])
15213 ($return ints))))
15214 (define elem ($or integer nested-list))
15215
15216 gosh> (peg-parse-string nested-list "(123, [456, @{@}, 789], 987)")
15217 (123 (456 () 789) 987)
15218 @end example
15219
15220 @c EN
15221 Ok, we're almost done. Our code can parse nested list of integers,
15222 checking bracket matches. But if you give an erroneous input, the message
15223 is cryptic and not helpful:
15224 @c JP
15225 さあ、ほとんど完成です。
15226 括弧の対応をチェックしながら、ネストした整数のリストをパーズできるようになりました。
15227 ただ、間違いのある入力を与えた時に出されるエラーメッセージがわかりにくいですね。
15228 @c COMMON
15229
15230 @example
15231 gosh> (peg-parse-string nested-list "(123, [456, @{@}, 789), 987)")
15232 *** PARSE-ERROR: expecting one of (#[0-9] #\]) at 19
15233 Stack Trace:
15234 _______________________________________
15235 0 (eval expr env)
15236 at "../lib/gauche/interactive.scm":267
15237 @end example
15238
15239 @c EN
15240 We could check the reason of failure in the parser, and call
15241 @code{$fail} with more reasonable error message. Let's replace
15242 @code{end-list} above with @code{end-list2} below:
15243 @c JP
15244 パーザの中で失敗の理由を調べて、意味のあるエラーメッセージで@code{$fail}を呼び出すことが
15245 できます。上の@code{end-list}を下の@code{end-list2}に置き換えてみて下さい。
15246 @c COMMON
15247
15248 @example
15249 (define (end-list2 opener)
15250 (define expected
15251 (assv-ref '((#\( . #\)) (#\[ . #\]) (#\@{ . #\@})) opener))
15252 ($seq ws
15253 ($let ([closer ($. #[\)\]\@}])])
15254 (if (eqv? closer expected)
15255 ($return closer)
15256 ($fail (format "Mismatched closing bracket. '~c' expected, \
15257 but got '~c'"
15258 expected closer))))))
15259 @end example
15260
15261 @c EN
15262 You also have to change @code{nested-list} and @code{elem} to
15263 use @code{end-list2}:
15264 @c JP
15265 @code{nested-list}と@code{elem}についても@code{end-list2}を使うように変更します:
15266 @c COMMON
15267
15268 @example
15269 (define nested-list2
15270 ($lazy
15271 ($let* ([opener begin-list]
15272 [ints ($sep-by elem2 separator)]
15273 [ (end-list2 opener) ])
15274 ($return ints))))
15275
15276 (define elem2 ($or integer nested-list2))
15277 @end example
15278
15279 @c EN
15280 (You could redefine @code{end-list}, but if you do so, don't forget to
15281 re-evaluate the definitions of @code{nested-list} and @code{elem}.
15282 It's because the combinators
15283 are caculated taking the value of other combinators when it's defined,
15284 unlike typical procedural approach where you redefine one procedure and
15285 other procedures will refer to the updated version after that.)
15286 @c JP
15287 (@code{end-list}を再定義しても良いのですが、その場合は
15288 @code{nested-list}と@code{elem}の定義を再評価することを忘れないでください。
15289 コンビネータは、定義時に他のコンビネータの値を使って計算されます。
15290 通常の手続き定義のアプローチでは、一つの手続きの定義を差し替えたら他の手続きは
15291 新しい定義を使うようになりますが、それと異なるので要注意です。)
15292 @c COMMON
15293
15294 @c EN
15295 And now you see this error:
15296 @c JP
15297 これで、エラーメッセージはこんなふうになります。
15298 @c COMMON
15299
15300 @example
15301 gosh> (peg-parse-string nested-list2 "(123, [456, @{@}, 789), 987)")
15302 *** PARSE-ERROR: Mismatched closing bracket. ']' expected, but got ')' at 20
15303 Stack Trace:
15304 _______________________________________
15305 0 (eval expr env)
15306 at "../lib/gauche/interactive.scm":267
15307 @end example
15308
15309 @c EN
15310 For further examples, you can take a look at some libraries in the
15311 Gauche source tree that use @code{parser.peg}:
15312 @c JP
15313 更なる例は、Gaucheソースツリーの中で@code{parser.peg}を使っているライブラリに
15314 見ることができます:
15315 @c COMMON
15316
15317 @itemize @bullet
15318 @item
15319 @file{lib/rfc/json.scm}
15320 @item
15321 @file{lib/text/edn.scm}
15322 @item
15323 @file{lib/www/css.scm}
15324 @end itemize
15325
15326
15327 @node PEG parser drivers, What is a PEG parser, PEG Walkthrough, PEG parser combinators
15328 @subsection Parser drivers
15329 @c NODE PEGパーザドライバ, パーザドライバ
15330
15331 @defun peg-run-parser parser list
15332 @c MOD parser.peg
15333 @c EN
15334 Apply @var{parser} on the input @var{list}. If @var{parser} accepts it,
15335 returns two values--the result of @var{parser}, and the rest of
15336 the input. If @var{parser} fails, raise @code{<parse-error>}.
15337 @c JP
15338 パーザ@var{parser}を入力@var{list}に適用します。入力が受理されたら、
15339 @var{parser}の結果と、残りの入力の二つの値を返します。
15340 @var{parser}が失敗したら、@code{<parse-error>}が投げられます。
15341 @c COMMON
15342
15343 @c EN
15344 The result of @var{parse} is a value yielded by @var{parser}
15345 passed to @code{rope-finalize}, so any unfinalized rope is
15346 finalized before being returned. @xref{PEG ropes}, for the details.
15347 @c JP
15348 @var{parse}の結果は@code{rope-finalize}を通されるので、結果中の
15349 ファイナライズされていないロープは全てファイナライズされて返されます。
15350 ロープについては@ref{PEG ropes}を参照してください。
15351 @c COMMON
15352
15353 @c EN
15354 Typically, you don't want to have entire input as a list beforehand,
15355 so you pass a lazy sequence as @var{list} (@pxref{Lazy sequences}).
15356 If the input is a string
15357 or a port, convenience procedures are defined.
15358 @c JP
15359 多くの場合、入力をあらかじめ全部リストで持っておきたくはないと思います。
15360 その場合、遅延シーケンスを@var{list}に渡せば良いでしょう (@ref{Lazy sequences})。
15361 なお、入力が文字列やポートの場合はユーティリティ手続きが定義されています。
15362 @c COMMON
15363
15364 @c EN
15365 Input doesn't need to be a character list. You may, for example,
15366 have a separate lexer that generates a (lazy) list of tokens, and let @var{parser}
15367 parse them.
15368 @c JP
15369 入力が文字のリストである必要はありません。
15370 例えば、別の字句解析器を使ってトークンの(遅延)リストにしてから、
15371 @var{parser}でそれをパーズすることもできます。
15372 @c COMMON
15373 @end defun
15374
15375 @defun peg-parse-string parser string :optional cont
15376 @defunx peg-parse-port parser iport :optional cont
15377 @c MOD parser.peg
15378 @c EN
15379 Convenience wrappers of @code{peg-run-parser} that takes input from
15380 @var{string} or @var{iport}.
15381 @c JP
15382 @code{peg-run-parser}で文字列@var{string}や入力ポート@var{iport}からの入力を
15383 パーズするユーティリティ手続きです。
15384 @c COMMON
15385
15386 @c EN
15387 Without @var{cont} argument or it is @code{#f},
15388 it returns the parsed result and discards
15389 the rest of the input. (Hint: To make sure there's no garbage
15390 following, use @code{$eos} parser.)
15391 @c JP
15392 @var{cont}引数が省略されるか@code{#f}であれば、
15393 この手続きはパーザが受理したところ以降の入力は捨てて、パーザの結果だけ返します。
15394 (ヒント: 余分なゴミが後に続いてないことを保証するには@code{$eos}パーザが使えます)。
15395 @c COMMON
15396
15397 @c EN
15398 If you want to keep parsing after @var{parser} accepts its input,
15399 pass @var{cont} a procedure; it must take two arguments, the result of
15400 @var{parser} and a lazy sequence of the rest of the input. What @var{cont}
15401 returns will be the result of these procedures.
15402 @c JP
15403 @var{parser}が入力を受理した後、さらにパーズを続けたければ、@var{cont}に手続きを
15404 渡します。その手続きは@var{parser}の結果と、残りの入力の遅延シーケンスの二つの
15405 引数を取ります。@var{cont}が返すものが全体の返り値となります。
15406 @c COMMON
15407
15408 @c EN
15409 It is an error to pass other values to @var{cont}.
15410 @c JP
15411 @var{cont}にそれ以外の値を渡すのはエラーです。
15412 @c COMMON
15413 @end defun
15414
15415 @defun peg-parser->generator parser list
15416 @c MOD parser.peg
15417 @c EN
15418 This is useful when you need to apply @var{parser} repeatedly over
15419 the input @var{list}. Returns a generator that generates
15420 the parsed result one match at a time.
15421 @c JP
15422 パーザ@var{parser}を入力@var{list}に繰り返し適用したい場合に便利です。
15423 マッチした入力をひとつづつ返すジェネレータを作って返します。
15424 @c COMMON
15425
15426 @c EN
15427 The same input can be accepted by
15428 by @code{(peg-run-parser ($many parser) list)}, but this one
15429 won't return until all input is consumed. On the other hand,
15430 @c JP
15431 @code{(peg-run-parser ($many parser) list)}としても同じ入力が受容されますが、
15432 こうした場合は全ての入力が消費されるまで戻ってきません。
15433 @c COMMON
15434 @end defun
15435
15436 @deftp {Condition type} <parse-error>
15437 @c MOD parser.peg
15438 @c EN
15439 An condition type raised by the parser driver when the given parser
15440 failed ultimately. Inherits @code{<error>}.
15441 (Note that each parser won't throw this; one
15442 parser's failure doesn't necessarily mean the entire parser fails.
15443 It's the driver that recognizes the ultimate failure and raise this
15444 condition.)
15445 @c JP
15446 パーザが最終的に失敗した場合にパーザドライバが投げるコンディション型です。
15447 @code{<error>}を継承します。
15448 (各パーザがこのコンディションを投げることはありません。
15449 一つのパーザが失敗したとしても、他の選択肢が成功するかもしれないからです。
15450 最終的な失敗を認識してこのコンディションを投げるのはドライバの仕事です。)
15451 @c COMMON
15452
15453 @c EN
15454 The following slots are available:
15455 @c JP
15456 以下のスロットを持ちます。
15457 @c COMMON
15458
15459 @defivar <parse-error> message
15460 @c EN
15461 This slot is inherited from @code{<error>}. Contains string error message.
15462 @c JP
15463 @code{<error>}から継承されたスロットで、エラーメッセージを保持しています。
15464 @c COMMON
15465 @end defivar
15466
15467 @defivar <parse-error> position
15468 @c EN
15469 The position the failure occured.
15470 @c JP
15471 失敗が起きた入力の場所です。
15472 @c COMMON
15473
15474 @c EN
15475 The exact meaning of this value depends on how you call the parser driver.
15476 @c JP
15477 この値の正確な意味は、パーザドライバがどう呼ばれたかに依存します。
15478 @c COMMON
15479
15480 @c EN
15481 At minimum, when you call it on a bare list or a string/port (using
15482 @code{peg-parse-string}/@code{peg-parse-port}), the parser driver
15483 counts the number of elements took from the input and put it here,
15484 for it is the only available information. Note that the number
15485 may not be what you want, e.g. if you start parsing in the middle of
15486 the stream.
15487 @c JP
15488 パーザドライバに普通のリストや、@code{peg-parse-string}/@code{peg-parse-port}を
15489 使って文字列/ポートを渡した場合、パーザドライバは入力の先頭から失敗箇所までの
15490 入力要素の数を数えてそれをこの値とします。それしか情報が無いからです。
15491 入力の途中からパーズを始めた場合などでは、この数値はあなたが必要としているものとは
15492 異なるかもしれません。
15493 @c COMMON
15494
15495 @c EN
15496 If you're parsing from a sequence with positions,
15497 this slot contains an instance of @code{<sequence-position>}, which
15498 may have line & column numbers or a source file name.
15499 @xref{Lazy sequence with positions}, for the details.
15500 @c JP
15501 位置情報つきシーケンスを入力として渡していれば、このスロットは@code{<sequence-position>}
15502 のインスタンスを保持し、そこから行番号、カラム番号、ソースファイル名などを
15503 取り出すことができます。
15504 詳しくは@xref{Lazy sequence with positions}を参照してください。
15505 @c COMMON
15506
15507 @c EN
15508 The user code should expect both cases.
15509 @c JP
15510 ユーザコードはどちらの場合にも対応できるようにしておかねばなりません。
15511 @c COMMON
15512 @end defivar
15513
15514 @defivar <parse-error> type
15515 @c EN
15516 The type of failure. It's either one of the follownig symbols:
15517 @c JP
15518 失敗のタイプ。次のいずれかのシンボルです。
15519 @c COMMON
15520 @table @code
15521 @item fail-expect
15522 @c EN
15523 The parser expects one of the objects in @var{objects} slot, but
15524 got a different one (stored in @var{token}).
15525 @c JP
15526 パーザは@var{objects}スロットに格納されたオブジェクトのどれかを期待していたが、
15527 入力はそうでないオブジェクトであった (入力オブジェクトは@var{token}スロットに格納される)。
15528 @c COMMON
15529 @item fail-unexpect
15530 @c EN
15531 The parser isn't expecting any of the objects in @var{objects} slot,
15532 but got the one in @var{token}.
15533 @c JP
15534 パーザは@var{object}スロットに格納されたオブジェクトのいずれも期待していなかったが、
15535 入力はそのいずれかであった (入力オブジェクトは@var{token}スロットに格納される)。
15536 @c COMMON
15537 @item fail-compound
15538 @c EN
15539 The parser failed multiple options. The @var{objects} slot contains
15540 a list of of @code{(type . msg)} where @var{type} is one of the
15541 @code{<parse-error>} types, and
15542 @var{msg} is the message associated with it.
15543 @c JP
15544 パーザは複数の選択肢を試しいずれも失敗した。@var{objects}スロットは
15545 @code{(type . msg)}のリストを保持している。ここで@var{type}は一つの選択肢の
15546 失敗の@code{<parse-error>}タイプ、@var{msg}はその選択肢の失敗メッセージ。
15547 @c COMMON
15548 @item fail-message
15549 @c EN
15550 Other miscellaneous failure. The @var{objects} slot contains
15551 a mmessage.
15552 @c JP
15553 その他の失敗。@var{message}スロットにメッセージがある。
15554 @c COMMON
15555 @item fail-error
15556 @c EN
15557 Non-recoverable failure. Once this failure is generated, parser
15558 conbinators don't backtrack and let the entire parsing fail.
15559 This type of failure can be generated by @code{$rause} parser constructor
15560 and @code{$cut} combinator. The @var{objects} slot contains a cons
15561 whose car is a symbol (@emph{error tag}) and whose cdr is
15562 a list of @code{(type . msg)}. The cdr part is the same as
15563 @code{fail-compound}.
15564 @c JP
15565 回復不能な失敗。この失敗が生成されると、パーザコンビネータは巻き戻して
15566 別の選択肢を試すことをせず、全体のパージングを失敗させます。
15567 このタイプの失敗は@code{$raise}パーザコンストラクタや@code{$cut}パーザコンビネータで
15568 生成されます。@var{object}スロットはコンスセルで、carにはシンボル (エラータグ) が、
15569 cdrには@code{(type . msg)}のリストが入っています。cdr部分は
15570 @code{fail-compound}の@var{object}スロットと同じです。
15571 @c COMMON
15572 @end table
15573 @end defivar
15574
15575 @defivar <parse-error> objects
15576 @c EN
15577 Value of this slot depends on the value of @var{type} slot.
15578 @c JP
15579 このスロットの値の意味は@var{type}スロットの値に依存します。
15580 @c COMMON
15581 @end defivar
15582
15583 @defivar <parse-error> rest
15584 @c EN
15585 The remaining input token stream, beginning from the point when
15586 the failure occur.
15587 @c JP
15588 失敗が起きた箇所から先の入力トークンストリーム。
15589 @c COMMON
15590 @end defivar
15591
15592 @defivar <parse-error> token
15593 @c EN
15594 The token at the head of input when failure occur. If input already
15595 reached at the end, this slot is set to @code{#<eof>}.
15596
15597 This is the same as the car of @code{rest} slot when there's more input.
15598 @c JP
15599 失敗が起きた時の入力トークン。もし入力が終端に達していた場合は@code{#<eof>}。
15600
15601 入力の残りがある場合、これは@code{rest}スロットのcarと同じです。
15602 @c COMMON
15603 @end defivar
15604 @end deftp
15605
15606 @node What is a PEG parser, PEG primitive parser builders, PEG parser drivers, PEG parser combinators
15607 @subsection What is a PEG parser, really?
15608 @c NODE PEGパーザの正体
15609
15610 @c EN
15611 A PEG parser is a Scheme procedure that takes a list of items as an input,
15612 and returns three values:
15613 @c JP
15614 PEGパーザは、入力にリストを取り、以下の3つの値を返す手続きです。
15615 @c COMMON
15616
15617 @itemize
15618 @item
15619 @c EN
15620 Failure type. If the parser successfully accepts the input, this value
15621 is @code{#f}. If the parser fails to accept the input,
15622 this value is either one of the symbols
15623 @code{fail-expect}, @code{fail-unexpect}, @code{fail-compound}
15624 and @code{fail-message}. It corresponds to the @code{type} slot
15625 of @code{<parse-error>}, and determines the meaning of the second
15626 return value.
15627 @c JP
15628 失敗のタイプ。パーザが入力を受理することに成功した場合、この値は@code{#f}です。
15629 失敗した場合は、この値は次のシンボルのうちのいずれかです:
15630 @code{fail-expect}、@code{fail-unexpect}、@code{fail-compound}、
15631 @code{fail-message}。これは@code{<parse-error>}オブジェクトの
15632 @code{type}スロットの値に対応します。二番目の戻り値の意味はこの値に依存します。
15633 @c COMMON
15634 @item
15635 @c EN
15636 Value. If the parser successfully accepts the input, this
15637 value is the parser's ``result'', sometimes called a semantic
15638 value. If the parser fails to accept the input,
15639 this value contains the hint of the failure. It corresponds
15640 to the @code{objects} slot of @code{<parse-error>}; see the documentation
15641 of @code{<parse-error>} for the details (@pxref{PEG parser drivers}).
15642 @c JP
15643 値。パーザが入力の受理に成功した場合は、これはパーザの「結果」、
15644 しばしばセマンティックバリューと呼ばれるものです。
15645 パーザが失敗した場合は、この値は失敗の原因のヒントとなるものです。
15646 @code{<parse-error>}オブジェクトの@code{objects}スロットの値に対応します。
15647 詳しくは@code{<parse-error>}のドキュメントを見てください
15648 (@ref{PEG parser drivers}参照)。
15649 @c COMMON
15650 @item
15651 @c EN
15652 The rest of the input list.
15653 @c JP
15654 入力の残り。
15655 @c COMMON
15656 @end itemize
15657
15658 @c EN
15659 Typically you don't need to write a parser as a procedure; instead,
15660 you can use one of the parser builders and combinators described in
15661 the following sections.
15662 @c JP
15663 通常、パーザを手続きとして書くことはあまりありません。
15664 以降の節で説明するパーザビルダやコンビネータを使ってパーザを作ります。
15665 @c COMMON
15666
15667 @c EN
15668 We do provide a few utilities to write a parser from scratch, in case
15669 you need to do so.
15670 @c JP
15671 しかし、パーザ手続きを一から書く必要が出てきた時のために、
15672 いくつかのユーティリティ手続きが用意してあります。
15673 @c COMMON
15674
15675 @defun return-result value rest
15676 @c MOD parser.peg
15677 @c EN
15678 Call this at the tail position of the parser when it succeeds, with
15679 @var{value} for the semantic value and @var{rest} for the rest of
15680 input. This is the same as @code{(values #f value rest)}, but
15681 clearer to show the intention.
15682 @c JP
15683 パーザが入力の受理に成功した時は、この手続きを末尾位置で呼んでください。
15684 @var{value}はパーザが返すセマンティックバリュー、
15685 @var{rest}は入力の残りです。これは@code{(values #f value rest)}と同じですが、
15686 意図をより明確に示すことができます。
15687 @c COMMON
15688 @end defun
15689
15690 @defun return-failure/expect objs rest
15691 @defunx return-failure/unexpect objs rest
15692 @defunx return-failure/message msg rest
15693 @defunx return-failure/compound fails rest
15694 @c MOD parser.peg
15695 @c EN
15696 Call one of these at the tail position of the parser when it fails.
15697 The first argument will be in @code{objects} slot of @code{<parse-error>}.
15698 The second argument should be a list of input, with the first element
15699 being a token that can't be accepted.
15700 @c JP
15701 パーザが入力を受理できなかった場合は、この手続きのいずれかを末尾位置で呼んでください。
15702 最初の引数は@var{<parse-error>}の@code{objects}スロットの値となります。
15703 2番目の引数は、受理できなかったトークンを先頭とする入力リストです。
15704 @c COMMON
15705
15706 @itemize
15707 @item
15708 @c EN
15709 If you're expecting some types of objects (@var{objs}) but got anything
15710 else, call @code{return-failure/expect}. It generates @code{fail-expect}
15711 type failure.
15712 @c JP
15713 限られた種類のオブジェクト (@var{objs}) を期待していて、それ以外の入力に
15714 出会った場合は、@code{return-failure/expect}を呼んでください。これは
15715 @code{fail-expect}タイプの失敗となります。
15716 @c COMMON
15717 @item
15718 @c EN
15719 If you're not expecting some types of objects (@var{objs}) but got one,
15720 call @code{return-failure/unexpect}. It generates @code{fail-unexpect}
15721 type failure
15722 @c JP
15723 限られた種類のオブジェクト (@var{objs}) 以外のものを期待していたのに、
15724 それに出会ってしまった場合は、@code{return-failure/unexpect}を呼んでください。
15725 これは@code{fail-unexpect}タイプの失敗となります。
15726 @c COMMON
15727 @item
15728 @c EN
15729 If you're failing because of all of multiple choices fail, you can
15730 gather those failures into an assoc list
15731 @code{((fail-type . objs) @dots{})}, and
15732 call @code{return-failure/compound}. It generates @code{fail-compound}
15733 type failure.
15734 @c JP
15735 複数の選択肢があってそのいずれにも失敗した場合は、
15736 全ての失敗を@code{((fail-type . objs) @dots{})}の形の連想リストにして、
15737 それを@var{fails}引数として@code{return-failure/compound}を呼んでください。
15738 これは@code{fail-compound}タイプの失敗となります。
15739 @c COMMON
15740 @item
15741 @c EN
15742 Finally, your failure can't be categorized to one of the above,
15743 you can call @code{return-failure/message}, with the message
15744 describing the reason of the failure.
15745 @c JP
15746 失敗が上記いずれにもあてはまらない場合は、失敗の理由を文字列のメッセージにして
15747 @code{return-failure/message}を呼んでください。
15748 @c COMMON
15749 @end itemize
15750 @end defun
15751
15752 @defun return-failure type objs rest
15753 @c MOD parser.peg
15754 @c EN
15755 This should only be used to pass down the failure form other parser.
15756 See the example in @code{parse-success?} entry below.
15757 @c JP
15758 これは他のパーザからの失敗をそのまま失敗として返す場合にのみ使ってください。
15759 下の@code{parse-success?}の説明を参照のこと。
15760 @c COMMON
15761 @end defun
15762
15763
15764 @defun parse-success? r
15765 @c MOD parser.peg
15766 @c EN
15767 Check the first return value of a parser to see if it is a success.
15768 A typical usage is to check another parser's result and take
15769 actions accordingly:
15770 @c JP
15771 パーザの最初の戻り値が成功であるかどうかを調べます。
15772 典型的な使い方は、他のパーザの結果によって分岐する場合です:
15773 @c COMMON
15774
15775 @example
15776 (receive (r v s) (parser input)
15777 (if (parse-success? r)
15778 (... do things after PARSER succeeds ...
15779 (return-result ...))
15780 (return-failure r v s)))
15781 @end example
15782
15783 @c EN
15784 This is simply checking if @var{r} is @code{#f}, but using this
15785 procedure indicates your intention clearly.
15786 @c JP
15787 この手続きは単に@var{r}が@code{#f}かどうか見ているだけですが、
15788 これを使うことにより意図を明確に示すことができます。
15789 @c COMMON
15790 @end defun
15791
15792
15793 @node PEG primitive parser builders, PEG ropes, What is a PEG parser, PEG parser combinators
15794 @subsection Primitive parser builders
15795 @c NODE 基本的なパーザビルダー
15796
15797 @c EN
15798 Procedures and macros that create parsers.
15799 @c JP
15800 パーザを作り出す手続きとマクロです。
15801 @c COMMON
15802
15803 @defun $return val
15804 @c MOD parser.peg
15805 @c EN
15806 Returns a parser that always succeeds, without consuming
15807 input, and yields @var{val} as the result of parser.
15808 @c JP
15809 入力を消費せず、常に成功して@var{val}を結果として返すパーザを作って返します。
15810 @c COMMON
15811
15812 @c EN
15813 Frequently used in @code{$let} and @code{$let*}'s body, but can be
15814 used anywhere where a parser is expected.
15815 @c JP
15816 @code{$let}や@code{$let*}の本体で使われることが多いですが、
15817 パーザを期待するところではどこでも使えます。
15818 @c COMMON
15819 @end defun
15820
15821 @defun $fail msg-string
15822 @c MOD parser.peg
15823 @c EN
15824 Returns a parser that always fails, without consuming input,
15825 and uses @var{msg-string} as the failure message.
15826
15827 Frequently used to produce user-friendly error messages.
15828 See also @code{$expect} below.
15829 @c JP
15830 入力を消費せず、常に失敗して、@var{msg-string}を失敗メッセージとするパーザを
15831 作って返します。
15832
15833 ユーザフレンドリなエラーメッセージを出すためによく使われます。
15834 下の@code{$expect}も参照してください。
15835 @c COMMON
15836 @end defun
15837
15838 @defun $raise msg-string
15839 @c MOD parser.peg
15840 @c EN
15841 Returns a parser that raises a non-recoverable failure.
15842 with @var{msg-string} as the failure message.
15843
15844 The difference from @code{$fail} is that, if @code{$or} sees
15845 a failure created by @code{$fail}, it may try the remaining
15846 branches, while if it sees a failure created by @code{$raise},
15847 no more branches are tried.
15848
15849 This can be used for better error reporting.
15850 If you detect the case that can't be a valid input in deep in the
15851 parse tree, a normal failure would try other alternatives exhaustively
15852 and generate an error message itemizing all the failed possibilities.
15853 It is often difficult to see the real cause from such a message.
15854 With @code{$raise}, you can let the parser give up immediately.
15855
15856 See also @code{$cut} combinator below, to convert a normal failure to
15857 non-recoverable failure.
15858 @c JP
15859 回復不可能な失敗を生成するパーザを作って返します。
15860 @var{msg-string}は失敗のメッセージに使われます。
15861
15862 @code{$fail}との違いは、@code{$or}が@code{$fail}で生成された失敗を見た場合は
15863 他の選択肢を試すことがあるのに対し、@code{$raise}で生成された失敗を見たら
15864 他の選択肢はもう試されないことです。
15865
15866 これはより良いエラー報告をするのに役立ちます。
15867 パーズツリーの深いところで、有効になり得ない入力を検出したとします。
15868 通常の失敗とした場合、パーザはツリーの上の方で他の選択肢も全部試し、
15869 失敗の理由をすべて列挙したエラーメッセージを生成するかもしれません。
15870 しかし多くの場合、そのメッセージから本当の失敗の原因を知るのは難しいです。
15871 @code{$raise}を使えば、パーザに即座に諦めさせることができます。
15872
15873 通常の失敗を回復不可能な失敗に変換する、下の@code{$cut}コンビネータも参照してください。
15874 @c COMMON
15875 @end defun
15876
15877 @defun $satisfy pred expect :optional result
15878 @c MOD parser.peg
15879 @c EN
15880 This corresponds to ``semantic predicate'' in PEG; a parser
15881 that can apply an arbitrary predicate on input.
15882 @c JP
15883 これはPEGでいう「先読み述語」、つまり
15884 入力トークンに任意の述語@var{pred}を適用するパーザを作って返します。
15885 @c COMMON
15886
15887 @c EN
15888 Returns a parser that works as follows:
15889 @c JP
15890 返されるパーザは次のように動作します。
15891 @c COMMON
15892 @itemize @bullet
15893 @item
15894 @c EN
15895 If the head of input stream satisfies @var{pred},
15896 call @code{(@var{result} head (@var{pred} head))} and
15897 yield its return value as the result of successful parsing.
15898 If @var{result} is omitted, it yields the head of input.
15899 @c JP
15900 入力の先頭headが述語@var{pred}を満たした場合、@var{result}を
15901 @code{(@var{result} head (@var{pred} head))} のように呼び出し、
15902 その戻り値をパーザ成功の結果とします。
15903 @var{result}が省略された場合は、入力の先頭が結果になります。
15904 @c COMMON
15905 @item
15906 @c EN
15907 Otherwise, the parsing fails with @var{expect} as the expected input.
15908 @c JP
15909 そうでなければ、@var{expect}を期待していた結果としてパーズは失敗します。
15910 @c COMMON
15911 @end itemize
15912
15913 @c EN
15914 If you just need a lookahead parser, you can use @code{$assert}.
15915 @c JP
15916 必要なのが先読みするパーザであれば、@code{$assert}も使えます。
15917 @c COMMON
15918 @end defun
15919
15920 @defun $. obj
15921 @c MOD parser.peg
15922 @c EN
15923 Creates a parser that matches a Scheme object @var{obj},
15924 which may be a character, a string, a char-set, or a symbol.
15925 If @var{obj} is a char-set, the parser matches any character in the set.
15926 Specifying a symbol can be used when you're parsing a token stream
15927 instead of a character stream.
15928
15929 On success, the value of the parser is the matched input.
15930
15931 The resulting parser is atomic, that is, it doesn't consume
15932 input when it fails.
15933 @c JP
15934 Schemebオブジェクト@var{obj}にマッチするパーザを作ります。
15935 @var{obj}には、文字、文字列、文字集合、およびシンボルを指定できます。
15936 @var{obj}が文字集合の場合は、パーザはその中のいずれか文字にマッチします。
15937 シンボルは、文字ストリームでなくトークンストリームをパーズしている時に使えます。
15938
15939 成功した場合はマッチした入力がパーザの値となります。
15940
15941 返されるパーザはアトミック、つまり失敗した場合には入力を消費しません。
15942 @c COMMON
15943 @end defun
15944
15945 @defun $char c
15946 @defunx $char-ci c
15947 @c MOD parser.peg
15948 @c EN
15949 Returns a parser that accepts a single character, @var{c}.
15950 @code{$char-ci} ignores case.
15951 On success, the parser yields the input character.
15952 The resulting parser is atomic, that is, it doesn't consume
15953 input when it fails.
15954
15955 When @var{c} is a character, @code{($char @var{c}}
15956 is the same as @code{($. @var{c})};
15957 you can use @code{$char} to emphasize you're matching a character.
15958 @c JP
15959 文字@var{c}とマッチするパーザを返します。@code{$char-ci}では大文字小文字を区別しません。
15960 成功した場合は入力文字が値となります。
15961 返されるパーザはアトミック、つまり失敗した場合には入力を消費しません。
15962
15963 @var{c}が文字の時、@code{($char @var{c}}は@code{($. @var{c})}と同じです。
15964 文字とのマッチを強調したい場合に@code{$char}を使うと良いでしょう。
15965 @c COMMON
15966 @end defun
15967
15968 @defun $string str
15969 @defunx $string-ci str
15970 @c MOD parser.peg
15971 @c EN
15972 Returns a parser that accepts an input that matches
15973 a string @var{str}. @code{$string-ci} ignores case.
15974 On success, the parser yields the matched string.
15975
15976 The parsing of string is atomic: When the parser fails,
15977 it doesn't consume the input. That is,
15978 @code{($string "ab")} is not the same as
15979 @code{($let ([a ($char #\a)] [b ($char #\b)]) ($return (string a b)))}.
15980 @c JP
15981 文字列@var{str}とマッチするパーザを返します。
15982 @code{$string-ci}では大文字小文字を区別しません。
15983 成功した場合はマッチした入力文字列が値となります。
15984
15985 返されるパーザはアトミック、つまり失敗した場合には入力を消費しません。
15986 つまり、@code{($string "ab")}は
15987 @code{($let ([a ($char #\a)] [b ($char #\b)]) ($return (string a b)))}
15988 と同じ@emph{ではありません}。
15989 @c COMMON
15990 @end defun
15991
15992 @defun $one-of cset
15993 @defunx $one-of obj-list
15994 @c MOD parser.peg
15995 @c EN
15996 The first form returns a parser that accepts any character in
15997 the character set @var{cset}.
15998 In the second form, @var{obj-list} must be a list of either
15999 a character, a string, a character set or a symbol, and each one
16000 is matched with the same way as @code{$.}.
16001
16002 On success, the parser yields the accepted object.
16003 On failure, the parser doesn't consume input.
16004 @c JP
16005 最初のフォームは、文字集合@var{cset}中のいずれかの文字にマッチするパーザーを返します。
16006 二番目のフォームでは、@var{obj-list}は文字、文字列、文字集合、シンボルからなる
16007 リストでなければならず、それぞれの要素が@code{$.}で順に試されます。
16008
16009 成功した場合はマッチしたオブジェクトをパーザの値とします。
16010 失敗した場合に入力を消費しません。
16011 @c COMMON
16012 @end defun
16013
16014 @defun $none-of cset
16015 @c MOD parser.peg
16016 @c EN
16017 Returns a parser that accepts any character not in the character set @var{cset}.
16018 On success, the parser yields the accepted character.
16019 @c JP
16020 文字集合@var{cset}に含まれない文字とマッチするパーザを返します。
16021 成功した場合にはマッチした文字をパーザの値とします。
16022 @c COMMON
16023 @end defun
16024
16025 @defun $any
16026 @c MOD parser.peg
16027 @c EN
16028 Returns a parser that matches any one item, and yields the matched
16029 input item on success.
16030 It fails only when the input already reached at the end.
16031 @c JP
16032 任意の1要素とマッチし、それをパーザの値とします。
16033 このパーザが失敗するのは、入力が末尾に達していた場合だけです。
16034 @c COMMON
16035 @end defun
16036
16037 @defun $eos
16038 @c MOD parser.peg
16039 @c EN
16040 Stands for ``end of stream''. Returns a parser that matches
16041 the end of input. The value of parser is @code{#<eof>} in that case.
16042 It never consumes input.
16043 @c JP
16044 EOSとはストリーム末尾(end of stream)です。入力が既に末尾に達していた場合に
16045 マッチが成功し、@code{#<eof>}を値とします。
16046 このパーザは入力を消費しません。
16047 @c COMMON
16048 @end defun
16049
16050 @defmac $match1 pattern result
16051 @defmacx $match1 pattern
16052 @defmacx $match1 pattern (@code{=>} fail) result
16053 @defmacx $match1* pattern result
16054 @defmacx $match1* pattern
16055 @defmacx $match1* pattern (@code{=>} fail) result
16056 @c MOD parser.peg
16057 @c EN
16058 The pattern matcher macro @code{match-let1} lifted to the parser.
16059 @xref{Pattern matching}, for the details of supported @var{pattern}.
16060 @c JP
16061 これは、パターンマッチを行う@code{match-let1}マクロをパーザ領域に持ち上げたものです。
16062 @var{pattern}部分は@code{match-let1}と同じです。
16063 @ref{Pattern matching}を参照してください。
16064 @c COMMON
16065
16066 @c EN
16067 The macro @code{$match1} returns a parser that takes one item
16068 from the input stream, and see if it matches @var{pattern}.
16069 If it matches, evaluate @var{result} within an environment
16070 where pattern variables are bound to matched content, and the
16071 parser yields the value of @var{result}. If the input doesn't
16072 match @var{pattern}, or the input is empty, the parser fails without
16073 consuming input.
16074 @c JP
16075 マクロ@code{$match1}は入力ストリームから1要素を取り出し、@var{pattern}とマッチするかどうか
16076 調べます。マッチすれば、パターン変数が束縛された環境で@var{result}を評価し、
16077 その値をパーザの値とします。入力要素がマッチしないか、入力が既に末尾に達していた
16078 場合は、入力を消費することなくパーザは失敗します。
16079 @c COMMON
16080
16081 @c EN
16082 In the third form @code{=>} must be a literal identifier and @var{fail}
16083 must be an identifier. The identifier @var{fail} is bound to a procedure
16084 that takes one string argument in @var{result}. You can call @var{fail}
16085 at the tail position of @var{result} to make the match fail, with
16086 the passed argument as the message. If @var{fail} is called,
16087 no input will be consumed.
16088 @c JP
16089 3番めの形式では、@code{=>}はリテラルの識別子、@var{fail}は任意の識別子です。
16090 @var{result}の評価環境で、@var{fail}は一つの文字列を取る手続きに束縛されます。
16091 @var{result}の末尾位置で@var{fail}を呼び出すとパーザは失敗し、@var{fail}に渡した
16092 文字列がメッセージとなります。@var{fail}が呼ばれた場合、入力は消費されません。
16093 @c COMMON
16094
16095 @c EN
16096 (NB: The @code{match} macro in @code{util.match} has a similar feature,
16097 but it binds @var{fail} to a continuation that abandons the current match
16098 clause and go to try the next pattern. So you can invoke @var{fail}
16099 anywhere in the dynamic extent of the clause.
16100 In @code{$match1}, @var{fail} is simply a procedure, so
16101 you have to call it at the tail position to make it work.)
16102 @c JP
16103 (註: @code{util.match}の@code{match}マクロも似た機能を持っていますが、
16104 @code{match}で@var{fail}が束縛されるのは現在のマッチ節を放棄して次のマッチ節を
16105 試す継続です。従ってマッチ節の動的スコープの中ならどこでも呼ぶことができます。
16106 @code{$match1}の@var{fail}は単なる手続きであり、
16107 @var{result}の末尾位置で呼ばないとマッチを失敗させることはできません。)
16108 @c COMMON
16109
16110 @c EN
16111 The macro @code{$match1*} is similar to @code{$match1}, except
16112 the entire input is matched @var{pattern}. It is useful to
16113 look into several items in input, instead of just one.
16114 Note that if you give a pattern that consumes arbitrary length
16115 of input (e.g. @code{($match1* (a ...))}, it will consume entire
16116 input.
16117 @c JP
16118 @code{$match1*}マクロは@code{$match1}と似ていますが、
16119 入力ストリーム全てが@var{pattern}とのマッチの対象になります。
16120 入力の要素を2つ以上見たい場合に便利です。
16121 任意個の要素を消費するパターンを与えた場合(例: @code{($match1* (a ...))})、
16122 このパーザは入力を最後まで消費することに注意してください。
16123 @c COMMON
16124
16125 @c EN
16126 These macros especially come handy when you have a token stream
16127 generated by a separate lexer---each token can have some structure
16128 (instead of just a character) and you can take advantage of @code{match}.
16129 @c JP
16130 これらのマクロは、別の字句解析を使って生成されるトークンストリームをパーズする時に
16131 特に役に立つでしょう。各トークンは単なる文字ではなく構造を持つことができ、
16132 @code{match}の力を活用することができます。
16133 @c COMMON
16134 @end defmac
16135
16136 @node PEG ropes, PEG choice, PEG primitive parser builders, PEG parser combinators
16137 @c EN
16138 @subsection Ropes
16139 @c JP
16140 @subsection ロープ
16141 @c COMMON
16142
16143 @c EN
16144 Often you want to construct a string out of the results of other parsers.
16145 It can be costly to construct strings eagerly, for a string may be
16146 just an intermediate one to be a part of a larger string. We provide
16147 a lightweight lazily string construction mechanism, called ropes.
16148 @c JP
16149 パーザの値として、文字列を返したいことはよくあります。
16150 しかし常に文字列を作るようにすると、後でより大きな文字列に取り込まれる中間結果の
16151 文字列を大量に作っては捨てることになり、効率が悪いです。
16152 ロープは、文字列構築を遅延させる軽量な仕組みです。
16153 @c COMMON
16154
16155 @c EN
16156 A rope represents text with a tree of characters, strings, and ropes.
16157 It allows
16158 O(1) concatenation. A rope becomes a string when @emph{finalized}.
16159 The parser drivers such as @code{peg-run-parser} automatically finalizes
16160 ropes in the parser result.
16161 @c JP
16162 ロープはテキストを、文字、文字列、そしてロープの木で表現し、
16163 O(1)での連結を可能にします。ロープは@emph{ファイナライズ}することで文字列になります。
16164 @code{peg-run-parser}のようなパーザドライバは最終的な結果がロープであればそれを
16165 自動的にファイナライズします。
16166 @c COMMON
16167
16168 @defun $->rope parser @dots{}
16169 @c MOD parser.peg
16170 The parsers must yield either a character, a string, a rope,
16171 or @code{#f} or @code{()}. This procedure
16172 returns a parser that matches @var{parser} @dots{}, then gather the
16173 result into a rope. @code{#f} and @code{()} in the results are ignored.
16174 @end defun
16175
16176 @defun $->string parser @dots{}
16177 @c MOD parser.peg
16178 This is a common idiom of @code{($lift rope->string ($->rope parser @dots{}))}.
16179 @end defun
16180
16181 @defun $->symbol parser @dots{}
16182 @c MOD parser.peg
16183 Like @code{$->string}, but yields a symbol rather than a string.
16184 @end defun
16185
16186 @defun rope->string rope
16187 @c MOD parser.peg
16188 Converts a rope to a string.
16189 @end defun
16190
16191 @defun rope-finalize obj
16192 @c MOD parser.peg
16193 Converts any ropes in in @var{obj} into strings.
16194 @end defun
16195
16196
16197 @node PEG choice, PEG sequencing combinators, PEG ropes, PEG parser combinators
16198 @subsection Choice, backtrack and assertion combinators
16199
16200 @defun $or p1 p2 @dots{}
16201 @defunx $or p1 p2 @dots{} :else plast
16202 @c MOD parser.peg
16203 Returns a choice parser. Tries the given parser in order on input.
16204 If one succeeds, immediately yields its result.
16205 If one fails, and does not consume input, then tries the next one.
16206 If one fails with consuming input, immediately fails.
16207
16208 If @var{p1} @var{p2} @dots{} don't share the same prefix
16209 to match, you can let it fail as soon as one parser fails with consuming
16210 input. If more than one parsers do match the same prefix,
16211 you want to wrap them with @code{$try} except the last one.
16212
16213 If all of the parsers p1 p2 @dots{} fail without consuming input,
16214 @code{$or} returns a compound failure of all the failures. You may
16215 wish to produce better error message than that. Putting @code{$fail}
16216 parser at the last doesn't cut it, for @code{$fail} doesn't consume
16217 input so all the previous failures would compound. In such cases,
16218 you can use the second form---if the argument before the last parser
16219 is a keyword @code{:else}, then @code{$or} discards the previous failures.
16220
16221 @example
16222 (peg-parse-string ($or ($. "ab")
16223 ($. "cd")
16224 :else ($fail "we want 'ab' or 'cd'"))
16225 "ef")
16226 @result{} PARSE-ERROR: 'ab' or 'cd' required at 0
16227 @end example
16228 @end defun
16229
16230 @defun $try p
16231 @c MOD parser.peg
16232 Returns a parser that accepts the same input
16233 the parser @var{p} accepts, but when @var{p} fails
16234 the returned parser doesn't consume input. Used with @code{$or},
16235 you can explicitly implement a backtrack behavior.
16236 @end defun
16237
16238 @defun $optional p :optional fallback
16239 @c MOD parser.peg
16240 Returns a parser that tries @var{p} on the input.
16241 If it succeeds, yielding its result. If it fails,
16242 it still succeeds, yielding @var{fallback} as the result.
16243
16244 This is atomic; if @var{p} fails, it doesn't consume input.
16245 @end defun
16246
16247 @defun $assert p
16248 @c MOD parser.peg
16249 Returns a parser that accepts the same input as @var{p}
16250 and returns its result on success, but never consumes the input.
16251 It can be used as a lookahead assertion.
16252 @end defun
16253
16254 @defun $not p
16255 @c MOD parser.peg
16256 Returns a parser that succeeds when @var{p} fails, and that fails
16257 when @var{p} succeeds. When @var{p} succeeds, it yields an
16258 ``unexpected'' error. It never consumes input in either way.
16259 It can be used as a negative lookahead assertion.
16260 @end defun
16261
16262 @defun $expect p msg-string
16263 @c MOD parser.peg
16264 Returns a parser that calls a parser @var{p}, and if it succeeds
16265 yields its result. If @var{p} fails, fails with an error message
16266 that says expecting @var{msg-string}.
16267 Useful to produce user-friendly error messages.
16268
16269 @example
16270 (define digits4
16271 ($expect ($->string ($repeat ($. #[\d]) 4))
16272 "4 consecutive digits"))
16273
16274 (peg-parse-string digits4 "123a")
16275 @result{} @r{error with}
16276 *** PARSE-ERROR: expecting 4 consecutive digits at 3, but got #\a
16277 @end example
16278 @end defun
16279
16280 @defun $cut p
16281 @c MOD parser.peg
16282 If @var{p} fails, make the failure non-recoverable. It prevents the
16283 upstream @code{$or} and @code{$try} from backtracking and trying other choices,
16284 and makes the entire parsing fail immediately.
16285
16286 See also @code{$raise} above.
16287 @end defun
16288
16289
16290 @node PEG sequencing combinators, PEG repetition combinators, PEG choice, PEG parser combinators
16291 @subsection Sequencing combinators
16292
16293 @defun $seq p1 p2 @dots{}
16294 @defunx $seq0 p1 p2 @dots{}
16295 @c MOD parser.peg
16296 Returns a parser that atches
16297 @var{p1}, @var{p2}, @dots{} sequentially. When all the parser
16298 succeeds, @code{$seq} returns
16299 the last result, while @var{$seq0} returns the first result.
16300 Fails immediately when one of the parsers fails.
16301 @end defun
16302
16303 @defun $between p1 p2 p3
16304 @c MOD parser.peg
16305 Returns a parser that matches
16306 @var{p1}, @var{p2} and @var{p3} sequentially, and returns
16307 the result of @var{p2}.
16308 @end defun
16309
16310 @defun $list p @dots{}
16311 @defunx $list* p @dots{}
16312 @c MOD parser.peg
16313 Returns a parser that matches @var{p} @dots{},
16314 and returns the list of the results.
16315 @code{$list*} uses the last parser's result as the last cdr.
16316
16317 They are the same as @code{($lift list p @dots{})} and
16318 @code{($lift list* p @dots{})}, but we encounter this pattern
16319 frequent enough to have these.
16320 @end defun
16321
16322 @defun $bind p f
16323 @c MOD parser.peg
16324 The basic block of parser combinators;
16325 @var{p} argument is a parser, and @var{f} is a procedure
16326 that takes a Scheme value and returns a parser.
16327
16328 Returns a parser that first applies @var{p} on the input, and if
16329 it succeeds, calls @var{f} with the result of @var{p}, and applies
16330 the returned parser on the subsequent input.
16331
16332 This combinator, along with @code{$return} and @code{$fail},
16333 composes a MonadFail interface as in Haskell. Theoretically any
16334 combinators can be built on top of these three. In practice,
16335 however, it is not always easy to build things directly on top
16336 of @code{$bind}, and more high-level forms such as @code{$let},
16337 @code{$let*} and @code{$lift} are frequently used.
16338 @end defun
16339
16340
16341 @defmac $let (binding @dots{}) body @dots{}
16342 @defmacx $let* (binding @dots{}) body @dots{}
16343 @c MOD parser.peg
16344 Monadic binding form. Each @var{binding} can be one of the
16345 following forms:
16346
16347 @table @code
16348 @item (var parser)
16349 Run the @var{parser}, and if it succeeds, bind its result to a variable
16350 @var{var}. If it fails, the entire @code{$let} or @code{$let*} immdiately
16351 fails.
16352
16353 @item (parser)
16354 The variable is omitted. The @var{parser} is run, and if it succeeds,
16355 its result is discarded and the next binding or body is evaluated.
16356 If it fails, the entire @code{$let} or @code{$let*} immdiately fails.
16357
16358 @item parser
16359 Same as above. This form can only be used if @var{parser} is just
16360 a vairable reference.
16361 @end table
16362
16363 Once all the parsers in @var{binding} @dots{} succeeds, @var{body} @dots{}
16364 are evaluated in the environment where @var{var} in bindings are bound
16365 to the parser results. The last expression of @var{body} must return
16366 a parser.
16367
16368 Unlike @code{let}, the parsers in @var{binding} @dots{} are always applied
16369 to the input sequentially. The difference of @code{$let} and
16370 @code{$let*} is the scope. With @code{$let*}, the variables bound
16371 in earlier @var{binding} can be used to construct the @var{parser} later.
16372
16373 This means @code{$let} can evaluate all the parsers beforehand, while
16374 @code{$let*} may need to construct parsers at the time of processing
16375 input. Creating a parser involves closure allocations, so you want
16376 to use @code{$let} whenever possible.
16377
16378 Note: @code{$let*} is similar to Haskell's @code{do} construct. We chose
16379 the name @code{$let} and @code{$let*}, for it is easier to see it's
16380 a binding form, and also Scheme already uses @code{do} for
16381 loop construct.
16382 @end defmac
16383
16384 @defun $lift f p @dots{}
16385 @defunx $lift* f p @dots{}
16386 @c MOD parser.peg
16387 Lifts a procedure @var{f} onto the parsers' world.
16388
16389 In a pseudo type declaration, @code{lift}'s type can be understood
16390 as follows:
16391 @example
16392 lift :: (a b ... -> z) (Parser a) (Parser b) ... -> (Parser z)
16393 @end example
16394
16395 That is, @code{lift} creates a parser such that
16396 it first applies parsers on the input, and if all of them succeeds,
16397 it calls @var{f} with the parsers' results as arguments,
16398 and the return value of @var{f} becomes the whole parser's result.
16399
16400 In other words, the following equivalence holds:
16401 @example
16402 ($lift f p0 p1 @dots{})
16403 @equiv{} ($let ([r0 p0] [r1 p1] @dots{}) ($return (f r0 r1 @dots{})))
16404 @end example
16405
16406 It is sometimes simpler to use @code{$lift} instead of @code{$let}.
16407 For example, the following code creates a parser that matches
16408 input with @var{p0} @var{p1} @dots{} sequentially, then yields
16409 the list of the parser results:
16410
16411 @example
16412 ($lift list p0 p1 @dots{})
16413 @end example
16414
16415 Note that after all the parsers succeed, the whole parser is
16416 destined to succeed---the procedure @var{f} can't make the parser
16417 fail. If you need to fail after all the parsers succeeds, use @code{$let}
16418 or @code{$let}.
16419 @end defun
16420
16421 @defmac $binding parser-bind-form @dots{} [(=> fail)] expr
16422 @defmacx $lbinding parser-bind-form @dots{} [(=> fail)] expr
16423 @c MOD parser.peg
16424 Each @var{parser-bind-form} may be a parser-yielding expression, except
16425 that you can insert a form @code{($: var parser-expression)} anywherer in it,
16426 where @var{parser-expression} is an expression that yields a parser.
16427 The @code{$:} form is equivalent to just the @var{parser-expression}, except
16428 that its semantic value is bound to a variable @var{var}.
16429
16430 Each parser created by @var{parser-bind-form} is applied to the input
16431 in sequence. One of @var{parser-bind-form} fails, the entire parser
16432 immediately fails. If all of @var{parser-bind-form} succeeds, @var{expr}
16433 is evaluated in the environment where all the @var{var}s are
16434 bound to the corresponding parser expression.
16435
16436 Since @code{$binding} walks entire @var{parser-bind-form} to look for
16437 @code{$:} forms, you can't have nested @code{$binding} form inside
16438 @var{parser-bind-form}.
16439
16440 If the parser expression associated with @var{var} fails, or never
16441 executed, the @var{var} is bound to @code{#<undef>}.
16442 If the parser expression succeeds multiple times, @var{var} holds
16443 the last value. Also, @var{var} can appear more than one places;
16444 it holds the last bound value.
16445
16446 The value of @var{expr} form becomes the semantic value of the
16447 entire parser.
16448
16449 @code{$lbinding} is a shorthand of @code{($lazy ($binding ...))}.
16450
16451 The optional @code{(=> fail)} form before @var{expr} is similar to the
16452 one with @code{$match}. If given, @var{fail}, which must be an identifier,
16453 is bound to a procedure that returns failure. You should call it in the
16454 tail position of @var{expr} to indicate failure. It can be
16455
16456 @itemize @bullet
16457 @item
16458 @code{(@var{fail} @var{message})} : Returns @code{fail-message} type
16459 failure, with a string @var{message} as the message.
16460 @item
16461 @code{(@var{fail} @var{tag} @var{message})} : Returns @code{fail-error} type
16462 (non-recoverable) failure, where @var{tag} must be a symobl @code{error}
16463 (in future, differtent tags will be supported).
16464 @end itemize
16465
16466 @end defmac
16467
16468
16469 @defun $fold-parsers proc seed ps
16470 @c MOD parser.peg
16471 @var{Ps} is a list of parsers. Apply those parsers sequentially
16472 on the input, passing around the seed value. That is, if we let
16473 @code{v0}, @var{v1} @dots{} @var{vn} be the result of each parsers in @var{ps},
16474 it returns @code{(proc vn (... (proc v2 (proc v1 seed))...))}.
16475
16476 If any of the parser in @var{ps} fails, @code{$fold-parsers} fails at
16477 that point.
16478
16479 Conceptually, it can be written as follows:
16480
16481 @example
16482 (define ($fold-parsers proc seed ps)
16483 (if (null? ps)
16484 ($return seed)
16485 ($let ([v (car ps)])
16486 ($fold-parsers proc (proc v seed) (cdr ps)))))
16487 @end example
16488
16489 But we use more efficient implementation.
16490 @end defun
16491
16492 @defun $fold-parsers-right proc seed ps
16493 @c MOD parser.peg
16494 Similar to @code{$fold-parsers}, but the folding by @var{proc}
16495 right to left. That is, if we let
16496 @code{v0}, @var{v1} @dots{} @var{vn} be the result of each parsers in @var{ps},
16497 it returns @code{(proc v1 (proc v2 (... (proc vn seed)...)))}.
16498
16499 If any of the parser in @var{ps} fails, @code{$fold-parsers-right} fails at
16500 that point.
16501 @end defun
16502
16503
16504 @node PEG repetition combinators, PEG miscellaneous combinators, PEG sequencing combinators, PEG parser combinators
16505 @subsection Repetition combinators
16506
16507
16508 @defun $many p :optional min max
16509 @defunx $many_ p :optional min max
16510 @c MOD parser.peg
16511 Without optional arguments, returns
16512 a parser that accepts zero or more repetition of @var{p}.
16513 On success, @code{$many} yields a list of mached results,
16514 while @var{$many_} doesn't keep the results (and faster).
16515
16516 Optinoal @var{min} and @var{max} must be nonnegative integers
16517 and limit the number of occurrences of @var{p}. The numbers are inclusive.
16518 For example,
16519 @code{($many ($. #\a) 3)} accepts three or more @code{#\a}'s,
16520 and @code{($many ($. #\a) 2 4)} accepts @code{aa}, @code{aaa} and
16521 @code{aaaa}.
16522
16523 Note that @code{$many} may fail if the input partially matches
16524 @code{p}.
16525
16526 @example
16527 (peg-parse-string ($many ($seq ($. #\a) ($. #\b))) "ababcd")
16528 @result{} (#\b #\b)
16529
16530 (peg-parse-string ($many ($seq ($. #\a) ($. #\b))) "ababac")
16531 @result{} *** PARSE-ERROR: expecting #\b at 5, but got #\c
16532 @end example
16533
16534 If you want to stop @code{$many} at the first two occurrences
16535 in the latter case, use @code{$try}:
16536
16537 @example
16538 (peg-parse-string ($many ($try ($seq ($. #\a) ($. #\b)))) "ababac")
16539 @result{} (#\b #\b)
16540 @end example
16541 @end defun
16542
16543 @defun $many1 p :optional max
16544 @defunx $many1_ p :optional max
16545 @c MOD parser.peg
16546 Returns a parser that accepts one or more occurences of @var{p}.
16547 On success, @code{$many1} yields a list of results of @var{p},
16548 while @var{$many_} discards the results of @var{p} and faster.
16549 If @var{max} is given, it specifies the maximum number of matches.
16550
16551 Same as @code{($many p 1 max)} and @code{($many_ p 1 max)}.
16552 Provided as a common pattern.
16553 @end defun
16554
16555 @defun $repeat p n
16556 @defunx $repeat_ p n
16557 @c MOD parser.peg
16558 Returns a parser that accepts exaclty @var{n} occurences of @var{p}.
16559 On success, @code{$repeat} yields a list of results of @var{p},
16560 while @code{$repeat_} discards the results of @var{p} and faster.
16561
16562 Same as @code{($many p n n)} and @code{($many_ p n n)}.
16563 Provided as a common pattern.
16564 @end defun
16565
16566 @defun $many-till p pe :optional min max
16567 @defunx $many-till_ p pe :optional min max
16568 @c MOD parser.peg
16569 Returns a parser that accepts repetition of @var{p}, until it
16570 sees input that accepts @var{pe}.
16571 On success, @code{$many-till} yields a list of results of @var{p},
16572 while @var{$many-till_} discards the results of @var{p} and faster.
16573
16574 @example
16575 (define comment ($seq ($.";") ($many-till ($any) ($."\n"))))
16576 @end example
16577 @end defun
16578
16579 @defun $sep-by p psep :optional min max
16580 @defunx $end-by p psep :optional min max
16581 @defunx $sep-end-by p psep :optional min max
16582 @c MOD parser.peg
16583 These combinators match repetition of @var{p} separated by @var{psep},
16584 such as comma-separated values.
16585 Returns the list of results of @var{p}.
16586 Optional @var{min} and @var{max} are integers that limits the
16587 number of repetitions.
16588
16589 These three differ only on treatment of the last separator; @code{$sep-by}
16590 accepts strictly infix syntax, that is, the input must not end
16591 with the separator; while @code{$end-by} accepts strictly suffix syntax,
16592 that is, the input must end with the separator; @code{$sep-end-by}
16593 makes the last separator optional.
16594 @end defun
16595
16596 @defun $chain-left p op
16597 @defunx $chain-right p op
16598 @c MOD parser.peg
16599 Returns a parser that parsers left-assosiative and right-associative operators,
16600 respectively.
16601
16602 The term of expression is parsed by a parser @var{p}, and the
16603 operator is parsed by @var{op}.
16604 @end defun
16605
16606 @node PEG miscellaneous combinators, PEG performance tips, PEG repetition combinators, PEG parser combinators
16607 @subsection Miscellaneous combinators
16608
16609 @defmac $parameterize ((param expr) @dots{}) parser @dots{}
16610 @c MOD parser.peg
16611 Returns a parser that runs @var{parser} @dots{}, while altering
16612 the parameter values of @var{param} @dots{} with the reuslt of
16613 @var{expr} @dots{}, like @code{parameterize}.
16614 The @var{parser} @dots{} are run as if in @code{$seq}, so only the value
16615 of them is returned on success.
16616
16617 You can't use ordinary @code{parameterize}, since such parameterization
16618 takes effect on parser construction time, and not when the parser
16619 parsing the input.
16620 @end defmac
16621
16622 @defun $debug name p
16623 @c MOD parser.peg
16624 Parses the same input as @var{p}, but reports when it is parsing
16625 the input, and the result, just like @code{debug-print}.
16626
16627 You can't use @code{debug-print} directly, for it will take effect
16628 on the parser construction time, not when the input is parsed.
16629 @end defun
16630
16631 @defmac $lazy p
16632 @c MOD parser.peg
16633 Returns a parser that works the same as @var{p}, but delays evaluation
16634 of @var{p} until needed. It is useful when you define mutually
16635 recursive parsers.
16636 @end defmac
16637
16638
16639
16640 @node PEG performance tips, , PEG miscellaneous combinators, PEG parser combinators
16641 @subsection Performance
16642
16643
16644
16645 @c ----------------------------------------------------------------------
16646 @node RFC822 message parsing, Base64 encoding/decoding, PEG parser combinators, Library modules - Utilities
16647 @section @code{rfc.822} - RFC822 message parsing
16648 @c NODE RFC822メッセージ形式, @code{rfc.822} - RFC822メッセージ形式
16649
16650 @deftp {Module} rfc.822
16651 @mdindex rfc.822
16652 @c EN
16653 Defines a set of functions that parses and constructs the ``Internet
16654 Message Format'', a text format used to exchange e-mails.
16655 The most recent specification can be found in
16656 RFC5322.
16657 The format was originally defined in RFC 822, and people still
16658 call it ``RFC822 format'', hence I named this module.
16659 In the following document, I also refer to the format as ``RFC822 format''.
16660 @c JP
16661 電子メールを交換する際に使用されるテキストのフォーマットである、``インターネット・
16662 メッセージ・フォーマット''をパーズ/生成する手続きを定義しています。
16663 最新の仕様は、RFC5322にあります。
16664 このフォーマットは最初 RFC 822 で定義されたため、未だに``RFC822形式''と
16665 呼ばれています。それがこのモジュール名の由来です。
16666 以下では、このフォーマットを``RFC822形式''と呼びます。
16667 @c COMMON
16668 @end deftp
16669
16670 @c EN
16671 @subheading Parsing message headers
16672 @c JP
16673 @subheading メッセージヘッダのパーズ
16674 @c COMMON
16675
16676 @defun rfc822-read-headers iport :key strict? reader
16677 @c MOD rfc.822
16678 @c EN
16679 Reads RFC822 format message from an input port @var{iport},
16680 until it reaches the end of the message header.
16681 The header fields are broken into a list of the following
16682 format:
16683 @c JP
16684 入力ポート @var{iport} から、メッセージ・ヘッダの終わりに達するまで、
16685 RFC822 形式のメッセージを読み込みます。
16686 ヘッダ・フィールドは以下のフォーマットのリストに展開、分離されます。
16687 @c COMMON
16688 @example
16689 ((name body) @dots{})
16690 @end example
16691 @c EN
16692 @var{Name} @dots{} are the field names, and @var{body} @dots{} are
16693 the corresponding field body, both as strings.
16694 Field names are converted to lower-case characters.
16695 Field bodies are not modified, except the folded line is unfolded.
16696 The order of fields are preserved.
16697 @c JP
16698 @var{Name} @dots{} はフィールド名で、@var{body} @dots{} は対応するフィールドの
16699 ボディ、ともに文字列です。
16700 フィールド名は小文字に変換されます。フィールドのボディは、行折り返しが
16701 取り除かれる以外は変更されません。
16702 フィールドの順番は保存されます。
16703 @c COMMON
16704
16705 @c EN
16706 By default, the parser works permissively. If EOF is encountered
16707 during parsing header, it is taken as the end of the message.
16708 And if a line that doesn't consist neither continuing (folded) line
16709 nor start a new header field, it is simply ignored.
16710 You can change this behavior by giving true value to
16711 the keyword argument @var{strict?}; then the parser raises an error
16712 for such a malformed header.
16713
16714 The keyword argument @var{reader} takes a procedure that reads
16715 a line from @var{iport}. Its default is @code{read-line}, which
16716 should be enough for most cases.
16717 @c JP
16718 デフォルトでは、パーザの動作は寛容です。ヘッダをパーズ中に EOF に
16719 出会うとそれをメッセージの終端とみなします。継続(折り返し)行でもなく、
16720 新しいヘッダフィールドの始端でもない行は無視します。このふるまいは
16721 キーワード引数 @var{strict?} に真の値を渡すことで変更することができます。
16722 真を渡すと、このような不正な形式のヘッダに対してエラーを発生させるように
16723 なります。
16724
16725 キーワード引数 @var{reader} は @var{iport} から一行読み込む手続きを
16726 とります。デフォルトは @code{read-line} です。ほとんどの場合これで
16727 十分のはずです。
16728 @c COMMON
16729 @end defun
16730
16731 @defun rfc822-header->list iport :key strict? reader
16732 @c MOD rfc.822
16733 @c DEPRECATED
16734 @c EN
16735 This is an old name of @code{rfc822-read-headers}. This is kept
16736 for the backward compatibility. The new code should use
16737 @code{rfc822-read-headers} instead.
16738 @c JP
16739 これは@code{rfc822-read-headers}の古い名前です。
16740 互換性のために残してありますが、新しいコードは
16741 @code{rfc822-read-headers}を使って下さい。
16742 @c COMMON
16743 @end defun
16744
16745
16746 @defun rfc822-header-ref header-list field-name :optional default
16747 @c MOD rfc.822
16748 @c EN
16749 An utility procedure to get a specific field from the parsed
16750 header list, which is returned by @code{rfc822-read-headers}.
16751
16752 @var{Field-name} specifies the field name in a lowercase string.
16753 If the field with given name is in @var{header-list}, the procedure
16754 returns its value in a string. Otherwise, if @var{default} is given,
16755 it is returned, and if not, @code{#f} is returned.
16756
16757 If there are more than one header with the same field name, value of
16758 the first one is returned. To get all values of multiple header fields,
16759 use @code{rfc822-header-ref*} below.
16760
16761 This procedure can actually be used not only for the result of
16762 @code{rfc822-read-headers}, but for retrieving a value keyed
16763 by strings in a list-of-list structure: @code{((name value option ...) ...)}.
16764 For example, the return value of @code{parse-cookie-string}
16765 can be passed to @code{rfc-822-header-ref}
16766 (@pxref{HTTP cookie handling}, for @code{parse-cookie-string}).
16767 @c JP
16768 @code{rfc822-read-headers} が返すパーズ済みのヘッダリストから
16769 特定のフィールドを得るためのユーティリティ手続きです。
16770
16771 @var{Field-name} は小文字の文字列でフィールド名を指定します。
16772 与えられた名前をもつフィールドが @var{header-list} 中にあれば、
16773 その値を文字列で返します。そうでない場合、もし @var{default} が
16774 与えられていればそれが返り、与えられていなければ @code{#f} が返されます。
16775
16776 もし同じフィールド名を持つヘッダエントリが複数あった場合は、
16777 最初のエントリの値が返されます。複数ヘッダエントリの全ての値を取りたい場合は
16778 下の@code{rfc822-header-ref*}を使ってください。
16779
16780 この手続きは@code{rfc822-read-headers}の結果だけでなく、
16781 文字列をキーにしたリストのリスト @code{((name value option ...) ...)}
16782 という構造からvalue部分を取り出すのに使えます。
16783 例えば@code{parse-cookie-string}の結果を@code{rfc-822-header-ref}に渡せます。
16784 (@code{parse-cookie-string}については@pxref{HTTP cookie handling}参照。)
16785 @c COMMON
16786
16787 @example
16788 (rfc822-header-ref
16789 '(("from" "foo@@example.com") ("to" "bar@@example.com"))
16790 "from")
16791 @result{} "foo@@example.com"
16792
16793 ;; If no entry matches, #f is returned by default
16794 (rfc822-header-ref
16795 '(("from" "foo@@example.com") ("to" "bar@@example.com"))
16796 "reply-to")
16797 @result{} #f
16798
16799 ;; You can give the default value for no-match case
16800 (rfc822-header-ref
16801 '(("from" "foo@@example.com") ("to" "bar@@example.com"))
16802 "reply-to" 'none)
16803 @result{} none
16804
16805 ;; By giving the default value, you can distinguish
16806 ;; the no-match case and there's actually an entry with value #f.
16807 (rfc822-header-ref
16808 '(("from" "foo@@example.com") ("reply-to" #f))
16809 "reply-to" 'none)
16810 @result{} #f
16811 @end example
16812 @end defun
16813
16814 @defun rfc822-header-ref* header-list field-name
16815 @c EN
16816 Like @code{rfc822-header-ref}, looks up header entries in
16817 @var{header-list} with the name @var{field-name}, however,
16818 this procedure returns all values of matching headers
16819 in a list. If there's no matching headers, an empty list
16820 is returned.
16821 @c JP
16822 @code{rfc822-header-ref}のように@var{header-list}から
16823 @var{field-name}を持つヘッダを探しますが、最初に見つかったものだけでなく
16824 @var{field-name}を持つ全てのヘッダの値をリストにして返します。
16825 指定の名前を持つヘッダが無ければ空リストが返されます。
16826 @c COMMON
16827 @end defun
16828
16829 @defun rfc822-header-put header-list field-name field-value
16830 @c EN
16831 Returns an rfc822 header list which is the same as @var{header-list}
16832 except that a header with @var{field-name} and @var{field-value}
16833 is added. @var{Field-name} is converted to lowercase letters.
16834 If @var{header-list} already contains headers with
16835 @var{field-name}, such headers are excluded from the output.
16836 The @var{header-list} won't be modified.
16837 @c JP
16838 RFC822ヘッダリスト@var{header-list}に、名前@var{field-name}と値
16839 @var{field-value}を持つヘッダを追加したヘッダリストを返します。
16840 @var{field-name}は全て小文字に変換されます。
16841 @var{header-list}が既に同名のヘッダを持っていた場合、それらは全て出力から除かれます。
16842 引数に渡した@var{header-list}自体は変更されません。
16843 @c COMMON
16844 @end defun
16845
16846 @c EN
16847 @subheading Basic field parsers
16848 @c JP
16849 @subheading 基本的なフィールドパーザ
16850 @c COMMON
16851
16852 @c EN
16853 Several procedures are provided to parse "structured" header fields
16854 of RFC2822 messages. These procedures deal with the body of
16855 a header field, i.e. if the header field is
16856 "@code{To: Wandering Schemer <schemer@@example.com>}",
16857 they parse "@code{Wandering Schemer <schemer@@example.com>}".
16858
16859 Most of procedures take an input port. Usually you first parse
16860 the entire header fields by @code{rfc822-read-headers},
16861 obtain the body of the header by @code{rfc822-header-ref},
16862 then open an input string port for the body and use those
16863 procedures to parse them.
16864
16865 The reason for this complexity is because you need
16866 different tokenization schemes depending on the type of the field.
16867 Rfc2822 also allows comments to appear between tokens for most cases,
16868 so a simple-minded regexp won't do the job,
16869 since rfc2822 comment can be nested
16870 and can't be represented by regular grammar.
16871 So, this layer of procedures are designed flexible enough
16872 to handle various syntaxes. For the standard header types,
16873 high-level parsers are also provided; see "specific field parsers" below.
16874 @c JP
16875 RFC2822メッセージの「構造化」されたヘッダフィールドをパーズするために、
16876 いくつかの手続きが提供されています。これらの手続きはヘッダフィールドの
16877 本体部を処理します。たとえば、ヘッダフィールドが、
16878 "@code{To: Wandering Schemer <schemer@@example.com>}" であれば、これらの
16879 手続きは "@code{Wandering Schemer <schemer@@example.com>}" をパーズします。
16880
16881 ほとんどの手続きは入力ポートを引数にとります。通常は最初に、ヘッダフィールド
16882 全部を @code{rfc822-read-headers} でパーズし、ヘッダの本体を
16883 @code{rfc822-header-ref} で取得してから、その本体用に入力文字列ポートを
16884 オープンして、それをこれらの手続きを用いてパーズします。
16885
16886 このように複雑になっているのは、フィールドのタイプによって別々の
16887 トークン化スキームが必要になるからです。RFC2822 では多くの場合
16888 トークン間にコメントがあらわれことを許しているので、初心な正規表現では
16889 うまくいきません。RFC2822 のコメントはネスト可能で、正規表現では表現
16890 しきれないからです。
16891 そういうわけで、このレイヤの手続きは、いろいろな構文に対応できるよう
16892 十分な柔軟性があるように設計されています。標準的なタイプのヘッダについては
16893 高水準のパーザも提供されています。後述の「特定フィールド用パーザ」を
16894 参照してください。
16895 @c COMMON
16896
16897 @defun rfc822-next-token iport :optional tokenizer-specs
16898 @c MOD rfc.822
16899 @c EN
16900 A basic tokenizer. First it skips whitespaces and/or
16901 comments (@code{CFWS}) from @var{iport}, if any. Then
16902 reads one token according to @var{tokenizer-specs}. If @var{iport}
16903 reaches EOF before any token is read, EOF is returned.
16904
16905 @var{Tokenizer-specs} is a list of tokenizer spec, which is
16906 either a char-set or a cons of a char-set and a procedure.
16907
16908 After skipping @code{CFWS}, the procedure peeks a character
16909 at the head of @var{iport}, and checks it
16910 against the char-sets in @var{tokenizer-specs} one by one.
16911 If a char-set that contains the character belongs to is found,
16912 then a token is retrieved as follows:
16913 If the tokenizer spec is just a char-set, a sequence of characters
16914 that belong to the char-set consists a token.
16915 If it is a cons, the procedure is called with @var{iport} to
16916 read a token.
16917
16918 If the head character doesn't match any char-sets,
16919 the character is taken from @var{iport} and returned.
16920
16921 The default @var{tokenizer-specs} is as follows:
16922 @c JP
16923 基本的なトークナイザです。まず、もしあれば、白空白および/または
16924 コメント (@code{CFWS}) を @var{iport} から読み飛ばします。それから、
16925 @var{tokenizer-specs} にしたがってトークンをひとつ読み込みます。
16926 トークンを読み込む前に、@var{iport} が EOF に到達したら、EOF が
16927 返されます。
16928
16929 @var{tokenizer-specs} はトークナイザ仕様のリストです。
16930 トークナイザ仕様は、文字集合または文字集合と手続きのペアのどちらかです。
16931
16932 @code{CFWS} を読み飛ばしたあと、この手続きは @var{iport} の先頭の一文字
16933 を見て、@var{tokenizer-specs} のひとつひとつに対してチェックします。
16934 その文字が含まれている文字集合がみつかれば、トークンを次のようにして
16935 引き出します。トークナイザ仕様が文字集合だけの場合、その文字集合に
16936 属している文字の並びがトークンを構成します。トークナイザ仕様が文字集合と
16937 手続きのペアだったら、その手続きを @var{iport} とともに呼びだし、
16938 トークンを読み込みます。
16939
16940 もし、先頭の文字がどの文字集合ともマッチしなければ、その文字が
16941 @var{iport} から取り出され、それが返されます。
16942
16943 デフォルトの @var{tokenizer-specs} は以下のようになっています。
16944 @c COMMON
16945 @example
16946 (list (cons #["] rfc822-quoted-string)
16947 (cons *rfc822-atext-chars* rfc822-dot-atom))
16948 @end example
16949 @c EN
16950 Where @code{rfc822-quoted-string} and @code{rfc822-dot-atom}
16951 are tokenizer procedures described below, and @code{*rfc822-atext-chars*}
16952 is bound to a char-set of @code{atext} specified in rfc2822.
16953 This means @code{rfc822-next-token} retrieves a token
16954 either @code{quoted-string} or @code{dot-atom} specified in rfc2822
16955 by default.
16956
16957 Using @var{tokenizer-specs}, you can customize how the header
16958 field is parsed. For example, if you want to retrieve a token
16959 that is either (1) a word constructed by alphabetic characters, or
16960 (2) a quoted string, then you can call @code{rfc822-next-token}
16961 by this:
16962 @c JP
16963 ここで @code{rfc822-quoted-string} および @code{rfc822-dot-atom} は
16964 後述するトークナイザ手続きで、@code{*rfc822-atext-chars*} は RFC2822 で
16965 規定された @code{atext} の文字集合に束縛されています。
16966 つまり、@code{rfc822-next-token} はデフォルトでは RFC2822 で規定された
16967 @code{quoted-string} あるいは @code{dot-atom} のトークンを引き出します。
16968
16969 @var{tokenizer-specs} をつかって、ヘッダフィールドのパーズ方法を
16970 カスタマイズすることができます。たとえば、(1) 英字で構成された単語、または
16971 (2) クウォート文字列、のトークンを取り出したいときには、
16972 @code{rfc822-next-token} をこんなふうに呼べます。
16973 @c COMMON
16974
16975 @example
16976 (rfc822-next-token iport
16977 `(#[[:alpha:]] (#["] . ,rfc822-quoted-string)))
16978 @end example
16979 @end defun
16980
16981 @defun rfc822-field->tokens field :optional tokenizer-specs
16982 @c MOD rfc.822
16983 @c EN
16984 A convenience procedure. Creates an input string port for
16985 a field body @var{field}, and calls @code{rfc822-next-token}
16986 repeatedly on it until it consumes all input, then returns
16987 a list of tokens. @var{Tokenizer-specs} is passed to
16988 @code{rfc822-next-token}.
16989 @c JP
16990 これは便利関数です。フィールド本体 @var{field} に対応する入力文字列ポート
16991 を生成し、それに対して、@code{rfc822-next-token} を全入力を消費するまで、
16992 繰り返しよび、トークンのリストを返します。@var{Tokenizer-specs} は、
16993 @code{rfc822-next-token} に渡されます。
16994 @c COMMON
16995 @end defun
16996
16997 @defun rfc822-skip-cfws iport
16998 @c MOD rfc.822
16999 @c EN
17000 A utility procedure that consumes any comments and/or whitespace
17001 characters from @var{iport}, and returns the head character
17002 that is neither a whitespace nor a comment. The returned character
17003 remains in @var{iport}.
17004 @c JP
17005 @var{iport} から、すべてのコメントおよび/または白空白文字を消費し、
17006 白空白でもコメントでもない、先頭の文字を返します。返された文字は、
17007 @var{iport}に残ります。
17008 @c COMMON
17009 @end defun
17010
17011 @defvr {Constant} *rfc822-atext-chars*
17012 @c MOD rfc.822
17013 @c EN
17014 Bound to a char-set that is a valid constituent of @code{atom}.
17015 @c JP
17016 @code{atom} を構成する有効な文字集合に束縛されています。
17017 @c COMMON
17018 @end defvr
17019
17020 @defvr {Constant} *rfc822-standard-tokenizers*
17021 @c MOD rfc.822
17022 @c EN
17023 Bound to the default @var{tokenizer-specs}.
17024 @c JP
17025 デフォルトの @var{tokenizer-specs} に束縛されています。
17026 @c COMMON
17027 @end defvr
17028
17029 @defun rfc822-atom iport
17030 @defunx rfc822-dot-atom iport
17031 @defunx rfc822-quoted-string iport
17032 @c MOD rfc.822
17033 @c EN
17034 Tokenizers for @code{atom}, @code{dot-atom} and @code{quoted-string},
17035 respectively. The double-quotes and escaping backslashes within
17036 @code{quoted-string} are removed by @code{rfc822-quoted-string}.
17037 @c JP
17038 それぞれ、@code{atom}、@code{dot-atom} および @code{quoted-string} に
17039 対応するトークナイザです。@code{quoted-string} 中の二重引用符および
17040 エスケープのためのバックスラッシュは @code{rfc822-quoted-string} に
17041 よって取り除かれます。
17042 @c COMMON
17043 @end defun
17044
17045 @c EN
17046 @subheading Specific field parsers
17047 @c JP
17048 @subheading 特定フィールド用パーザ
17049 @c COMMON
17050
17051 @defun rfc822-parse-date string
17052 @c MOD rfc.822
17053 @c EN
17054 Takes RFC-822 type date string, and returns eight values:
17055 @c JP
17056 RFC822 形式の日付文字列を取り、8つの値を返します。
17057 @c COMMON
17058 @example
17059 year, month, day-of-month, hour, minutes, seconds, timezone,
17060 day-of-week.
17061 @end example
17062
17063 @c EN
17064 @emph{Timezone} is an offset from UT in minutes.
17065 @emph{Day-of-week} is a day from sunday,
17066 and may be #f if that information is not available.
17067 @emph{Month} is an integer between 1 and 12, inclusive.
17068 If the string is not parsable, all the elements are #f.
17069 @c JP
17070 @emph{timezone} は UT(グリニッジ標準時)からの分単位のオフセットです。
17071 @emph{day-of-week} は日曜日から数えた曜日で、情報が不足している場合は #f です。
17072 @emph{month}は1から12までの整数です。
17073 文字列がパーズ不可能ならば、全ての要素が #f になります。
17074 @c COMMON
17075 @end defun
17076
17077 @defun rfc822-date->date string
17078 @c MOD rfc.822
17079 @c EN
17080 Parses RFC822 type date format and returns SRFI-19 @code{<date>} object
17081 (see @ref{SRFI-19 Date}). If @var{string} can't be parsed,
17082 returns @code{#f} instead.
17083
17084 To construct rfc822 date string from SRFI-19 date, you can use
17085 @code{date->rfc822-date} below.
17086 @c JP
17087 RFC822形式の日付フォーマットをパーズし、SRFI-19 の @code{<date>} オブジェクト
17088 (@ref{SRFI-19 Date} 参照) を返します。@var{string} がパーズできないときは
17089 かわりに @code{#f} を返します。
17090
17091 SRFI-19の日付からRFC822形式の日付文字列を作成するには、
17092 後で述べる@code{date->rfc822-date}が使えます。
17093 @c COMMON
17094 @end defun
17095
17096 @c EN
17097 @subheading Message constructors
17098 @c JP
17099 @subheading メッセージの構築
17100 @c COMMON
17101
17102 @defun rfc822-write-headers headers :key output continue check
17103 @c MOD rfc.822
17104 @c EN
17105 This is a sort of inverse function of @code{rfc822-read-headers}.
17106 It receives a list of header data, in which each header data
17107 consists of @code{(<name> <body>)}, and writes them out in RFC822 header
17108 field format to the output port specified by the @var{output} keyword
17109 argument. The default output is the current output port.
17110 @c JP
17111 これは@code{rfc822-read-headers}の一種の逆関数と言えます。
17112 各ヘッダデータが@code{(<name> <body>)}の形になっているリストを受け取り、
17113 @var{output}キーワード引数で指定されるポートにRFC822形式で書き出します。
17114 @var{output}が省略された場合は現在の出力ポートが使われます。
17115 @c COMMON
17116
17117 @c EN
17118 By default, the procedure assumes @var{headers} contains all the
17119 header fields, and adds an empty line in the end of output
17120 to indicate the end of the header. You can pass a true value to
17121 the @var{continue} keyword argument to prevent this, enabling
17122 more headers can be added later.
17123 @c JP
17124 デフォルトでは、この手続きは@var{header}で全てのヘッダが完結するものと
17125 みなし、最後にヘッダ部分の終了を示す空行を出力します。
17126 ただし@var{continue}キーワード引数に真の値を渡すとこの動作は抑制され、
17127 後からヘッダを追加で出力することができます。
17128 @c COMMON
17129
17130 @c EN
17131 I said ``a sort of'' above. That's because this function doesn't
17132 (and can't) do the exact inverse.
17133 Specifically, the caller is responsible for line folding and
17134 make sure each header line doesn't exceed the ``hard limit'' defined
17135 by RFC2822 (998 octets). If the line length of header data exceeds
17136 that, the caller should insert newline (@code{\r\n}) and one or
17137 more whitespaces as needed.
17138 This procedure cannot do the line
17139 folding on behalf of the caller, because the places where
17140 line folding is possible depend on the semantics of each
17141 header field.
17142 @c JP
17143 上で「一種の」と書きましたが、それはこの手続きが完全な逆関数ではないからです
17144 特に、ヘッダ行が長い場合の「行の折り返し」は呼び出し側でやっておかねばなりません。
17145 RFC2822ではヘッダ行の絶対的な長さを998オクテットに制限しています。
17146 データがそれを越える場合は適宜改行(@code{\r\n})+空白文字を挿入してください。
17147 これは自動ではできません。ヘッダデータのどこに改行を挿入できるかは
17148 各ヘッダのセマンティクスに依存するからです。
17149 @c COMMON
17150
17151 @c EN
17152 It is also the caller's responsibility to make sure header
17153 field bodies don't have any characters except non-NUL US-ASCII
17154 characters. If you want to include characters outside of that
17155 range, you should convert them in the way allowed by the
17156 protocol, e.g. MIME. The @code{rfc.mime} module
17157 (@pxref{MIME message handling}) provides a convenience procedure
17158 @code{mime-encode-text} for such purpose.
17159 Again, this procedure cannot do the encoding automatically,
17160 since the way the field
17161 should be encoded depends on header fields.
17162 @c JP
17163 また、ヘッダフィールドボディはNUL文字以外のASCII文字のみで構成されている
17164 必要があります。それ以外の文字を含めたい場合は、MIME等適切なプロトコルを
17165 使ってあらかじめエンコードしておいてください。
17166 @code{rfc.mime}モジュールの@code{mime-encode-text}が便利でしょう
17167 (@ref{MIME message handling})。
17168 これもまた、ヘッダフィールド毎のセマンティクスに依存するため、
17169 自動で行うことができません。
17170 @c COMMON
17171
17172 @c EN
17173 What this procedure can do is to check and report such violations.
17174 By default, it runs several checks and signals an error if it finds any
17175 violations of RFC2822. You can control this checking behavior
17176 by the @var{check} keyword argument. It can take one of the
17177 following values:
17178 @c JP
17179 しかしこの手続きは、渡されたデータがRFC2822に沿っているかどうかをチェック
17180 できます。デフォルトではRFC2822に違反していればエラーが投げられます。
17181 @var{check}キーワード引数でこの振る舞いを変えられます。
17182 可能な値は次のとおりです。
17183 @c COMMON
17184
17185 @table @code
17186 @item :error
17187 @c EN
17188 Default. Signals an error if a violation is found.
17189 @c JP
17190 デフォルト。違反があればエラーを投げます。
17191 @c COMMON
17192 @item #f, :ignore
17193 @c EN
17194 Doesn't perform any check. Trust the caller.
17195 @c JP
17196 呼び出し側を信頼し、チェックを行いません。
17197 @c COMMON
17198 @item @var{procedure}
17199 @c EN
17200 When @code{rfc822-write-headers} finds a violation, the procedure
17201 is called with three arguments; the header field name,
17202 the header field body, and the type of violation explained below.
17203 The procedure may correct the problem and return two values,
17204 the corrected header field name and body. The returned values
17205 are checked again. If the procedure returns the
17206 header field name and body unchanged, an error is signaled
17207 in the same way as @code{:error} is specified.
17208 @c JP
17209 @code{rfc822-write-headers}が違反を検出したら、
17210 この手続きを3つの引数で呼び出します。
17211 ヘッダフィールド名、ヘッダフィールドボディ、
17212 そして違反の種類を示す以下のシンボルです。
17213 この手続きは、修正されたヘッダフィールド名とヘッダフィールドボディの
17214 ふたつの値を返さなければなりません。
17215 もしこの手続きがヘッダフィールド名とヘッダフィールドボディを修正せずに
17216 返したら、@code{:error}を指定したときのようにエラーが投げられます。
17217 @c COMMON
17218 @end table
17219
17220 @c EN
17221 The third argument passed to the procedure given to the @var{check}
17222 argument is one of the following symbols. New symbols may be
17223 added in future versions for more checks.
17224 @c JP
17225 @var{check}引数に手続きを渡した際に、第3引数に渡されるシンボルは以下のとおりです。
17226 将来のバージョンでは新たなシンボルが追加されるかもしれません。
17227 @c COMMON
17228
17229 @table @code
17230 @item incomplete-string
17231 @c EN
17232 Incomplete string is passed.
17233 @c JP
17234 不完全な文字列が渡された
17235 @c COMMON
17236 @item bad-character
17237 @c EN
17238 Header field contains characters outside of US-ASCII or NUL.
17239 @c JP
17240 NUL文字または非ASCII文字が含まれている
17241 @c COMMON
17242 @item line-too-long
17243 @c EN
17244 Line length exceeds 998 octet limit.
17245 @c JP
17246 1行が998オクテットの制限を越えている
17247 @c COMMON
17248 @item stray-crlf
17249 @c EN
17250 The string contains CR and/or LF character that doesn't consist of
17251 proper line folding.
17252 @c JP
17253 CRLFの組み合わせでない、CRのみまたはLFのみが含まれている。
17254 @c COMMON
17255 @end table
17256
17257 @end defun
17258
17259 @defun date->rfc822-date date
17260 @c MOD rfc.822
17261 @c EN
17262 Takes SRFI-19 @code{<date>} object (see @ref{SRFI-19 Date})
17263 and returns a string of its rfc822 date representation.
17264 This is a reverse operation of @code{rfc822-date->date}.
17265 @c JP
17266 SRFI-19の@code{<date>}オブジェクト(@ref{SRFI-19 Date}参照)
17267 を取り、そのrfc822日付形式表現の文字列を返します。
17268 @code{rfc822-date->date}の逆関数です。
17269 @c COMMON
17270 @end defun
17271
17272
17273 @c ----------------------------------------------------------------------
17274 @node Base64 encoding/decoding, HTTP cookie handling, RFC822 message parsing, Library modules - Utilities
17275 @section @code{rfc.base64} - Base64 encoding/decoding
17276 @c NODE Base64エンコーディング, @code{rfc.base64} - Base64エンコーディング
17277
17278 @deftp {Module} rfc.base64
17279 @mdindex rfc.base64
17280 @c EN
17281 This module defines a few functions to encode/decode Base64 format,
17282 defined in RFC 4648 (@uref{https://www.ietf.org/rfc/rfc4648.txt}).
17283 It also supports Base32 and Base16 formats defined in it as well.
17284 @c JP
17285 このモジュールでは、RFC 4648 (@uref{https://www.ietf.org/rfc/rfc4648.txt})
17286 で定義されている Base64フォーマットへエンコード/デコードするいくつかの
17287 手続きを定義しています。同RFCで定義されている
17288 Base32フォーマット、Base16フォーマットもサポートしています。
17289 @c COMMON
17290
17291 @c EN
17292 The common naming convention is as follows.
17293 @c JP
17294 共通の名前付け規則は次のとおりです。
17295 @c COMMON
17296
17297 @table @code
17298 @item @var{encoding}-encode, @var{encoding}-decode
17299 @c EN
17300 Port-based encoder/decoder. It reads
17301 input from the current input port, and emits encoded/decoded output
17302 to the current output port.
17303 @c JP
17304 ポートを使うストリームエンコーダー/デコーダー。
17305 入力を現在の入力ポートから取り、結果を現在の出力ポートに出力します。
17306 @c COMMON
17307 @item @var{encoding}-encode-message
17308 @c EN
17309 Takes the input as either a string or a u8vector, and returns
17310 the encoded result as a string. Note that BaseN encoding always
17311 results readable strings.
17312 @c JP
17313 入力を文字列かu8vectorで受け取り、エンコード結果を文字列で返します。
17314 BaseNエンコーディングの結果は常に可読文字列になります。
17315 @c COMMON
17316 @item @var{encoding}-decode-string-to
17317 @c EN
17318 Takes the encoded string, and returns the result in either
17319 a u8vector or a string, as specified by the @var{target} argument.
17320 Note that the decoded result is a byte sequence in general,
17321 so a string may be incomplete.
17322 @c JP
17323 エンコードされた文字列を取り、結果をu8vectorもしくは文字列で返します。
17324 どちらを返すからは@var{target}引数で指定されます。
17325 デコード結果は一般にはバイトシーケンスになるので、文字列の場合は
17326 不完全な文字列が返ることに注意してください。
17327 @c COMMON
17328 @end table
17329 @end deftp
17330
17331 @subheading Base64
17332
17333 @defun base64-encode :key line-width digits url-safe omit-padding
17334 @c MOD rfc.base64
17335 @c EN
17336 Reads byte stream from the current input port, encodes it in Base64
17337 format and writes the result character stream to the current output port.
17338 The conversion ends when it reads EOF from the current input port.
17339
17340 Newline characters can be inserted to keep the maximum line width to
17341 the value given to the @var{line-width} keyword argument. The default
17342 value of @var{line-width} is 76, as specified in RFC2045. You can give
17343 @code{#f} or zero to @var{line-width} to suppress line splitting.
17344 @c JP
17345 現在の入力ポートからバイト・ストリームを読み込み、それを Base64 フォーマットに
17346 エンコードし、現在の出力ポートに文字ストリームとして書き出します。
17347 現在の入力ポートから EOF を読み込むと変換を終了します。
17348
17349 一行あたりの文字数が@var{line-width}に与えられた文字数を越えないように、
17350 改行文字が適切に出力に挿入されます。@var{line-width}のデフォルト値は
17351 RFC2045に従い76となっています。@var{line-width}に@code{#f}または@code{0}
17352 を与えることで改行を抑制することができます。
17353 @c COMMON
17354
17355 @c EN
17356 Base64 can have different mappings in the digit of 62 and 63; the ``standard''
17357 encoding uses @code{+} and @code{/}, and the ``url-safe'' encoding
17358 uses @code{-} and @code{_}. You can specify which to use by either
17359 @var{url-safe} or @var{digits}.
17360 @c JP
17361 Base64は62と63を表現するのにいくつかの異なるマッピングがあります。
17362 「標準の」エンコーディングでは@code{+}と@code{/}が、
17363 「URL安全」なエンコーディングでは@code{-}と@code{_}がそれぞれ使われます。
17364 どちらを使うかは@var{url-safe}または@var{digits}引数で制御できます。
17365 @c COMMON
17366
17367 @c EN
17368 If a true value is given to @var{url-safe},
17369 the input bytes will be encoded with ``url-safe'' encoding.
17370 Otherwise, you can give a two-letter string to @var{digits} argument,
17371 in which case the first character is used for digit 62 and the
17372 second character is used for digit 63. The @var{digits} argument
17373 is added to support SRFI-207 (@pxref{String-notated bytevectors}).
17374 @c JP
17375 @var{url-safe}に真の値を与えると、URL安全なエンコーディングが使われます。
17376 そうでない場合、@var{digits}に2文字からなる文字列を渡すことができ、
17377 1文字目が62を、2文字目が63を現す文字として使われます。
17378 @var{digits}引数はSRFI-207をサポートするために追加されました
17379 (@ref{String-notated bytevectors}参照)。
17380 @c COMMON
17381
17382 @c EN
17383 If a true value is given to @var{omit-padding}, the trailing
17384 padding characters (@code{#\=}) are omitted.
17385 (See RFC4648 Section 3.2 (@url{https://www.rfc-editor.org/rfc/rfc4648#section-3.2})). The default is not omitting padding characters.
17386 @c JP
17387 @var{omit-padding}引数に真の値が与えられると、
17388 パディング文字(@code{#\=})が省略されます
17389 (RFC4648 Section 3.2参照 (@url{https://www.rfc-editor.org/rfc/rfc4648#section-3.2}))。
17390 デフォルトではパディング文字は省略されません。
17391 @c COMMON
17392 @end defun
17393
17394 @defun base64-encode-message message :key line-width digits url-safe omit-padding
17395 @c MOD rfc.base64
17396 @c EN
17397 Encodes @var{message}, which must be either a string or a u8vector,
17398 with Base64 encoding and returns the result as a string.
17399 The meaning of keyword arguments are the same as @code{base64-encode} above.
17400 @c JP
17401 文字列かu8vectorの@var{message}をBase64エンコードして、結果を文字列で返します。
17402 キーワード引数の意味は上の@code{base64-encode}と同じです。
17403 @c COMMON
17404
17405 @example
17406 (base64-encode-message "Hau'oli makahiki hou")
17407 @result{} "SGF1J29saSBtYWthaGlraSBob3U="
17408 @end example
17409
17410 @c EN
17411 For the portable code, you may want to use @code{bytestring->base64}
17412 in @code{srfi.207} (@pxref{String-notated bytevectors}).
17413 @c JP
17414 ポータブルなコードでは、@code{srfi.207}の@code{bytestring->base64}を使うことができます
17415 (@ref{String-notated bytevectors}参照)。
17416 @c COMMON
17417 @end defun
17418
17419
17420 @defun base64-decode :key digits url-safe strict
17421 @c MOD rfc.base64
17422 @c EN
17423 Reads character stream from the current input port, decodes it from Base64
17424 format and writes the result byte stream to the current output port.
17425 The conversion ends when it reads EOF or the termination character
17426 (@code{=}).
17427 @c JP
17428 現在の入力ポートから文字ストリームを読み込み、それを Base64 フォーマットとして
17429 デコードし、現在の出力ポートにバイトストリームとして書き出します。
17430 変換は EOF か、終端文字 (@code{=}) を読み込むと終了します。
17431 @c COMMON
17432
17433 @c EN
17434 The characters which does not in legal Base64 encoded character set are
17435 silently ignored by default. If a true value is given to the
17436 @var{strict} keyword argument, however, non-whitespace out-of-set characters
17437 in the input raises an error.
17438 @c JP
17439 Base64 でエンコードされた文字として適当でない文字は、デフォルトでは黙って無視されます。
17440 ただし、@var{strict}キーワード引数に真の値が与えられた場合は、
17441 空白文字以外の不適切な文字が入力にあったらそこでエラーが投げられます。
17442 @c COMMON
17443
17444 @c EN
17445 The input can lack the trailing padding character by default. However,
17446 if @var{strict} argument is true, an error is thrown unless
17447 the input has a proper number of padding characters.
17448 @c JP
17449 入力が必要なパディング文字を欠いていても、デフォルトでは許容されます。
17450 @var{strict}引数が真の場合は、入力に正しい数のパディング文字がないとエラーが投げられます。
17451 @c COMMON
17452
17453
17454 @c EN
17455 The @var{digits} and @var{url-safe} keyword arguments can be used
17456 to choose different mappings of digit 62 and 63. See @code{base64-encode}
17457 above for the details.
17458 @c JP
17459 @var{digits}と@var{url-safe}キーワード引数は62と63の異なるエンコーディングを
17460 指定するのに使えます。詳しくは上の@code{base64-encod}のエントリを参照してください。
17461 @c COMMON
17462 @end defun
17463
17464 @defun base64-decode-string-to target string :key line-width digits url-safe omit-padding
17465 @c MOD rfc.base64
17466 @c EN
17467 The @var{target} argument must be a class object @code{<string>} or @code{<u8vector>}.
17468 This procedure takes Base64-encoded input @var{string}, and returns the
17469 decoded result as an instance of @var{target}.
17470
17471 The meaning of keyword arguments are the same as @code{base64-decode} above.
17472 @c JP
17473 @var{target}引数はクラスオブジェクト@code{<string>}か@code{<u8vector>}でなければなりません。
17474 Base64エンコードされた入力@var{string}を取り、結果を@var{target}のインスタンスで
17475 返します。
17476
17477 キーワード引数の意味は上の@code{base64-decode}と同じです。
17478 @c COMMON
17479
17480 @example
17481 (base64-decode-string-to <string> "SGF1J29saSBtYWthaGlraSBob3U=")
17482 @result{} "Hau'oli makahiki hou"
17483 (base64-decode-string-to <u8vector> "SGF1J29saSBtYWthaGlraSBob3U=")
17484 @result{} #u8(72 97 117 39 111 108 105 32 109 97 107 97 104 105
17485 107 105 32 104 111 117)
17486 @end example
17487
17488 @c EN
17489 Note that if you ask a string to be returned, the result may be
17490 an incomplete string.
17491 @c JP
17492 結果を文字列で得る場合、不完全文字列が返される可能性があることに注意してください。
17493 @c COMMON
17494
17495 @example
17496 (base64-decode-string-to <string> "8PHy8w==")
17497 @result{} #**"\xf0;\xf1;\xf2;\xf3;"
17498 @end example
17499
17500 @c EN
17501 For the portable code, you may want to use @code{base64->bytestring}
17502 in @code{srfi.207} (@pxref{String-notated bytevectors}).
17503 @c JP
17504 ポータブルなコードでは、@code{srfi.207}の@code{base64->bytestring}を使うことができます
17505 (@ref{String-notated bytevectors}参照)。
17506 @c COMMON
17507 @end defun
17508
17509
17510 @subheading Base32
17511
17512 @c EN
17513 RFC4648 defines two completely different encodings as base-32;
17514 The standard Base32 uses @code{A-Z} for 0 to 25, and @code{2-7}
17515 for 26 to 31. The ``base32hex'' variant uses
17516 @code{0-9} for 0 to 9, and @code{A-V} for 10 to 31.
17517 Since RFC states the latter should not be referred to as base32,
17518 we provide separate procedures for those encodings.
17519 @c JP
17520 RFC4648は基数32のエンコーディングとして2つの全く異なるアルファベットを規定しています。
17521 標準のBase32は@code{A-Z}を0から25に、@code{2-7}を26から31に使います。
17522 ``base32hex'' は@code{0-9}を0から9に、@code{A-V}を10から31に使います。
17523 RFCでは後者をbase32と呼ばないように言っているので、
17524 二つのエンコーディングに対応する別々の手続きを用意しました。
17525 @c COMMON
17526
17527 @defun base32-encode :key omit-padding line-width
17528 @defunx base32hex-encode :key omit-padding line-width
17529 @c MOD rfc.base64
17530 @c EN
17531 The procedures are port-based; they read input from the
17532 current standard port, and emits the base32 or base32hex
17533 encoded result to the current output port.
17534 @c JP
17535 これらの手続きは現在の入力ポートからデータを読み、
17536 Base32またはBase32hexでエンコードされた結果を現在の出力ポートに書き出します。
17537 @c COMMON
17538
17539 @c EN
17540 The keyword arguments @var{omit-padding} and @var{line-width} are
17541 the same as @code{base64-encode}.
17542 @c JP
17543 キーワード引数@var{omit-padding}と@var{line-width}は
17544 @code{base64-encode}と同じです。
17545 @c COMMON
17546 @end defun
17547
17548 @defun base32-encode-message message :key omit-padding line-width
17549 @defunx base32hex-encode-message message :key omit-padding line-width
17550 @c MOD rfc.base64
17551 @c EN
17552 Base32 or Base32hex encode @var{message}, which should be a string or a u8vector,
17553 and returns the result in a string.
17554 @c JP
17555 文字列もしくはu8vectorの@var{message}をBase32/Base32hexでエンコードして、
17556 結果を文字列として返します。
17557 @c COMMON
17558
17559 @c EN
17560 The keyword arguments @var{omit-padding} and @var{line-width} are
17561 the same as @code{base64-encode}.
17562 @c JP
17563 キーワード引数@var{omit-padding}と@var{line-width}は
17564 @code{base64-encode}と同じです。
17565 @c COMMON
17566
17567 @example
17568 (base32-encode-message "Hau'oli makahiki hou!")
17569 @result{} "JBQXKJ3PNRUSA3LBNNQWQ2LLNEQGQ33VEE======"
17570 (base32hex-encode-message "Hau'oli makahiki hou!")
17571 @result{} "91GNA9RFDHKI0RB1DDGMGQBBD4G6GRRL44======"
17572 @end example
17573 @end defun
17574
17575 @defun base32-decode :key strict
17576 @defunx base32hex-decode :key strict
17577 @c MOD rfc.base64
17578 @c EN
17579 Read Base32/Base32hex encoded string from the current input port,
17580 and emits the decoded result to the current output port.
17581 @c JP
17582 Base32/Base32hexエンコードされた文字列を現在の入力ポートから読み、
17583 デコード結果を現在の出力ポートに書き出します。
17584 @c COMMON
17585
17586 @c EN
17587 If a true value is given to the @var{strict} argument,
17588 an error is thrown if non-whitespace illegal characters exist
17589 in the input, or the proper padding characters are missing.
17590 The default of @var{strict} is @code{#f} and illegal characters
17591 are just ignored.
17592 @c JP
17593 @var{strict}引数に真の値が与えられると、
17594 入力に空白文字でもエンコードに使われる文字でもない文字が現れたり、
17595 必要なパディング文字が無かったりした場合にエラーが投げられます。
17596 @var{strict}のデフォルト値は@code{#f}で、不正な文字は単に無視されます。
17597 @c COMMON
17598 @end defun
17599
17600 @defun base32-decode-string-to target string :key strict
17601 @defunx base32hex-decode-string-to target string :key strict
17602 @c MOD rfc.base64
17603 @c EN
17604 Decode a Base32/Base32hex encoded string @var{string}, and
17605 returns the result as an instance of class @var{target}, which
17606 must be either @code{<u8vector>} or @code{<string>}.
17607 @c JP
17608 Base32/Base32hexエンコードされた文字列@var{string}をデコードして、
17609 結果を@var{target}クラスのインスタンスとして返します。
17610 @var{target}はクラスオブジェクト@code{<u8vector>}か@code{<string>}
17611 でなければなりません。
17612 @c COMMON
17613
17614 @c EN
17615 The meaning of @var{strict} argument is the same as
17616 in @code{base32-decode}.
17617 @c JP
17618 @var{strict}引数の意味は@code{base32-decode}と同じです。
17619 @c COMMON
17620
17621 @example
17622 (base32-decode-string-to <string>
17623 "JBQXKJ3PNRUSA3LBNNQWQ2LLNEQGQ33VEE======")
17624 @result{} "Hau'oli makahiki hou!"
17625 @end example
17626
17627 @end defun
17628
17629 @subheading Base16
17630
17631 @c EN
17632 Base16 is simply the hexadecimal encoding of input octets.
17633 RFC4648 defines to use uppercase letters @code{A-F} for digits
17634 10 to 15. In practice, lowercase letters are also used
17635 for hexadecimal encoding, so we provide that option, too.
17636 @c JP
17637 Base16は入力オクテットの単純な16進数エンコーディングです。
17638 RFC4648では10から15の数字に大文字の@code{A-F}を当てていますが、
17639 16進数エンコーディングに小文字を使う場合も良くあるので、
17640 このライブラリではそのオプションも用意しています。
17641 @c COMMON
17642
17643 @defun base16-encode :key lowercase
17644 @c MOD rfc.base64
17645 @c EN
17646 Read data from the current input port, and emits Base16 encoded
17647 result to the current output port.
17648
17649 By default, @code{A-F} are used for digit 10 to 15, as specified
17650 in RFC4648. If @var{lowercase} argument is given and true,
17651 @code{a-f} are used instead.
17652
17653 Note that no padding character is ever generated in Base16 encoding.
17654 @c JP
17655 現在の入力ポートからデータを読み込み、Base16エンコードした結果を
17656 現在の出力ポートに書き出します。
17657
17658 デフォルトでは、RFC4648の規定により、10から15に大文字の@code{A-F}を使います。
17659 @var{lowercase}引数が与えられて真ならば、小文字の@code{a-f}を使います。
17660
17661 Base16エンコーディングではパディング文字は出力されません。
17662 @c COMMON
17663 @end defun
17664
17665 @defun base16-encode-message message :key lowercase
17666 @c MOD rfc.base64
17667 @c EN
17668 Base16 encode @var{message}, which should be a string or a u8vector,
17669 and returns the result in a string. The @var{lowercase} argument
17670 is the same as @code{base16-encode}.
17671 @c JP
17672 文字列もしくはu8vectorの@var{message}をBase16エンコードして、
17673 結果を文字列として返します。@var{lowercase}引数は@code{base16-encode}と同じです。
17674 @c COMMON
17675
17676 @example
17677 (base16-encode-message "Aloha")
17678 @result{} "416C6F6861"
17679 (base16-encode-message "Aloha" :lowercase #t)
17680 @result{} "416c6f6861"
17681 @end example
17682 @end defun
17683
17684 @defun base16-decode :key strict
17685 @c MOD rfc.base64
17686 @c EN
17687 Read Base16 encoded string from the current input port,
17688 and emits the decoded result to the current output port.
17689 @c JP
17690 Base16エンコードされた文字列を現在の入力ポートから読み、
17691 デコード結果を現在の出力ポートに書き出します。
17692 @c COMMON
17693
17694 @c EN
17695 By default, characters other than Base16 digits are ignored,
17696 and both upperase and lowercase alphabets are recognized.
17697 If @var{strict} argument is given and true, however,
17698 characters other than @code{#[0-9A-F]} throws an error.
17699 @c JP
17700 デフォルトでは、Base16アルファベット以外の文字は無視され、
17701 また大文字も小文字も認識されます。
17702 @var{strict}引数が与えられて真ならば、
17703 @code{#[0-9A-F]}以外の文字が見つかるとエラーが投げられます。
17704 @c COMMON
17705 @end defun
17706
17707 @defun base16-decode-string-to target string :key strict
17708 @c MOD rfc.base64
17709 @c EN
17710 Decode Base16-encoded string @var{string}, and returns
17711 the result as an instance of class @var{target}, which must
17712 be either @code{<u8vector>} or @code{<string>}.
17713
17714 The @var{strict} argument is the same as @code{base16-decode}.
17715 @c JP
17716 Base16エンコードされた文字列@var{string}をデコードして、
17717 結果をクラス@var{target}のインスタンスで返します。
17718 @var{target}は@code{<u8vector>}か@code{<string>}でなければなりません。
17719
17720 @var{strict}引数は@code{base16-decode}と同じです。
17721 @c COMMON
17722
17723 @example
17724 (base16-decode-string-to <u8vector> "416c6f6861")
17725 @result{} #u8(65 108 111 104 97)
17726 (base16-decode-string-to <string> "416c6f6861")
17727 @result{} "Aloha"
17728 @end example
17729 @end defun
17730
17731 @c EN
17732 @subheading Deprecated API
17733 @c JP
17734 @subheading 非推奨API
17735 @c COMMON
17736
17737 @c EN
17738 The following API is deprecated. Avoid using them in new code.
17739 @c JP
17740 以下のAPIは非推奨となりました。新規コードでは使わないでください。
17741 @c COMMON
17742
17743
17744 @defun base64-encode-string string :key line-width digits url-safe
17745 @defunx base64-encode-bytevector u8vector :key line-width digits url-safe
17746 @c MOD rfc.base64
17747 @c DEPRECATED
17748 @c EN
17749 Converts contents of @var{string}/@var{u8vector} to Base64 encoded format.
17750 For @code{base64-encode-string},
17751 input string can be either complete or incomplete string;
17752 it is always interpreted as a byte sequence.
17753 The @var{digits} and @var{url-safe} arguments are the same as
17754 @code{base64-encode}.
17755 @c JP
17756 @var{string}/@var{u8vector} の内容を Base64 でエンコードされたフォーマットに変換します。
17757 @code{base64-encode-string}の入力となる文字列は、
17758 完全文字列でも不完全文字列でも良いです。常にバイト・シーケンスとして扱われます。
17759 @var{digits}と@var{url-safe}引数は@code{base64-encode}と同じです。
17760 @c COMMON
17761 @end defun
17762
17763 @defun base64-decode-string string :key url-safe strict
17764 @defunx base64-decode-bytevector u8vector :key url-safe strict
17765 @c MOD rfc.base64
17766 @c DEPRECATED
17767 @c EN
17768 Decodes a Base64 encoded string @var{string} and returns
17769 the result as a string or a u8vector, respectively.
17770 The conversion terminates at the end of @var{string} or
17771 the termination character (@code{=}).
17772 @c JP
17773 Base64 でエンコードされた文字列 @var{string} をデコードしてそれぞれ文字列
17774 あるいはu8vectorとして返します。
17775 変換は @var{string} の終わりか、終端文字 (@code{=}) で終了します。
17776 @c COMMON
17777
17778 @c EN
17779 The characters which are not in legal Base64 encoded character set are
17780 silently ignored by default. If a true value is given to the
17781 @var{strict} keyword argument, however, non-whitespace out-of-set characters
17782 in the input raises an error.
17783 @c JP
17784 Base64 でエンコードされた文字として適当でない文字は、デフォルトでは黙って無視されます。
17785 ただし、@var{strict}キーワード引数に真の値が与えられた場合は、
17786 空白文字以外の不適切な文字が入力にあったらそこでエラーが投げられます。
17787 @c COMMON
17788
17789 @c EN
17790 The @var{digits} and @var{url-safe} arguments are the same as
17791 @code{base64-encode}.
17792 @c JP
17793 @var{digits}と@var{url-safe}引数は@code{base64-encode}と同じです。
17794 @c COMMON
17795 @end defun
17796
17797 @c ----------------------------------------------------------------------
17798 @node HTTP cookie handling, FTP, Base64 encoding/decoding, Library modules - Utilities
17799 @section @code{rfc.cookie} - HTTP cookie handling
17800 @c NODE HTTPクッキー, @code{rfc.cookie} - HTTPクッキー
17801
17802 @deftp {Module} rfc.cookie
17803 @mdindex rfc.cookie
17804 @c EN
17805 Defines a set of functions to parse and construct a ``cookie'' information
17806 defined in RFC 6265.
17807 @c JP
17808 RFC 6265で定義されている「クッキー」情報を
17809 パースしたり構築したりするための手続きを定義しています。
17810 @c COMMON
17811 @end deftp
17812
17813 @defun parse-cookie-string string :optional version
17814 @c MOD rfc.cookie
17815 @c EN
17816 Parse a cookie string @var{string}, which is the value of ``Cookie''
17817 request header. Usually, the same information is available to CGI
17818 program via the environment variable @code{HTTP_COOKIE}.
17819
17820 If the cookie version is known, via ``Cookie2'' request header,
17821 the integer version must be passed to @var{version}. Otherwise,
17822 @code{parse-cookie-string} figures out the version from @var{string}.
17823
17824 The result has the following format.
17825 @c JP
17826 リクエスト・ヘッダの Cookie の値のクッキー文字列 @var{string} を
17827 パースします。通常、CGI プログラムでは、同じ情報は環境変数
17828 @var{HTTP_COOKIE} を通して利用できます。
17829
17830 リクエスト・ヘッダ Cookie2 を通してクッキーのバージョンが分かる
17831 場合は、@var{version} へ整数のバージョンとして渡されなければなりません。
17832 そうでなければ、@code{parse-cookie-string} は @var{string} からバージョンを
17833 取り出します。
17834
17835 結果は以下のフォーマットを持ちます。
17836 @c COMMON
17837 @example
17838 ((<name> <value> [:path <path>] [:domain <domain>] [:port <port>])
17839 @dots{})
17840 @end example
17841 @c EN
17842 where @var{<name>} is the attribute name, and @var{<value>} is
17843 the corresponding value. If the attribute doesn't have value,
17844 @var{<value>} is @code{#f}. (Note that it differs from the attribute
17845 having null value, @code{""}.)
17846 If the attribute has path, domain or port options, it is given
17847 as a form of keyword-value pair.
17848 @c JP
17849 @var{<name>} は属性名で、@var{<value>} は対応する値です。
17850 属性が値を持たない場合、@var{<value>} は @code{#f} になります。
17851 (属性が NULL 値を持つ場合は、@code{""} となることに注意。)
17852 属性がパスやドメイン、ポート番号のオプションを持つ場合は、
17853 キーワード-値のペアの形式で与えられます。
17854 @c COMMON
17855
17856 @c EN
17857 Note: To retrieve the value of a specific cookie conveniently, you can use
17858 @code{rfc822-header-ref} (@pxref{RFC822 message parsing}).
17859 @c JP
17860 註: 特定のクッキーの値を簡単に取り出すには
17861 @code{rfc822-header-ref}が使えます (@ref{RFC822 message parsing}参照)。
17862 @c COMMON
17863 @end defun
17864
17865 @defun construct-cookie-string specs :optional version
17866 @c MOD rfc.cookie
17867 @c EN
17868 Given list of cookie specs, creates a cookie string suitable for
17869 @code{Set-cookie2} or @code{Set-cookie} header.
17870
17871 Optional @var{version} argument is accepted but ignored; it's for the backward
17872 compatibility.
17873
17874 Each cookie spec has the following format.
17875 @c JP
17876 与えられたクッキーの仕様のリストから、@code{Set-cookie2} か
17877 @code{Set-cookie} ヘッダに適切なクッキー文字列を作ります。
17878
17879 オプションの @var{version} 引数は、互換性のために受容されますが無視されます。
17880
17881 クッキーの仕様は以下のフォーマットを持ちます。
17882 @c COMMON
17883 @example
17884 (<name> <value> [:expires <data/time>] [:max-age <age>]
17885 [:domain <domain>] [:path <path>]
17886 [:secure <boolean>] [:http-only <boolean>]
17887 @end example
17888 @c EN
17889 Where,
17890 @table @code
17891 @item <name>
17892 A string. Name of the cookie.
17893 @item <value>
17894 Value of the cookie. May be a string, or @code{#f} if no value is needed.
17895 @item <domain> <path>
17896 Strings.
17897 @item <boolean>
17898 Boolean value
17899 @item <age>
17900 Non-negative exact integers
17901 @item <date/time>
17902 Either an integer (seconds since Epoch), a formatted date string,
17903 @code{<time>} or @code{<date>} objects
17904 (@pxref{Time}, @pxref{Time data types and procedures}).
17905 @end table
17906 @c JP
17907 @table @code
17908 @item <name>
17909 文字列。クッキーの名前。
17910 @item <value>
17911 クッキーの値。文字列か、値が必要なければ @code{#f} 。
17912 @item <domain> <path>
17913 文字列。
17914 @item <boolean>
17915 真偽値。
17916 @item <age>
17917 非負の正確な整数。
17918 @item <date/time>
17919 整数(エポックからの秒数)か、Netscape のクッキー仕様に従うフォーマットされた
17920 日付文字列か、@code{<time>}もしくは@code{<date>}オブジェクト
17921 (@ref{Time},および @ref{Time data types and procedures}参照)。
17922 @end table
17923 @c COMMON
17924
17925 @c EN
17926 The order of attributes does not matter.
17927 The attribute values are quoted appropriately.
17928
17929 For the backward compatibility to the older specification
17930 (RFC2965, RFC2109, and old Netscape cookie specification), it
17931 recognizes a few more attributes (@code{comment}, @code{comment-url},
17932 @code{discard}, @code{port}, and @code{version}). They are rendered
17933 to the output, but the new code should not use them.
17934
17935 Return value is a list of cookie strings, each of which stands for
17936 each cookie. For old-style protocol (using @code{Set-cookie} header)
17937 you must send each of them by individual header. For new-style
17938 protocol (using @code{Set-cookie2} header), you can join them
17939 with comma and send it at once. See RFC6265 for further details.
17940
17941 Example:
17942 @c JP
17943 属性の指定は順不同です。属性値は適切にクォートされます。
17944
17945 互換性のために、古い規格(RFC2965, RFC2109, 古のNetscape cookie specificaiton)
17946 で指定されていたいくつかの属性も認識され出力に含められます
17947 (@code{comment}, @code{comment-url}, @code{discard}, @code{port},
17948 @code{version})。が、新規のコードではこれらの属性を使うべきではありません。
17949
17950 戻り値はそれぞれのクッキー文字列のリストです。(@code{Set-cookie} を使う)
17951 古いスタイルのプロトコルでは、それぞれを独立したヘッダとして送らなければ
17952 なりません。(@code{Set-cookie2} ヘッダを使う)新しいプロトコルでは、
17953 それらをカンマで繋ぎ、一度に送ることができます。詳細は RFC6265 を見て下さい。
17954
17955 例:
17956 @c COMMON
17957 @example
17958 (construct-cookie-string
17959 `(("name" "foo" :domain "foo.com" :path "/" :max-age 86400)))
17960 @result{} ("name=foo;Domain=foo.com;Path=/;Max-age=86400")
17961 @end example
17962 @end defun
17963
17964 @c ----------------------------------------------------------------------
17965 @node FTP, HMAC keyed-hashing, HTTP cookie handling, Library modules - Utilities
17966 @section @code{rfc.ftp} - FTP client
17967 @c NODE FTPクライアント, @code{rfc.ftp} - FTPクライアント
17968
17969 @deftp {Module} rfc.ftp
17970 @mdindex rfc.ftp
17971 @c EN
17972 This module provides a set of convenient functions to access ftp
17973 servers.
17974 @c JP
17975 このモジュールはFTPサーバーにアクセスするための便利関数群を提供します。
17976 @c COMMON
17977 @end deftp
17978
17979 @deftp {Class} <ftp-connection>
17980 @clindex ftp-connection
17981 @c MOD rfc.ftp
17982 @c EN
17983 An object to keep FTP connection to a server. It has the following
17984 public slots.
17985 @c JP
17986 ひとつのサーバーへのFTPコネクションを保持するオブジェクト。以下の公開
17987 スロットがあります。
17988 @c COMMON
17989
17990 @defivar {<ftp-connection>} transfer-type
17991 @c EN
17992 FTP transfer type. Must be one of the following symbols:
17993 @code{ascii}, @code{binary} (default), and @code{image}.
17994 @c JP
17995 FTPの転送タイプ。以下のシンボルのどれかひとつでなければなりません。
17996 @code{ascii}、@code{binary} (デフォルト)、および@code{image}。
17997 @c COMMON
17998 @end defivar
17999
18000 @defivar {<ftp-connection>} passive
18001 @c EN
18002 True if the client uses passive connection.c
18003 @c JP
18004 パッシブコネクションを使うとき真。
18005 @c COMMON
18006 @end defivar
18007
18008 @defivar {<ftp-connection>} log-drain
18009 @c EN
18010 This slot must hold a @code{<log-drain>} instance (@pxref{User-level logging})
18011 or @code{#f}. If it has a @code{<log-drain>} instance, ftp communication
18012 logs are put to it.
18013 @c JP
18014 このスロットは@code{<log-drain>}のインスタンス(@ref{User-level logging}参照)
18015 を保持しているかあるいは@code{#f}でなければなりません。@code{<log-drain>}
18016 のインスタンスを保持している場合、FTP通信のログがそこに記録されます。
18017 @c COMMON
18018
18019 @end defivar
18020 @end deftp
18021
18022 @deftp {Condition Type} <ftp-error>
18023 @clindex ftp-error
18024 @c MOD rfc.ftp
18025 @c EN
18026 This type of exception is thrown when the ftp server returns an error code.
18027 Inherits @code{<error>}. The message field contains the server reply,
18028 including the status code.
18029 @c JP
18030 このタイプの例外はFTPサーバーがエラーコードを返したときに投げられます。
18031 @code{<error>}を継承しています。メッセージフィールドにはステータスコー
18032 ドを含むサーバーからの返答が含まれます。
18033 @c COMMON
18034 @end deftp
18035
18036 @defun call-with-ftp-connection host proc :key passive port username password account log-drain
18037 @c MOD rfc.ftp
18038 @c EN
18039 A high-level convenience routine to open an ftp connection to
18040 an ftp server and calls the given procedure.
18041 @c JP
18042 高水準の便利関数で、ひとつのFTPサーバーへのFTPコネクションをオープンし、
18043 与えられた手続きを呼びます。
18044 @c COMMON
18045
18046 @c EN
18047 The server is specified by @var{host}. Optionally, you can add user
18048 name and/or port number by the form
18049 @code{@var{user}@@@var{servername}:@var{port}}.
18050 If present, user and port portion in @var{host} supersedes the
18051 keyword arguments.
18052 @c JP
18053 接続するサーバーは@var{host}で指定します。オプションでユーザー名、ポー
18054 ト番号を@code{@var{user}@@@var{servername}:@var{port}}という形式で指定
18055 できます。もしあれば、@var{host}の部分をキーワード引数にすることもでき
18056 ます。
18057 @c COMMON
18058
18059 @c EN
18060 If ftp connection to @var{host} is established successfully,
18061 @var{proc} is called with one argument, which is an instance
18062 of @code{<ftp-connection>}. When @var{proc} returns,
18063 the connection is closed and the return value(s) of @var{proc}
18064 is/are returned from @code{call-with-ftp-connection}.
18065 When an exception is thrown, the ftp connection is closed
18066 before the exception escapes from @code{call-with-ftp-connection}.
18067 @c JP
18068 @var{host}へのFTPコネクション確立が成功したら、@var{proc}が引数を1つとっ
18069 て呼ばれます。この引数は@code{<ftp-connection>}のインスタンスです。
18070 @var{proc}から返ったときにこのコネクションはクローズされ、@var{proc}の
18071 返り値が@code{call-with-ftp-connection}から返されます。例外がなげられ
18072 たら、その例外が@code{call-with-ftp-connection}から外へでる前にFTPコネ
18073 クションはクローズされます。
18074 @c COMMON
18075
18076 @c EN
18077 When a true value is given to the keyword argument @var{passive},
18078 created ftp connection will use passive mode to send/receive
18079 data. The default is the active mode.
18080 @c JP
18081 キーワード引数@var{passive}に真値を与えると、FTPコネクションはパッシブ
18082 モードになります。デフォルトではアクティブモードです。
18083 @c COMMON
18084
18085 @c EN
18086 The keyword argument @var{port}, @var{username}, and @var{password}
18087 specify the port number, username, and password, respectively.
18088 When omitted, the port number defaults to 21, @var{username} to
18089 @code{"anonymous"}, and @var{password} to @code{"anonymous@@"}.
18090 Note that the port number and/or username are ignored when
18091 those information is given in the @var{host} argument.
18092 @c JP
18093 キーワード引数@var{port}、@var{username}および@var{password}は
18094 それぞれ、ポート番号、ユーザー名、パスワードを指定するのに使います。
18095 省略された場合のデフォルトは、ポート番号が21,@var{username}が
18096 @code{"anonymous"}、@var{password}が@code{"anonymous@@"}にセットされま
18097 す。ポート番号とユーザー名は@var{host}引数で指定されたものが優先されま
18098 す。
18099 @c COMMON
18100
18101 @c EN
18102 If the keyword argument @var{account} is given, its value
18103 is passed to ftp @code{ACCT} command when requested by
18104 the server at login time. The default value is a null string @code{""}.
18105 @c JP
18106 キーワード引数@var{account}が与えられた場合には、その値が、ログイン時
18107 にサーバーからの要求でFTPの@code{ACCT}コマンドに渡されます。デフォルト
18108 では空文字列@code{""}です。
18109 @c COMMON
18110
18111 @c EN
18112 The keyword argument @var{log-drain} is set to the created
18113 ftp connection's @code{log-drain} slot.
18114 @c JP
18115 キーワード引数@var{log-drain}が生成したFTPコネクションの
18116 @code{log-drain}スロットに設定されます。
18117 @c COMMON
18118 @end defun
18119
18120 @defun ftp-transfer-type conn
18121 @c MOD rfc.ftp
18122 @c EN
18123 Returns the transfer type of the ftp connection @code{conn}.
18124 Can be used with setter, e.g. @code{(set! (ftp-transfer-type conn) 'ascii)}.
18125 @c JP
18126 指定したFTPコネクション@code{conn}の転送タイプを返します。セッターを適
18127 用することもできます。たとえば、@code{(set! (ftp-transfer-type conn) 'ascii)}
18128 とします。
18129 @c COMMON
18130 @end defun
18131
18132 @defun ftp-passive? conn
18133 @c MOD rfc.ftp
18134 @c EN
18135 Returns true iff ftp connection uses passive data retrieval.
18136 @c JP
18137 指定したFTPコネクションがパッシブモードである場合でその場合に限り真を
18138 返します。
18139 @c COMMON
18140 @end defun
18141
18142 @defun ftp-login host :key passive port username password account log-drain
18143 @c MOD rfc.ftp
18144 @c EN
18145 Connects to the ftp server specified by @var{host}, authenticate the user,
18146 and returns a newly created @code{<ftp-connection>} instance.
18147 This procedure is called implicitly when you use
18148 @code{call-with-ftp-connection}. The semantics of
18149 the @var{host} argument and the keyword arguments are
18150 the same as @code{call-with-ftp-connection}.
18151 @c JP
18152 @var{host}で指定されたFTPサーバーに接続し、ユーザー認証をすませ、新し
18153 く生成した@code{<ftp-connection>}のインスタンスを返します。この手続き
18154 は@code{call-with-ftp-connection}を使ったときに暗黙の内に呼ばれます。
18155 @var{host}引数およびキーワード引数のセマンティクスは
18156 @code{call-with-ftp-connection}と同じです。
18157 @c COMMON
18158 @end defun
18159
18160 @defun ftp-quit conn
18161 @c MOD rfc.ftp
18162 @c EN
18163 Sends ftp @code{QUIT} command to the connection @var{conn} and
18164 shutdown the connection.
18165 This procedure is called implicitly when you use
18166 @code{call-with-ftp-connection}.
18167 @c JP
18168 FTPの@code{QUIT}コマンドをコネクション@var{conn}に送り、コネクションを
18169 シャットダウンします。この手続きは@code{call-with-ftp-connection}を使っ
18170 たときに暗黙の内に呼ばれます。
18171 @c COMMON
18172
18173 @c EN
18174 Once a connection is shut down, you cannot communicate through
18175 this connection.
18176 @c JP
18177 いったんシャットダウンしたコネクションをつかっての通信はできません。
18178 @c COMMON
18179 @end defun
18180
18181 @defun ftp-chdir conn dirname
18182 @c MOD rfc.ftp
18183 @c EN
18184 Changes the remote directory to @var{dirname}.
18185 @c JP
18186 リモートディレクトリを@var{dirname}に変更します。
18187 @c COMMON
18188 @end defun
18189
18190 @defun ftp-remove conn path
18191 @c MOD rfc.ftp
18192 @c EN
18193 Removes the remote file named by @var{path}.
18194 @c JP
18195 @var{path}で指定したリモートファイルを削除します。
18196 @c COMMON
18197 @end defun
18198
18199 @defun ftp-help conn :optional option @dots{}
18200 @c MOD rfc.ftp
18201 @c EN
18202 Sends ftp @code{HELP} commands. @var{Option}s must be strings,
18203 and will be passed to the @code{HELP} command arguments.
18204 @c JP
18205 FTPコマンド@code{HELP}を送ります。@var{Option}は文字列でなければなりま
18206 せん。これは@code{HELP}コマンドの引数にわたされます。
18207 @c COMMON
18208 @end defun
18209
18210 @defun ftp-mkdir conn dirname
18211 @c MOD rfc.ftp
18212 @c EN
18213 Creates a directory @var{dirname}. Returns the created directory
18214 name.
18215 @c JP
18216 ディレクトリ@var{dirname}を作成します。作成されたディレクトリ名が返り
18217 ます。
18218 @c COMMON
18219 @end defun
18220
18221 @defun ftp-current-directory conn
18222 @c MOD rfc.ftp
18223 @c EN
18224 Returns the current remote directory.
18225 @c JP
18226 現在のリモートディレクトリを返します。
18227 @c COMMON
18228 @end defun
18229
18230 @defun ftp-site conn arg
18231 @c MOD rfc.ftp
18232 @c EN
18233 Sends ftp @code{SITE} command with the argument @var{arg}.
18234 The @code{SITE} command's semantics depends on the server.
18235 Returns the server reply.
18236 @c JP
18237 FTPコマンド@code{SITE}を引数@var{arg}とともに送ります。@code{SITE}コマ
18238 ンドのセマンティクスはサーバーに依存します。返り値はサーバーのリプライ
18239 です。
18240 @c COMMON
18241 @end defun
18242
18243 @defun ftp-rmdir conn dirname
18244 @c MOD rfc.ftp
18245 @c EN
18246 Removes remote directory specified by @var{dirname}.
18247 Returns the server reply.
18248 @c JP
18249 @var{dirname}で指定したリモートディレクトリを削除します。返り値はサー
18250 バーのリプライです。
18251 @c COMMON
18252 @end defun
18253
18254 @defun ftp-stat conn :optional pathname
18255 @c MOD rfc.ftp
18256 @c EN
18257 Sends ftp @code{STAT} command to the server.
18258 RFC959 defines several different semantics of this command.
18259 See RFC959 for the details.
18260 Returns the server reply.
18261 @c JP
18262 FTPコマンド@code{STAT}をサーバーに送信します。
18263 RFC959ではこのコマンドのセマンティクスをいくつか定義しています。詳細は
18264 RFC959を見てください。返り値はサーバーのリプライです。
18265 @c COMMON
18266 @end defun
18267
18268 @defun ftp-system conn
18269 @c MOD rfc.ftp
18270 @c EN
18271 Queries the server's operating system by ftp @code{SYST} command.
18272 Returns the server reply without status code.
18273 @c JP
18274 FTPコマンド@code{SYST}をつかってサーバーのオペレーティングシステムを問
18275 合せます。返り値はステータスコードを含まないサーバーのリプライです。
18276 @c COMMON
18277
18278 @example
18279 (call-with-ftp-connection "localhost" ftp-system)
18280 @result{} "UNIX Type: L8"
18281 @end example
18282 @end defun
18283
18284 @defun ftp-size conn path
18285 @c MOD rfc.ftp
18286 @c EN
18287 Queries the size of the remote file specified by @var{path}.
18288 Returns the integer value.
18289
18290 Note: The size may differ whether the connection is in ascii mode
18291 or binary mode; furthermore, some ftp server may returns the value
18292 only if the connection is in binary mode. Make sure you have
18293 desired transfer type in the connection.
18294 @c JP
18295 @var{path}で指定したリモートファイルのサイズを問合せます。
18296 整数値が返ります。
18297
18298 註:コネクションがasciiモードかbinaryモードかによって、返されるサイズは
18299 異なるかもしれません。ftpサーバによっては、binaryモードでしか
18300 sizeリクエストに答えないものもあります。この関数を呼ぶ際には、
18301 コネクションに望みのtransfer typeがセットされているようにしてください。
18302 @c COMMON
18303 @end defun
18304
18305 @defun ftp-mdtm conn path
18306 @c MOD rfc.ftp
18307 @c EN
18308 Queries the modification time of the remote file specified by @var{path}.
18309 This function returns the server's reply as is, including the status
18310 code. Use @code{ftp-mtime} below to obtain a parsed result.
18311 @c JP
18312 @var{path}で指定したリモートファイルの更新時刻を問合せます。この関数は
18313 サーバーからのリプライをステータスコードも含めそのまま返します。解析済
18314 みの結果が欲しいときは後述の@code{ftp-mtime}を使ってください。
18315 @c COMMON
18316 @end defun
18317
18318 @defun ftp-mtime conn path :optional local-time?
18319 @c MOD rfc.ftp
18320 @c EN
18321 Queries the modification time of the remote file specified by @var{path},
18322 and returns the result in a @code{<date>} object
18323 (@pxref{Time data types and procedures}).
18324 If a true value is given to @code{local-time?}, the returned date is
18325 in local time. Otherwise, the returned date is in UTC.
18326 @c JP
18327 @var{path}で指定したリモートファイルの更新日時を問合せます。結果は
18328 @code{<date>}オブジェクト(@ref{Time data types and procedures}参照)で
18329 返ります。@code{local-time?}が真値に設定されている場合、日付はローカル
18330 時刻で返ります。そうでない場合は日付はUTCです。
18331 @c COMMON
18332 @end defun
18333
18334 @defun ftp-noop conn
18335 @c MOD rfc.ftp
18336 @c EN
18337 Sends ftp @code{NOOP} command and returns the server's reply.
18338 @c JP
18339 FTPコマンド@code{NOOP}を送り、サーバーからのリプライを返します。
18340 @c COMMON
18341 @end defun
18342
18343 @defun ftp-list conn :optional path
18344 @c MOD rfc.ftp
18345 @c EN
18346 Returns the information about the files within the remote file
18347 or directory specified by @var{path}, or the current remote directory,
18348 much like @code{ls(1)} format. Returns a list of strings, where
18349 each string is for each line of the server's reply. The exact
18350 format depends on the server.
18351 @c JP
18352 @var{path}で指定されたリモートディレクトリあるいはリモートファイル内の
18353 ファイルに関する情報を返します。@var{path}指定がない場合は現在のリモー
18354 トディレクトリで、結果のフォーマットは@code{ls(1)}のフォーマットと非常
18355 によく似ています。文字列のリストが返り、それぞれの文字列はサーバーのリ
18356 プライの行に対応します。正確なフォーマットについてはサーバーに依存しま
18357 す。
18358 @c COMMON
18359 @end defun
18360
18361 @defun ftp-name-list conn :optional path
18362 @defunx ftp-ls conn :optional path
18363 @c MOD rfc.ftp
18364 @c EN
18365 Return the list of names in the specified @var{path}, or the current
18366 remote directory, without any other information. @code{ftp-ls}
18367 is just an alias of @code{ftp-name-list} for the convenience.
18368 @c JP
18369 @var{path}で指定したパスもしくは現在のリモートディレクトリにあるファイ
18370 ル名リストを返します。ただし、他の情報は含みません。@code{ftp-ls}は
18371 @code{ftp-name-list}の別名です。便利なので定義してあります。
18372 @c COMMON
18373
18374 @c EN
18375 Note that the server may return an error if there's no files
18376 in the remote directory.
18377 @c JP
18378 リモートディレクトリにファイルが含まれていないときにはサーバーはエラー
18379 を返すことがあることに注意してください。
18380 @c COMMON
18381 @end defun
18382
18383 @defun ftp-get conn path :key sink flusher
18384 @c MOD rfc.ftp
18385 @c EN
18386 Retrieves a remote file @var{path}. The retrieved data is
18387 sent to an output port given to @var{sink}. Once all the data
18388 is retrieved, a procedure given to @var{flusher} is called
18389 with the port @var{sink} as an argument, and its return value(s)
18390 is/are returned from @code{ftp-get}.
18391 @c JP
18392 リモートファイル@var{path}を検索します。検索データは@var{sink}で与えら
18393 れた出力ポートに送られます。すべてのデータが検索されたあと、
18394 @var{flusher}で与えられた手続きをポート@var{sink}を引数として呼びます。
18395 返り値は@code{ftp-get}から返されたものです。
18396 @c COMMON
18397
18398 @c EN
18399 The default values of @var{sink} and @var{flusher} are
18400 a newly created string port and @code{get-output-string}, respectively.
18401 That is, @code{ftp-get} returns the retrieved data as a string
18402 by default.
18403 You don't want this behavior if the retrieved file is huge.
18404 @c JP
18405 @var{sink}および@var{flusher}のデフォルト値はそれぞれ、新しく作成され
18406 た文字列ポートと@code{get-output-string}です。すなわち、@code{ftp-get}
18407 はデフォルトでは検索データを文字列として返します。巨大なファイルの場合
18408 このデフォルトの挙動ではありがたくありません。
18409 @c COMMON
18410 @end defun
18411
18412 @defun ftp-put conn from-file :optional to-file
18413 @c MOD rfc.ftp
18414 @c EN
18415 Sends the local file specified by @var{from-file} to the remote
18416 server as the name specified by @var{to-file}. If @var{to-file}
18417 is omitted, the basename of @var{from-file} is used.
18418 Returns the server response.
18419 @c JP
18420 @var{from-file}で指定したローカルファイルを@var{to-file}で指定した名前
18421 でリモートサーバーに送信します。@var{to-file}が省略された場合にはベー
18422 ス名として@var{from-file}が使われます。返り値はサーバーのレスポンスで
18423 す。
18424 @c COMMON
18425 @end defun
18426
18427 @defun ftp-put-unique conn from-file
18428 @c MOD rfc.ftp
18429 @c EN
18430 Sends the local file specified by @var{from-file} to the
18431 remote server. The remote side filename is guaranteed to
18432 be unique. Returns two values---the final server response,
18433 and the remote file name. The second value can be @code{#f}
18434 if the remote host doesn't support RFC1123 (which must be rare).
18435 @c JP
18436 @var{from-file}で指定したローカルファイルをリモートサーバーへ送信しま
18437 す。リモート側のファイル名重複しないことを保証します。返り値は2つで、
18438 最終的なリモートサーバーからのレスポンスとリモートファイル名です。2つ
18439 めの値は、リモートサーバーがRFC1123をサポートしていない(ほとんどない)
18440 場合に@code{#f}になります。
18441 @c COMMON
18442 @end defun
18443
18444 @defun ftp-rename conn from-name to-name
18445 @c MOD rfc.ftp
18446 @c EN
18447 Renames the remote file specified by @var{from-name} to the
18448 name @var{to-name}. Returns the final response of the server.
18449 @c JP
18450 @var{from-name}で指定したリモートファイル名を@var{to-name}に変更する。
18451 返り値は最終的なサーバーのレスポンスです。
18452 @c COMMON
18453 @end defun
18454
18455 @c ----------------------------------------------------------------------
18456 @node HMAC keyed-hashing, HTTP client, FTP, Library modules - Utilities
18457 @section @code{rfc.hmac} - HMAC keyed-hashing
18458 @c NODE HMAC鍵付きハッシング, @code{rfc.hmac} - HMAC鍵付きハッシング
18459
18460 @deftp {Module} rfc.hmac
18461 @mdindex rfc.hmac
18462 @c EN
18463 This module implements HMAC algorithm,
18464 Keyed-hashing for message authentication, defined in RFC 2104.
18465
18466 For simple batched keyed hashing, you can use high-level API
18467 @code{hmac-digest} and @code{hmac-digest-string}.
18468 Or you can create @code{<hmac>} object and update its state
18469 as the data coming in.
18470 @c JP
18471 このモジュールは、RFC 2104で定義されている、メッセージ認証のための
18472 鍵付きハッシングのHMACアルゴリズムを実装しています。
18473
18474 シンプルなバッチ処理での鍵付きハッシングでは、高レベルなAPIである
18475 @code{hmac-digest}と@code{hmac-digest-string}が使えます。
18476 あるいは、@code{<hmac>}オブジェクトを作成して、入力となるデータで
18477 その状態を更新することもできます。
18478 @c COMMON
18479
18480 @c EN
18481 Following is a typical way to digest a given string.
18482 @c JP
18483 以下は典型的なHMACハッシュを計算する例です。
18484 @c COMMON
18485
18486 @example
18487 (use rfc.sha) ; import desired digest algorithm
18488 (use rfc.hmac)
18489
18490 (hmac-message <sha256> "secret-key" "payload")
18491 @result{} #u8(16 170 46 28 37 56 70 79 247 95 6 71 39 30 59 167 70 188 163
18492 252 222 175 50 44 88 27 245 133 30 140 221 183)
18493
18494 (hmac-message-to 'hex <sha256> "secret-key" "payload")
18495 @result{} "10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7"
18496 @end example
18497 @end deftp
18498
18499 @c EN
18500 @subheading High-level API
18501 @c JP
18502 @subheading 高レベルAPI
18503 @c COMMON
18504
18505 @defun hmac-to target algorithm key
18506 @c MOD rfc.hmac
18507 @c EN
18508 Read input data from the current input port, and compute HMAC digest
18509 with a hash algorithm @var{hash-class} and a key @var{key}.
18510
18511 The result is returned as an instance of class @var{target}, which
18512 can be @code{<u8vector>} or @code{<string>}. Some symbols is also
18513 allowed to specify encoding: @code{base64}, @code{base64url},
18514 @code{base64url-nopad}, @code{base32}, @code{base32hex}, @code{base16},
18515 and @code{hex}. @xref{Message digester framework} for the details
18516 of those encodings.
18517
18518 The @var{hash-class} argument must be a class implementing
18519 @code{<message-digest-algorithm>}, such as @code{<sha256>}
18520 of @code{rfc.sha} (@pxref{SHA message digest}).
18521
18522 The key @var{key} may be a string or a u8vector.
18523 @c JP
18524 現在の入力ポートから読んだデータの鍵つきHMACダイジェストを計算します。
18525 @var{hash-class}はダイジェストアルゴリズムを指定するクラス、
18526 @var{key}はダイジェストに使う鍵です。
18527
18528 @var{target}は結果の返し方を指定します。クラスオブジェクト@code{<u8vector>}
18529 もしくは@code{<string>}の場合はそのインスタンスが返ります。
18530 @var{target}にはまた、エンコーディングを表す以下のシンボルを渡すこともできます:
18531 @code{base64}, @code{base64url},
18532 @code{base64url-nopad}, @code{base32}, @code{base32hex}, @code{base16},
18533 @code{hex}。詳しくは@ref{Message digester framework}を参照してください。
18534
18535 @var{hash-class}引数には@code{<message-digest-algorithm>}を実装している
18536 クラスを渡します。例えば@code{rfc.sha}モジュールの@code{<sha256>}です。
18537 (@ref{SHA message digest}参照)。
18538
18539 @var{key}は文字列かu8vectorでなければなりません。
18540 @c COMMON
18541 @end defun
18542
18543 @defun hmac-message-to target hash-class key message
18544 @c MOD rfc.hmac
18545 @c EN
18546 Returns an HMAC digest of @var{message},
18547 computed with a hash algorithm @var{hash-class},
18548 with a key @var{key}.
18549 @c JP
18550 @var{message}のHMACダイジェストを、
18551 @var{hash-class}をアルゴリズム、@var{key}を鍵として計算して返します。
18552 @c COMMON
18553
18554 @c EN
18555 The @var{hash-class} argument must be a class inheriting
18556 @code{<message-digest-algorithm>}, e.g. @code{<sha256>} class
18557 from @code{rfc.sha} (@pxref{SHA message digest}).
18558 @c JP
18559 @var{hash-class}引数は@code{<message-digest-algorithm>}を実装している
18560 クラスでなければなりません。例えば@code{rfc.sha}モジュールの@code{<sha256>}です。
18561 (@ref{SHA message digest}参照)。
18562 @c COMMON
18563
18564 @c EN
18565 You can pass both a stirng and a u8vector
18566 to @var{key}/@var{message}.
18567 @c JP
18568 @var{key}、@var{message}には文字列かu8vectorを渡せます。
18569 @c COMMON
18570
18571 @c EN
18572 The @var{target} can be a class in which the result is returned,
18573 either @code{<u8vector>} or @var{<string>}, or a symbol specifying
18574 the encoding: @code{base64}, @code{base64url},
18575 @code{base64url-nopad}, @var{base32}, @var{base32hex}, @code{base16},
18576 and @code{hex}. @xref{Message digester framework} for the details
18577 of those encodings.
18578 @c JP
18579 @var{target}は結果のを返すオブジェクトのクラスを指定します。
18580 @code{<u8vector>}と@code{<string>}がサポートされています。
18581 @var{target}にはまた、エンコーディングを表す以下のシンボルを渡すこともできます:
18582 @code{base64}, @code{base64url},
18583 @code{base64url-nopad}, @var{base32}, @var{base32hex}, @code{base16},
18584 @code{hex}。詳しくは@ref{Message digester framework}を参照してください。
18585 @c COMMON
18586 @end defun
18587
18588 @defun hmac-message hash-class key message
18589 @c MOD rfc.hmac
18590 @c EN
18591 A shortcut of @code{(hmac-message-to <u8vector> hash-class key message)}.
18592 @c JP
18593 @code{(hmac-message-to <u8vector> hash-class key message)}
18594 の短縮形です。
18595 @c COMMON
18596
18597 @example
18598 (hmac-message <sha256> "secret" "Aloha, honua")
18599 @result{} #u8(78 232 135 13 246 139 36 242 133 33 99 185 4 249 244
18600 22 243 46 120 130 192 235 60 187 172 180 223 169 179 247 186 185)
18601 @end example
18602 @end defun
18603
18604 @defun hmac-verify hash-class digest key message
18605 @c MOD rfc.hmac
18606 @c EN
18607 Verify @var{message} by comparing its digest with the given @var{digest}.
18608 Functionally it is @code{(equal? digest (hmac-message hash-class key message))},
18609 but the digests are compared in a way that can avoid timing attack.
18610
18611 @var{Hash-class} is a class inherits @code{<message-digest-algorithm>}
18612 such as @code{<sha256>}.
18613 @var{Digest} must be a u8vector. Either a string or a u8vector
18614 is allowed for each of @var{key} and @var{message}.
18615
18616 Returns @code{#t} if @var{digest} is valid digest for the message,
18617 @code{#f} if not.
18618 @c JP
18619 @var{message}の鍵つきダイジェストが@var{digest}と一致するかどうか調べます。
18620 機能的には@code{(equal? digest (hmac-message hash-class key message))}
18621 と同じですが、タイミングアタックを防ぐ比較が使われます。
18622
18623 @var{hash-class}は@code{<message-digest-algorithm>}を継承したクラス、
18624 例えば@code{<sha256>}です。@var{digest}はu8vectorでなければなりません。
18625 @var{key}と@var{message}には文字列edもu8vectorでも渡せます。
18626 @c COMMON
18627
18628 @example
18629 (hmac-verify <sha256>
18630 '#u8(78 232 135 13 246 139 36 242 133 33 99 185 4 249 244 22 243 46
18631 120 130 192 235 60 187 172 180 223 169 179 247 186 185)
18632 "secret"
18633 "Aloha, honua")
18634 @result{} #t
18635 @end example
18636 @end defun
18637
18638 @c EN
18639 @subheading Low-level API
18640 @c JP
18641 @subheading 低レベルAPI
18642 @c COMMON
18643
18644
18645 @deftp {Class} <hmac>
18646 @clindex hmac
18647 @c MOD rfc.hmac
18648 @c EN
18649 Keeps state information of HMAC algorithm. This should not be
18650 directly instantiated; use @code{make-hmac} below.
18651 @c JP
18652 HMACアルゴリズムの状態情報を保持します。インスタンスを作るには、
18653 このクラスを@code{make}するのではなく、下に示す@code{make-hmac}を使ってください。
18654 @c COMMON
18655 @end deftp
18656
18657 @defun make-hmac algorithm key
18658 @c MOD rfc.hmac
18659 @c EN
18660 Creates and returns a new @code{<hmac>} object. The @var{algorithm}
18661 argument is a class inheriting @code{<message-digest-algorithm>} to
18662 specify digest algorithm, for example, @code{<sha256>}
18663 (@pxref{SHA message digest}, for the details).
18664 The @var{key} argument is a key, either a string or a u8vector.
18665 @c JP
18666 新たな@code{<hmac>}オブジェクトを作って返します。
18667 @var{algorithm}引数は@code{<message-digest-algorithm>}を継承する
18668 クラスで、ダイジェストアルゴリズムを指定します。
18669 例えば@code{<sha256>}が使えます。詳しくは@ref{SHA message digest}参照。
18670 @var{key}引数は文字列かu8vectorで鍵を指定します。
18671 @c COMMON
18672
18673 @c EN
18674 When you use high-level APIs such as @code{hmac-message}, you don't
18675 need to make an @code{<hmac>} object since it is implicitly created.
18676 You only need to create it explicitly to use the following
18677 streaming update procedures.
18678 @c JP
18679 @code{hmac-message}などの高レベルAPIを使う場合、
18680 @code{<hmac>}オブジェクトは内部で自動的に作られるので明示的にmakeする必要はありません。
18681 下のストリーム更新手続きを使う場合だけ、@code{<hmac>}オブジェクトを
18682 明示的に作る必要があります。
18683 @c COMMON
18684 @end defun
18685
18686 @deffn {Method} hmac-update! (hmac <hmac>) data
18687 @c MOD rfc.hmac
18688 @c EN
18689 Updates the internal state of @var{hmac} by @var{data},
18690 which must be represented by a (possibly incomplete) string.
18691 @c JP
18692 (不完全かもしれない)文字列で表現される@var{data}により、
18693 @var{hmac}の内部状態を更新します。
18694 @c COMMON
18695 @end deffn
18696
18697 @deffn {Method} hmac-final! (hmac <hmac>) :optional target
18698 @c MOD rfc.hmac
18699 @c EN
18700 Finalizes the internal state of @var{hmac} and returns the
18701 digest in an instance of @var{target}, which must be
18702 a @code{<string>} or @code{<u8vector>} class metaobject,
18703 or a symbol to specify encoding. See @code{hmac-to} above for the
18704 details of @var{target}. The default is @code{<string>}, for a
18705 historical reason.
18706
18707 Once finalized, you can't call @code{hmac-update!} or @code{hmac-final!}
18708 on @var{hmac}.
18709 @c JP
18710 @var{hmac}の内部状態を終了させ、ダイジェストを@var{target}で指定される
18711 インスタンスで返します。@var{target}はクラスオブジェクト@code{<string>}
18712 または@code{<u8vector>}、あるいはエンコーディングを示すシンボルでなければ
18713 なりません。@var{target}について詳しくは上の@code{hmac-to}の項を参照してください。
18714 @var{target}が省略された場合は、歴史的な理由から@code{<string>}が使われます。
18715
18716 一旦終了されると、@var{hmac}に対しては@code{hmac-update!}や
18717 @code{hmac-final!}を呼ぶことはできません。
18718 @c COMMON
18719 @end deffn
18720
18721 @c EN
18722 @subheading Deprecated API
18723 @c JP
18724 @subheading 非推奨API
18725 @c COMMON
18726
18727 @c EN
18728 The following procedures are deprecated. You can use @code{hmac-to}
18729 and @code{hmac-message} instead.
18730 @c JP
18731 以下の手続きは非推奨になりました。@code{hmac-to}や@code{hmac-message}が
18732 かわりに使えます。
18733 @c COMMON
18734
18735 @defun hmac-digest :key key hasher
18736 @c MOD rfc.hmac
18737 @c DEPRECATED
18738 @c EN
18739 Creates an @code{<hmac>} object and hash the data stream
18740 from the current input port, then returns the hashed result
18741 in an incomplete string.
18742 @c JP
18743 @code{<hmac>}オブジェクトを作り、現在の入力ポートからの
18744 データストリームをハッシュし、不完全文字列でそのハッシュされた
18745 結果を返します。
18746 @c COMMON
18747 @end defun
18748
18749 @defun hmac-digest-string string :key key hasher
18750 @c MOD rfc.hmac
18751 @c DEPRECATED
18752 @c EN
18753 Creates an @code{<hmac>} object and hash the data in @var{string},
18754 then returns the hashed result in an incomplete string.
18755 @c JP
18756 @code{<hmac>}オブジェクトを作り、@var{string}にあるデータをハッシュし、
18757 不完全文字列でそのハッシュされた結果を返します。
18758 @c COMMON
18759 @end defun
18760
18761 @c ----------------------------------------------------------------------
18762 @node HTTP client, ICMP packets, HMAC keyed-hashing, Library modules - Utilities
18763 @section @code{rfc.http} - HTTP client
18764 @c NODE HTTPクライアント, @code{rfc.http} - HTTPクライアント
18765
18766 @deftp {Module} rfc.http
18767 @mdindex rfc.http
18768 @c EN
18769 This module provides a simple client API for
18770 HTTP/1.1, defined in RFC2616, "Hypertext Transfer Protocol -- HTTP/1.1"
18771 @c JP
18772 このモジュールは、RFC2616 "Hypertext Transfer Protocol -- HTTP/1.1"
18773 で定義されているHTTP/1.1に対する簡単なクライアントAPIを提供します。
18774 @c COMMON
18775 (@uref{https://www.ietf.org/rfc/rfc2616.txt}).
18776
18777 @c EN
18778 Current API implements only a part of HTTP/1.1 protocol.
18779 Support for some advanced features such as persistent connection
18780 may be added in the future versions.
18781 @c JP
18782 現在のAPIは、HTTP/1.1のプロトコルの一部のみ実装されています。
18783 より先進的な機能、例えば永続的接続などは将来のバージョンで追加されるでしょう。
18784 @c COMMON
18785
18786 @c EN
18787 If you're looking a library to write HTTP @emph{server}, see
18788 Gauche-makiki (@url{https://github.com/shirok/Gauche-makiki}).
18789 @c JP
18790 HTTPサーバを書くためのライブラリを探しているなら、
18791 Gauche-makikiを見てください (@url{https://github.com/shirok/Gauche-makiki})。
18792 @c COMMON
18793 @end deftp
18794
18795 @deftp {Condition Type} <http-error>
18796 @clindex http-error
18797 @c MOD rfc.http
18798 @c EN
18799 This type of condition is raised when the server terminates
18800 connection prematurely or server's response has invalid
18801 header fields. Inherits @code{<error>}.
18802 @c JP
18803 サーバから接続が切られた場合や、サーバの返したHTTPレスポンスのフォーマットが
18804 正しくない場合に投げられるコンディションです。@code{<error>}を継承します。
18805 @c COMMON
18806 @end deftp
18807
18808 @menu
18809 * Http client mid-level API::
18810 * Http client utilities::
18811 * Secure http connection::
18812 @end menu
18813
18814 @node Http client mid-level API, Http client utilities, HTTP client, HTTP client
18815 @subsection Http client mid-level API
18816 @c NODE HTTPクライアント中間レベルAPI
18817
18818 @defun http-get server request-uri :key sink flusher redirect-handler secure @dots{}
18819 @defunx http-head server request-uri :key redirect-handler secure @dots{}
18820 @defunx http-post server request-uri body :key sink flusher redirect-handler secure @dots{}
18821 @defunx http-put server request-uri body :key sink flusher redirect-handler secure @dots{}
18822 @defunx http-delete server request-uri :key sink flusher redirect-handler secure @dots{}
18823 @c MOD rfc.http
18824 @c EN
18825 Send http GET, HEAD, POST, PUT and DELETE requests to the http @var{server},
18826 respectively, and returns the server's reply.
18827
18828 By default, if the server returns 300, 301, 302, 303, 305 and 307 status,
18829 these procedures attempts to fetch the redirected URL by the
18830 "location" reply message header if it is allowed by RFC2616.
18831 This behavior can be turned off or customized by the @var{redirect-handler}
18832 keyword argument;
18833 see the "keyword arguments" heading below for the details.
18834 @c JP
18835 @var{server}に、それぞれHTTPのGET、HEAD、POST、PUT、DELETEリクエストを送り、
18836 サーバの応答を返します。
18837
18838 デフォルトでは、
18839 サーバがステータスコード 300, 301, 302, 303, 305 の応答を返し、
18840 RFC2616による自動リダイレクトが許されている場合は、
18841 これらの手続きは自動的に応答のメッセージヘッダの "location" で返されるURIに対して
18842 リクエストを再送します。
18843 この動作は@var{redirect-handler}キーワード引数でカスタマイズしたり
18844 抑制したりできます。下の"キーワード引数"を参照してください。
18845 @c COMMON
18846
18847 @c EN
18848 @strong{Required arguments:}
18849 The @var{server} argument specifies http server name in a string.
18850 A server name can be optionally followed by colon and a port number.
18851 You can use IP address, too; for IPv6, you have to surround the
18852 address in brackets.
18853
18854 Additionally, you can specify @code{"unix:/path"} where @code{/path}
18855 is the absolute path to the unix domain socket; this allows to connect
18856 to httpd listening on unix domain sockets.
18857 @c JP
18858 @strong{必須の引数:}
18859 @var{server}引数では、文字列でHTTPサーバ名を指定します。
18860 サーバ名は、オプションでコロンに続いてポート番号を付加できます。
18861 IPアドレスも使えます。IPv6アドレスは角括弧で囲んでください。
18862
18863 また、@code{"unix:/path"}という形式でUnixドメインソケットに接続することもできます。
18864 @code{/path}部分にはソケットへの絶対パスを指定します。
18865 @c COMMON
18866 Examples: @code{"w3c.org"}, @code{"mycompany.com:8080"},
18867 @code{"192.168.0.1:8000"}, @code{"[::1]:8000"}
18868
18869 @c EN
18870 The @var{request-uri} argument can be a string or a list.
18871 If it is a string, it's @emph{request-uri} specified in
18872 RFC2616; usually, this is the path part of http url.
18873 The string is passed to the server as is, so the caller must
18874 properly convert character encodings and perform necessary
18875 url encodings.
18876
18877 If @var{request-uri} is a list, it must be in the following form:
18878 @c JP
18879 @var{request-uri}引数は文字列かリストです。
18880 文字列の場合、RFC2616で規定されているリクエストURIと解釈されます。
18881 通常これはHTTP URLのパス部分です。
18882 文字列はそのままサーバに渡されるので、呼び出し側で必要な
18883 文字コード変換やurlエンコーディングを行う必要があります。
18884
18885 @var{request-uri}がリストの場合は、次の形式でなければなりません。
18886 @c COMMON
18887
18888 @example
18889 (@var{path} (@var{name} @var{value}) ...)
18890 @end example
18891
18892 @c EN
18893 Here, @var{path} is a string specifying up to the path component
18894 of the request-uri.
18895 From provided alist of @var{name}s and @var{value}s,
18896 http procedures compose a query string in
18897 @code{application/x-www-form-urlencoded} format
18898 as defined in HTML4, and append it to @var{path}.
18899 For example, the following two requests have the same effect.
18900 Note that url escaping is automatically handled in the second call.
18901 @c JP
18902 ここで@var{path}はリクエストURIのパスコンポーネントまでを指定する
18903 文字列です。与えられた@var{name}と@var{value}のalistから、
18904 httpリクエスト手続きはHTML4で定められた
18905 @code{application/x-www-form-urlencoded}形式の
18906 クエリ文字列を構成し、@var{path}にアペンドします。
18907 例えば次のふたつのリクエストは同じ効果を持ちます。
18908 二番目の呼び出しではurlエスケープが自動的に行われることに注目してください。
18909 @c COMMON
18910
18911 @example
18912 (http-get "example.com" "/search?q=foo%20bar&n=20")
18913
18914 (http-get "example.com" '("/search" (q "foo bar") (n 20)))
18915 @end example
18916
18917 @c EN
18918 If @var{request-encoding} keyword argument is also given,
18919 @var{name}s and @var{value}s
18920 are converted into the specified character encoding before url escaping.
18921 If it is omitted, gauche's internal character encoding is used.
18922 @c JP
18923 @var{request-encoding}キーワード引数が与えられた場合、
18924 @var{name}と@var{value}はまずその文字エンコーディングに変換されたのちに
18925 urlエスケープされます。そうでない場合はgaucheの内部
18926 エンコーディングがそのまま使われます。
18927 @c COMMON
18928
18929 @c EN
18930 Some procedures take the third argument, @var{body},
18931 to specify the body of the request message.
18932 It can be a string, which will be copied verbatim to the request body,
18933 or a list, which will be encoded in @code{multipart/form-data} message.
18934
18935 If @var{body} is a list, it is a list of parameter specs. Each parameter
18936 spec is either a list of name and value, e.g.
18937 @code{("submit" "OK")} or a name followed by keyword-value list,
18938 e.g. @code{("upload" :file "logo.png" :content-type "image/png")}.
18939
18940 The first form is for the convenience. It is also compatible to the
18941 query parameter list in @var{request-uri}, so that you can use the
18942 same format for GET and POST request. Each value is put
18943 in a MIME part with @code{text/plain} media type, with the
18944 character encoding specified by @code{request-encoding} keyword argument
18945 described below.
18946
18947 The second form allows further control over each MIME part's attributes.
18948 The following keywords are treated specially.
18949
18950 @table @code
18951 @item :value
18952 Specifies the value of the parameter. The convenience form,
18953 @code{(@var{name} @var{val})}, is just an abbreviation of
18954 @code{(@var{name} :value @var{val})}.
18955 @item :file
18956 Specifies the pathname of the file, whose content is inserted
18957 as the value of the parameter. Useful to upload a file.
18958 This option has precedence over @code{:value}.
18959 MIME type of the part is set to @code{application/octet-stream}
18960 unless specified otherwise.
18961 @item :content-type
18962 Overrides the MIME type of the part. A charset parameter is
18963 added to the content-type if not given in this argument.
18964 @item :content-transfer-encoding
18965 Specifies the value of content-transfer-encoding; currently the
18966 following values are supported: @code{7bit},
18967 @code{binary}, @code{quoted-printable} and @code{base64}.
18968 If omitted, @code{binary} is used.
18969 @end table
18970
18971 Other keywords are used as the header of the MIME part.
18972 @c JP
18973 いくつかの手続きは、リクエストメッセージのボディを指定する@var{body}を第3引数として
18974 取ります。@var{body}は文字列かリストで、文字列の場合はそのまま送られ、
18975 リストの場合は@code{multipart/form-data}形式にエンコードされて送られます。
18976
18977 @var{body}がリストの場合、それはパラメータ指定のリストです。
18978 各パラメータ指定は、@code{("submit" "OK")}のような名前と値のリスト、
18979 もしくは@code{("upload" :file "logo.png" :content-type "image/png")}
18980 のように名前の後にキーワード-値リストを付加したものです。
18981
18982 最初の形式は使うのが簡単で、また@var{request-uri}のクエリパラメータリストと
18983 同じ形式なのでGETとPOSTでルーチンを共有したい場合にも便利でしょう。
18984 この形式では、各値はMIMEパートに@code{text/plain}として置かれます。
18985 文字コードは下に述べる@code{request-encoding}キーワード引数により変換されます。
18986
18987 二番目の形式では、MIMEパートの属性についてより細かな指定を行うことができます。
18988 以下のキーワードが特別に扱われます。
18989
18990 @table @code
18991 @item :value
18992 パラメータの値を指定します。簡潔な@code{(@var{name} @var{val})}形式は
18993 @code{(@var{name} :value @var{val})}の省略形です。
18994 @item :file
18995 指定された名前のファイルの中身をパラメータの値として挿入します。
18996 ファイルのアップロードに便利です。このオプションは@code{:value}より
18997 優先されます。MIMEタイプは、指定が無ければ
18998 @code{application/octet-stream}となります。
18999 @item :content-type
19000 MIMEタイプをオーバライドします。与えられた値にcharsetパラメータが
19001 ついていない場合は自動的に付加されます。
19002 @item :content-transfer-encoding
19003 content-transfer-encodingを
19004 @code{7bit}、@code{binary}、@code{quoted-printable}、@code{base64}の
19005 いずれかで指定します。指定が無ければ@code{binary}が使われます。
19006 @end table
19007
19008 残りのキーワードはMIMEパートのヘッダにそのまま使われます。
19009 @c COMMON
19010
19011 @c EN
19012 @strong{Return values:}
19013 All procedures return three values.
19014
19015 The first value is the status code defined in RFC2616
19016 in a string (such as "200" for success, "404" for "not found").
19017 @c JP
19018 @strong{戻り値:}
19019 全ての手続きは3つの値を返します。
19020
19021 1つ目は、RFC2616で定義されているステータスコードの文字列値(例えば、成功時の
19022 200、"Not found"の404など)です。
19023 @c COMMON
19024
19025 @c EN
19026 The second value is a list of parsed headers---each element of list
19027 is a list of @code{(@var{header-name} @var{value} @dots{})},
19028 where @var{header-name} is a string name of the header
19029 (such as "content-type" or "location"), and @var{value} is
19030 the corresponding value in a string. The header name is converted
19031 to lowercase letters. The value is untouched except that "soft line breaks"
19032 are removed, as defined in RFC2822. If the server returns
19033 more than one headers with the same name, their values are
19034 consolidated to one list. Except that, the order of the header list
19035 in the second return value is the same as the order in the server's reply.
19036 @c JP
19037 2つ目は、パーズされたヘッダのリストで、リストの要素は@code{(@var{header-name}
19038 @var{value} @dots{})}です。@var{header-name}はヘッダの文字列名(例えば、
19039 "content-type"や"location"など)で、@var{value}は対応する値の文字列値です。
19040 ヘッダ名は小文字に変換されます。値は、RFC2822で定義されている無指定行区切
19041 (ソフト・ライン・ブレイク)が除かれる以外はそのままです。
19042 サーバが同じ名前のヘッダを1つ以上返した場合は、
19043 1つのリストに統合されます。それ以外では、2つ目の戻り値に
19044 おけるヘッダのリストの順番は、サーバの応答での順番と同じです。
19045 @c COMMON
19046
19047 @c EN
19048 The third value is for the message body of the server's reply.
19049 By default, it is a message body itself in a string. If the server's
19050 reply doesn't have a body, the third value is @code{#f}. You can
19051 change how the message body is handled by keyword arguments; for example,
19052 you can directly store the returned message body to a file without
19053 creating intermediate string. The details are explained below.
19054 @c JP
19055 3つ目の戻り値は、サーバの応答におけるメッセージボディです。
19056 デフォルトでは、文字列で表現されたメッセージボディそのものです。
19057 サーバの応答がボディを持たない場合、3つ目の戻り値は@code{#f}です。
19058 キーワード引数によって、メッセージボディがどのように扱われるかを制御できます。
19059 例えば、中間的な文字列を作らずに、返されたメッセージボディを直接ファイルに
19060 格納することが出来ます。詳細は以下で説明しています。
19061 @c COMMON
19062
19063 @c EN
19064 @strong{Keyword arguments:}
19065 By default, these procedures only attaches @code{"Host"} header
19066 field to the request message. You can give keyword arguments
19067 to add more header fields.
19068 @c JP
19069 @strong{キーワード引数:}
19070 デフォルトで、これらの手続きはリクエストメッセージに@code{"Host"}ヘッダ・フィールドを
19071 追加するだけです。他のヘッダ・フィールドを追加するためにキーワード引数を
19072 与えることができます。
19073 @c COMMON
19074 @example
19075 (http-get "foo.bar.com" "/index.html"
19076 :accept-language "ja"
19077 :user-agent "My Scheme Program/1.0")
19078 @end example
19079
19080 @c EN
19081 The following keyword arguments are recognized by the procedure
19082 and do not appear in the request headers.
19083 @c JP
19084 以下のキーワード引数は手続きによって解釈され、リクエストヘッダには現れません。
19085 @c COMMON
19086
19087 @table @code
19088 @item request-encoding
19089 @c EN
19090 When a list is given to the @var{request-uri} or @var{body} arguments,
19091 the characters in names and values of the parameters are first
19092 converted to the character encoding specified by this keyword
19093 argument, then encoded into @code{application/x-www-form-urlencoded}
19094 or @code{multipart/form-data} MIME formats.
19095 If this argument is omitted, Gauche's internal character encoding is used.
19096
19097 For @code{multipart/form-data}, you can override character encodings
19098 for individual parameters by giving @code{content-type} header.
19099 See the description of @var{body} arguments above.
19100
19101 If you give a string to @var{request-uri} or @var{body},
19102 it is used without encoding conversion. It is caller's responsibility
19103 to ensure desired character encodings are used.
19104 @c JP
19105 @var{request-uri}や@var{body}がリストで与えられた場合、パラメータの
19106 名前や値はまずこの引数で指定される文字エンコーディングへと変換され、
19107 その後、@code{application/x-www-form-urlencoded}や
19108 @code{multipart/form-data} MIME形式にしたがったエンコーディングが行われます。
19109 この引数が省略された場合はGaucheの内部文字エンコーディングが使われます。
19110
19111 @code{multipart/form-data}については、パラメータに@code{content-type}ヘッダを
19112 与えることでパラメータごとに文字エンコーディングの設定をオーバライドできます。
19113 詳しくは上の@var{body}引数の説明を参照してください。
19114
19115 @var{request-uri}や@var{body}に文字列を与えた場合は、文字エンコーディング変換は
19116 行われません。呼び出し側で望みの文字コードにあらかじめ変換しておいてください。
19117 @c COMMON
19118 @item proxy
19119 @c EN
19120 Specify http proxy server in a string of a form @code{hostname} or
19121 @code{hostname:port}. If omitted, the value of the parameter
19122 @code{http-proxy} is used.
19123 @c JP
19124 httpプロキシサーバを、@code{hostname}または@code{hostname:port}形式の
19125 文字列で指定します。省略された場合、パラメータ@code{http-proxy}の値が
19126 使われます。
19127 @c COMMON
19128 @item redirect-handler
19129 @c EN
19130 Specifies how the redirection is handled when the server responds with
19131 3xx status code.
19132 You can pass @code{#f}, @code{#t} or a procedure. The default is @code{#t}.
19133
19134 If @code{#f} is given, no redirect attempt will be made; the 3xx status
19135 code and response is just returned from @code{http-*} procedures as they are.
19136
19137 If a procedure is given, it is called when the response status code
19138 is 3xx. The procedure takes four arguments, the request method (in symbol,
19139 e.g. @code{GET}), the response status code (in string, e.g. @code{"302"}),
19140 the parsed response headers and the response body (a string
19141 if there's a body, or @code{#f} if the response doesn't have a body).
19142
19143 The procedure can return a pair or @code{#f}.
19144 If it is a pair, it should be @code{(method . url)}, where @var{method}
19145 is a symbol (e.g. @code{GET}) and @var{url} is a string representing url.
19146 If a pair is returned, the @code{http-*} procedures tries to send
19147 the request with the given method (it allows a redirection of POST request
19148 to be GET, for example). If it is @code{#f}, no further attempt of
19149 redirection is made.
19150
19151 If @var{redirect-handler} is @code{#t}, which is the default,
19152 then it works as if the value of the parameter
19153 @code{http-default-redirect-handler} is passed to @var{redirect-handler}.
19154 The parameter contains a procedure with reasonable default behavior.
19155 See the @code{http-default-redirect-handler} entry below for the details.
19156
19157 A loop in redirection is detected automatically and @code{<http-error>}
19158 is thrown.
19159 @c JP
19160 サーバが3xxステータスコードを返した場合のリダイレクトの処理を指定します。
19161 @code{#f}, @code{#t}もしくは手続きを渡すことができます。省略時は@code{#t}となります。
19162
19163 @code{#f}が渡された場合は、リダイレクトは処理されません。3xxステータスコードを
19164 持つレスポンスもそのまま@code{http-*}から返されます。
19165
19166 手続きが渡された場合は、サーバが3xxステータスコードを返すとその手続きが4つの引数で
19167 呼ばれます。最初の引数はリクエストメソッド(シンボル、例:@code{GET})、
19168 次がレスポンスステータスコード(文字列、例:@code{"302"})、
19169 次がパーズされたレスポンスヘッダ、そして最後がレスポンスボディです(レスポンスボディが
19170 あれば文字列、なければ@code{#f})。
19171
19172 この手続きは、ペアか@code{#f}を返さねばなりません。ペアの場合、それは
19173 @code{(method . url)}という形で、@var{method}がシンボルによるリクエストメソッド、
19174 @var{url}が文字列で次にリクエストすべきURLを表します。
19175 ペアが返されれば、@code{http-*}手続きはそのURLへ、指定されたメソッドでリクエストを
19176 再送します。(メソッドを返すことで、例えばPOSTリクエストのリダイレクトをGETリクエストに
19177 置き換えることが可能です)。
19178 手続きが@code{#f}を返した場合、リダイレクトは行われません。
19179
19180 @var{redirect-handler}が@code{#t}(デフォルト値)の場合、
19181 パラメータ@code{http-default-redirect-handler}の値が
19182 @var{redirect-handler}に渡されたかのように振る舞います。
19183 このパラメータの初期値は、標準的なリダイレクトの振る舞いをする手続きになっています。
19184 下の@code{http-default-redirect-handler}の項目を参照してください。
19185
19186 リダイレクトのループは自動的に検出され、@code{<http-error>}が投げられます。
19187 @c COMMON
19188 @item no-redirect
19189 @c EN
19190 This is an obsoleted keyword argument kept only for the backward
19191 compatibility. If a true value is given, it has the same effect
19192 as specifying @code{#f} to @var{redirect-handler}.
19193 @c JP
19194 これは互換性のためだけに残されている、古い引数です。真の値を与えると、
19195 @var{redirect-handler}に@code{#f}を渡したのと同じ効果を持ちます。
19196 @c COMMON
19197 @item secure
19198 @c EN
19199 If a true value is given, the secure connection is used. The value
19200 specifies the secure transport agent to establish https connection.
19201 It can be @code{#t} or a symbol @code{tls} or @code{stunnel}.
19202 If @code{#f} is given (default), non-secure plain http is used.
19203 See the ``Secure connection'' section below.
19204 @c JP
19205 真の値が与えられた場合、セキュアな接続が使われます。
19206 値によってhttps接続につかうトランスポートエージェントを指定できます。
19207 有効な値は@code{#t}もしくはシンボルの@code{tls}か@code{stunnel}です。
19208 @code{#f}が与えられた場合(デフォルト)はセキュアでない通常のhttpが使われます。
19209 詳しくは下の「セキュアな接続」の項を参照してください。
19210 @c COMMON
19211 @item auth-user, auth-password
19212 @c EN
19213 If given, the authorization header using Basic Authentication
19214 (RFC2617) is added to the request.
19215 In future, we might add support for other authentication scheme.
19216 @c JP
19217 これらのキーワード引数が与えられた場合、Basic認証用のAuthorizationヘッダが
19218 リクエストに付加されます。将来はBasic認証以外の認証方式もサポートするかもしれません。
19219 @c COMMON
19220 @item sink, flusher
19221 @c EN
19222 You can customize how the reply message body is handled by these
19223 keyword arguments. You have to pass an output port to @var{sink},
19224 and a procedure that takes two arguments to @var{flusher}.
19225
19226 When the procedure starts receiving the message body, it
19227 feeds the received chunk to @var{sink}. When the procedure
19228 receives entire message body, @var{flusher} method is called
19229 with @var{sink} and a list of message header fields (in the
19230 same format to be returned in the second value from the procedure).
19231 The return value of @var{flusher} becomes the third return value
19232 from the procedure.
19233
19234 So, the default value of @var{sink} is a newly opened string
19235 port and the default value of @var{flusher} is
19236 @code{(lambda (sink headers) (get-output-string sink))}.
19237
19238 The following example saves the message body directly to a file,
19239 without allocating (potentially very big) string buffer.
19240 @c JP
19241 これらのキーワード引数によりリプライメッセージ・ボディがどのように扱われるかを
19242 カスタマイズできます。@var{sink}には出力ポートを、@var{flusher}には2引数を
19243 取る手続きを渡さなければなりません。
19244
19245 手続きがメッセージ・ボディを受信し始めると、@var{sink}へ受け取った
19246 データ片をフィードします。手続きがメッセージ・ボディを受信し終わると、
19247 @var{flusher}に与えられた手続きが、@var{sink}と(手続きからの2つ目の
19248 戻り値と同じフォーマットの)メッセージ・ヘッダ・フィールドのリストとともに
19249 呼び出されます。@var{flusher}の戻り値が、手続きからの3つ目の戻り値と
19250 なります。
19251
19252 したがって、@var{sink}のデフォルト値は、新しく開かれた文字列ポートで、
19253 @var{flusher}のデフォルト値は@code{(lambda (sink headers) (get-output-string sink))}
19254 とも言えます。
19255
19256 以下のサンプルは、(とても大きい可能性のある)文字列バッファを作らずに、
19257 メッセージ・ボディを直接ファイルに保存します。
19258 @c COMMON
19259 @example
19260 (call-with-output-file "page.html"
19261 (lambda (out)
19262 (http-get "www.schemers.org" "/"
19263 :sink out :flusher (lambda _ #t))))
19264 @end example
19265
19266 @end table
19267
19268 @end defun
19269
19270 @node Http client utilities, Secure http connection, Http client mid-level API, HTTP client
19271 @subsection Http client utilities
19272 @c NODE HTTPクライアントユーティリティ
19273
19274 The module also provides some utility procedures.
19275
19276 @deffn {Parameter} http-user-agent :optional value
19277 @c MOD rfc.http
19278 @c EN
19279 The value of this parameter is used as a default value
19280 to pass to the user-agent header.
19281 The default value is something like @code{gauche.http/*},
19282 where @code{*} is Gauche's version.
19283 An application is encouraged to set this parameter appropriately.
19284 @c JP
19285 user-agentヘッダに渡される値のデフォルト値を指定するパラメータです。
19286 デフォルトの値は@code{gauche.http/*} (@code{*}部分はGaucheのバージョン)
19287 になっています。
19288 各アプリケーションは適切な値を設定するようにしてください。
19289 @c COMMON
19290 @end deffn
19291
19292 @deffn {Parameter} http-proxy :optional value
19293 @c MOD rfc.http
19294 @c EN
19295 This value is used as the default http proxy name by @code{http-get} etc.
19296 The default value is @code{#f} (no proxy).
19297 @c JP
19298 このパラメータの値が@code{http-get}等のhttpプロキシのデフォルトの値として
19299 使われます。デフォルトの値は@code{#f} (プロキシを使用しない) です。
19300 @c COMMON
19301 @end deffn
19302
19303 @deffn {Parameter} http-default-redirect-handler :optional value
19304 @c MOD rfc.http
19305 @c EN
19306 Specifies the behavior of redirection if no @code{redirect-handler} keyword
19307 argument is given to the @code{http-*} procedures.
19308 If you change this value, it must be a procedure that follows the
19309 protocol of @code{redirect-handler}; see the description of @code{http-*}
19310 procedures above.
19311 @c JP
19312 @code{http-*}手続きに@code{redirect-handler}キーワード引数が与えられなかった
19313 場合のデフォルトの動作を指定します。この値を変える場合、それは
19314 @code{redirect-handler}引数のプロトコルに従う手続きでなければなりません。
19315 上の@code{http-*}手続きの項目を参照してください。
19316 @c COMMON
19317
19318 @c EN
19319 The default behavior is as follows:
19320 @c JP
19321 デフォルトの動作は以下の通りです。
19322 @c COMMON
19323
19324 @table @asis
19325 @item @code{300}, @code{301}, @code{305}, @code{307}
19326 @c EN
19327 Redirect to the url given to the @code{location} header only if
19328 the original request method is @code{GET} or @code{HEAD}.
19329 @c JP
19330 元のリクエストが@code{GET}か@code{HEAD}の場合に限り、同じリクエストを使って
19331 @code{location}ヘッダに与えられたURLにリダイレクトします。
19332 @c COMMON
19333 @item @code{302}
19334 @c EN
19335 Redirect to the url given to the @code{location} header. If
19336 the original request method is @code{HEAD}, it is used again.
19337 Otherwise, @code{GET} method is used.
19338
19339 Strictly speaking, this is a violation of RFC2616. However, as the note
19340 in RFC2616 says, many user agent do this, so we follow the flock.
19341 (We may change this in future.)
19342 @c JP
19343 @code{location}ヘッダに与えられたURLにリダイレクトします。
19344 元が@code{HEAD}リクエストなら@code{HEAD}を、それ以外なら@code{GET}リクエストを
19345 使います。
19346
19347 厳密に言えばこれはRFC2616違反ですが、RFC2616の注記にもあるように、
19348 多くのユーザエージェントがこの振る舞いをするので、それに合わせてあります。
19349 (将来は変えるかもしれません。)
19350 @c COMMON
19351 @item @code{303}
19352 @c EN
19353 Redirect to the url given to the @code{location} header. If
19354 the original request method is @code{HEAD}, it is used again.
19355 Otherwise, @code{GET} method is used.
19356 @c JP
19357 @code{location}ヘッダに与えられたURLにリダイレクトします。
19358 元が@code{HEAD}リクエストなら@code{HEAD}を、それ以外なら@code{GET}リクエストを
19359 使います。
19360 @c COMMON
19361 @item other than above
19362 @c EN
19363 No redirection is made.
19364 @c JP
19365 リダイレクトしません。
19366 @c COMMON
19367 @end table
19368
19369 @c EN
19370 The following code is an example of intercepting the default
19371 behavior in a specific request:
19372 @c JP
19373 次のコードは、デフォルトの振る舞いを特定のリクエストでインターセプトする例です。
19374 @c COMMON
19375
19376 @example
19377 (http-get server uri
19378 :redirect-handler
19379 (^[method status headers body]
19380 (if (and (equal? status "302")
19381 (not (member method '(GET HEAD))))
19382 #f
19383 ((http-default-request-handler) method status headers body))))
19384 @end example
19385 @end deffn
19386
19387
19388 @defun http-compose-query path params :optional encoding
19389 @c MOD rfc.http
19390 @c EN
19391 A helper procedure to create a request-uri from
19392 a list of query parameters. @var{Encoding} specifies
19393 the character encodings to be used.
19394 @c JP
19395 クエリパラメータのリストからリクエストURIを生成する補助関数です。
19396 @var{encoding}引数はクエリパラメータの文字エンコーディングを指定します。
19397 @c COMMON
19398
19399 @example
19400 (http-compose-query "/search" '((q "$foo") (n 20)))
19401 @result{} "/search?q=%24foo&n=20"
19402
19403 (http-compose-query "" '((x "a b") (x 2)))
19404 @result{} "?x=a%20b&x=2"
19405 @end example
19406
19407 @c EN
19408 If @var{path} is @code{#f}, only the query parameter part
19409 is returned (compare the following example and the last
19410 example):
19411 @c JP
19412 @var{path}が@code{#f}の場合は、クエリパラメータの部分だけが返されます
19413 (次の例と直前の例を比べてみてください)。
19414 @c COMMON
19415
19416 @example
19417 (http-compose-query #f '((x "a b") (x 2)))
19418 @result{} "x=a%20b&x=2"
19419 @end example
19420
19421 @c EN
19422 This is built on top of @code{uri-compose-query} in @code{rfc.uri}
19423 (@pxref{URI parsing and construction}).
19424 @c JP
19425 これは@code{rfc.uri}モジュールの@code{uri-compose-query}手続きの上に
19426 作られています (@ref{URI parsing and construction}参照)。
19427 @c COMMON
19428 @end defun
19429
19430 @defun http-compose-form-data params port :optional encoding
19431 @c MOD rfc.http
19432 @c EN
19433 A helper procedure to create @code{multipart/form-data}
19434 from a list of parameters. The format of @var{params} argument
19435 is the same as the list format of @var{body} argument of
19436 http request procedures. The result is written to an output
19437 port @var{port}, and the boundary string used to compose
19438 MIME message is returned. Alternatively you can pass @code{#f}
19439 to the @var{port} to get the result in a string.
19440 In that case, two values are returned, the MIME message string
19441 and the boundary string.
19442 @c JP
19443 @code{multibyte/form-data}形式にエンコードされたデータを
19444 パラメータのリストから組み立てるための補助手続きです。
19445 @var{params}の形式はhttpリクエスト手続きの@var{body}部にリストを渡す場合の形式と同様です。
19446 結果は出力ポート@var{port}に書き出され、
19447 MIMEメッセージを構築するのに必要なboundary stringが返されます。
19448 @var{port}に@code{#f}を渡した場合は、
19449 boundary stringとデータをエンコードした文字列の二つの値が返されます。
19450 @c COMMON
19451
19452 @c EN
19453 @var{Encoding} specifies the character encodings to be used.
19454 When omitted, Gauche's native encoding is used.
19455 @c JP
19456 @var{encoding}は文字エンコーディングを指定します。
19457 省略時はGaucheのネイティブエンコーディングが使われます。
19458 @c COMMON
19459
19460 @example
19461 (define p (open-output-string))
19462
19463 (http-compose-form-data '((name "Preludes and Fugues")
19464 (composer "Shostakovich, Dmitri")
19465 (opus "87"))
19466 p)
19467 @result{} "boundary-fh87o52rp6zkubp2uhdmo"
19468
19469 (get-output-string p)
19470 @result{}
19471 "\r\n--boundary-fh87o52rp6zkubp2uhdmo\r\nContent-type: te
19472 xt/plain; charset=utf-8\r\nContent-transfer-encoding: bi
19473 nary\r\ncontent-disposition: form-data; name=title\r\n\r\n
19474 Preludes and Fugues\r\n--boundary-fh87o52rp6zkubp2uhdmo...
19475 @c EN
19476 ;; (result is truncated)
19477 @c JP
19478 ;; (以下省略)
19479 @c COMMON
19480 @end example
19481 @end defun
19482
19483 @defun http-status-code->description code
19484 @c MOD rfc.http
19485 @c EN
19486 Returns a brief description of http status code @code{code},
19487 which may be an integer or a string (e.g. @code{"404"}).
19488 If @code{code} isn't one of known code, @code{#f} is returned.
19489 @c JP
19490 HTTPステータスコード@code{code}の簡単な説明を返します。
19491 @code{code}は整数か、整数を表す文字列です(例: @code{"404"})。
19492 @code{code}が知られているものでなかった場合は@code{#f}が返されます。
19493 @c COMMON
19494
19495 @example
19496 (http-status-code->description 404)
19497 @result{} "Not Found"
19498 @end example
19499 @end defun
19500
19501 @node Secure http connection, , Http client utilities, HTTP client
19502 @subsection Secure http connection
19503 @c NODE セキュアhttpコネクション
19504
19505 @c EN
19506 When you pass a true value to @code{secure} keyword argument,
19507 the request-making APIs such as @code{http-get} use a secure
19508 connection. That is, it connects with @code{https} instead of
19509 @code{http}. The actual value for the keyword argument can be one of the
19510 followings:
19511 @c JP
19512 @code{http-get}等httpリクエスト発行APIの@code{secure}キーワード引数に、
19513 真の値を渡した場合、セキュアなコネクションが使われます。
19514 すなわち、@code{http}ではなく@code{https}で接続されるということです。
19515 実際に@code{secure}キーワード引数に渡せる値は以下の通りです。
19516 @c COMMON
19517
19518 @table @code
19519 @item #t
19520 @itemx tls
19521 @c EN
19522 The @code{rfc.tls} module is used for the secure connection.
19523 @xref{Transport layer security}, for the details---you might need to
19524 set CA certificate bundle path.
19525 @c JP
19526 @code{rfc.tls}モジュールを使ってセキュアな接続を行います。
19527 詳しくは@ref{Transport layer security}を参照してください。
19528 CA証明書のパスを設定する必要があるかもしれません。
19529 @c COMMON
19530 @item stunnel
19531 @c EN
19532 The external process @code{stunnel} is spawned and used for the
19533 secure connection.
19534 @c JP
19535 @code{stunnel}プロセスをサブプロセスとして起動してそれを通じてセキュアな接続を作ります。
19536 @c COMMON
19537 @item #f
19538 @c EN
19539 Secure connection is not used.
19540 @c JP
19541 セキュアな接続を行いません。
19542 @c COMMON
19543 @end table
19544
19545 @c EN
19546 If specified secure connection subsystem isn't available in the running Gauche,
19547 an error is signaled.
19548 Use the following procedure to check if you can use secure
19549 connections:
19550 @c JP
19551 指定されたセキュア接続を行うサブシステムが実行中のGaucheでは使えない場合は、
19552 エラーが報告されます。
19553 サブシステムが使えるかどうかをチェックしたい場合は次の手続きを使ってください。
19554 @c COMMON
19555
19556 @defun http-secure-connection-available? :optional type
19557 @c MOD rfc.http
19558 @c EN
19559 The @var{type} argument may be @code{tls} or @code{stunnel}.
19560 If omitted, @code{tls} is assumed.
19561 Returns @code{#t} if running Gauche can use secure connection of the given type,
19562 @code{#f} otherwise.
19563 @c JP
19564 @var{type}引数は@code{tls}か@code{stunnel}でなければなりません。
19565 省略時は@code{tls}とみなされます。
19566 指定のセキュア接続を行うサブシステムが実行中のGaucheで使える場合は@code{#t}が、
19567 使えない場合は@code{#f}が返されます。
19568 @c COMMON
19569 @end defun
19570
19571 @c ----------------------------------------------------------------------
19572 @node ICMP packets, IP packets, HTTP client, Library modules - Utilities
19573 @section @code{rfc.icmp} - ICMP packets
19574 @c NODE ICMPパケット, @code{rfc.icmp} - ICMPパケット
19575
19576 @deftp {Module} rfc.icmp
19577 @mdindex rfc.icmp
19578 @c MOD rfc.icmp
19579 @c EN
19580 This module provides some basic utilities to construct and parse ICMP
19581 packets.
19582 @c JP
19583 このモジュールではICMPパケットの構築および解析用の基本的ユーティリティ
19584 を提供しています。
19585 @c COMMON
19586 @end deftp
19587
19588 @c EN
19589 For the functions below, @var{buffer} should be a writable
19590 u8vector of the enough size.
19591 @c JP
19592 以下の関数の@var{buffer}は十分なサイズの書き込み可能なu8vectorでなけれ
19593 ばなりません。
19594 @c COMMON
19595
19596 @c EN
19597 Parsing functions takes @var{offset} as well as @var{buffer},
19598 which specifies the beginning of the ICMP packet. Using the offset
19599 you can carry the whole IP packet in @var{buffer}, without
19600 creating a new buffer to extract ICMP portion.
19601 @c JP
19602 解析用の関数は@var{buffer}のほかに@var{offset}を引数としてとります。こ
19603 れはICMPパケットの開始位置を示すものです。このオフセットを用いて、ICMP
19604 部分を取り出して新しいバッファを作るということなしに、IPパケット全体を
19605 @var{buffer}内に格納できます。
19606 @c COMMON
19607
19608 @defun icmp4-fill-echo! buffer ident sequence data
19609 @c MOD rfc.icmp
19610 @c EN
19611 Fills @var{buffer} with the ICMPv4 Echo Request packet.
19612 @var{Data} must be a u8vector. The checksum field is
19613 left to be zero, which can be filled by @code{icmp4-fill-checksum!}.
19614 @c JP
19615 @var{buffer}にICMPv4のエコーリクエストパケットを詰め込みます。
19616 @var{Data}はu8vectorでなければなりません。チェックサムフィールドはゼロ
19617 のままです。チェックサムは@code{icmp4-fill-checksum!}を使って埋め込み
19618 ます。
19619 @c COMMON
19620 @end defun
19621
19622 @defun icmp4-fill-checksum! buffer size
19623 @c MOD rfc.icmp
19624 @c EN
19625 Calculates the ICMPv4 checksum of the packet in the @var{buffer},
19626 of @var{size} length (the size of the packet, not the buffer),
19627 and fills the checksum field of the packet.
19628 @c JP
19629 @var{buffer}中の@var{size}(バッファではなくパケットの長さ)分のパケット
19630 のICMPv4チェックサムを計算し、そのパケットのチェックサムフィールドをう
19631 めます。
19632 @c COMMON
19633 @end defun
19634
19635 @defun icmp6-fill-echo! buffer ident sequence data
19636 @c MOD rfc.icmp
19637 @c EN
19638 Fills @var{buffer} with the ICMPv6 Echo Request packet.
19639 @var{Data} must be a u8vector. The checksum field is
19640 left to be zero, which is to be filled by the kernel
19641 (so you don't need to fill by yourself).
19642 @c JP
19643 @var{buffer}にICMPv6のエコーリクエストパケットを詰め込みます。
19644 @var{Data}はu8vectorでなければなりません。チェックサムフィールドは
19645 ゼロのままで、ここはカーネルが埋めることになっています。したがって、
19646 ユーザーが自分で埋める必要はありません。
19647 @c COMMON
19648 @end defun
19649
19650 @defun icmp-packet-type buffer offset
19651 @defunx icmp-packet-code buffer offset
19652 @defunx icmp-packet-ident buffer offset
19653 @defunx icmp-packet-sequence buffer offset
19654 @c MOD rfc.icmp
19655 @c EN
19656 Extracts type, code, ident and sequence fields of ICMP packet.
19657 These functions are common to both ICMPv4/v6.
19658 @c JP
19659 それぞれICMPパケットのタイプ、コード、識別子、シーケンスフィールドを抜
19660 き出します。これらの関数はICMPv4/v6で共通です。
19661 @c COMMON
19662 @end defun
19663
19664 @defun icmp4-describe-packet buffer offset
19665 @defunx icmp6-describe-packet buffer offset
19666 @c MOD rfc.icmp
19667 @c EN
19668 Prints out a simple text description of the given ICMPv4 and v6 packet,
19669 respectively.
19670 @c JP
19671 それぞれ与えられたICMPv4およびICMPv6パケットの簡単な説明を印字します。
19672 @c COMMON
19673 @end defun
19674
19675 @defun icmp4-message-type->string type
19676 @defunx icmp4-unreach-code->string code
19677 @defunx icmp4-redirect-code->string code
19678 @defunx icmp4-router-code->string code
19679 @defunx icmp4-exceeded-code->string code
19680 @defunx icmp4-parameter-code->string code
19681 @defunx icmp4-security-code->string code
19682 @defunx icmp6-message-type->string type
19683 @defunx icmp6-unreach-code->string code
19684 @defunx icmp6-exceeded-code->string code
19685 @defunx icmp6-parameter-code->string code
19686 @c MOD rfc.icmp
19687 @c EN
19688 Returns a text description of ICMPv4 and ICMPv6 types and codes.
19689 @c JP
19690 ICMPv4およびICMPv6のタイプとコードの説明テキストを返します。
19691 @c COMMON
19692 @end defun
19693
19694 @c ----------------------------------------------------------------------
19695 @node IP packets, JSON parsing and construction, ICMP packets, Library modules - Utilities
19696 @section @code{rfc.ip} - IP packets
19697 @c NODE IPパケット, @code{rfc.ip} - IPパケット
19698
19699 @deftp {Module} rfc.ip
19700 @mdindex rfc.ip
19701 @c EN
19702 This module provides some basic utilities to parse raw IP packets.
19703 @c JP
19704 このモジュールは生のIPパケットを解析する基本的なユーティリティを提供し
19705 ます。
19706 @c COMMON
19707 @end deftp
19708
19709 @c EN
19710 The @var{packet} argument in the following functions must be
19711 any type of uniform vector (@pxref{Uniform vectors}), containing
19712 a raw IP packet including its IP header.
19713 Those functions work for both IPv4 and IPv6 packets; however,
19714 reading from a raw IPv6 socket returns a packet without IPv6 header,
19715 so you usually don't need to use these functions.
19716 @c JP
19717 次からの関数における@var{packet}引数はユニフォームベクタ
19718 (@ref{Uniform vectors}参照)型でなければなりません。これにはIPヘッダを
19719 含む生のIPパケットが入ります。以下の関数はIPv4およびIPv6パケットの両方
19720 で動きます。しかしながら、生のIPv6ソケットから読むときは、IPv6ヘッダを
19721 含まないパケットが返ります。とうわけで、通常これらの関数が必要になるこ
19722 とはないでしょう。
19723 @c COMMON
19724
19725 @c EN
19726 The @var{offset} argument specifies the beginning of the IP packet
19727 in @var{packet}. If @var{packet} contains only one IP packet
19728 you can pass 0. It is not an optional argument, since these routines
19729 may be used in speed-sensitive inner loop.
19730 @c JP
19731 @c COMMON
19732
19733 @defun ip-version packet offset
19734 @c MOD rfc.ip
19735 @c EN
19736 Returns the IP version number (either 4 or 6) of the given IP packet.
19737 @c JP
19738 与えられたIPパケットのIPバージョン番号(4または6)が返ります。
19739 @c COMMON
19740 @end defun
19741
19742 @defun ip-header-length packet offset
19743 @c MOD rfc.ip
19744 @c EN
19745 Returns the size of IP header of the given packet in octets,
19746 including any IP header options.
19747 @c JP
19748 与えられたパケットのIPヘッダ(IPヘッダオプションもすべて含む)のオクテッ
19749 トで数えたサイズを返します。
19750 @c COMMON
19751 @end defun
19752
19753 @defun ip-protocol packet offset
19754 @c MOD rfc.ip
19755 @c EN
19756 Returns the IP protocol number of the given packet.
19757 @c JP
19758 与えられたパケットのIPプロトコル番号を返します。
19759 @c COMMON
19760 @end defun
19761
19762 @defun ip-source-address packet offset
19763 @defunx ip-destination-address packet offset
19764 @c MOD rfc.ip
19765 @c EN
19766 Returns the source and destination address in the given packet
19767 in an integer, respectively.
19768 @c JP
19769 与えられたパケットの送信元アドレスと送信先アドレスをそれぞれ整数で返し
19770 ます。
19771 @c COMMON
19772 @end defun
19773
19774
19775 @c ----------------------------------------------------------------------
19776 @node JSON parsing and construction, MD5 message digest, IP packets, Library modules - Utilities
19777 @section @code{rfc.json} - JSON parsing and construction
19778 @c NODE JSONのパーズと構築, @code{rfc.json} - JSONのパーズと構築
19779
19780 @deftp {Module} rfc.json
19781 @mdindex rfc.json
19782 @c EN
19783 Procedures to parse JSON (RFC7159) data to S-expressions,
19784 and convert S-expressions to JSON representation, are provided.
19785 @c JP
19786 RFC7159で規定される、JSON形式をパーズしてS式に直す手続きと、
19787 S式をJSON形式に変換する手続きが提供されます。
19788 @c COMMON
19789 @end deftp
19790
19791 @c EN
19792 @subheading Parsing JSON
19793 @c JP
19794 @subheading JSONのパーズ
19795 @c COMMON
19796
19797 @deftp {Condition type} <json-parse-error>
19798 @c MOD rfc.json
19799 @c EN
19800 The parser @code{parse-json} and @code{parse-json-string} raise
19801 this condition when they encounter
19802 invalid JSON syntax. It inherits @code{<error>}, and adds the following
19803 slot.
19804 @c JP
19805 パーズ手続き@code{parse-json}と@code{parse-json-string}は、
19806 無効なJSON構文に出会った時にこのコンディションを投げます。
19807 @code{<error>}を継承し、次のスロットを追加で持ちます。
19808 @c COMMON
19809
19810 @defivar {<json-parse-error>} position
19811 @c EN
19812 The input position, counted in characters, where the error occurred.
19813 @c JP
19814 エラーが起きた入力位置(文字数)。
19815 @c COMMON
19816 @end defivar
19817 @end deftp
19818
19819 @deffn {Parameter} json-nesting-depth-limit
19820 [SRFI-180]
19821 @c MOD rfc.json
19822 @c EN
19823 Its value must be a real number, specifying the maximum nesting depth
19824 of JSON text that can be parsed by @code{parse-json}. If the input
19825 exceeds the value, an @code{<json-parse-error>} is thrown.
19826 The default value is @code{+inf.0}.
19827 @c JP
19828 このパラメータの値は実数でなければなりません。
19829 @code{parse-json}がパーズするJSONテキストに許される最大のネストの深さを指定します。
19830 入力のネスト深さがこのパラメータの値を越えた場合、@code{<json-parse-error>}が
19831 投げられます。
19832 デフォルトは@code{+inf.0}です。
19833 @c COMMON
19834 @end deffn
19835
19836
19837 @defun parse-json :optional input-port
19838 @c MOD rfc.json
19839 @c EN
19840 Reads and parses the JSON representation from @var{input-port} (default is
19841 the current input port), and returns the result in an S-expression.
19842 May raise a @code{<json-parse-error>} condition when parse error occurs,
19843 or the nesting level exceeds the value of @code{json-nesting-depth-limit}.
19844 @c JP
19845 JSON表記を@var{input-port} (省略された場合はcurrent-input-port)から
19846 読み込みパーズして、結果をS式で返します。
19847 パーズエラーが起きたり、ネストレベルが@code{json-nesting-depth-limit}の
19848 値を超過した場合は@code{<json-parse-error>}コンディションを投げます。
19849 @c COMMON
19850
19851 @c EN
19852 The following table shows how JSON datatypes are
19853 mapped to Scheme objects.
19854 @c JP
19855 下のテーブルに、JSONのデータ型がどのようにSchemeにマップされるかを示します。
19856 @c COMMON
19857
19858 @table @asis
19859 @c EN
19860 @item @code{true}, @code{false}, @code{null}
19861 Symbols @code{true}, @code{false} and @code{null}.
19862 (Customizable by @code{json-special-handler})
19863 @item Arrays
19864 Scheme vectors. (Customizable by @code{json-array-handler})
19865 @item Objects
19866 Scheme assoc-lists, in which keys are strings, and values
19867 are Scheme objects. (Customizable by @code{json-object-handler})
19868 @item Numbers
19869 Scheme inexact real numbers.
19870 @item Strings
19871 Scheme strings.
19872 @c JP
19873 @item @code{true}, @code{false}, @code{null}
19874 シンボル@code{true}, @code{false} and @code{null}。
19875 (@code{json-special-handler}で変更可能)
19876 @item 配列
19877 Schemeのベクタ。 (@code{json-array-handler}で変更可能)
19878 @item オブジェクト
19879 Schemeの連想リスト。キーは文字列で、値はSchemeオブジェクト。
19880 (@code{json-object-handler}で変更可能)
19881 @item 数値
19882 Schemeの非正確な実数。
19883 @item 文字列
19884 Schemeの文字列。
19885 @c COMMON
19886 @end table
19887
19888 @c EN
19889 Since the parser used internally in @code{parse-json} prefetches
19890 characters, some characters after the parsed JSON expression
19891 may already been read from @var{port} when @code{parse-json} returns.
19892 That is, you cannot call @code{parse-json} repeatedly on @var{port}
19893 to read subsequent JSON expressions. Use @code{parse-json*} if you
19894 need to read multiple JSON expressions.
19895 @c JP
19896 @code{parse-json}内で使っているパーザは文字の先読みを行う可能性があるので、
19897 @code{parse-json}が戻って来た時点で、パーズされたJSON式以降のいくつかの文字が
19898 @var{port}から既に読まれてしまっている可能性があります。
19899 すなわち、複数のJSON式を読み出すのに、@var{port}に対して@code{parse-json}
19900 を繰り返し呼び出すのはうまくいきません。複数のJSON式をパーズしたい場合は
19901 @code{parse-json*}を使ってください。
19902 @c COMMON
19903 @end defun
19904
19905 @defun parse-json* :optional input-port
19906 @c MOD rfc.json
19907 @c EN
19908 Read JSON repeatedly from @var{input-port} until it reaches EOF,
19909 and returns parsed results as a list.
19910 @c JP
19911 @var{input-port}から、EOFに達するまでJSON式を繰り返し読み取り、
19912 パーズ結果をリストにして返します。
19913 @c COMMON
19914 @end defun
19915
19916 @defun parse-json-string str
19917 @c MOD rfc.json
19918 @c EN
19919 Parses the JSON string and returns the result in an S-expression.
19920 May raise a @code{<json-parse-error>} condition when parse error occurs.
19921
19922 See @code{parse-json} above for the mappings from JSON datatypes
19923 to Scheme types.
19924 @c JP
19925 文字列@var{str}をJSONとしてパーズし、結果をS式で返します。
19926 パーズエラーが起きた場合は@code{<json-parse-error>}コンディションを投げます。
19927
19928 JSONのデータ型とSchemeの型とのマッピングについては上の@code{parse-json}
19929 を参照してください。
19930 @c COMMON
19931 @end defun
19932
19933 @deffn {Parameter} json-array-handler
19934 @deffnx {Parameter} json-object-handler
19935 @deffnx {Parameter} json-special-handler
19936 @c MOD rfc.json
19937 @c EN
19938 The value of these parameters must be a procedure that takes
19939 one argument: for @code{json-array-handler}, it is a list of
19940 elements of a JSON array, for @code{json-object-handler},
19941 it is a list of conses of key and value of a JSON object,
19942 and for @code{json-special-handler}, it is one of the
19943 symbols @code{false}, @code{true} or @code{null}.
19944
19945 Whenever @code{parse-json} reads a JSON array, a JSON object,
19946 or one of those special values,
19947 it calls corresponding parameter to get a Scheme object.
19948
19949 The default value of these parameters are @code{list->vector},
19950 @code{identity}, and @code{identity}, respectively.
19951
19952 The following example maps JSON objects to hash tables.
19953 @c JP
19954 これらのパラメータの値は、引数をひとつ取る手続きでなければなりません。
19955 @code{json-array-handler}の値の手続きに渡される引数は、
19956 JSON配列の要素のリストです。
19957 @code{json-object-handler}では
19958 JSONオブジェクトのキーと値をconsしたもののリスト、
19959 @code{json-special-handler}では
19960 シンボル@code{false}, @code{true}, @code{null}のいずれかです。
19961
19962 @code{parse-json}はJSON配列やオブジェクト、false、true、nullに
19963 出会う度に、
19964 このパラメータの値の手続きを起動して、JSONに対応するSchemeオブジェクトを
19965 得ます。
19966
19967 これらのパラメータのデフォルト値はそれぞれ@code{list->object}、
19968 @code{identity}、@code{identity}です。
19969
19970 次の例では、JSONオブジェクトをハッシュテーブルに変換しています。
19971 @c COMMON
19972
19973 @example
19974 (parameterize ([json-object-handler (cut alist->hash-table <> 'string=?)])
19975 (parse-json-string "@{\"a\":1, \"b\":2@}"))
19976 @result{} #<hash-table ...>
19977 @end example
19978 @end deffn
19979
19980 @c EN
19981 @subheading Constructing JSON
19982 @c JP
19983 @subheading JSONの構築
19984 @c COMMON
19985
19986 @deftp {Condition type} <json-construct-error>
19987 @c MOD rfc.json
19988 @c EN
19989 The converters @code{construct-json} and
19990 @code{construct-json-string} raise this condition
19991 when they cannot convert given Scheme object to JSON.
19992 It inherits @code{<error>}, and adds the following slot.
19993 @c JP
19994 @code{construct-json}と@code{construct-json-string}は、
19995 JSONに変換できないSchemeオブジェクトを見つけるとこのコンディションを投げます。
19996 @code{<error>}を継承し、次のスロットを追加で持ちます。
19997 @c COMMON
19998
19999 @defivar {<json-construct-error>} object
20000 @c EN
20001 The Scheme object that cannot convert to JSON representation.
20002 @c JP
20003 JSON表現に変換できなかったSchemeオブジェクト。
20004 @c COMMON
20005 @end defivar
20006 @end deftp
20007
20008 @deftp {Class} <json-mixin>
20009 @c MOD rfc.json
20010 @c EN
20011 A Gauche object of a class inheriting this mixin class is automatically
20012 serialized to JSON object with the following rule:
20013 @c JP
20014 このmixinクラスを継承しているクラスのインスタンスは、以下の規則を使って
20015 自動的にJSONオブジェクトにシリアライズされます。
20016 @c COMMON
20017
20018 @itemize @bullet
20019 @item
20020 @c EN
20021 Each slot of the object is examined. Only the slots
20022 with its slot definition has a true value in @code{:json-name}
20023 option are the subject to be serialized.
20024 @c JP
20025 オブジェクトのスロットのうち、@code{:json-name}がそのスロット定義オプション
20026 に含まれていて偽でないもののみがシリアライズの対象となります。
20027 @c COMMON
20028 @item
20029 @c EN
20030 If @code{:json-name} option is @code{#t}, the slot name is used
20031 as the key; otherwise, string representation (@code{x->string})
20032 of the option's value is used as the key.
20033 @c JP
20034 @code{:json-name}スロット定義オプションが@code{#t}ならばスロット名が
20035 キーとして使われ、そうでなければその値を@code{x->string}で文字列化したものがキー
20036 として使われます。
20037 @c COMMON
20038 @item
20039 @c EN
20040 Then the slot value is serialized recursively.
20041 @c JP
20042 スロットの値が再帰的にシリアライズされます。
20043 @c COMMON
20044 @end itemize
20045
20046 @example
20047 (define-class <foo> (<json-mixin>)
20048 ((slot-1 :init-keyword :slot-1 :json-name "Slot1")
20049 (slot-2 :init-keyword :slot-2 :json-name #t)
20050 (slot-3 :init-keyword :slot-3)))
20051
20052 (construct-json
20053 (make <foo> :slot-1 "xyz" :slot-2 123 :slot-3 'abc))
20054 @result{} @r{prints}
20055 @{"Slot1":"xyz","slot-2":123@}
20056 @end example
20057 @end deftp
20058
20059
20060 @defun construct-json obj :optional output-port
20061 @defunx construct-json-string obj
20062 @c MOD rfc.json
20063 @c EN
20064 Creates JSON representation of Scheme object @var{obj}.
20065 @code{construct-json} writes out the result to @var{output-port},
20066 whose default is the current output port. @code{construct-json-string}
20067 returns the result in a string.
20068
20069 If @var{obj} contains a Scheme object that cannot be mapped
20070 to JSON representation, a @code{<json-construct-error>} condition
20071 is raised.
20072
20073 Scheme objects are mapped to JSON as follows:
20074 @c JP
20075 Schemeオブジェクト@var{obj}のJSON表現を作ります。
20076 @code{construct-json}は結果を@var{output-port}に書き出します。デフォルトは
20077 current-output-portです。@code{construct-json-string}は結果を文字列で返します。
20078
20079 @var{obj}がJSONにマップできないオブジェクトを含んでいた場合は
20080 @code{<json-construct-error>}コンディションが投げられます。
20081
20082 Schemeオブジェクトは以下のようにJSONへと変換されます。
20083 @c COMMON
20084
20085 @table @asis
20086 @c EN
20087 @item symbol @code{false}, @code{#f}
20088 @code{false}
20089 @item symbol @code{true}, @code{#t}
20090 @code{true}
20091 @item symbol @code{null}
20092 @code{null}
20093 @item list, instance of @code{<dictionary>}
20094 JSON object (list must be an assoc list of key and value).
20095 @item string
20096 string
20097 @item real number
20098 number
20099 @item instance of @code{<sequence>} (except strings and lists)
20100 JSON array
20101 @c JP
20102 @item シンボル@code{false}, @code{#f}
20103 @code{false}
20104 @item シンボル@code{true}, @code{#t}
20105 @code{true}
20106 @item シンボル@code{null}
20107 @code{null}
20108 @item リスト、 @code{<dictionary>}のインスタンス
20109 JSONオブジェクト (リストはキーと値の連想リストでなければならない)
20110 @item 文字列
20111 文字列
20112 @item 実数
20113 数値
20114 @item @code{<sequence>}のインスタンス (文字列とリストを除く)
20115 JSON配列
20116 @c COMMON
20117 @end table
20118
20119 @end defun
20120
20121 @c ----------------------------------------------------------------------
20122 @node MD5 message digest, MIME message handling, JSON parsing and construction, Library modules - Utilities
20123 @section @code{rfc.md5} - MD5 message digest
20124 @c NODE MD5メッセージダイジェスト, @code{rfc.md5} - MD5メッセージダイジェスト
20125
20126 @deftp {Module} rfc.md5
20127 @mdindex rfc.md5
20128 @c EN
20129 This module implements MD5 message digest algorithm, defined in
20130 RFC 1321 (@uref{https://www.ietf.org/rfc/rfc1321.txt}).
20131 The module extends util.digest
20132 (@pxref{Message digester framework}).
20133 @c JP
20134 このモジュールは、RFC 1321 (@uref{https://www.ietf.org/rfc/rfc1321.txt}) で
20135 定義されている、MD5メッセージダイジェストアルゴリズムを実装しています。
20136 このモジュールは、util.digest (@ref{Message digester framework}参照)
20137 を拡張しています。
20138 @c COMMON
20139
20140 @c EN
20141 Typically, all you need to do is to pass the class object @code{<md5>}
20142 to the message
20143 digester; @pxref{Message digester framework}, and also
20144 @pxref{HMAC keyed-hashing}.
20145 @c JP
20146 通常、メッセージダイジェストを行う手続きにクラスオブジェクト@code{<md5>}
20147 を渡すだけで使うことができます。
20148 詳しくは@ref{Message digester framework}および
20149 @ref{HMAC keyed-hashing}を参照してください。
20150 @c COMMON
20151 @end deftp
20152
20153 @deftp {Class} <md5>
20154 @clindex md5
20155 @c MOD rfc.md5
20156 @c EN
20157 The instance of this class keeps internal state of MD5 digest algorithm.
20158 This class implements @code{util.digest} framework interface,
20159 so you can pass this class to message digest procedures such as
20160 @code{digest-message-to} (@pxref{Message digester framework}).
20161 @c JP
20162 このクラスのインスタンスは、MD5ダイジェストアルゴリズムの内部状態を
20163 保持しています。
20164 このクラスは、@code{util.digest}フレームワークのインターフェース、
20165 を実装しており、
20166 メッセージダイジェストを行う@code{digest-message-to}などの手続きに
20167 このクラスオブジェクトを渡すことができます(@ref{Message digester framework}参照)。
20168 @c COMMON
20169 @end deftp
20170
20171 @c EN
20172 The following procedures are deprecated. Use generic
20173 message digester (@pxref{Message digester framework}) or
20174 HMAC keyed digester (@pxref{HMAC keyed-hashing}).
20175 @c JP
20176 以下の手続きは非推奨です。
20177 ジェネリックなメッセージダイジェスター(@ref{Message digester framework}参照)や、
20178 HMAC鍵つきダイジェスター(@ref{HMAC keyed-hashing}参照)を使ってください。
20179 @c COMMON
20180
20181 @defun md5-digest
20182 @c MOD rfc.md5
20183 @c DEPRECATED
20184 @c EN
20185 Reads data from the current input port until EOF, and returns
20186 its digest in an incomplete string.
20187 @c JP
20188 現在の入力ポートからEOFまで読み込み、そのダイジェストを不完全文字列で
20189 返します。
20190 @c COMMON
20191 @end defun
20192
20193 @defun md5-digest-string string
20194 @c MOD rfc.md5
20195 @c DEPRECATED
20196 @c EN
20197 Digest the data in @var{string}, and returns the result
20198 in an incomplete string.
20199 @c JP
20200 @var{string}にあるデータをダイジェストし、その結果を不完全文字列で
20201 返します。
20202 @c COMMON
20203 @end defun
20204
20205 @c ----------------------------------------------------------------------
20206 @node MIME message handling, Quoted-printable encoding/decoding, MD5 message digest, Library modules - Utilities
20207 @section @code{rfc.mime} - MIME message handling
20208 @c NODE MIMEメッセージ処理, @code{rfc.mime} - MIMEメッセージ処理
20209
20210 @deftp {Module} rfc.mime
20211 @mdindex rfc.mime
20212 @c EN
20213 This module provides utility procedures to handle
20214 Multipurpose Internet Mail Extensions (MIME) messages,
20215 defined in RFC2045 thorough RFC2049.
20216 Provided APIs include procedures to parse or compose MIME-specific
20217 header fields, and parse or compose MIME-encoded message bodies.
20218 @c JP
20219 RFC2045からRFC2049で定義されている、
20220 多目的インターネットメール拡張(Multipurpose Internet Mail Extensions; MIME)
20221 メッセージを扱う便利な手続きです。MIME特有のヘッダフィールドやメッセージボディを
20222 パーズしたり作成したりするAPIが提供されます。
20223 @c COMMON
20224
20225 @c EN
20226 This module mainly focuses on providing low-level building-block procedures,
20227 on top of which application-specific modules are to be built.
20228 For example, @code{rfc.http} uses this module to compose
20229 @code{multipart/form-data} message for the body of POST requests
20230 (@pxref{HTTP client}).
20231 @c JP
20232 このモジュールは主としてビルディングブロックとなる低レベルの手続きに
20233 フォーカスしており、アプリケーション特有のモジュールがこの上に
20234 構築されることを意図しています。例えば@code{rfc.http}はPOSTリクエストの
20235 ボディを@code{multipart/form-data}として構築する際にこのモジュールを
20236 利用します(@ref{HTTP client}参照)。
20237 @c COMMON
20238
20239 @c EN
20240 This module is supposed to be used with @code{rfc.822} module
20241 (@pxref{RFC822 message parsing}).
20242 @c JP
20243 このモジュールは、@code{rfc.822}モジュールと一緒に使うことを
20244 想定しています(@ref{RFC822 message parsing}参照)。
20245 @c COMMON
20246 @end deftp
20247
20248 @c EN
20249 @subheading Utilities for header fields
20250 @c JP
20251 @subheading ヘッダフィールドのユーティリティ
20252 @c COMMON
20253
20254 @c EN
20255 A few utility procedures to parse and generate MIME-specific header fields.
20256 @c JP
20257 MIME特有のヘッダフィールドをパーズしたり生成したりする便利な手続き。
20258 @c COMMON
20259
20260 @defun mime-parse-version field
20261 @c MOD rfc.mime
20262 @c EN
20263 If @var{field} is a valid header field for MIME-Version, returns
20264 its major and minor versions in a list. Otherwise, returns @code{#f}.
20265 It is allowed to pass @code{#f} to @var{field}, so that
20266 you can directly pass the result of @code{rfc822-header-ref} to it.
20267 Given parsed header list by @code{rfc822-read-headers}, you can
20268 get mime version (currently, it should be @code{(1 0)}) by the
20269 following code.
20270 @c JP
20271 @var{field}がそのMIMEバージョンのヘッダフィールドとして有効であれば、
20272 そのメジャーバージョン番号とマイナーバージョン番号をリストにして
20273 返します。そうでなければ、@code{#f}を返します。
20274 @var{field}には@code{#f}を渡せるので、@code{rfc822-header-ref}の
20275 戻り値を直接渡すこともできます。@code{rfc822-read-headers}により
20276 返されるパーズ済みヘッダのリストを渡すことで、以下のように
20277 MIMEのバージョンを得ることができます。(現在は、@code{(1 0)}です。)
20278 @c COMMON
20279 @example
20280 (mime-parse-version (rfc822-header-ref headers "mime-version"))
20281 @end example
20282
20283 @c EN
20284 Note: simple regexp such as @code{#/\d+\.\d+/} doesn't do this job,
20285 for @var{field} may contain comments between tokens.
20286 @c JP
20287 注意: @var{field}はトークンの間にコメントを含むかもしれないので、
20288 @code{#/\d+\.\d+/}のような単純な正規表現では不十分です。
20289 @c COMMON
20290 @end defun
20291
20292 @defun mime-parse-content-type field
20293 @c MOD rfc.mime
20294 @c EN
20295 Parses the "content-type" header field, and returns a list such as:
20296 @c JP
20297 ``content-type''ヘッダフィールドをパーズし、次のようなリストを
20298 返します。
20299 @c COMMON
20300 @example
20301 (@i{type} @i{subtype} (@i{attribute} . @i{value}) @dots{})
20302 @end example
20303 @c EN
20304 where @i{type} and @i{subtype} are MIME media type and
20305 subtype in a string, respectively
20306 @c JP
20307 ここで、@i{type}と@i{subtype}はそれぞれ、MIMEメディアタイプと
20308 サブタイプを文字列で表したものになります。
20309 @c COMMON
20310
20311 @example
20312 (mime-parse-content-type "text/html; charset=iso-2022-jp")
20313 @result{} ("text" "html" ("charset" . "iso-2022-jp"))
20314 @end example
20315
20316 @c EN
20317 If @var{field} is not a valid content-type field, @code{#f} is
20318 returned.
20319 @c JP
20320 @var{field}が有効なcontent-typeフィールドでない場合は、
20321 @code{#f}が返ります。
20322 @c COMMON
20323 @end defun
20324
20325 @defun mime-parse-content-disposition field
20326 @c MOD rfc.mime
20327 @c EN
20328 Parses Content-disposition header field as specified in RFC2183.
20329 @c JP
20330 RFC2183に定められたContent-Dispositionヘッダフィールドをパーズします。
20331 @c COMMON
20332 (mime-parse-content-disposition "attachment; filename=genome.jpeg;\
20333 modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";")
20334 @result{} ("attachment"
20335 ("filename" . "genome.jpeg")
20336 ("modification-date" . "Wed, 12 Feb 1997 16:29:51 -0500"))
20337 @end defun
20338
20339
20340 @defun mime-parse-parameters :optional iport
20341 @defunx mime-compose-parameters params :optional oport :key start-column
20342 @c MOD rfc.mime
20343 @c EN
20344 These are low-level utility procedures to parse and compose @emph{parameter}
20345 part of header fields (as appeared in RFC2045 Section 5.1 etc).
20346
20347 @code{Mime-parse-parameters} reads the parameter
20348 part of the header body from an input port @var{iport}, and
20349 returns an assoc list of the parameter names and values.
20350 Conversely, @code{mime-compose-parameters} takes an assoc
20351 list of names and values, compose parameter part and
20352 emit it to @var{oport}. When omitted, the current input
20353 port and the current output port are used for @var{iport}
20354 and @var{oport}, respectively. You can pass @code{#f} to
20355 @var{oport} and @code{mime-compose-parameters} returns the
20356 result in a string instead of emitting it to a port.
20357 @c JP
20358 これらは、(RFC2045の5.1節にあるような)ヘッダフィールドの値の@emph{parameter}
20359 部分をパーズしたり作成したりするための低レベルのユーティリティ手続きです。
20360
20361 @code{mime-parse-parameters}はヘッダフィールドの値のパラメータ部分を
20362 入力ポート@var{iport}から読んでパーズし、パラメータの名前と値の
20363 連想リストを返します。
20364 @code{mime-compose-parameters}はその逆で、連想リストをとり、
20365 パラメータ部分を構成して@var{oport}へと書き出します。
20366 @var{iport}、@var{oport}はそれぞれ省略された場合、
20367 @code{current-input-port}と@code{current-output-port}を
20368 デフォルトとします。また、@var{oport}に@code{#f}を渡すと
20369 @code{mime-compose-parameters}は結果をポートに書き出すかわりに
20370 文字列として返します。
20371 @c COMMON
20372
20373 @example
20374 (call-with-input-string
20375 "; name=foo; filename=\"foo/bar/baz\""
20376 mime-parse-parameters)
20377 @result{} (("name" . "foo") ("filename" . "foo/bar/baz"))
20378
20379 (mime-compose-parameters
20380 '(("name" . "foo") ("filename" . "foo/bar/baz"))
20381 #f)
20382 @result{} "; name=foo; filename=\"foo/bar/baz\""
20383 @end example
20384
20385 @c EN
20386 @code{Mime-compose-parameters} tries to insert folding line breaks
20387 between parameters to avoid the header line becomes too long.
20388 You can pass the beginning column position of the parameter
20389 part via @var{start-column} argument.
20390 @c JP
20391 @var{mime-compose-parameters}はヘッダ行が長くなりすぎる場合に
20392 パラメータ間に折り返し改行を入れようとします。パラメータ部分が始まる
20393 カラム数は@var{start-column}で与えることができます。
20394 @c COMMON
20395
20396 @c EN
20397 We plan to make these procedures handle RFC2231's parameter value
20398 extension transparently in future.
20399 @c JP
20400 将来は、これらの手続きにRFC2231のパラメータ値拡張を透過的に処理させる予定です。
20401 @c COMMON
20402 @end defun
20403
20404
20405 @defun mime-decode-word word
20406 @c MOD rfc.mime
20407 @c EN
20408 Decodes RFC2047-encoded word. If @var{word} isn't an encoded word,
20409 it is returned as is.
20410
20411 Note that this procedure decodes only if the entire @var{word} is
20412 an ``encoded word'' defined in RFC2047. If you are dealing with
20413 a field that may contain multiple encoded word and/or unencoded parts,
20414 use @code{mime-decode-text} below.
20415 @c JP
20416 RFC2047でエンコードされた@var{word}をデコードします。
20417 @var{word}がRFC2047でエンコードされたものでない場合は、そのまま
20418 返されます。
20419
20420 この手続きは@var{word}全体がRFC2047の規定する``encoded-word''である場合にのみ
20421 デコードを行うことに注意してください。複数のエンコードされた部分や
20422 エンコードされていない部分が混ざっているフィールドを扱う場合は、
20423 下に示す@code{mime-decode-text}を使います。
20424 @c COMMON
20425
20426 @example
20427 (mime-decode-word "=?iso-8859-1?q?this=20is=20some=20text?=")
20428 @result{} "this is some text"
20429 @end example
20430
20431 @end defun
20432 @defun mime-decode-text text
20433 @c MOD rfc.mime
20434 @c EN
20435 Returns a string in which
20436 all encoded words contained within @var{text} are decoded.
20437 This procedure can deal with a header field body that may contain
20438 mixture of non-encoded and encoded parts, and/or multiple encoded
20439 parts. One of such header field is the Subject field of email.
20440
20441 @example
20442 (mime-decode-text "This is =?US-ASCII?q?some=20text?=")
20443 @result{} "This is some text"
20444 @end example
20445 @c JP
20446 @var{text}中に含まれるすべてのencoded wordをデコードした文字列を返します。
20447 この手続きは、エンコードされていない部分とエンコードされている部分が混ざっていたり、
20448 複数のエンコードされている部分を持つヘッダフィールドボディを処理することが
20449 できます。そのようなフィールドの例はemailのSubjectフィールドです。
20450
20451 @example
20452 (mime-decode-text "Yamada Taro (=?utf-8?B?5bGx55SwIOWkqumDjg==?=)")
20453 @result{} "Yamada Taro (山田 太郎)"
20454 @end example
20455 @c COMMON
20456
20457 @c EN
20458 Care should be taken if you apply this procedure to a ``structured''
20459 header field body (see RFC2822 section 2.2.2).
20460 The proper way of parsing a structured header field body is
20461 to tokenize it first, then to decode each word using @code{mime-decode-word}.
20462 since the decoded text may contain characters that affects the tokenization.
20463 (However, if you can just show the header field in human readable way
20464 for informational purposes, you may just use @code{mime-decode-text}
20465 on entire header field for the convenience).
20466 @c JP
20467 この手続きを「構造化された」ヘッダフィールドボディ (RFC2822 2.2.2節参照)
20468 に適用する際には注意が必要です。
20469 構造化されたヘッダフィールドボディをパーズする正式な方法は、
20470 最初にトークンに分割して、それから各wordを
20471 @code{mime-decode-word}を使ってデコードするというものです。
20472 なぜならデコード後のテキスト中に、パージングに影響を与える文字が含まれている
20473 かもしれないからです。
20474 (ただし、単に参考情報を人間にわかりやすいように表示するだけの目的の場合は、
20475 簡便のためにヘッダフィールド全体をこの手続きで一度にデコードしてしまっても
20476 良いでしょう)。
20477 @c COMMON
20478 @end defun
20479
20480 @defun mime-encode-word word :key charset transfer-encoding
20481 @c MOD rfc.mime
20482 @c EN
20483 Encodes @var{word} in the RFC2047 format. The keyword
20484 argument @var{charset} specifies the character encoding scheme
20485 in string or symbol.
20486 whose default is @code{utf-8}. If @var{charset} is other
20487 than @code{utf-8} and @var{word} is a complete string,
20488 the procedure converts the character encoding to @var{charset},
20489 then performs transfer encoding.
20490 @c JP
20491 @var{word}をRFC2047フォーマットにエンコードします。キーワード引数
20492 @var{charset}は文字列かシンボルで文字エンコーディングスキームを指定します。
20493 デフォルトは@code{utf-8}です。@var{charset}の指定が@code{utf-8}以外で、
20494 @var{word}が完全な文字列である場合は、
20495 まず@var{word}が@var{charset}のエンコーディングへと変換され、
20496 その上でトランスファーエンコーディングがかけられます。
20497 @c COMMON
20498
20499 @example
20500 (mime-encode-word "this is some text")
20501 @result{} "=?utf-8?B?dGhpcyBpcyBzb21lIHRleHQ=?="
20502 @end example
20503
20504 @c EN
20505 The keyword argument @var{transfer-encoding} specifies how
20506 the octets are encoded to transfer-safe characters. You can
20507 give a symbol @code{b}, @code{B} or @code{base64} for Base64,
20508 and @code{Q}, @code{q}, @code{quoted-printable} for Quoted-printable
20509 transfer encodings. An error is raised if you pass values other
20510 than those. The default is Base64 encoding.
20511 @c JP
20512 キーワード引数@var{transfer-encoding}は各オクテットを伝達上安全な
20513 文字列へどエンコードする方法を指定します。サポートされている値は、
20514 Base64を指定するシンボル@code{b}、@code{B}、@code{base64}、
20515 およびQuoted printableを指定する
20516 @code{Q}、@code{q}、@code{quoted-printable}です。
20517 これ以外の値を渡した場合はエラーが通知されます。デフォルトはBase64です。
20518 @c COMMON
20519
20520 @c EN
20521 This procedure does not consider the length of the resulting
20522 encoded word, which RFC2047 recommends to be less than 75 octets.
20523 Use @code{mime-encode-text} below to conform the line length limit.
20524 @c JP
20525 この手続きは結果のencoded wordの長さを気にしませんが、
20526 RFC2047によればencoded wordは75オクテットまでに収めることが
20527 要請されています。この要請に対応するには下に示す
20528 @code{mime-encode-text}を使って下さい。
20529 @c COMMON
20530
20531 @c EN
20532 (Note: In most Gauche procedures, a keyword argument @code{encoding}
20533 is used to specify character encodings. In this context we have
20534 two encodings, however, and to avoid the confusion we chose to use
20535 the terms ``charset'' and ``transfer-encoding'' that appear in
20536 RFC documents.)
20537 @c JP
20538 (註:ほとんどのGaucheの手続きでは、キーワード引数@code{encoding}により
20539 文字エンコーディングを指定します。しかしこの手続きの文脈では
20540 2つの「エンコーディング」が存在しているので、混乱を避けるために
20541 RFC文書で使われている``charset''および``transfer-encoding''の用語を
20542 使うこととしました。)
20543 @c COMMON
20544 @end defun
20545
20546 @defun mime-encode-text text :key charset transfer-encoding line-width start-column force
20547 @c MOD rfc.mime
20548 @c EN
20549 Encode @var{text} in RFC2047 format if necessary, and considering
20550 line folding if the result gets too long.
20551
20552 The keyword arguments @var{charset} and @var{transfer-encoding} are the same
20553 as @code{mime-encode-word}.
20554 @c JP
20555 @var{text}を、必要ならばRFC2047フォーマットに従いエンコードします。
20556 また、結果が長すぎる場合の行の折り返しも考慮します。
20557
20558 キーワード引数@var{charset}と@var{transfer-encoding}の意味は
20559 @code{mime-encode-word}と同じです。
20560 @c COMMON
20561
20562 @c EN
20563 If the @var{text} only consists of printable ASCII characters,
20564 no encoding is done, and only line folding is considered.
20565 However, if a true value is given to the @var{force} argument,
20566 even ASCII-only @var{text} is encoded.
20567 @c JP
20568 もし@var{word}が印字可能なASCII文字のみで構成されていた場合は
20569 エンコーディングは行われず、行の折り返しのみが処理されます。
20570 但し、@var{force}引数に真の値が与えられた場合はASCIIのみの@var{text}も
20571 エンコードされます。
20572 @c COMMON
20573
20574 @c EN
20575 The @var{line-width} specifies the maximum line width of the result.
20576 Its default is 76.
20577 If the encoded word gets too long, it is splitted to multiple encoded
20578 words and CR LF SPC sequence (``folding white space'' defined in RFC2822)
20579 are inserted inbetween.
20580 You can suppress this behavior by passing @code{#f} or @code{0} to
20581 @var{line-width}.
20582 Since encoded word needs some overhead characters, it doesn't make much sense
20583 to specify small value to @code{line-width}. Current implementation
20584 rejects @code{line-width} smaller than 30.
20585 @c JP
20586 @var{line-width}は結果に現れる行の最大値を指定します。デフォルトは76です。
20587 encoded wordがこれを越える場合は、複数のencoded wordへと結果は分割され、
20588 間にCR LF SPCシーケンス(RFC2822で定義される``folding white space'')が挿入されます。
20589 @var{line-width}に@code{#f}か@code{0}を渡すことで
20590 行の折り返しを抑制することができます。
20591 encoded wordには文字数でいくらかのオーバヘッドがあるため、
20592 あまり小さい@code{line-width}には意味がありません。現在の実装では
20593 30以下の値は拒否されます。
20594 @c COMMON
20595
20596 @c EN
20597 The @var{start-column} keyword argument can be used to
20598 shorten the first of folded
20599 lines to make room for header field name. For example, if
20600 you want to encode the body of a Subject header field,
20601 you can pass the value of @code{(string-length "Subject: ")} so that
20602 the encoded result can directly concatenated after the header
20603 field name. The default value is 0.
20604 @c JP
20605 @var{start-column}キーワード引数は、ヘッダフィールド名を入れるために
20606 エンコード結果の最初の行だけを短くするのに使えます。
20607 例えばSubjectヘッダフィールドのボディをエンコードする際に、
20608 @code{(string-length "Subject: ")}の値を渡してやれば、
20609 結果を直接"Subject: "の後に連結することができるわけです。
20610 デフォルトの値は0です。
20611 @c COMMON
20612
20613 @c EN
20614 This procedure is not designed to encode parts of structured
20615 header fields, which have further restrictions such as which parts
20616 can be encoded and where the folding white spaces can be inserted.
20617 The robust way is to encode some parts first, then construct
20618 a structured header fields, considering line folding.
20619 @c JP
20620 この手続きはstructured header fieldをエンコードするようには設計
20621 されていません。structured header fieldには、どの部分がエンコード
20622 可能でどの部分にfolding white spaceが挿入可能かについてさらなる
20623 制約があるためです。安全な方法は、まず必要な部分をエンコードし、
20624 それから折り返しを考慮しつつstructured header fieldを組み立てることです。
20625 @c COMMON
20626 @end defun
20627
20628 @c EN
20629 @subheading Streaming parser
20630 @c JP
20631 @subheading ストリーミングパーザ
20632 @c COMMON
20633
20634 @c EN
20635 The streaming parser is designed so that you can decide how
20636 to do with the message body before the entire message is read.
20637 @c JP
20638 メッセージ全体が読み込まれる前にメッセージボディをどのように
20639 扱うかをコントロールできるように、ストリームパーザが用意されて
20640 います。
20641 @c COMMON
20642
20643 @defun mime-parse-message port headers handler
20644 @c MOD rfc.mime
20645 @c EN
20646 The fundamental streaming parser. @var{Port} is an input port
20647 from where the message is read. @var{Headers} is a list of headers
20648 parsed by @code{rfc822-read-headers}; that is, this procedure
20649 is supposed to be called after the header part of the message
20650 is parsed from @var{port}:
20651 @c JP
20652 基本的なストリームパーザです。@var{port}は、メッセージを読み込む
20653 入力ポートです。@var{headers}は@code{rfc822-read-headers}により
20654 パーズされたヘッダのリストです。つまり、この手続きは、
20655 @var{port}から読み込まれたメッセージのヘッダ部分がパーズされた
20656 後に使われることを想定しています。
20657 @c COMMON
20658 @example
20659 (let* ((headers (rfc822-read-headers port)))
20660 (if (mime-parse-version (rfc822-header-ref headers "mime-version"))
20661 ;; parse MIME message
20662 (mime-parse-message port headers handler)
20663 ;; retrieve a non-MIME body
20664 ...))
20665 @end example
20666
20667 @c EN
20668 @code{Mime-parse-message} analyzes @var{headers}, and calls
20669 @var{handler} on each message body with two arguments:
20670 @c JP
20671 @code{mime-parse-message}は@var{headers}を解析し、
20672 メッセージボディのそれぞれについて、2引数をもって
20673 @var{handler}を呼び出します。
20674 @c COMMON
20675
20676 @example
20677 (handler @var{part-info} @var{xport})
20678 @end example
20679
20680 @c EN
20681 @var{Part-Info} is a @code{<mime-part>} structure described below
20682 that encapsulates the information of this part of the message.
20683 @c JP
20684 @var{part-info}は、以下で説明するような、メッセージのこのパートの
20685 情報をカプセル化した@code{<mime-part>}ストラクチャです。
20686
20687 @c EN
20688 @var{Xport} is an input port, initially points to the beginning
20689 of the body of message. The handler can read from the port
20690 as if it is reading from the original @var{port}. However,
20691 @var{xport} recognizes MIME boundary internally, and returns EOF
20692 when it reaches the end of the part.
20693 (Do not read from the original @var{port} directly, or it will mess up
20694 the internal state of @var{vport}).
20695 @c JP
20696 @var{xport}は入力ポートで、最初はメッセージボディの先頭を指しています。
20697 ハンドラはこのポートからメッセージボディを読み込むことが出来ます。
20698 @var{xport}はMIMEバウンダリを認識し、パートの最後に到達したら
20699 EOFを返します。
20700 (元の@var{port}から直接読み込まないようにして下さい。
20701 そうしてしまうと、@var{vport}の内部状態がおかしくなります)。
20702 @c COMMON
20703
20704 @c EN
20705 @var{Handler} can read the part into the memory, or
20706 save it to the disk, or even discard the part.
20707 Whatever it does, it has to read from @var{vport} until it
20708 returns EOF.
20709
20710 The return value of @var{handler} will be set in
20711 the @code{content} slot of @var{part-info}.
20712 @c JP
20713 @var{handler}は、パートをメモリに読み込んだり、ディスクに保存したり、
20714 あるいはそのパートを無視したりできます。ただ、何をするにせよ、
20715 @var{vport}がEOFを返すまでデータを読まなければなりません。
20716
20717 @var{handler}の戻り値は、@var{part-info}の@code{content}スロットに
20718 セットされます。
20719
20720 @c EN
20721 If the message has nested multipart messages, @var{handler} is
20722 called for each "leaf" part, in depth-first order. @var{Handler}
20723 can know its nesting level by examining @var{part-info} structure.
20724 @c JP
20725 メッセージが、ネストしたマルチパートメッセージを含んでいる場合は、
20726 @var{handler}は深さ優先でそれぞれの``葉''のパートに対して呼ばれます。
20727 @var{handler}は、@var{part-info}ストラクチャを調べることで、
20728 そのネストのレベルを知ることができます。
20729
20730 @c EN
20731 The message doesn't need to be a multipart type; if it is a
20732 MIME @code{message} type, @var{handler} is called on the body
20733 of enclosed message. If it is other media types such as @code{text}
20734 or @code{application}, @var{handler} is called on the (only) message body.
20735 @c JP
20736 メッセージはマルチパートである必要はありません。メッセージが
20737 MIME @code{message}タイプである場合は、@var{handler}は囲まれたメッセージの
20738 ボディに対して呼ばれます。メッセージが、@code{text}や@code{application}
20739 などの他のメディアタイプの場合は、@var{handler}は単にメッセージボディに
20740 対して呼ばれます。
20741 @c COMMON
20742 @end defun
20743
20744 @deftp {Class} <mime-part>
20745 @clindex mime-message
20746 @c MOD rfc.mime
20747 @c EN
20748 A structure that encloses metainformation about a MIME part.
20749 It is constructed when the header of the part is read, and
20750 passed to the handler that reads the body of the part.
20751
20752 It has the following slots:
20753 @c JP
20754 MIMEパートのメタ情報を含むストラクチャです。
20755 これは、そのパートのヘッダが読み込まれた時点で構築され、
20756 そのパートのボディを読み込むハンドラに渡されます。
20757
20758 以下のスロットを持ちます。
20759 @c COMMON
20760
20761 @defivar {<mime-part>} type
20762 @c EN
20763 MIME media type string. If @code{content-type} header is omitted
20764 to the part, an appropriate default value is set.
20765 @c JP
20766 MIMEメディアタイプの文字列。そのパートの@code{content-type}ヘッダが
20767 省略された場合は、適切なデフォルト値がセットされます。
20768 @c COMMON
20769 @end defivar
20770
20771 @defivar {<mime-part>} subtype
20772 @c EN
20773 MIME media subtype string. If @code{content-type} header is omitted
20774 to the part, an appropriate default value is set.
20775 @c JP
20776 MIMEメディアのサブタイプの文字列。そのパートの@code{content-type}
20777 ヘッダが省略された場合は、適切なデフォルト値がセットされます。
20778 @c COMMON
20779 @end defivar
20780
20781 @defivar {<mime-part>} parameters
20782 @c EN
20783 Associative list of parameters given to @code{content-type} header field.
20784 @c JP
20785 @code{content-type}ヘッダフィールドに渡されるパラメータの連想リスト。
20786 @c COMMON
20787 @end defivar
20788
20789 @defivar {<mime-part>} transfer-encoding
20790 @c EN
20791 The value of @code{content-transfer-encoding} header field.
20792 If the header field is omitted, an appropriate default value is set.
20793 @c JP
20794 @code{content-transfer-encoding}ヘッダフィールドの値。
20795 このヘッダフィールドが省略された場合は、適切なデフォルト値が
20796 セットされます。
20797 @c COMMON
20798 @end defivar
20799
20800 @defivar {<mime-part>} headers
20801 @c EN
20802 The list of header fields, as parsed by @code{rfc822-read-headers}.
20803 @c JP
20804 @code{rfc822-read-headers}によりパーズされた、ヘッダフィールドのリスト。
20805 @c COMMON
20806 @end defivar
20807
20808 @defivar {<mime-part>} parent
20809 @c EN
20810 If this is a part of multipart message or encapsulated message,
20811 points to the enclosing part's @code{<mime-part>} structure.
20812 Otherwise @code{#f}.
20813 @c JP
20814 それがマルチパートメッセージあるいはカプセル化されたメッセージの
20815 パートである場合は、それを含んでいるパートの@code{<mime-part>}
20816 ストラクチャを指します。そうでなければ@code{#f}を返します。
20817 @c COMMON
20818 @end defivar
20819
20820 @defivar {<mime-part>} index
20821 @c EN
20822 Sequence number of this part within the same parent.
20823 @c JP
20824 同じ親を持つパートの中でのそのパートのシーケンス番号。
20825 @c COMMON
20826 @end defivar
20827
20828 @defivar {<mime-part>} content
20829 @c EN
20830 If this part is multipart/* or message/* media type,
20831 this slot contains a list of parts within it.
20832 Otherwise, the return value of @var{handler} is stored.
20833 @c JP
20834 そのパートのメディアタイプがmultipart/*あるいはmessage/*で
20835 ある場合は、このスロットにはそれに含まれるパートのリストが
20836 入っています。そうでなければ、@var{handler}の戻り値が
20837 格納されています。
20838 @c COMMON
20839 @end defivar
20840
20841 @defivar {<mime-part>} source
20842 @c EN
20843 This slot is only used when composing a MIME message.
20844 The caller can set this slot a name of the file to be inserted
20845 into this part, instead of setting the entire content of the
20846 file to the @code{content} slot. See
20847 @code{mime-compose-message} below for the more details.
20848 @c JP
20849 このスロットはMIMEメッセージを作成する時のみ使われます。
20850 呼び出し元は、このスロットにファイル名をセットすることで、
20851 MIMEメッセージのこのパートにファイルの内容を挿入することができます。
20852 詳しくは下の@code{mime-compose-message}の項を参照してください。
20853 @c COMMON
20854 @end defivar
20855 @end deftp
20856
20857 @defun mime-retrieve-body part-info xport outp
20858 @c MOD rfc.mime
20859 @c EN
20860 A procedure to retrieve message body. It is intended to
20861 to be a building block of @var{handler} to be passed to
20862 @code{mime-parse-message}.
20863
20864 @var{Part-info} is a @code{<mime-part>} object.
20865 @var{Xport} is an input port passed to the handler,
20866 from which the MIME part can be read.
20867 @c JP
20868 メッセージボディを取得するための手続きです。
20869 @code{mime-parse-message}へ渡される、@var{handler}の
20870 ビルディングブロックとなることを意図しています。
20871
20872 @var{part-info}は、@code{<mime-part>}のオブジェクトです。
20873 @var{xport}はハンドラに渡された入力ポートで、
20874 そこからMIMEパートが読みこまれるものです。
20875
20876 @c EN
20877 This procedure read from @var{xport}
20878 until it returns EOF. It also looks at the
20879 @code{transfer-encoding} of @var{part-info}, and decodes
20880 the body accordingly; that is, base64 encoding and
20881 quoted-printable encoding is handled. The result is
20882 written out to an output port @var{outp}.
20883
20884 This procedure does not handle charset conversion.
20885 The caller must use CES conversion port as @var{outp}
20886 (@pxref{Character code conversion}) if desired.
20887 @c JP
20888 この手続きは、@var{xport}からEOFに達するまで読み込み、
20889 @var{part-info}の@code{transfer-encoding}も見て、
20890 ボディを適切にデコードします。つまり、base64やquoted-printable
20891 のエンコーディングは適切に処理されます。結果が出力ポート@var{outp}へと
20892 出力されます。
20893
20894 この手続きは文字集合の変換は扱いません。
20895 必要であれば、呼び出し側が@var{outp}としてCES変換ポートを
20896 使う必要があります(@ref{Character code conversion}参照)。
20897
20898 @c COMMON
20899 @end defun
20900
20901 @c EN
20902 A couple of convenience procedures are defined for typical
20903 cases on top of @code{mime-retrieve-body}.
20904 @c JP
20905 典型的なケースのために、いくつかの便利な手続きが@code{mime-retrieve-body}
20906 の上に定義されています。
20907 @c COMMON
20908
20909 @defun mime-body->string part-info xport
20910 @defunx mime-body->file part-info xport filename
20911 @c MOD rfc.mime
20912 @c EN
20913 Reads in the body of mime message, decoding transfer encoding,
20914 and returns it as a string or writes it to a file, respectively.
20915 @c JP
20916 MIMEメッセージのボディを読み込み、転送(transfer)エンコーディングを
20917 デコードし、それぞれ文字列として返すか、ファイルへ書き出します。
20918 @c COMMON
20919 @end defun
20920
20921 @c EN
20922 The simplest form of MIME message parser would be like this:
20923 @c JP
20924 MIMEメッセージパーザの最もシンプルな使い方は次のように
20925 なります。
20926 @c COMMON
20927
20928 @example
20929 (let ((headers (rfc822-read-headers port)))
20930 (mime-parse-message port headers
20931 (cut mime-body->string <> <>)))
20932 @end example
20933
20934 @c EN
20935 This reads all the message on memory (i.e. the "leaf" @code{<mime-part>}
20936 objects' @code{content} field would hold the part's body as a string),
20937 and returns the top @code{<mime-part>} object. Content transfer encoding
20938 is recognized and handled, but character set conversion isn't done.
20939
20940 You may want to feed the message body to a file directly,
20941 or even want to skip some body according to mime media types and/or
20942 other header information. Then you can put the logic in the handler
20943 closure. That's the reason that this module provides building
20944 blocks, instead of all-in-one procedure.
20945 @c JP
20946 これは、メッセージの全てをメモリに読み込み、
20947 一番上層の@code{<mime-part>}オブジェクトを返します。
20948 (``葉''である@code{<mime-part>}オブジェクトの@code{content}フィールドは、
20949 そのパートのボディを文字列として保持しています。)
20950 内容の転送エンコーディング(content transfer encoding)は認識され処理
20951 されますが、文字集合の変換は行われません。
20952
20953 メッセージボディを直接ファイルに書き出したり、MIMEメディアタイプや
20954 他のヘッダ情報に基づいていくつかのボディをスキップしたいかもしれません。
20955 その場合は、ロジックをハンドラのクロージャに入れることができます。
20956 それが、このモジュールが、オールインワンの手続きではなく、
20957 ビルディングブロックを提供している理由です。
20958 @c COMMON
20959
20960 @c EN
20961 @subheading Message composer
20962 @c JP
20963 @subheading メッセージの構築
20964 @c COMMON
20965
20966 @defun mime-compose-message parts :optional port :key boundary
20967 @defunx mime-compose-message-string parts :key boundary
20968 @c MOD rfc.mime
20969 @c EN
20970 Composes a MIME multipart message. @code{Mime-compose-message}
20971 emits the result to an output port @var{port}, whose default
20972 is the current output port. @code{Mime-compose-message-string}
20973 makes the result into a string. You can give a boundary string
20974 via @var{boundary} argument; when omitted, a fresh boundary string
20975 is automatically generated by @code{mime-make-boundary} below.
20976 @c JP
20977 MIMEマルチパートメッセージを構築します。
20978 @code{mime-compose-message}は結果を@var{port}(省略時は現在の出力ポート)
20979 に書き出します。@code{mime-compose-message-string}は結果を文字列で返します。
20980 バウンダリ文字列を@var{boundary}引数で渡すことができます。省略された場合は
20981 新しいバウンダリ文字列が下の@code{mime-make-boundary}によって作られます。
20982 @c COMMON
20983
20984 @c EN
20985 @code{Mime-compose-message} returns the boundary string.
20986 @code{Mime-compose-message-string} returns two values, the result
20987 string and the boundary string.
20988 @c JP
20989 @code{mime-compose-message}はバウンダリ文字列を、
20990 @code{mime-compose-message-string}は構築されたメッセージ文字列と
20991 バウンダリ文字列の二つの値を返します。
20992 @c COMMON
20993
20994 @c EN
20995 The content of the message is provided by the @var{parts} argument,
20996 which can be a list of instances of @code{<mime-part>} (see above)
20997 or lists that describe parts. The list form is supported for
20998 the caller's convenience, and internally it is converted to
20999 a list of @code{<mime-part>}s.
21000 @c JP
21001 メッセージの内容は@var{parts}引数で与えます。これは
21002 上で説明した@code{<mime-part>}のインスタンスのリストか、
21003 もしくはパートを記述するリストのリストです。後者は簡便のためにサポートされていて、
21004 内部的には@code{<mime-part>}のリストに変換されます。
21005 @c COMMON
21006
21007 @c EN
21008 The syntax of each part element in @var{parts} are defined as follow.
21009 @c JP
21010 @var{part}のリストの各要素は以下の形式を取ります。
21011 @c COMMON
21012
21013 @example
21014 <part> : <mime-part> | <mime-part-desc>
21015
21016 <mime-part> : @r{an instance of the class} <mime-part>
21017
21018 <mime-part-desc> : (<content-type> (<header> ...) <body>)
21019 <content-type> : (<type> <subtype> <header-param> ...)
21020 <header-param> : (<key> . <value>) ...
21021 <header> : (<header-name> <encoded-header-value>)
21022 | (<header-name> (<header-value> <header-param> ...))
21023 <body> : @r{a string}
21024 | (file <filename>)
21025 | (subparts <part> ...)
21026 @end example
21027
21028 @c EN
21029 Note: In the first form of @code{<header>},
21030 @code{<encoded-header-value>} must already be encoded using RFC2047
21031 or RFC2231 if the original value contains non-ascii characters.
21032 In the second form, we plan to do RFC2231 encoding on behalf of
21033 the caller; but the current version does not implement it. The
21034 caller should not pass encoded words in this form, since it may
21035 result double-encoding when we implement the auto encoding feature;
21036 for the time being, the second form restricts ASCII-only values.
21037 @c JP
21038 @code{<header>}の最初の形式において、
21039 @code{<encoded-header-value>}は、元の値がASCII以外の文字を含んでいる場合、
21040 呼び出し側でRFC2047やRFC2231であらかじめエンコードしておかなければなりません。
21041 二番目の形式では、自動的にRFC2231によるエンコードを行う予定がありますが、
21042 今はまだ実装されていません。二番目の形式でエンコード済みの値を渡してしまうと、
21043 将来のバージョンで二重にエンコードされる可能性があるので、
21044 二番目の形式ではASCII文字のみを使ってください。
21045 @c COMMON
21046
21047 @c EN
21048 If @code{<body>} is a string, it is used as the part's content.
21049 If @code{<body>} is @code{(file @var{filename})}, the content is
21050 read from the named file. If @code{<body>} is
21051 @code{(subparts @var{part} @dots{})}, the part becomes nested
21052 MIME part.
21053 @c JP
21054 @code{<body>}が文字列の場合はそれがそのままパートの内容として使われます。
21055 @code{<body>}が@code{(file @var{filename})}の場合は、
21056 指定されたファイルが読み込まれてその内容が使われます。
21057 @code{<body>}が@code{(subparts @var{part} @dots{})}の場合は、
21058 ネストされたMIMEパートになります。
21059 @c COMMON
21060
21061 @c EN
21062 It is the caller's responsibility to match the content type and the content.
21063 For example, if @code{<body>} is in the third form, the
21064 part must have @code{multipart} content type.
21065 @c JP
21066 パートのcontent-typeと内容を一致させるのは呼び出し側の責任です。
21067 例えば@code{<body>}がネストしたMIMEパートである場合は、
21068 content-typeは@code{multipart}でなければなりません。
21069 @c COMMON
21070
21071 @c EN
21072 The caller needs to provide proper @code{content-transfer-encoding}
21073 header, depending on the application. If none is given, the content
21074 is inserted into the message as is, which may be appropriate for
21075 some applications, but if you want to use the result in email
21076 message you certainly want to encode binary part with base64,
21077 for example.
21078 @c JP
21079 アプリケーションによっては、@code{content-transfer-encoding}ヘッダを適切に
21080 与えることも重要です。@code{content-transfer-encoding}ヘッダが与えられない場合、
21081 内容はそのままMIMEメッセージ中に挿入されます。
21082 アプリケーションによってはそれでも良いのですが、
21083 例えばemailで送る場合は、バイナリの内容はbase64でエンコードするなどの配慮が必要です。
21084 @c COMMON
21085 @end defun
21086
21087 @defun mime-make-boundary
21088 @c MOD rfc.mime
21089 @c EN
21090 Returns a unique string that can be used as a boundary of a MIME multipart
21091 message.
21092 @c JP
21093 MIMEマルチパートメッセージのboundaryとして使えるユニークな文字列を返します。
21094 @c COMMON
21095 @end defun
21096
21097
21098 @c ----------------------------------------------------------------------
21099 @node Quoted-printable encoding/decoding, SHA message digest, MIME message handling, Library modules - Utilities
21100 @section @code{rfc.quoted-printable} - Quoted-printable encoding/decoding
21101 @c NODE Quoted-printableエンコーディング, @code{rfc.quoted-printable} - Quoted-printableエンコーディング
21102
21103 @deftp {Module} rfc.quoted-printable
21104 @mdindex rfc.quoted-printable
21105 @c EN
21106 This module defines a few functions to encode/decode Quoted-printable format,
21107 defined in RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}), section 6.7.
21108 @c JP
21109 このモジュールでは、RFC 2045 (@uref{https://www.ietf.org/rfc/rfc2045.txt}) の
21110 セクション6.7で定義されている、Quoted-printableフォーマットにエンコード/から
21111 デコードするためのいくつかの関数を定義しています。
21112 @c COMMON
21113 @end deftp
21114
21115 @defun quoted-printable-encode :key line-width binary
21116 @c MOD rfc.quoted-printable
21117 @c EN
21118 Reads byte stream from the current input port, encodes it in Quoted-printable
21119 format and writes the result character stream to the current output port.
21120 The conversion ends when it reads EOF from the current input port.
21121 @c JP
21122 現在の入力ポートからバイトストリームを読み込み、それをQuoted-printable
21123 フォーマットにエンコードし、現在の出力ポートへ結果の文字ストリームを
21124 書き出します。この変換は、現在の入力ポートからEOFを読み出すと終了します。
21125 @c COMMON
21126 @c EN
21127 The keyword argument @var{line-width} specifies the maximum
21128 line width of the generated output in characters. If the encoded
21129 output creates a long line, the procedure inserts a ``soft line break''
21130 so that the each line is equal to or shorter than this number.
21131 Soft line breaks are removed when quoted-printable text is
21132 decoded.
21133 The default line width is 76. (The minimum meaningful number of
21134 line-width is 4). You can suppress soft line breaks by
21135 giving @code{#f} or @code{0} to @var{line-width}.
21136 @c JP
21137 キーワード引数@var{line-width}は、出力に現れる行の最大長を指定します。
21138 エンコードされた行の長さがこの値を越えそうな場合は、「ソフトラインブレーク」が
21139 適宜挿入され、各行の長さがこの値を越えないように調整されます。
21140 ソフトラインブレークはquoted-printableフォーマットのデコード時に
21141 取り除かれます。
21142 @var{line-width}のデフォルト値は76です。(最小の意味のある値は4です。)
21143 @var{line-width}に@code{#f}または@code{0}を渡せば、
21144 ソフトラインブレークは挿入されません。
21145 @c COMMON
21146 @c EN
21147 By default, @code{quoted-printable-encode} generates @code{CR-LF} sequence
21148 for each line break in the input (``hard line break'').
21149 When a true value is given to the keyword argument @var{binary},
21150 however, octets @code{#x0a} and @code{#x0d} in the input are encoded
21151 as @code{=0A} and @code{=0D}, respectively. See RFC2045 section 6.7
21152 for the details.
21153 @c JP
21154 デフォルトでは、@code{quoted-printable-encode}は入力中の改行に対して
21155 @code{CR-LF}シーケンスを出力します(「ハードラインブレーク」)。
21156 しかし、@var{binary}キーワード引数に真の値が与えられた場合、
21157 入力中のオクテット@code{#x0a}および@code{#x0d}はそれぞれ
21158 @code{=0A}、@code{=0D}のようにエンコードされます。
21159 詳しくはRFC2045の6.7節を参照してください。
21160 @c COMMON
21161 @end defun
21162
21163 @defun quoted-printable-encode-message message :key line-width binary
21164 @c MOD rfc.quoted-printable
21165 @c EN
21166 Converts content of @var{message}, which can be either a string
21167 or a u8vector, to a string of Quoted-printable encoded format.
21168
21169 The keyword arguments are the same as @code{quoted-printable-encode}.
21170 @c JP
21171 文字列かu8vectorの@var{message}の内容をQuoted-printableエンコードして、
21172 結果を文字列で返します。
21173
21174 キーワード引数の意味は@code{quoted-printable-encode}と同じです。
21175 @c COMMON
21176 @end defun
21177
21178 @defun quoted-printable-decode
21179 @c MOD rfc.quoted-printable
21180 @c EN
21181 Reads character stream from the current input port,
21182 decodes it from Quoted-printable
21183 format and writes the result byte stream to the current output port.
21184 The conversion ends when it reads EOF.
21185 If it encounters illegal character sequence (such as '=' followed
21186 by non-hexadecimal characters), it copies them literally to the output.
21187 @c JP
21188 現在の入力ポートから文字ストリームを読み込み、それをQuoted-printable
21189 フォーマットからデコードし、結果のバイトストリームを現在の出力ポートへ
21190 書き出します。
21191 この変換は、EOFを読み出すと終了します。
21192 不正なシーケンス('='の後に16進文字が続かない、など)に出会うと、それらを
21193 リテラルのまま出力へコピーします。
21194 @c COMMON
21195 @end defun
21196
21197 @defun quoted-printable-decode-string-to target string
21198 @c MOD rfc.quoted-printable
21199 @c EN
21200 Decodes a Quoted-printable encoded string @var{string}, and returns
21201 the result as an instance of @var{target}, which must be
21202 either @code{<string>} or @code{<u8vector>}.
21203 @c JP
21204 Quoted-printableエンコードされた文字列@var{string}をデコードし、
21205 その結果を@var{target}のインスタンスで返します。
21206 @var{target}は@code{<string>}か@code{<u8vector>}でなければなりません。
21207 @c COMMON
21208 @end defun
21209
21210
21211 @defun quoted-printable-encode-string string :key line-width binary
21212 @c MOD rfc.quoted-printable
21213 @c DEPRECATED
21214 @c EN
21215 This is for the backward compatibility.
21216 Use @code{quoted-printable-encode-message} instead.
21217 @c JP
21218 これは互換性のために残してある手続きです。
21219 @code{quoted-printable-encode-message}を使うようにしてください。
21220 @c COMMON
21221 @end defun
21222
21223 @defun quoted-printable-decode-string string
21224 @c MOD rfc.quoted-printable
21225 @c DEPRECATED
21226 @c EN
21227 This is for the backward compatibility. It is same as
21228 @code{(quoted-printable-decode-string-to <string> string)}.
21229 @c JP
21230 これは互換性のために残してある手続きです。
21231 @code{(quoted-printable-decode-string-to <string> string)}と同じです。
21232 @c COMMON
21233 @end defun
21234
21235
21236 @c ----------------------------------------------------------------------
21237 @node SHA message digest, Transport layer security, Quoted-printable encoding/decoding, Library modules - Utilities
21238 @section @code{rfc.sha} - SHA message digest
21239 @c NODE SHAメッセージダイジェスト, @code{rfc.sha} - SHAメッセージダイジェスト
21240
21241 @deftp {Module} rfc.sha
21242 @mdindex rfc.sha
21243 @c EN
21244 This module implements US Secure Hash Algorithms.
21245 It provides SHA-1, SHA-2, and SHA-3.
21246
21247 The module extends util.digest
21248 (@pxref{Message digester framework}).
21249 @c JP
21250 このモジュールは、RFC 4634で定義されている
21251 US Secure Hash Algorithmを実装しています。
21252 提供されるアルゴリズムはSHA-1, SHA-2, SHA-3を実装しています。
21253
21254 このモジュールは、util.digest (@ref{Message digester framework}参照)
21255 を拡張しています。
21256 @c COMMON
21257
21258 @c EN
21259 Typically, all you need to do is to pass the class object @code{<sha256>} etc.
21260 to the message
21261 digester; @pxref{Message digester framework}, and also
21262 @pxref{HMAC keyed-hashing}.
21263 @c JP
21264 通常、メッセージダイジェストを行う手続きにクラスオブジェクト@code{<sha256>
21265 }等を渡すだけで使うことができます。
21266 詳しくは@ref{Message digester framework}および
21267 @ref{HMAC keyed-hashing}を参照してください。
21268 @c COMMON
21269
21270 @end deftp
21271
21272 @deftp {Module} rfc.sha1
21273 @mdindex rfc.sha1
21274 @c DEPRECATED
21275 @c EN
21276 This is the old module that provided only SHA-1. It is kept as
21277 an alias of @code{rfc.sha} for the backward compatibility. New code
21278 should use @code{rfc.sha}.
21279 @c JP
21280 これはSHA-1だけを提供していた古いモジュールです。互換性のため、
21281 この名前は@code{rfc.sha}の別名として残されています。
21282 新たに書くコードは@code{rfc.sha}を使ってください。
21283 @c COMMON
21284 @end deftp
21285
21286
21287 @deftp {Class} <sha1>
21288 @deftpx {Class} <sha224>
21289 @deftpx {Class} <sha256>
21290 @deftpx {Class} <sha384>
21291 @deftpx {Class} <sha512>
21292 @deftpx {Class} <sha3-224>
21293 @deftpx {Class} <sha3-256>
21294 @deftpx {Class} <sha3-384>
21295 @deftpx {Class} <sha3-512>
21296 @clindex sha1
21297 @clindex sha224
21298 @clindex sha256
21299 @clindex sha384
21300 @clindex sha512
21301 @clindex sha3-224
21302 @clindex sha3-256
21303 @clindex sha3-384
21304 @clindex sha3-512
21305 @c MOD rfc.sha
21306 @c EN
21307 An instance of these class keeps internal state of SHA digest algorithm.
21308 This class implements @code{util.digest} framework interface,
21309 so you can pass this class to message digest procedures such as
21310 @code{digest-message-to} (@pxref{Message digester framework}).
21311 @c JP
21312 これらのクラスのインスタンスは、SHAダイジェストアルゴリズムの内部状態を
21313 保持しています。
21314 このクラスは、@code{util.digest}フレームワークのインターフェース、
21315 を実装しており、
21316 メッセージダイジェストを行う@code{digest-message-to}などの手続きに
21317 このクラスオブジェクトを渡すことができます(@ref{Message digester framework}参照)。
21318 @c COMMON
21319
21320 @c EN
21321 Classes @code{<sha224>}, @code{<sha256>}, @code{<sha384>}, and @code{<sha512>}
21322 implement SHA-2. Classes @code{<sha3-256>}, @code{<sha3-384>}, and
21323 @code{<sha3-512>} implement SHA-3.
21324 @c JP
21325 @code{<sha224>}、@code{<sha256>}、@code{<sha384>}、@code{<sha512>}の
21326 各クラスはSHA-2を実装しています。
21327 @code{<sha3-256>}、@code{<sha3-384>}、@code{<sha3-512>}の各クラスは
21328 SHA-3を実装しています。
21329 @c COMMON
21330 @end deftp
21331
21332 @c EN
21333 The following procedures are deprecated. Use generic
21334 message digester (@pxref{Message digester framework}) or
21335 HMAC keyed digester (@pxref{HMAC keyed-hashing}).
21336 @c JP
21337 以下の手続きは非推奨です。
21338 ジェネリックなメッセージダイジェスター(@ref{Message digester framework}参照)や、
21339 HMAC鍵つきダイジェスター(@ref{HMAC keyed-hashing}参照)を使ってください。
21340 @c COMMON
21341
21342 @defun sha1-digest
21343 @defunx sha224-digest
21344 @defunx sha256-digest
21345 @defunx sha384-digest
21346 @defunx sha512-digest
21347 @defunx sha3-224-digest
21348 @defunx sha3-256-digest
21349 @defunx sha3-384-digest
21350 @defunx sha3-512-digest
21351 @c MOD rfc.sha
21352 @c DEPRECATED
21353 @c EN
21354 Reads data from the current input port until EOF, and returns
21355 its digest in an incomplete string.
21356 @c JP
21357 現在の入力ポートからデータをEOFまで読み込み、そのダイジェストを
21358 不完全文字列で返します。
21359 @c COMMON
21360 @end defun
21361
21362 @defun sha1-digest-string string
21363 @defunx sha224-digest-string string
21364 @defunx sha256-digest-string string
21365 @defunx sha384-digest-string string
21366 @defunx sha512-digest-string string
21367 @defunx sha3-224-digest-string string
21368 @defunx sha3-256-digest-string string
21369 @defunx sha3-384-digest-string string
21370 @defunx sha3-512-digest-string string
21371 @c MOD rfc.sha
21372 @c DEPRECATED
21373 @c EN
21374 Digest the data in @var{string}, and returns the result
21375 in an incomplete string.
21376 @c JP
21377 @var{string}のデータをダイジェストし、その結果を不完全文字列で
21378 返します。
21379 @c COMMON
21380 @end defun
21381
21382 @c ----------------------------------------------------------------------
21383 @node Transport layer security, URI parsing and construction, SHA message digest, Library modules - Utilities
21384 @section @code{rfc.tls} - Transport layer security
21385 @c NODE トランスポート・レイヤ・セキュリティ, @code{rfc.tls} - トランスポート・レイヤ・セキュリティ
21386
21387 @deftp {Module} rfc.tls
21388 @mdindex rfc.tls
21389 @c EN
21390 This module handles secure connection over TCP socket.
21391 This module is used by @code{rfc.http} to realize https connection
21392 (@pxref{HTTP client}).
21393 @c JP
21394 このモジュールはTCPソケット上のセキュアな接続を処理します。
21395 @code{rfc.http}で、https接続を実現するのに使われています
21396 (@ref{HTTP client}参照)。
21397 @c COMMON
21398 @end deftp
21399
21400 @subheading TLS subsystems
21401
21402 @c EN
21403 Whether the running Gauche has TLS support depends on the build
21404 options, and can be checked with
21405 a feature identifier @code{gauche.net.tls}.
21406 @xref{Feature conditional}, for more about feature identifiers.
21407 @c JP
21408 実行中のGaucheがTLSをサポートしているかどうかは機能識別子
21409 @code{gauche.net.tls}で判別できます。
21410 機能識別子については@ref{Feature conditional}を参照してください。
21411 @c COMMON
21412
21413 @c EN
21414 Gauche uses MbedTLS (@url{https://tls.mbed.org/}) as TLS implementation.
21415 We used to support alternative subsystems, so the library is designed
21416 to handle multiple subsystems. In future we may support additional subsystems.
21417 @c JP
21418 GaucheはTLS実装としてMbedTLS(@url{https://tls.mbed.org/})を使っています。
21419 以前は複数のTLSサブシステムをサポートしていたので、ライブラリは複数のサブシステムを
21420 切り替えて使えるようになっています。将来また別のTLSサブシステムをサポートするかもしれません。
21421 @c COMMON
21422
21423 @deftp {Class} <tls>
21424 @clindex tls
21425 @c MOD rfc.tls
21426 @c EN
21427 An abstract base class of a TLS implementation.
21428 You can use its instance to communicate with peer over secure connection.
21429 You usually don't need to care the concrete subclass; just treat
21430 their instances as @code{<tls>} instance.
21431
21432 This inherits @code{<connection>} (@pxref{Connection framework}).
21433 @c JP
21434 TLS実装のベースクラスです。このクラスのインスタンスを使って、
21435 セキュアなコネクションを張って通信ができます。
21436 通常、具体的なサブクラスを気にする必要はありません。
21437
21438 このクラスは@code{<connection>}を継承します (@ref{Connection framework}参照)。
21439 @c COMMON
21440 @end deftp
21441
21442 @deftp {Class} <mbed-tls>
21443 @clindex mbed-tls
21444 @c MOD rfc.tls
21445 @c EN
21446 A class that implements MbedTLS subsystem interface.
21447 @c JP
21448 MbedTLSサブシステムを実装しているクラスです。
21449 @c COMMON
21450 @end deftp
21451
21452 @deffn {Parameter} default-tls-class
21453 @c MOD rfc.tls
21454 @c EN
21455 The default TLS subsystem to be used. In the current version,
21456 it may just be @code{<mbed-tls>}, or @code{#f} if the system is not
21457 compiled with TLS support.
21458 @c JP
21459 デフォルトのTLSサブシステムです。現在のバージョンでは、
21460 これは@code{<mbed-tls>}クラスか@code{#f}です。
21461 @code{#f}は、GaucheがTLSをサポートしていないことを示します。
21462 @c COMMON
21463 @end deffn
21464
21465 @c EN
21466 @subheading TLS common operations
21467 @c JP
21468 @subheading TLS共通の操作
21469 @c COMMON
21470
21471 @defun make-tls initargs @dots{}
21472 @c MOD rfc.tls
21473 @c EN
21474 Creates and returns a new TLS instance of the class @code{default-tls-class}.
21475 The returned TLS instance can be used either as a client, by passing it
21476 to @code{tls-connect}, or as a server, by passing it to @code{tls-bind}
21477 and @code{tls-accept}. See the following subsections for each usage.
21478 @c JP
21479 新たなTLSインスタンスを作って返します。インスタンスの具体的なクラスは
21480 @code{default-tls-class}の値が使われます。
21481 TLSインスタンスは@code{tls-connect}に渡すことでクライアントとして使ったり、
21482 @code{tls-bind}と@code{tls-accept}に渡すことでサーバーとして使うことができます。
21483 以下のそれぞれのサブセクションを参照してください。
21484 @c COMMON
21485
21486 @c EN
21487 The arguments must be a keyword-value list, and passed to the constructor
21488 of the TLS class.
21489 The following keyword arguments are recognized.
21490 @c JP
21491 引数はTLSクラスに渡されるキーワード-値リストでなければなりません。
21492 以下のキーワード引数が認識されます。
21493 @c COMMON
21494
21495 @table @code
21496 @item :server-name
21497 @c EN
21498 Server name to be used for TLS Server Name Indication extension.
21499 In general, if you use the created TLS object as a client,
21500 you want to specify the server name. If you use the create TLS object
21501 as a server, you can omit this option.
21502 @c JP
21503 TLS Server Name Indication拡張に使うサーバー名を指定します。
21504 一般的には、TLSオブジェクトをクライアントとして使う場合に接続先サーバ名を渡します。
21505 サーバとして使う場合は必要ありません。
21506 @c COMMON
21507 @item :skip-verification
21508 @c EN
21509 Client only. If the argument is true, skip server certificate
21510 verification upon connection.
21511 This is unsafe and should not be used except experimental purposes.
21512 @c JP
21513 クライアントのみ。この引数が真の値の場合、接続時の証明書の認証を省略します。
21514 これは危険な動作なので、実験目的以外では使わないでください。
21515 @c COMMON
21516 @end table
21517 @end defun
21518
21519 @defun tls-close tls
21520 @c MOD rfc.tls
21521 @c EN
21522 Shuts down the underling connection. The peer will notified
21523 the connection is closed.
21524 Once @var{tls} is closed, it can no longer be used.
21525
21526 You can also call @code{connection-close} on @var{tls} to get the same effect
21527 (@pxref{Connection framework}).
21528 @c JP
21529 TLSコネクションを閉じます。通信相手は接続が閉じられたことを知ります。
21530 @var{tls}がひとたびクローズされるとそれはもう使うことができません。
21531
21532 @var{tls}に対し@code{connection-close}を呼び出すことでも同じ動作になります
21533 (@ref{Connection framework}参照)。
21534 @c COMMON
21535 @end defun
21536
21537 @defun tls-input-port tls
21538 @defunx tls-output-port tls
21539 @c MOD rfc.tls
21540 @c EN
21541 If @var{tls} is connected, they return input and output port to communicate
21542 with the peer, respectively.
21543
21544 If @var{tls} is not connected, @code{#f} is returned.
21545
21546 You can also call @code{connection-input-port} and @code{connection-output-port}
21547 on @var{tls} got get the same efffect
21548 (@pxref{Connection framework}).
21549 @c JP
21550 @var{tls}が接続状態にある時、これらは相手と通信するための入力ポートと出力ポートを
21551 それぞれ返します。
21552
21553 @var{tls}が接続状態に無い時にこれらを呼ぶと@code{#f}が返されます。
21554
21555 @var{tls}に対し@code{connection-input-port}および
21556 @code{connection-output-port}を呼び出すことでも同じ動作になります
21557 (@ref{Connection framework}参照)。
21558 @c COMMON
21559 @end defun
21560
21561 @defun tls-poll tls rw :optional timeout
21562 @c MOD rfc.tls
21563 @c EN
21564 Wait for @var{tls} to be ready for reading or writing. The tls object must
21565 be already bound or connected; otherwise, it immediately returns @code{()}.
21566
21567 The @var{rw} argument is a list of symbols @code{read} and/or @code{write},
21568 to specify what condition(s) to be checked. The @var{timeout} argument
21569 is either a @code{<time>} object to specify an absolute time point,
21570 a real number to specify the number of seconds from the current time,
21571 or @code{#f} to wait indefinitely. If omitted, @code{#f} is assumed.
21572
21573 The return value is a list of symbols that are satisfied. That is,
21574 if you pass @code{(read)} or @code{(read write)} in @var{rw} and the
21575 tls communication is ready to read, @code{(read)} is returned.
21576 If timeout reaches before any condition is met, @code{()} is returned.
21577 @c JP
21578 @var{tls}が読み込みもしくは書き込み可能になるまで待ちます。@var{tls}は既に
21579 bindされているか接続されていなければなりません。そうでない場合は直ちに@code{()}が
21580 返されます。
21581
21582 @var{rw}はシンボル@code{read}、@code{write}の組み合わせのリストで、
21583 待つべき条件を指定します。@var{timeout}引数は、
21584 時刻を指定する@code{<time>}オブジェクトか、
21585 現在からの経過時間を秒で指定する実数値か、
21586 タイムアウトしないことを指示する@code{#f}です。省略時は@code{#f}が使われます。
21587
21588 戻り値は満たされた条件のリストです。例えば@var{rw}引数に
21589 @code{(read)}もしくは@code{(read write)}を指定して、tlsが読み込み可能になったら
21590 @code{(read)}が返されます。条件が満たされる前にタイムアウトした場合は@code{()}が
21591 返されます。
21592 @c COMMON
21593 @end defun
21594
21595 @defun tls-debug-level-set! level
21596 @c MOD rfc.tls
21597 @c EN
21598 This is for troubleshooting. Set the global debug log level of
21599 the TLS subsystem to @var{level}, which is an exact integer between
21600 0 (no debug logging, default) to 9 (maximum debug logging).
21601
21602 The actual granularity of log levels depends on the TLS subsystem,
21603 and 0-9 scale is mapped to each subsystem's logging mechanism.
21604 You want some experiment to find appropriate value.
21605 @c JP
21606 これはトラブルシューティング用のAPIです。
21607 TLSサブシステムのグローバルなデバッグログレベルを@var{level}に設定します。@var{level}
21608 は0(ログなし、デフォルト)から9(ログ最大)までの正確な整数です。
21609
21610 実際のログ段階の細かさは各TLSサブシステムにより、0-9のレベルがサブシステムのサポートする
21611 段階へとマップされます。いくらか試行して適切な値を見つけてください。
21612 @c COMMON
21613 @end defun
21614
21615 @c EN
21616 @subheading TLS client
21617 @c JP
21618 @subheading TLSクライアント
21619 @c COMMON
21620
21621 @c EN
21622 When your code is a client to connect to a server over TLS,
21623 you need CA certificates to verify server certificates properly.
21624 Gauche doesn't have its own CA certificates, and relies on the
21625 system's certificate store by default. On Unix-based systems,
21626 we search several known locations: On popular Linux distributions
21627 we recommend you to install @code{ca-certificates} package (or similar one).
21628 On OSX, we recommend to install openssl via Homebrew. On Windows,
21629 we use system's certificate store via Wincrypt API.
21630 @c JP
21631 クライアントとしてサーバにTLS接続する場合、
21632 サーバの認証を適切に行うために、CA証明書が必要です。
21633 Gaucheは自前でCA証明書を持っておらず、デフォルトでシステムのCA証明書バンドルを利用します。
21634 Unixベースのシステムでは、いくつかのよくあるパスを探索します。
21635 例えばLinuxディストリビューションなら@code{ca-certificates}やそれに類する
21636 パッケージをインストールしておくと良いでしょう。
21637 OSXではopensslをHomebrewでインストールしておくのをおすすめします。
21638 WindowsではWincrypt API経由でシステムの証明書ストアを使います。
21639 @c COMMON
21640
21641 @c EN
21642 With the default configuration, Gauche checks the availability of the system's
21643 certificate store at initilization and use one if available. You can explicitly
21644 give the path of CA certificate bundle, or disable it and provide
21645 individual certificate per connection.
21646 @c JP
21647 デフォルトのコンフィグレーションでは、Gaucheは初期化時にシステムのCA証明書バンドルを探し、
21648 見つかればそれを使うようになっています。かわりとなるCA証明書バンドルのパスを指定したり、
21649 接続毎に独自の証明書を与えることもできます。
21650 @c COMMON
21651
21652 @c EN
21653 If, for some reasons, you cannot install system-wide CA certificate bundle,
21654 you can also download Curl's CA certificate bundle
21655 @url{https://curl.haxx.se/ca/cacert.pem}, and install it in
21656 Gauche installation directory. We have a convenience script.
21657 After installing Gauche, run the following command:
21658 @c JP
21659 もし、何らかの理由で、システム全体で使えるCA証明書バンドルがインストールできない場合、
21660 独自にCurlのCA証明書バンドルを@url{https://curl.haxx.se/ca/cacert.pem}から
21661 ダウンロードしてGaucheのインストールディレクトリに置いておくことができます。
21662 便利なスクリプトが用意してあります。
21663 Gaucheをインストールした後、次のコマンドを実行してください。
21664 @c COMMON
21665
21666 @example
21667 gosh tools/get-cacert
21668 @end example
21669
21670 @c EN
21671 You need curl installed on your system. If you've installed
21672 Gauche with root priviledge, you'll be asked sudo password to install
21673 the CA bundle file.
21674
21675 If you decided to do this, make sure you run the above command occasionally
21676 to get updated CA certificate bundles, for certificates may expire or
21677 be revoked.
21678 @c JP
21679 curlがシステムにインストールされている必要があります。また、Gaucheをインストールする時に
21680 root権限で行ったのであれば、このコマンドがCA証明書バンドルをインストールする時に
21681 sudoのパスワードを尋ねるでしょう。
21682
21683 もしこの方法を取ることに決めたなら、時々このコマンドを実行してCA証明書バンドルを
21684 最新版に更新するのを忘れないようにしてください。
21685 CA証明書は期限が切れたり無効化されることがあります。
21686 @c COMMON
21687
21688 @deffn {Parameter} tls-ca-bundle-path :optional path
21689 @c MOD rfc.tls
21690 @c EN
21691 Holds CA certificate bundle to be used. The value
21692 can be either a string path to a CA bundle file, a symbol @code{system},
21693 or @code{#f}.
21694 @c JP
21695 CA証明書バンドルのパスを保持しています。値は、CA証明書バンドルファイルの
21696 パス名、シンボル@code{system}、あるいは@code{#f}のいずれかです。
21697 @c COMMON
21698
21699 @c EN
21700 If it is @code{system}, Gauche uses system's default bundle.
21701 An error is signaled on connection
21702 if Gauche can't find one.
21703 @c JP
21704 この値が@code{system}の場合、Gaucheはシステムのデフォルトの証明書バンドルを
21705 使おうとします。もしそれが見つからなければ接続時にエラーが報告されます。
21706 @c COMMON
21707
21708 @c EN
21709 If it is @code{#f}, CA certificate won't be loaded automatically,
21710 and you have to manually load one using @code{tls-load-object}.
21711 (Note: This option is only valid with @code{<ax-tls>}. If you're using
21712 @code{<mbed-tls>}, you need valid CA certificate bundle.)
21713 @c JP
21714 この値が@code{#f}の場合、CA証明書は自動的にロードされないので、
21715 @code{tls-load-object}を使って自分で適切な証明書をロードしてやる必要があります。
21716 (このオプションは@code{<ax-tls>}のみ有効です。
21717 @code{<mbed-tls>}を使う場合は、必ず有効なCA証明書バンドルが必要です。)
21718 @c COMMON
21719
21720 @c EN
21721 With the default configuration, Gauche scans the system CA bundle
21722 when @code{rfc.tls} module is initialized, and if it finds one,
21723 @code{tls-ca-bundle-path} is set to @code{system}; otherwise,
21724 @code{tls-ca-bundle-path} is set to @code{#f}. So if you're using
21725 with default configuration and you see its value is @code{system},
21726 you can count on the system CA certificate bundle.
21727 @c JP
21728 デフォルトのコンフィグレーションでは、Gaucheは@code{rfc.tls}モジュール初期化時に
21729 システムのCA証明書バンドルが使えるかどうか調べて、使えるなら@code{tls-ca-bundle-path}の
21730 初期値を@code{system}に、使えないなら@code{#f}にセットします。
21731 したがって、デフォルトのコンフィグレーションで使っている限り、
21732 この値が@code{system}であればシステムのCA証明書を使えると考えて良いでしょう。
21733 @c COMMON
21734
21735 @c EN
21736 This default behavior may be altered if Gauche is configured
21737 with @code{--with-ca-bundle} option. You can execute
21738 @code{gauche-config --reconfigure} command to see if
21739 special @code{--with-ca-bundle} option is given.
21740 @c JP
21741 このデフォルトの振る舞いはconfigure時に@code{--with-ca-bundle}オプションで
21742 変えられます。使っているGaucheのコンフィグレーションが変えられているかどうかは、
21743 @code{gauche-config --reconfigure}コマンドを実行して@code{--with-ca-bundle}
21744 オプションがあるかどうかを見ればわかります。
21745 @c COMMON
21746 @end deffn
21747
21748 @defun tls-connect tls host port :optional proto
21749 @c MOD rfc.tls
21750 @c EN
21751 Establishes TLS connection as a client.
21752
21753 The @var{tls} argument must be an unconnected TLS object. The
21754 @var{host} and @var{port} arguments are strings to specify
21755 server's hostname and port. Besides the common hostname, IP notation
21756 (e.g. @code{"127.0.0.1"} or @code{"[::1]"}) are allowed in @var{host}.
21757 Integre port number or a service name (e.g. @code{"https"})
21758 are allowed in @var{port}.
21759 The @var{proto} argument must be either one of the symbols
21760 @code{tcp} or @code{udp}. If omitted, @code{tcp} is assumed.
21761 (If it is @code{udp}, DTLS is used instead of TLS. However, we still
21762 lack some additional API support to make DTLS usable.)
21763 @c JP
21764 クライアントとして、指定されたサーバにTLSで接続します。
21765
21766 @var{tls}引数はまだ接続されていないTLSオブジェクトでなければなりません。
21767 @var{host}と@var{port}は文字列で、それぞれサーバのホスト名とポートを指定します。
21768 ホスト名についてはドメイン名のほか、IP表記が使えます
21769 (例: @code{"127.0.0.1"}、@code{"[::1]"})。
21770 ポートについては整数のポート番号も名前による指定(例: @code{"https"})も使えます。
21771 @var{proto}引数はシンボル@code{tcp}か@code{udp}のどちらかでなければならず、
21772 省略時は@code{tcp}とみなされます
21773 (@var{udp}を指定した場合はTLSのかわりにDTLSが使われることになりますが、
21774 今はDTLSを実用的に使うために必要なAPIがいくつか未実装です。)
21775 @c COMMON
21776
21777 @c EN
21778 Once the procedure contacted to the server,
21779 it obtains its server certificate and tries to validate it
21780 against the known CA certificates. If the server can't be validated,
21781 an error is signaled. To establish a proper connection,
21782 a CA certificate storage must be specified
21783 by the parameter @code{tls-ca-bundle-path}.
21784 @c JP
21785 サーバにコンタクトできたら、この手続きはサーバ証明書を入手して
21786 CA証明書を使ってバリデーションを試みます。
21787 バリデーションが失敗したらエラーが投げられます。正しく接続を確立するには、
21788 有効なCA証明書ストアがパラメータ@code{tls-ca-bundle-path}で指定されていなければ
21789 なりません。
21790 @c COMMON
21791
21792 @c EN
21793 Once the connection is established and TLS handshake is succeeded,
21794 the passed @var{tls} becomes 'connected' state and
21795 can be used to read/write data from/to the connected peer.
21796 @c JP
21797 接続が確立してTLSハンドシェイクが成功したら、
21798 引数に渡した@var{tls}オブジェクトはconnected状態になり、
21799 相手とデータをやりとりすることができます。
21800 @c COMMON
21801 @end defun
21802
21803 @c EN
21804 @subheading TLS server
21805 @c JP
21806 @subheading TLSサーバー
21807 @c COMMON
21808
21809 @c EN
21810 To open a TLS connection as a server, you have to prepare
21811 a private key, a server certificate, and
21812 intermediate certificates. Those must be loaded before accepting
21813 TLS connections from clients.
21814 @c JP
21815 TLSコネクションをサーバとして使うには、秘密鍵、サーバ証明書、および中間証明書を
21816 用意する必要があります。これらはクライアントからのTLS接続を受け付ける前に
21817 読み込まれている必要があります。
21818 @c COMMON
21819
21820 @defun tls-load-certificate tls path
21821 @c MOD rfc.tls
21822 @c EN
21823 Read and register server certifcate(s) stored in a file named by @var{path}.
21824 The given file may contain multiple certificates. You can call this
21825 multiple times to add intermediate certifictes.
21826 @c JP
21827 @var{path}で示されるファイルに格納されたサーバ証明書を読み込みます。
21828 ファイル中に複数の証明書を含めることができます。また、この関数は複数回呼び出せて、
21829 @var{tls}に中間証明書を追加してゆくことができます。
21830 @c COMMON
21831 @end defun
21832
21833 @defun tls-load-private-key tls path password
21834 @c MOD rfc.tls
21835 @c EN
21836 Read and register server private key storead in a file named by @var{path},
21837 with the @var{password}. If the private key file is not encrypted,
21838 you can pass @code{#f} to @var{password}.
21839 @c JP
21840 @var{path}で示されるファイルに格納されたサーバの秘密鍵を読み出して登録します。
21841 秘密鍵が暗号化されている場合は@var{password}にパスワードを指定します。
21842 秘密鍵が暗号されていない場合は@var{password}に@code{#f}を渡します。
21843 @c COMMON
21844 @end defun
21845
21846 @defun tls-bind tls host port :optional proto
21847 @c MOD rfc.tls
21848 @c EN
21849 Creates a server endpoint of tls connection.
21850
21851 The @var{tls} argument must be an unconnected, unbound TLS object.
21852 The @var{host} argument may be a string hostname or @code{#f}.
21853 The @var{port} argument is an integer or a string to specify the port.
21854 The @var{proto} argument must be either one of the symbols
21855 @code{tcp} or @code{udp}, and assumed @code{tcp} if omitted.
21856 (NB: @var{udp} server (DTLS) needs some more API support, so
21857 it is not very usable now.)
21858 @c JP
21859 TLS接続のサーバー側エンドポイントを作ります。
21860
21861 @var{tls}引数はまだ接続もbindもされていないTLSオブジェクトでなければなりません。
21862 @var{host}引数は文字列のホスト名か@code{#f}です。
21863 @var{port}引数は整数のポート番号か文字列によるポート名です。
21864 @var{proto}にはシンボル@code{tcp}か@code{udp}を渡します。
21865 省略時は@code{tcp}が仮定されます。
21866 (NB: @var{udp}サーバー (DTLS) を使うにはいくつか追加のAPIサポートが
21867 必要なので、今のところDTLSは使えません)。
21868 @c COMMON
21869
21870 @c EN
21871 Like @code{socket-bind}, you can give 0 to @var{port} to let the
21872 system choose an available port number. The actual port number
21873 can be obtained by
21874 @code{(sockaddr-port (connection-self-address @var{tls}))}.
21875 @c JP
21876 @code{socket-bind}と同じように、@var{port}に0を指定することで、
21877 空いているポート番号をシステムに選んでもらうことができます。
21878 実際にどのポートにバインドされたかは
21879 @code{(sockaddr-port (connection-self-address @var{tls}))}
21880 でわかります。
21881 @c COMMON
21882 @end defun
21883
21884 @defun tls-accept tls
21885 @c MOD rfc.tls
21886 @c EN
21887 The passed tls object must already be bound by @code{tls-bind}.
21888 Server certificates and private key must be already loaded to @var{tls}
21889 by @code{tls-load-certificate} and @code{tls-load-private-key}.
21890
21891 This waits for a client to connect to the bound endpoint. Once
21892 a client tries to connect, it present the server certificate
21893 and performs TLS handshake. If everything succeeds,
21894 returns a fresh @var{tls} object that can be used
21895 to read/write dat from/to the connected peer.
21896 @c JP
21897 引数の@var{tls}は、@code{tls-bind}でバインドされたTLSオブジェクトでなければなりません。
21898 サーバ証明書と秘密鍵は@code{tls-load-certificate}および@code{tls-load-private-key}
21899 によって@var{tls}にロードされていなければなりません。
21900
21901 この手続きはクライアントの接続要求を待ちます。接続要求が来たら、
21902 サーバ証明書をクライアントに提示し、TLSハンドシェークを行います。
21903 全てが成功すれば、クライアントに接続された新たな@var{tls}オブジェクトを作って返します。
21904 @c COMMON
21905 @end defun
21906
21907 @c EN
21908 @subheading Connection methods
21909 @c JP
21910 @subheading コネクションメソッド
21911 @c COMMON
21912
21913 @c EN
21914 Since @code{<tls>} class implements connection framework
21915 (@pxref{Connection framework}), the following methods
21916 can be called on a tls object. Notably, the first two
21917 can be used to obtain IP address of the underlying connection.
21918 @c JP
21919 @code{<tls>}クラスはコネクションフレームワークを実装しているので、
21920 以下のメソッドがtlsオブジェクトに対して使えます。特に最初の2つは
21921 下位にあるコネクションのIPアドレスを得るのに使えます。
21922 @c COMMON
21923
21924 @example
21925 connection-self-address (c <tls)
21926 connection-peer-address (c <tls>)
21927 connection-input-port (c <tls>)
21928 connection-output-port (c <tls>)
21929 connection-close (c <tls>)
21930 @end example
21931
21932 @c ----------------------------------------------------------------------
21933 @node URI parsing and construction, UUID, Transport layer security, Library modules - Utilities
21934 @section @code{rfc.uri} - URI parsing and construction
21935 @c NODE URIの解析と作成, @code{rfc.uri} - URIの解析と作成
21936
21937 @deftp {Module} rfc.uri
21938 @mdindex rfc.uri
21939 @c EN
21940 Provides a set of procedures to parse and construct Uniform Resource Identifiers
21941 defined in RFC 2396 (@uref{https://www.ietf.org/rfc/rfc2396.txt}),
21942 as well as Data URI scheme defined in RFC2397.
21943 @c JP
21944 RFC 2396 (@uref{https://www.ietf.org/rfc/rfc2396.txt})で定義されている
21945 Uniform Resource Identifiers、
21946 またRFC 2397で定義されているData URI Schemeをパーズおよび構築する
21947 手続き群を提供します。
21948 @c COMMON
21949 @end deftp
21950
21951 @c EN
21952 First, lets review the structure of URI briefly.
21953 The following graph shows how the URI is constructed:
21954 @c JP
21955 はじめに、URIの構造をざっとみておきましょう。次のグラフはURIがどのように構築されるかを
21956 示しています。
21957 @c COMMON
21958
21959 @example
21960 URI-+-scheme
21961 |
21962 +-specific--+--authority-+--userinfo
21963 | +--host
21964 | +--port
21965 +--path
21966 +--query
21967 +--fragment
21968 @end example
21969
21970 @c EN
21971 Not all URIs have this full hierarchy. For example,
21972 @code{mailto:admin@@example.com} has only @emph{scheme} (@code{mailto})
21973 and @emph{specific} (@code{admin@@example.com}) parts.
21974 @c JP
21975 全てのURIがここに示される完全な木構造を備えているわけではありません。
21976 例えば@code{mailto:admin@@example.com}は@emph{scheme} (@code{mailto})
21977 と @emph{specific} (@code{admin@@example.com}) だけから構成されます。
21978 @c COMMON
21979
21980 @c EN
21981 Most popular URI schemes, however, organize resources
21982 in a tree, so they adopt @emph{authority} (which usually identifies
21983 the server) and the hierarchical @emph{path}. In the URI
21984 @code{http://example.com:8080/search?q=key#results}, the authority
21985 part is @code{example.com:8080}, the path is @code{/search},
21986 the query is @code{key} and the fragment is @code{results}.
21987 The userinfo can be provided before hostname, such as @code{anonymous}
21988 in @code{ftp://anonymous@@example.com/pub/}.
21989 @c JP
21990 しかし、良く使われるURIのほとんどはリソースを木構造で管理するので、
21991 @emph{authority} (通常はサーバ)と階層的な@var{path}を持ちます。
21992 @code{http://example.com:8080/search?q=key#results}では、
21993 authorityは@code{example.com:8080}、pathは@code{/search}、
21994 queryは@code{key}で、fragmentが@code{results}です。
21995 userinfoはあればホスト名の前に付加されます。例えば
21996 @code{ftp://anonymous@@example.com/pub/}における@code{anonymous}です。
21997 @c COMMON
21998
21999 @c EN
22000 We have procedures that decompose a URI into those parts,
22001 and that compose a URI from those parts.
22002 @c JP
22003 URIをこれらの部分に分解する手続きと、
22004 部分からURIを組み立てる手続きが提供されます。
22005 @c COMMON
22006
22007 @c EN
22008 @subheading Parsing URI
22009 @c JP
22010 @subheading URIのパーズ
22011 @c COMMON
22012
22013 @defun uri-ref uri parts
22014 @c MOD rfc.uri
22015 @c EN
22016 Extract specific part(s) from the given URI. This module offers
22017 a set of procedures to fully decompose URI, but in actual
22018 applications, you often need only some of the parts. This procedure
22019 comes handy for it.
22020 @c JP
22021 与えられたURIから、指定部分を抜き出します。
22022 このモジュールはURIを完全に分解する手続きも提供していますが、
22023 現実のアプリケーションでは特定部分のみを取り出したい場合も多く、
22024 この手続きはそういう場合に便利に使えます。
22025 @c COMMON
22026
22027 @c EN
22028 The @var{parts} argument may be a symbol, or a list of symbols,
22029 to name the desired parts. The recognized symbos are as follows.
22030 @c JP
22031 @var{parts}引数はシンボルもしくはシンボルのリストで、
22032 抜き出したい部分を指定します。指定可能なシンボルは以下の通りです。
22033 @c COMMON
22034
22035 @table @code
22036 @item scheme
22037 @c EN
22038 The scheme part, as string.
22039 @c JP
22040 schemeパートを文字列で抜き出します。
22041 @c COMMON
22042 @item authority
22043 @c EN
22044 The authority part, as string.
22045 If URI doesn't have the part, @code{#f}.
22046 @c JP
22047 authorityパートを文字列で抜き出します。
22048 URIにauthorityパートが無ければ@code{#f}が返されます。
22049 @c COMMON
22050 @item userinfo
22051 @c EN
22052 The userinfo part, as string. If URI doesn't have the part, @code{#f}.
22053 @c JP
22054 userinfoパートを文字列で抜き出します。
22055 URIにuserinfoパートが無ければ@code{#f}が返されます。
22056 @c COMMON
22057 @item host
22058 @c EN
22059 The host part, as string. If URI doesn't have the part, @code{#f}.
22060 @c JP
22061 hostパートを文字列で抜き出します。
22062 URIにhostパートが無ければ@code{#f}が返されます。
22063 @c COMMON
22064 @item port
22065 @c EN
22066 The port part, as integer. If URI doesn't have the part, @code{#f}.
22067 @c JP
22068 portパートを文字列で抜き出します。
22069 URIにportパートが無ければ@code{#f}が返されます。
22070 @c COMMON
22071 @item path
22072 @c EN
22073 The path part, as string. If URI isn't hierarchical, this returns
22074 the specific part.
22075 @c JP
22076 pathパートを文字列で抜き出します。
22077 URIが階層的でない場合は、specificパートが返されます。
22078 @c COMMON
22079 @item query
22080 @c EN
22081 The query part, as string. If URI doesn't have the part, @code{#f}.
22082 @c JP
22083 queryパートを文字列で抜き出します。
22084 URIにqueryパートが無ければ@code{#f}が返されます。
22085 @c COMMON
22086 @item fragment
22087 @c EN
22088 The fragment part, as string. If URI doesn't have the part, @code{#f}.
22089 @c JP
22090 fragmentパートを文字列で抜き出します。
22091 URIにfragmentパートが無ければ@code{#f}が返されます。
22092 @c COMMON
22093 @item scheme+authority
22094 @c EN
22095 The scheme and authority part, as string
22096 @c JP
22097 schemeパートとauthorityパートの部分を文字列で。
22098 @c COMMON
22099 @item host+port
22100 @c EN
22101 The host and port part, as string.
22102 @c JP
22103 hostパートとportパートの部分を文字列で。
22104 @c COMMON
22105 @item userinfo+host+port
22106 @c EN
22107 The userinfo, host and port part, as string.
22108 @c JP
22109 usertinfoパート、hostパート、portパートの部分を文字列で。
22110 @c COMMON
22111 @item path+query
22112 @c EN
22113 The path and query part.
22114 @c JP
22115 pathパートとqueryパートの部分を文字列で。
22116 @c COMMON
22117 @item path+query+fragment
22118 @c EN
22119 The path, query and fragment part.
22120 @c JP
22121 pathパートとqueryパートとfragmentパートの部分を文字列で。
22122 @c COMMON
22123 @end table
22124
22125 @example
22126 (define uri "http://foo:bar@@example.com:8080/search?q=word#results")
22127
22128 (uri-ref uri 'scheme) @result{} "http"
22129 (uri-ref uri 'authority) @result{} "//foo:bar@@example.com:8080/"
22130 (uri-ref uri 'userinfo) @result{} "foo:bar"
22131 (uri-ref uri 'host) @result{} "example.com"
22132 (uri-ref uri 'port) @result{} 8080
22133 (uri-ref uri 'path) @result{} "/search"
22134 (uri-ref uri 'query) @result{} "q=word"
22135 (uri-ref uri 'fragment) @result{} "results"
22136 (uri-ref uri 'scheme+authority) @result{} "http://foo:bar@@example.com:8080/"
22137 (uri-ref uri 'host+port) @result{} "example.com:8080"
22138 (uri-ref uri 'userinfo+host+port) @result{} "foo:bar@@example.com:8080"
22139 (uri-ref uri 'path+query) @result{} "/search?q=word"
22140 (uri-ref uri 'path+query+fragment)@result{} "/search?q=word#results"
22141 @end example
22142
22143 @c EN
22144 You can extract multiple parts at once by specifying a list of parts.
22145 A list of parts is returned.
22146 @c JP
22147 @var{parts}に抜き出したい部分を指定するリストを渡すと、
22148 それぞの部分のリストが返されます。
22149 @c COMMON
22150
22151 @example
22152 (uri-ref uri '(host+port path+query))
22153 @result{} ("example.com:8080" "/search?q=word")
22154 @end example
22155 @end defun
22156
22157
22158 @defun uri-parse uri
22159 @defunx uri-scheme&specific uri
22160 @defunx uri-decompose-hierarchical specific
22161 @defunx uri-decompose-authority authority
22162 @c MOD rfc.uri
22163 @c EN
22164 General parser of URI. These functions does not decode
22165 URI encoding, since the parts to be decoded differ among
22166 the uri schemes. After parsing uri, use @code{uri-decode} below
22167 to decode them.
22168 @c JP
22169 URIの一般的なパーザです。これらの関数はURIエンコーディングを
22170 デコードしません。URIスキームによってどの部分をデコードすべきかが
22171 異なるからです。パージングを行った後に、後述の@code{uri-decode}等を
22172 使ってデコードを行ってください。
22173 @c COMMON
22174
22175 @c EN
22176 @code{uri-parse} is the most handy procedure. It breaks the uri
22177 into the following parts and returns them as multiple values.
22178 If the uri doesn't have the corresponding
22179 parts, @code{#f} are returned for the parts.
22180
22181 @itemize @bullet
22182 @item
22183 URI scheme as a string
22184 (e.g. @code{"mailto"} in @code{"mailto:foo@@example.com"}).
22185 @item
22186 User-info in the authority part (e.g. @code{"anonymous"}
22187 in @code{ftp://anonymous@@ftp.example.com/pub/foo}).
22188 @item
22189 Hostname in the authority part (e.g. @code{"ftp.example.com"}
22190 in @code{ftp://anonymous@@ftp.example.com/pub/foo}).
22191 @item
22192 Port number in the authority part, as an integer (e.g. @code{8080}
22193 in @code{http://www.example.com:8080/}).
22194 @item
22195 Path part (e.g. @code{"/index.html"} in
22196 @code{http://www.example.com/index.html}).
22197 @item
22198 Query part (e.g. @code{"key=xyz&lang=en"} in
22199 @code{http://www.example.com/search?key=xyz&lang=en}).
22200 @item
22201 Fragment part (e.g. @code{"section4"} in
22202 @code{http://www.example.com/document.html#section4}).
22203 @end itemize
22204 @c JP
22205 @code{uri-parse}は最も手軽な手続きで、uriを以下に示す部分に
22206 分割し、多値で返します。
22207 もし該当する部分がuriに無かった場合は、その部分には@code{#f}が返ります。
22208 @itemize @bullet
22209 @item
22210 URIスキームを文字列で。
22211 (例: @code{"mailto:foo@@example.com"}の@code{"mailto"})。
22212 @item
22213 authorityパートのuser-infoを文字列で。
22214 (例: @code{ftp://anonymous@@ftp.example.com/pub/foo}の@code{"anonymous"})。
22215 @item
22216 authorityパートのhostnameを文字列で。
22217 (例: @code{ftp://anonymous@@ftp.example.com/pub/foo}の
22218 @code{"ftp.example.com"})。
22219 @item
22220 authorityパートのport番号を整数で。
22221 (例: @code{http://www.example.com:8080/}の@code{8080})。
22222 @item
22223 pathパート。
22224 (例: @code{http://www.example.com/index.html}の@code{"/index.html"})。
22225 @item
22226 queryパート。
22227 (例: @code{http://www.example.com/search?key=xyz&lang=en}の
22228 @code{"key=xyz&lang=en"})。
22229 @item
22230 fragmentパート。
22231 (例: @code{http://www.example.com/document.html#section4}の
22232 @code{"section4"})。
22233 @end itemize
22234 @c COMMON
22235
22236 @c EN
22237 The following procedures are finer grained and break up
22238 uris with different stages.
22239 @c JP
22240 以下の手続きはより詳細に、段階をふんでuriを分割してゆくものです。
22241 @c COMMON
22242
22243 @c EN
22244 @code{uri-scheme&specific} takes a URI @var{uri}, and
22245 returns two values, its scheme part and its scheme-specific part.
22246 If @var{uri} doesn't have a scheme part, @code{#f} is returned for it.
22247 @c JP
22248 @code{uri-scheme&specific} は URI @var{uri} を引数に取り、
22249 スキーム部分と、そのスキーム特有の部分を表す2つの値を返します。
22250 @var{uri} がスキーム部分を持たない場合、@code{#f} を返します。
22251 @c COMMON
22252 @example
22253 (uri-scheme&specific "mailto:sclaus@@north.pole")
22254 @result{} "mailto" @r{and} "sclaus@@north.pole"
22255 (uri-scheme&specific "/icons/new.gif")
22256 @result{} #f @r{and} "/icons/new.gif"
22257 @end example
22258
22259 @c EN
22260 If the URI scheme uses hierarchical notation, i.e.
22261 ``@code{//@var{authority}/@var{path}?@var{query}#@var{fragment}}'',
22262 you can pass
22263 the scheme-specific part to @code{uri-decompose-hierarchical}
22264 and it returns four values, @var{authority}, @var{path}, @var{query}
22265 and @var{fragment}.
22266 @c JP
22267 URI が階層的な記法を用いている場合、すなわち、
22268 ``@code{//@var{authority}/@var{path}?@var{query}#@var{fragment}}''
22269 のような場合、スキーム特有の部分を @code{uri-decompose-hierarchical}
22270 に渡すと、@var{authority}、@var{path}、@var{query}、@var{fragment}
22271 の4つの値が返ります。
22272 @c COMMON
22273 @example
22274 (uri-decompose-hierarchical "//www.foo.com/about/company.html")
22275 @result{} "www.foo.com"@r{,} "/about/company.html"@r{,} #f @r{and} #f
22276 (uri-decompose-hierarchical "//zzz.org/search?key=%3fhelp")
22277 @result{} "zzz.org"@r{,} "/search"@r{,} "key=%3fhelp" @r{and} #f
22278 (uri-decompose-hierarchical "//jjj.jp/index.html#whatsnew")
22279 @result{} "jjj.jp"@r{,} "/index.html"@r{,} #f @r{and} "whatsnew"
22280 (uri-decompose-hierarchical "my@@address")
22281 @result{} #f@r{,} #f@r{,} #f @r{and} #f
22282 @end example
22283
22284 @c EN
22285 Furthermore, you can parse @var{authority} part of the
22286 hierarchical URI by @code{uri-decompose-authority}.
22287 It returns @var{userinfo}, @var{host} and @var{port}.
22288 @c JP
22289 さらに、階層的 URI の @var{authority} の部分を
22290 @code{uri-decompose-authority} に渡すと、@var{userinfo}、
22291 @var{host}、@var{port} が返ります。
22292 @c COMMON
22293 @example
22294 (uri-decompose-authority "yyy.jp:8080")
22295 @result{} #f@r{,} "yyy.jp" @r{and} "8080"
22296 (uri-decompose-authority "[::1]:8080") ;@r{(IPv6 host address)}
22297 @result{} #f@r{,} "::1" @r{and} "8080"
22298 (uri-decompose-authority "mylogin@@yyy.jp")
22299 @result{} "mylogin"@r{,} "yyy.jp" @r{and} #f
22300 @end example
22301 @end defun
22302
22303 @defun uri-decompose-query query-string :key separators
22304 @c MOD rfc.uri
22305 @c EN
22306 Decompose query string such as @code{"foo=abc&bar"} into
22307 a list of parameters @code{(("foo" ""abc") ("bar" #t)},
22308 where each parameter is represented by a list of its name (string) and
22309 value (string or @code{#t}).
22310
22311 If you're writing a CGI script, @code{cgi-parse-parameters}
22312 in @code{www.cgi} is handier, for it
22313 integrates handling of query string, form parameters,
22314 and cookies, on top of this procedure (@pxref{CGI utility}).
22315 @c JP
22316 クエリ文字列(例: @code{"foo=abc&bar"}) を、
22317 パラメータのリスト(例: @code{(("foo" ""abc") ("bar" #t)})へと分解します。
22318 各パラメータは名前(文字列)と値(文字列または@code{#t})のリストで表されます。
22319
22320 CGIスクリプトを書いているなら、@code{www.cgi}モジュールの
22321 @code{cgi-parse-parameters}の方が便利でしょう。この手続きの上に、
22322 フォームパラメータやクッキーの取扱いなどを統合的に扱えるからです
22323 (@ref{CGI utility}参照)。
22324 @c COMMON
22325
22326 @itemize @bullet
22327 @item
22328 Each parameter name and value is urldecoded.
22329 @item
22330 If there are multiple parameters with the same name, they are
22331 @emph{not} merged.
22332 @example
22333 (uri-decompose-query "a=b&a=c") @result{} (("a" "b") ("a" "c"))
22334 @end example
22335 @item
22336 If the parameter isn't given a value, its value in the output is @code{#t}.
22337 @example
22338 (uri-decompose-query "a&b") @result{} (("a" #t) ("b" #t))
22339 @end example
22340 @item
22341 The order of input parameters is preserved.
22342 @end itemize
22343 @c JP
22344 @itemize @bullet
22345 @item
22346 各パラメータ名と値はそれぞれurldecodeされます。
22347 @item
22348 同名のパラメータが複数ある場合、それらは統合されず、別々の要素として出力に現れます。
22349 @example
22350 (uri-decompose-query "a=b&a=c") @result{} (("a" "b") ("a" "c"))
22351 @end example
22352 @item
22353 値を持たないパラメータについては、出力の値は@code{#t}となります。
22354 @example
22355 (uri-decompose-query "a&b") @result{} (("a" #t) ("b" #t))
22356 @end example
22357 @item
22358 パラメータの順序は保存されます。
22359 @end itemize
22360 @c COMMON
22361
22362 @c EN
22363 The optional @var{separators} argument takes a char-set object
22364 to be used to separate each parameters. The default is
22365 @code{#[&;]}, for historically both @code{&} and @code{;} can be used.
22366 However, some application only allows @code{&}.
22367 @c JP
22368 省略可能引数@var{separators}には、パラメータの区切りに使われる文字集合を指定します。
22369 デフォルトは@code{#[&;]}です。歴史的に@code{&}と@code{;}の両方が区切りに使われてきたので。
22370 ただ、アプリケーションによっては@code{&}しか受け付けない場合があります。
22371 @c COMMON
22372
22373 @c EN
22374 See also @code{url-compose-query} below, for the inverse of this procedure.
22375 @c JP
22376 この手続きの逆関数については下の@code{url-compose-query}を見てください。
22377 @c COMMON
22378 @end defun
22379
22380
22381 @defun uri-decompose-data uri
22382 @c MOD rfc.uri
22383 @c EN
22384 Parse a Data schemed @var{uri}. You can either pass the entire
22385 uri including @code{data:} scheme part, or just the specific part.
22386 If the passed uri is invalid as a data uri, an error is signalled.
22387
22388 Returns two values: parsed content type and the decoded data.
22389 The data is a string if the content type is @code{text/*}, and
22390 a u8vector otherwise.
22391
22392 The content-type is parsed by @code{mime-parse-content-type}
22393 (@pxref{MIME message handling}). The result format is a list as follows:
22394 @c JP
22395 Data scheme形式の@var{uri}をパーズします。@code{data:}スキーム部分は有っても無くても
22396 構いません。渡されたuriがdata uriとして無効な文字列であればエラーが投げられます。
22397
22398 二つの値、パーズされたContent-Typeおよびデコードされたデータを返します。
22399 Content-Typeが@code{text/*}であればデコードされたデータは文字列で、
22400 そうでなければu8vectorで返されます。
22401
22402 Content-Typeは@code{mime-parse-content-type}でパーズされます
22403 (@ref{MIME message handling}参照)。結果のデータ形式は次のようなリストです。
22404 @c COMMON
22405
22406 @example
22407 @code{(@i{type} @i{subtype} (@i{attribute} . @i{value}) @dots{})}.
22408 @end example
22409
22410 @c EN
22411 Here are a couple of examples:
22412 @c JP
22413 いくつか例を示します。
22414 @c COMMON
22415
22416 @example
22417 (uri-decompose-data
22418 "data:text/plain;charset=utf-8;base64,KGhlbGxvIHdvcmxkKQ==")
22419 @result{} ("text" "plain" ("charset" . "utf-8")) @r{and} "(hello world)"
22420
22421 (uri-decompose-data
22422 "application/octet-stream;base64,AAECAw==")
22423 @result{} ("application" "octet-stream") @r{and} #u8(0 1 2 3)
22424 @end example
22425
22426 @end defun
22427
22428
22429 @c EN
22430 @subheading Constructing URI
22431 @c JP
22432 @subheading URIの構築
22433 @c COMMON
22434
22435 @defun uri-compose :key scheme userinfo host port authority path path* query fragment specific
22436 @c MOD rfc.uri
22437 @c EN
22438 Compose a URI from given components.
22439 There can be various combinations of components to create a valid
22440 URI---the following diagram shows the possible 'paths' of
22441 combinations:
22442 @c JP
22443 与えられたコンポーネントから URI を構成します。
22444 妥当な URI を作成するためのコンポーネントの組み合わせはたくさんあります。
22445 以下のダイアグラムは、考え得る組み合わせの方法を示しています。
22446 @c COMMON
22447
22448 @example
22449 /-----------------specific-------------------\
22450 | |
22451 scheme-+------authority-----+-+-------path*---------+-
22452 | | | |
22453 \-userinfo-host-port-/ \-path-query-fragment-/
22454 @end example
22455
22456 @c EN
22457 If @code{#f} is given to a keyword argument, it is
22458 equivalent to the absence of that keyword argument.
22459 It is particularly useful to pass the results of
22460 parsed uri.
22461
22462 If a component contains a character that is not appropriate
22463 for that component, it must be properly escaped before
22464 being passed to @code{url-compose}.
22465
22466 Some examples:
22467 @c JP
22468 キーワード引数に @code{#f} が与えられた場合、それはキーワード引数が
22469 指定されないことと等価です。これは URI をパーズした結果を渡す場合に
22470 特に有用です。
22471
22472 コンポーネントに適切でない文字が含まれている場合は、
22473 @code{url-compose} に渡す前に正しくエスケープされなければなりません。
22474
22475 いくつかの例を示します。
22476 @c COMMON
22477 @example
22478 (uri-compose :scheme "http" :host "foo.com" :port 80
22479 :path "/index.html" :fragment "top")
22480 @result{} "http://foo.com:80/index.html#top"
22481
22482 (uri-compose :scheme "http" :host "foo.net"
22483 :path* "/cgi-bin/query.cgi?keyword=foo")
22484 @result{} "http://foo.net/cgi-bin/query.cgi?keyword=foo"
22485
22486 (uri-compose :scheme "mailto" :specific "a@@foo.org")
22487 @result{} "mailto:a@@foo.org"
22488
22489 (receive (authority path query fragment)
22490 (uri-decompose-hierarchical "//foo.jp/index.html#whatsnew")
22491 (uri-compose :authority authority :path path
22492 :query query :fragment fragment))
22493 @result{} "//foo.jp/index.html#whatsnew"
22494 @end example
22495 @end defun
22496
22497
22498 @defun uri-merge base-uri relative-uri relative-uri2 @dots{}
22499 @c MOD rfc.uri
22500 @c EN
22501 Arguments are strings representing
22502 full or part of URIs. This procedure resolves @var{relative-uri}
22503 in relative to @var{base-uri}, as defined in RFC3986 Section 5.2.
22504 ``Relative Resolution''.
22505
22506 If more @var{relative-uri2}s are given, first @var{relative-uri}
22507 is merged to @var{base-uri}, then the next argument is merged
22508 to the resulting uri, and so on.
22509 @c JP
22510 引数は、完全な、あるいは部分的なURIを表す文字列です。
22511 この手続きは、RFC3986 Section 5.2. ``Relative Resolution'' に
22512 示されるアルゴリズムに従い、@var{relative-uri}を@var{base-uri}からの相対
22513 として解決します。
22514
22515 @var{relative-uri2} @dots{} が与えられた場合は、まず@var{relative-uri}
22516 が@var{base-uri}を基準に解決され、その結果を新たな基準として次の
22517 @var{relative-uri2}を解決し、以下同様に続けます。
22518 @c COMMON
22519
22520 @example
22521 (uri-merge "http://example.com/foo/index.html" "a/b/c")
22522 @result{} "http://example.com/foo/a/b/c"
22523
22524 (uri-merge "http://example.com/foo/search?q=abc" "../about#me")
22525 @result{} "http://example.com/about#me"
22526
22527 (uri-merge "http://example.com/foo" "http://example.net/bar")
22528 @result{} "http://example.net/bar"
22529
22530 (uri-merge "http://example.com/foo/" "q" "?xyz")
22531 @result{} "http://example.com/foo/q?xyz"
22532 @end example
22533 @end defun
22534
22535 @defun uri-compose-query params :optional encoding
22536 @c MOD rfc.uri
22537 @c EN
22538 The argument @var{params} is a list of parameter specs. Each parameter
22539 spec must be in the form of @code{(@var{name} @var{value})}, where @var{name}
22540 is a string and @var{value} is either a string or @code{#t}
22541 (see @code{url-decompose-query} above).
22542
22543 Each parameter's name and value is urlencoded and concatenated
22544 as a url query string. If a parameter's value is @code{#t},
22545 the output only includes parameter's name but not value.
22546 @c JP
22547 @var{params}はパラーメータ指定のリストです。各パラメータ指定は
22548 @code{(@var{name} @var{value})}の形式で、@var{name}は文字列、
22549 @var{value}は文字列もしくは@code{#t}です
22550 (上の@code{url-decompose-query}も参照)。
22551
22552 各パラメータの名前と値はurlencodeされてから、URLのクエリパラメータとして結合されます。
22553 パラメータの値が@code{#t}の場合は、名前だけのパラメータとなります。
22554 @c COMMON
22555
22556 @example
22557 (uri-compose-query '(("foo" "abc") ("bar" #t)))
22558 @result{} "foo=abc&bar"
22559 @end example
22560
22561 @c EN
22562 The optional @var{encoding} argument specifies character encoding
22563 of the output. The default is @code{utf-8}. If it is other than that,
22564 the strings are converted to the specified encoding before urlencoding.
22565 @c JP
22566 省略可能な@var{encoding}引数はパラメータの文字エンコーディングを指定します。
22567 デフォルトは@code{utf-8}です。それ以外の場合は、各文字列はその文字エンコーディングに
22568 変換された後でurlencodeされます。
22569 @c COMMON
22570
22571 @c EN
22572 A higher-level utility, @code{http-compose-query} in @code{rfc.http},
22573 is build on top of this
22574 (@pxref{Http client utilities}).
22575 @c JP
22576 @code{rfc.http}の@code{http-compose-query}はこの手続きの上に作られた
22577 ユーティリティです(@ref{Http client utilities}参照)。
22578 @c COMMON
22579 @end defun
22580
22581 @defun uri-compose-data data :key content-type encoding
22582 @c MOD rfc.uri
22583 @c EN
22584 Creates a Data URI of the given @var{data}, with specified content-type
22585 and transfer encoding. Returns a string.
22586
22587 The @var{data} argument must be a string or a u8vector.
22588
22589 The @var{content-type} argument can be @code{#f} (default),
22590 a string that represents a content type (e.g. @code{"text/plain;charset=utf-8"}),
22591 or a list form of parsed content type
22592 (e.g. @code{("application" "octet-stream")}. If it is @code{#f},
22593 @code{text/plain} with the gauche's native character encoding is
22594 used when @var{data} is a complete string, and @code{application/octet-stream}
22595 is used otherwise.
22596
22597 The @var{encoding} argument can be either @code{#f} (default),
22598 or a symbol @code{uri} or @code{base64}. This is for transfer encoding,
22599 not character encoding. If it is @code{#f}, URI encoding is used
22600 for text data and base64 encoding is used for binary data.
22601 @c JP
22602 与えられた@var{data}からData URIを構築して文字列で返します。
22603
22604 @var{data}引数は文字列かu8vectorでなければなりません。
22605
22606 @var{content-type}キーワード引数は、@code{#f} (デフォルト)、
22607 content typeを表現する文字列 (例: @code{"text/plain;charset=utf-8"})、
22608 もしくはパーズされたcontent type (例: @code{("application" "octet-stream")})です。
22609 @code{#f}である場合は、@var{data}が完全な文字列であれば
22610 @code{text/plain}にGaucheのネイティブ文字エンコーディングに基づく@code{charset}を
22611 つけたもの、@var{data}がそれ以外であれば@code{application/octet-stream}が
22612 使われます。
22613
22614 @var{encoding}キーワード引数は@code{#f} (デフォルト)、
22615 もしくはシンボル@code{uri}または@code{base64}です。これは文字エンコーディングではなく
22616 トランスファーエンコーディングであることに注意。
22617 @code{#f}の場合は、テキストデータなら@code{uri}が、バイナリデータなら@code{base64}が
22618 使われます。
22619 @c COMMON
22620
22621 @example
22622 (uri-compose-data "(hello world)")
22623 @result{} "data:text/plain;charset=utf-8,%28hello%20world%29"
22624
22625 (uri-compose-data "(hello world)" :encoding 'base64)
22626 @result{} "data:text/plain;charset=utf-8;base64,KGhlbGxvIHdvcmxkKQ=="
22627
22628 (uri-compose-data '#u8(0 1 2 3))
22629 @result{} "data:application/octet-stream;base64,AAECAw=="
22630 @end example
22631 @end defun
22632
22633
22634 @c EN
22635 @subheading URI Encoding and decoding
22636 @c JP
22637 @subheading URIのエンコードとデコード
22638 @c COMMON
22639
22640 @defun uri-decode :key :cgi-decode
22641 @defunx uri-decode-string string :key :cgi-decode :encoding
22642 @c MOD rfc.uri
22643 @c EN
22644 Decodes ``URI encoding'', i.e. @code{%}-escapes.
22645 @code{uri-decode} takes input from the current input port,
22646 and writes decoded result to the current output port.
22647 @code{uri-decode-string} takes input from @var{string} and
22648 returns decoded string.
22649
22650 If @var{cgi-decode} is true, also replaces @code{+} to a space character.
22651
22652 To @code{uri-decode-string} you can provide the external character
22653 encoding by the @var{encoding} keyword argument. When it is given,
22654 the decoded octet sequence is assumed to be in the specified encoding
22655 and converted to the Gauche's internal character encoding.
22656 @c JP
22657 URI エンコーディング、すなわち、@code{%}でエスケープされた URI 文字列を
22658 デコードします。@code{uri-decode} は現在の入力ポートから入力を受け取り、
22659 デコードした結果を現在の出力ポートに書き出します。
22660 @code{uri-decode-string} は @var{string} を入力とし、デコードした
22661 文字列を返します。
22662
22663 @var{cgi-decode} が真の場合は、@code{+} がスペース文字に置換されます。
22664
22665 @code{uri-decode-string}には、外部の文字エンコーディングを指定する
22666 @var{encoding}キーワード引数を与えることができます。この引数が与えれた
22667 場合、デコードされたオクテットの列を指定された文字エンコーディングであると
22668 してGaucheの内部文字エンコーディングへと変換したものが返されます。
22669 @c COMMON
22670 @end defun
22671
22672 @defun uri-encode :key :noescape
22673 @defunx uri-encode-string string :key :noescape :encoding
22674 @c MOD rfc.uri
22675 @c EN
22676 Encodes unsafe characters by @code{%}-escape. @code{uri-encode}
22677 takes input from the current input port and writes the result to
22678 the current output port. @code{uri-encode-string} takes input
22679 from @var{string} and returns the encoded string.
22680
22681 By default, characters that are not specified ``unreserved'' in
22682 RFC3986 are escaped. You can pass different character
22683 set to @var{noescape} argument to keep from being encoded.
22684 For example, the older RFC2396 has several more ``unreserved''
22685 characters, and passing @code{*rfc2396-unreserved-char-set*} (see below)
22686 prevents those characters from being escaped.
22687
22688 The multibyte characters are encoded as the octet stream of Gauche's
22689 native multibyte representation by default. However, you can pass
22690 the @code{encoding} keyword argument to @code{uri-encode-string},
22691 to convert @var{string} to the specified character encoding.
22692 @c JP
22693 安全でない文字を、@code{%}によるエスケープでエンコードします。
22694 @code{uri-encode} は現在の入力ポートから入力を受け取り、
22695 結果を現在の出力ポートに書き出します。
22696 @code{uri-encode-string} は @var{string} を入力とし、エンコードした
22697 文字列を返します。
22698
22699 デフォルトでは、RFC3986 で"非予約文字"として規定されていない文字は
22700 エスケープされます。@var{noescape} 引数に異なる文字集合を渡すことで、
22701 それらがエンコードされるのを抑止することができます。
22702 例えば古いRFC2396では"非予約文字"がいくつか多かったのですが、
22703 @code{*rfc2396-unreserved-char-set*} (下記参照) を渡すことで
22704 それらの文字がエスケープされるのを防ぐことができます。
22705
22706 マルチバイト文字は、デフォルトではGauche のネイティブなマルチバイト表現の
22707 オクテット・ストリームとしてエンコードされます。ただし
22708 @code{uri-encode-string}には@var{encoding}キーワード引数を渡すことができて、
22709 その場合はまず@var{string}が指定された文字エンコーディングへと変換されます。
22710 @c COMMON
22711 @end defun
22712
22713 @defvr {Constant} *rfc2396-unreserved-char-set*
22714 @defvrx {Constant} *rfc3986-unreserved-char-set*
22715 @c MOD rfc.uri
22716 @c EN
22717 These constants are bound to character sets that represents
22718 ``unreserved'' characters defined in RFC2396 and RFC3986, respectively.
22719 (See @ref{Character sets}, and @ref{R7RS character sets}, for
22720 operations on character sets).
22721 @c JP
22722 これらの定数はそれぞれ、RFC2396とRFC3986で定義されている
22723 「非予約文字」の文字集合に束縛されています。
22724 (文字集合の操作については、@ref{Character sets}および@ref{R7RS character sets}
22725 を参照して下さい。)
22726 @c COMMON
22727 @end defvr
22728
22729 @c ----------------------------------------------------------------------
22730 @node UUID, Zlib compression library, URI parsing and construction, Library modules - Utilities
22731 @section @code{rfc.uuid} - UUID
22732 @c NODE UUID, @code{rfc.uuid} - UUID
22733
22734 @deftp {Module} rfc.uuid
22735 @mdindex rfc.uuid
22736 @c EN
22737 This module implements UUID defined in RFC9562.
22738
22739 It provides generators of UUID version 1, 4, 6 and 7, and writer/parser
22740 of the string represenation of UUIDs.
22741 @c JP
22742 RFC9562で定義されたUUIDを実装しています。
22743
22744 UUIDバージョン1、4、6、7を生成する機能、及びUUIDの文字列表記をパーズしたり
22745 バイナリから文字列表記を生成する機能が提供されます。
22746 @c COMMON
22747 @end deftp
22748
22749 @deftp {Class} <uuid>
22750 @c MOD rfc.uuid
22751 @c EN
22752 Class of UUID instances. UUID instances are immutable.
22753 @c JP
22754 UUIDクラスです。UUIDインスタンスは変更不可なオブジェクトです。
22755 @c COMMON
22756 @end deftp
22757
22758 @c EN
22759 @subheading Common uuid operations
22760 @c JP
22761 @subheading uuid共通の操作
22762 @c COMMON
22763
22764 @defun uuid-value uuid
22765 @c MOD rfc.uuid
22766 @c EN
22767 Returns the raw value of @var{uuid} as 16-element @code{u8vector}.
22768 You shouldn't mutate the returned u8vector.
22769 @c JP
22770 UUID @var{uuid}の「生の」値を、16要素の@code{u8vector}として返します。
22771 返されたベクタを変更してはいけません。
22772 @c COMMON
22773 @end defun
22774
22775 @defun uuid-version uuid
22776 @c MOD rfc.uuid
22777 @c EN
22778 Returns the version number of @var{uuid}.
22779 @c JP
22780 @var{uuid}のバージョン番号を返します。
22781 @c COMMON
22782 @end defun
22783
22784 @defvar uuid-comparator
22785 @c MOD rfc.uuid
22786 @c EN
22787 A comparator to compare and hash uuids. @xref{Basic comparators}.
22788
22789 Note: Equality of uuids can be tested with @code{equal?}.
22790 @c JP
22791 UUID同士を比較したりハッシュ値を取れる比較器です。
22792 比較器については@ref{Basic comparators}参照。
22793
22794 註: 二つのUUIDが等しいかどうかは@code{equal?}で検査できます。
22795 @c COMMON
22796 @end defvar
22797
22798 @c EN
22799 @subheading Read/write UUIDs
22800 @c JP
22801 @subheading UUIDの読み書き
22802 @c COMMON
22803
22804 @defun parse-uuid string :key if-invalid
22805 @c MOD rfc.uuid
22806 @c EN
22807 Takes a string representation of UUID, parses it and returns
22808 an uuid instance. If the string isn't a valid UUID representation,
22809 an error is thrown if the @var{if-invalid} keyword argument is omitted
22810 or @code{:error}, and @code{#f} is returned if @var{if-invalid} is @code{#f}.
22811 @c JP
22812 UUIDの文字列表現をパーズし、UUIDインスタンスにして返します。
22813 文字列が有効なUUID表現でない場合、@var{if-invalid}キーワード引数が
22814 省略されるか@code{:error}であればエラーが投げられ、
22815 @var{if-invalid}が@code{#f}であれば@code{#f}が返されます。
22816 @c COMMON
22817
22818 @c EN
22819 Other than @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format,
22820 it recognizes the one with @code{urn:uuid:} prefix,
22821 the one enclosed by curly braces, and the one without hyphens.
22822 @c JP
22823 典型的な@code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}という形式に加え、
22824 @code{urn:uuid:}プレフィクスがついた形、前後がカーリーブレイスで囲まれた形、
22825 そしてハイフンを持たない形が認識されます。
22826 @c COMMON
22827 @end defun
22828
22829 @defun write-uuid uuid :optional port
22830 @c MOD rfc.uuid
22831 @c EN
22832 Writes out a string representation of @var{uuid},
22833 in @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format, to the given
22834 port. If the port is omitted, current output port is used.
22835 @c JP
22836 @var{uuid}の文字列表現を@code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}形式で
22837 @var{port}に書き出します。@var{port}が省略された場合は現在の出力ポートが使われます。
22838 @c COMMON
22839 @end defun
22840
22841 @defun uuid->string uuid
22842 @c MOD rfc.uuid
22843 @c EN
22844 Returns a string representation of @var{uuid},
22845 in @code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} format.
22846 @c JP
22847 @var{uuid}の文字列表現を@code{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}形式で
22848 返します。
22849 @c COMMON
22850 @end defun
22851
22852
22853 @c EN
22854 @subheading UUID generator makers
22855 @c JP
22856 @subheading UUIDジェネレータ作成
22857 @c COMMON
22858
22859 @deffn {Parameter} uuid-random-source
22860 @c MOD rfc.uuid
22861 @c EN
22862 We use PRNG to generate UUIDs. By default, we internally creates
22863 a random source and randomize it. You can alter the random source
22864 using @code{parameterize}. The value must be a SRFI-27 random source
22865 (@pxref{Sources of random bits}).
22866 @c JP
22867 UUIDを生成するのに乱数発生器を使います。
22868 デフォルトでは、内部的に乱数源を作って乱数化したものを使いますが、
22869 このパラメータを@code{parameterize}することで独自の乱数源を使うことができます。
22870 パラメータの値はSRFI-27の規定する乱数源でなければなりません
22871 (@ref{Sources of random bits}参照)。
22872 @c COMMON
22873
22874 @c EN
22875 The value of this parameter is taken when a uuid generator
22876 is created by one of @code{make-uuid*-generator}. Once a
22877 generator is created, the random source is kept in the generator
22878 and won't be affected by changing the value of this parameter.
22879 @c JP
22880 このパラメータの値は、@code{make-uuid*-generator}でUUIDのジェネレータが
22881 作られる時に参照され、その乱数源がジェネレータの中に保持されます。
22882 このパラメータの値の変更は、既に作られたジェネレータには影響を与えません。
22883 @c COMMON
22884 @end deffn
22885
22886 @defun make-uuid1-generator :optional node-id
22887 @defunx make-uuid6-generator :optional node-id
22888 @c MOD rfc.uuid
22889 @c EN
22890 Returns new generators of uuid v1 and uuis v6
22891 (timestamp and node id based), respectively.
22892
22893 The difference between version 1 and version 6 is the order of timestamp field;
22894 version 1 stores lower bits of timestamp first, while version 6
22895 stores higher bits first. That makes v6 uuids created around
22896 the same time cluster together when sorted, making it favorable
22897 choice over v1 for database index. (However, if you need
22898 chronologically orderable uuids, you should use v7 uuids.)
22899
22900 The optional @var{node-id} argument must be 48bit exact integer
22901 specifing the node ID (IEEE802 MAC address of the machine).
22902 If it is omitted, we generate a process-global
22903 random node ID (with the multicast bit set to 1, so that it won't
22904 conflict with existing MAC address).
22905 @c JP
22906 それぞれ、バージョン1およびバージョン6アルゴリズム(タイムスタンプとノードID)による
22907 UUIDのジェネレータを生成して返します。二つのバージョンの違いは、
22908 バージョン1ではタイムスタンプをいくつかに分けたうちの下位ビットから順に格納する
22909 のに対し、バージョン6では上位ビットから格納することです。
22910 これにより、近い時間に作られたv6 uuidはソートした時に固まることになり、
22911 データベースのインデックスとして使う場合にv1より有利になります。
22912 (但し、完全に時間的に整列可能なuuidが必要な場合はv7 uuidを使ってください)。
22913
22914 省略可能な@var{node-id}引数はノードIDを指定する48ビットの正確な整数でなければ
22915 なりません (IEEE802 MACアドレスが通常使われます)。
22916 省略された場合は、プロセス内でひとつのランダムノードIDを生成して使います
22917 (この場合、生成されるノードIDはマルチキャストビットが立てられるので、
22918 現実に存在するMACアドレスとかぶることはありません)。
22919 @c COMMON
22920
22921 @c EN
22922 The generators created by these procedures are thread-safe.
22923 @c JP
22924 これらの手続きで作られるジェネレータはスレッドセーフです。
22925 @c COMMON
22926 @end defun
22927
22928 @defun make-uuid4-generator
22929 @c MOD rfc.uuid
22930 @c EN
22931 Returns a new generator that yields uuids with
22932 version 4 algorithm (random numbers).
22933 @c JP
22934 バージョン4アルゴリズム(乱数)によるUUIDを生成するジェネレータを作って返します。
22935 @c COMMON
22936
22937 @c EN
22938 The generators created by this procedures are thread-safe.
22939 @c JP
22940 この手続きで作られるジェネレータはスレッドセーフです。
22941 @c COMMON
22942 @end defun
22943
22944 @defun make-uuid7-generator :optional increment-bits
22945 @c MOD rfc.uuid
22946 @c EN
22947 Returns a new generator that yields uuids with version 7 algorithm
22948 (time-ordered).
22949 The uuid consists of timestamp part, and monotonically increasing
22950 random bits. Overall, it is ordered chronologically.
22951 @c JP
22952 バージョン7アルゴリズム(時間順列可能)でuuidを作るジェネレータを作って返します。
22953 uuidは、タイムスタンプ部分と、時間的に単調増加するランダムビット部分からなります。
22954 全体として、uuidをソートすると生成順になります。
22955 @c COMMON
22956
22957 @c EN
22958 The random bit part is splitted to 12bit @code{rand_a} field
22959 and 62bit @code{rand_b} field in UUID RFC. The RFC doesn't
22960 precisely specify how to fill them. In our implementation,
22961 we treat it as 74bit unsigned integer, and use the following
22962 strategy:
22963 @c JP
22964 ランダムビット部分はUUID RFCの仕様では12ビットの@code{rand_a}フィールドと
22965 62bitの@code{rand_b}フィールドに分かれています。
22966 RFCではどのようにそれらを埋めるかは具体的に指定されていません。
22967 Gaucheの実装では、それを74ビットの非負整数とみなし、
22968 次の戦略を取ります。
22969 @c COMMON
22970
22971 @c EN
22972 @itemize @bullet
22973 @item
22974 It is initialized with random integer per process.
22975 @item
22976 When a v7 uuid is asked, we increment the field with a
22977 random unsigned integer up to 2^@var{increment-bits}.
22978 If it does not overflow, we use it as is.
22979 @item
22980 If it does overflow, if the timestamp is already incremented
22981 from the previous generation, we use the wraparound value.
22982 @item
22983 Otherwise, we wait until the timestamp field is incremented,
22984 and then use the wraparound value.
22985 @end itemize
22986 @c JP
22987 @itemize @bullet
22988 @item
22989 プロセスごとに、ランダムの整数を初期値とします。
22990 @item
22991 v7 uuidを生成する度に、ランダムな2^@var{increment-bits}未満の
22992 非負整数をフィールドに加算します。
22993 フィールドがオーバーフローしなければそれをそのまま使います。
22994 @item
22995 フィールドがオーバーフローした場合、前回の生成からタイムスタンプが進んでいれば、
22996 ラップアラウンドした値を使います。
22997 @item
22998 そうでなければ、タイムスタンプが進むまで待って、
22999 ラップアラウンドした値を使います。
23000 @end itemize
23001 @c COMMON
23002
23003 @c EN
23004 The optional @var{increment-bits} argument must be an positive exact integer.
23005 The default value is 64. You may want to pass a smaller number if you
23006 need to create a lots of UUIDs in very short span of time.
23007 @c JP
23008 省略可能な@var{increment-bits}引数は正確な正の整数でなければなりません。
23009 デフォルトの値は64です。極めて短い時間内に大量のUUIDを作りたい場合は、
23010 小さな数を指定するのが良いでしょう。
23011 @c COMMON
23012
23013 @c EN
23014 The generators created by this procedures are thread-safe.
23015 @c JP
23016 この手続きで作られるジェネレータはスレッドセーフです。
23017 @c COMMON
23018 @end defun
23019
23020 @defun uuid-random-source-set! random-source
23021 @c MOD rfc.uuid
23022 @c DEPRECATED
23023 @c EN
23024 Use @code{uuid-random-source} parameter
23025 to customize random source to be used in uuid generation.
23026 @c JP
23027 UUID生成に使われる乱数源をカスタマイズするには
23028 @code{uuid-random-source}パラメータを使ってください。
23029 @c COMMON
23030 @end defun
23031
23032 @c EN
23033 @subheading Pre-created UUID generators
23034 @c JP
23035 @subheading あらかじめ作られているUUIDジェネレータ
23036 @c COMMON
23037
23038 @defun uuid1 :optional node-id
23039 @defunx uuid4
23040 @defunx uuid6 :optional node-id
23041 @defunx uuid7
23042 @c MOD rfc.uuid
23043 @c EN
23044 Pre-created uuid generators for convenience.
23045 Those generators are created with the corresponding
23046 @code{make-uuid*-generator} when the library is loaded,
23047 so they use the default random source.
23048 @c JP
23049 簡便のために、あらかじめ作られているUUIDのジェネレータです。
23050 これらのジェネレータはライブラリのロード時に
23051 対応する@code{make-uuid*-generator}で作られるので、
23052 デフォルトの乱数源を使います。
23053 @c COMMON
23054
23055 @c EN
23056 These generators are thread-safe.
23057 @c JP
23058 これらのジェネレータはスレッドセーフです。
23059 @c COMMON
23060 @end defun
23061
23062 @defun nil-uuid
23063 @c MOD rfc.uuid
23064 @c EN
23065 Returns a nil-UUID (all bits zero).
23066 @c JP
23067 全てのビットが0であるnil UUIDを返します。
23068 @c COMMON
23069 @end defun
23070
23071 @c ----------------------------------------------------------------------
23072 @node Zlib compression library, SLIB, UUID, Library modules - Utilities
23073 @section @code{rfc.zlib} - zlib compression library
23074 @c NODE zlib圧縮ライブラリ, @code{rfc.zlib} - zlib圧縮ライブラリ
23075
23076 @deftp {Module} rfc.zlib
23077 @mdindex rfc.zlib
23078 @c EN
23079 This module provides bindings to zlib compression library.
23080 Most features of zlib can be used through this module.
23081
23082 Zlib supports reading and writing of
23083 Zlib compressed data format (RFC1950),
23084 DEFLATE compressed data format (RFC1951),
23085 and GZIP file format (RFC1052). It also provides
23086 procedures to calculate CRC32 and Adler32 checksums.
23087
23088 Compression and decompression are done through specialized ports.
23089 There are number of parameters to fine-tune compression; refer
23090 to zlib documentation for the details.
23091 @c JP
23092 このモジュールは、Zlib圧縮ライブラリに対するバインディングを提供します。
23093 Zlibのほとんどの機能がこのモジュールを通して利用可能です。
23094
23095 Zlibは、ZLIB圧縮データフォーマット(RFC1950)、DEFLATE圧縮データフォー
23096 マット(RFC1951)、GZIPファイルフォーマット(RFC1952)の読み書きをサポー
23097 トするライブラリです。また、CRC32とAdler32チェックサムの計算のための
23098 関数も提供します。
23099
23100 圧縮・展開機能はポートを通して提供されます。圧縮をチューンするパラ
23101 メータの詳細については、Zlibのドキュメントも合わせて参照してください。
23102 @c COMMON
23103 @end deftp
23104
23105 @subheading Condition types
23106
23107 @c EN
23108 The following condition types are defined to represent errors
23109 during processing by zlib.
23110 @c JP
23111 Zlib処理中のエラーを示すために、以下のコンディションタイプが定義されています。
23112 @c COMMON
23113
23114 @deftp {Condition Type} <zlib-error>
23115 @c MOD rfc.zlib
23116 @c EN
23117 Subclass of @code{<error>} and superclass of the following
23118 condition types. This class is an abstract class to catch any of the
23119 zlib-specific errors. Zlib-specific errors raised by
23120 procedures in @code{rfc.zlib} are always an instance (or a compound
23121 condition including) one of the following specific classes.
23122 @c JP
23123 @code{<error>}のサブクラスで、以下のコンディションタイプのスーパークラスです。
23124 このクラスはzlib特有のエラーをまとめて捕捉するための抽象クラスとして設けられています。
23125 @code{rfc.zlib}が投げるZlib固有のエラーは常に以下の特定のクラスのインスタンス、
23126 もしくはそのインスタンスを含む複合コンディションです。
23127 @c COMMON
23128 @end deftp
23129
23130 @deftp {Condition Type} <zlib-need-dict-error>
23131 @deftpx {Condition Type} <zlib-stream-error>
23132 @deftpx {Condition Type} <zlib-data-error>
23133 @deftpx {Condition Type} <zlib-memory-error>
23134 @deftpx {Condition Type} <zlib-version-error>
23135 @c MOD rfc.zlib
23136 @c EN
23137 Subclasses of @code{<zlib-error>}. Those condition type correspond
23138 to zlib's
23139 @code{Z_NEED_DICT_ERROR},
23140 @code{Z_STREAM_ERROR},
23141 @code{Z_DATA_ERROR},
23142 @code{Z_MEMORY_ERROR}, and
23143 @code{Z_VERSION_ERROR} errors.
23144 @c JP
23145 @code{<zlib-error>}のサブクラスです。それぞれ、Zlibの
23146 @code{Z_NEED_DICT_ERROR}、
23147 @code{Z_STREAM_ERROR}、
23148 @code{Z_DATA_ERROR}、
23149 @code{Z_MEMORY_ERROR}、
23150 @code{Z_VERSION_ERROR}
23151 に対応します。
23152 @c COMMON
23153
23154 @c EN
23155 When an error occurs during reading data, a compound
23156 condition of a subclass of @code{<zlib-error>} and
23157 @code{<io-read-error>} is raised.
23158 When an error occurs without I/O, a simple condition
23159 of a subclass of @code{<zlib-error>} is raised.
23160 Errors unrelated to zlib, such as invalid argument error,
23161 would be a simple @code{<error>} condition.
23162 @c JP
23163 データの読み出し時にエラーが発生した場合、
23164 @code{<zlib-error>}のサブクラスと
23165 @code{<io-read-error>}の合成コンディションが投げられます。入力が伴わ
23166 ない場合、例えば圧縮ストリームの初期化エラーのときには、合成され
23167 ていない@code{<zlib-error>}のサブクラスが投げられます。ただの引数の型の
23168 エラーのように、Zlibの関数が呼び出されない場合は、ただの@code{<error>}が
23169 投げられるかもしれません。
23170 @c COMMON
23171 @end deftp
23172
23173 @subheading Compression/decompression ports
23174
23175 @deftp {Class} <deflating-port>
23176 @deftpx {Class} <inflating-port>
23177 @clindex deflating-port
23178 @clindex inflating-port
23179 @c MOD rfc.zlib
23180 @c EN
23181 Compression and decompression functions are provided
23182 via ports. A @emph{deflating port} is an output port
23183 that compresses the output data. An @emph{inflating port}
23184 is an input that reads compressed data and decompress it.
23185
23186 When an inflating port encounters a corrupted compressed
23187 data, a compound condition of @code{<io-read-error>}
23188 and @code{<zlib-data-error>} is raised during read operation.
23189 @c JP
23190 圧縮と展開の機能はポートを通じて提供されます。
23191 @emph{deflating port}は出力されたデータを圧縮する出力ポートです。
23192 @emph{inflating port}は圧縮されたデータソースからデータを展開しつつ
23193 読み込む入力ポートです。
23194
23195 inflating portが読み出す圧縮データが壊れていた場合、読み出し時に
23196 @code{<io-read-error>}と@code{<zlib-data-error>}の
23197 合成コンディションが投げられます。
23198 @c COMMON
23199 @end deftp
23200
23201
23202 @defun open-deflating-port drain :key compression-level buffer-size window-bits memory-level strategy dictionary owner?
23203 @c MOD rfc.zlib
23204 @c EN
23205 Creates and returns an instance of @code{<deflating-port>},
23206 an output port that compresses the output data and sends
23207 the compressed data to another output port @var{drain}.
23208 This combines the functionality of zlib's @code{deflateInit2()}
23209 and @code{deflateSetDictionary()}.
23210 @c JP
23211 新たな@code{<deflating-port>}のインスタンス、
23212 すなわち書き込まれたデータを圧縮し出力ポート@var{drain}に書き出す出力ポートを作成して、
23213 そのポートを返します。Zlibの関数@code{deflateInit2()}と
23214 @code{deflateSetDictionary()}とを合わせた手続きです。
23215 @c COMMON
23216
23217 @c EN
23218 You can specify an exact integer between 1 and 9 (inclusive) to
23219 @var{compression-level}. Larger integer means larger compression ratio.
23220 When omitted, a default compression level is used, which is usually 6.
23221 @c JP
23222 @var{compression-level}には1から9の整数を指定することができ、
23223 大きい数が高い圧縮率を意味します。引数が省略された場合は、
23224 デフォルトの圧縮レベルと見なされます。これは通常6です。
23225 @c COMMON
23226
23227 @c EN
23228 The following constants are defined to specify @var{compression-level}
23229 conveniently:
23230 @c JP
23231 @var{compression-level}をわかりやすく指定するために以下の定数が定義されています。
23232 @c COMMON
23233
23234 @defvr {Constant} Z_NO_COMPRESSION
23235 @defvrx {Constant} Z_BEST_SPEED
23236 @defvrx {Constant} Z_BEST_COMPRESSION
23237 @defvrx {Constant} Z_DEFAULT_COMPRESSION
23238 @c MOD rfc.zlib
23239 @end defvr
23240
23241 @c EN
23242 The @var{buffer-size} argument specifies the buffer size of the port in bytes.
23243 The default is 4096.
23244 @c JP
23245 @var{buffer-size}は、ポートのバッファサイズを指定します。デフォルトは4096バイトです。
23246 @c COMMON
23247
23248 @c EN
23249 The @var{window-bits} argument specifies the size of the window in
23250 exact integer. Typically the value should be
23251 between 8 and 15, inclusive, and it specifies the base two logarithm
23252 of the window size used in compression.
23253 Larger number yields better compression ratio, but more memory usage.
23254 The default value is 15.
23255 @c JP
23256 @var{window-bits}はウィンドウサイズを指定します。
23257 通常この値は8から15までの整数で、圧縮に使われるウィンドウサイズの
23258 2を底とするlogをとった値です。
23259 大きい数であるだけ圧縮率が高くなりますが、
23260 そのぶんメモリの使用量が増加します。デフォルトは15です。
23261 @c COMMON
23262
23263 @c EN
23264 There are a couple of special modes specifiable by @var{window-bits}.
23265 When an integer between -8 and -15 is given to
23266 @var{window-bits}, the port produces a raw deflated data,
23267 that lacks zlib header and trailer. In this case, Adler32 checksum isn't
23268 calculated. The actual window size is determined by the absolute value of
23269 @var{window-bits}.
23270 @c JP
23271 @var{window-bits}よって、2つばかり特別なモードを指定することができます。
23272 @var{window-bits}に-8から-15の整数を指定された場合は、
23273 ZLIBヘッダとトレイラのない生のdeflateデータを作成します。
23274 この場合Adler32チェックサムも計算されません。
23275 実際のウィンドウサイズは@var{window-bits}の絶対値によって計算されます。
23276 @c COMMON
23277
23278 @c EN
23279 When @var{window-bits} is between 24 and 31, the port uses GZIP encoding;
23280 that is, instead of zlib wrapper,
23281 the compressed data is enveloped by simple gzip header and trailer.
23282 The gzip header added by this case doesn't have filenames, comments,
23283 header CRC and other data, and have zero modified time, and 255 (unknown)
23284 in the OS field. The @code{zstream-adler32} procedure will return
23285 CRC32 checksum instead of Adler32.
23286 The actual window size is determined by @var{window-bits}-16.
23287 @c JP
23288 @var{window-bits}が24から31の間である場合、
23289 ポートはgzipエンコーディングを使うようになります。すなわち、
23290 zlibラッパの代わりに、シンプルなgzipヘッダとトレイラが圧縮データの前後に書き出されます。
23291 gzipヘッダはファイル名やその他のデータ、コメントを持たず、変更時刻は0、
23292 ヘッダCRCはなし、OS名は不明を意味する255になります。gzipストリームが書き出
23293 されるときは、@code{zstream-adler32}で取得できるチェックサムはAdler32
23294 ではなくCRC32になります。
23295 実際のウィンドウサイズは @var{window-bits}-16 で決定されます。
23296 @c COMMON
23297
23298 @c EN
23299 The @var{memory-level} argument specifies how much memory
23300 should be allocated to keep the internal state during compression.
23301 1 means smallest memory, which causes slow and less compression.
23302 9 means fastest and best compression with largest amount of memory.
23303 The default value is 8.
23304 @c JP
23305 @var{memory-level}は、圧縮の内部状態のためにどれだけのメモリを割り当て
23306 るかを指定するパラメータです。1ではメモリの使用量は最小ですが、遅
23307 くなり圧縮率が低下します。9では高速な処理のためにメモリが最も多く
23308 使われます。デフォルトは8です。
23309 @c COMMON
23310
23311 @c EN
23312 To fine tune compression algorithm, you can use the @var{strategy}
23313 argument. The following constants are defined as the valid
23314 value as @var{strategy}:
23315 @c JP
23316 @var{strategy}で圧縮アルゴリズムをチューンできます。
23317 以下の定数が@var{strategy}に有効な値として定義されています。
23318 @c COMMON
23319
23320 @defvr {Constant} Z_DEFAULT_STRATEGY
23321 @c MOD rfc.zlib
23322 @c EN
23323 The default strategy, suitable for most ordinary data.
23324 @c JP
23325 通常のデータに適する、デフォルトのアルゴリズムを使います。
23326 @c COMMON
23327 @end defvr
23328
23329 @defvr {Constant} Z_FILTERED
23330 @c MOD rfc.zlib
23331 @c EN
23332 Suitable for data generated by filters.
23333 Filtered data consists mostly of small values with a
23334 random distribution, and this makes the compression algorithm
23335 to use more huffman encoding and less string match.
23336 @c JP
23337 フィルタにより生成されたデータに適したアルゴリズムを使います。
23338 このようなデータは小さな値とランダムな分散を持つことが多いため、
23339 このアルゴリズムではハフマンエンコーディングをより優先し、
23340 文字列一致の使用をやや抑えます。
23341 @c COMMON
23342 @end defvr
23343
23344 @defvr {Constant} Z_HUFFMAN_ONLY
23345 @c MOD rfc.zlib
23346 @c EN
23347 Force huffman encoding only (no string match).
23348 @c JP
23349 ハフマンエンコーディングのみを使います (文字列一致を使いません)。
23350 @c COMMON
23351 @end defvr
23352
23353 @defvr {Constant} Z_RLE
23354 @c MOD rfc.zlib
23355 @c EN
23356 Limit match distance to 1 (that is, to force run-length encoding).
23357 It is as fast as @code{Z_HUFFMAN_ONLY} and gives better compression
23358 for png image data.
23359 @c JP
23360 マッチ距離を1に制限します (ランレングスエンコーディングを強制することになります)。
23361 @code{Z_HUFFMAN_ONLY}と同じくらい高速で、かつpngイメージデータに対して
23362 良い圧縮率が得られます。
23363 @c COMMON
23364 @end defvr
23365
23366 @defvr {Constant} Z_FIXED
23367 @c MOD rfc.zlib
23368 @c EN
23369 Prohibits dynamic huffman encoding. It allows a simple decoder
23370 for special applications.
23371 @c JP
23372 動的ハフマンエンコーディングを禁止します。特殊なアプリケーションで、
23373 単純なデコーダを使いたい場合に便利です。
23374 @c COMMON
23375 @end defvr
23376
23377 @c EN
23378 The choice of @var{strategy} only affects compression ratio and
23379 speed. Any choice produces correct and decompressable data.
23380 @c JP
23381 @var{strategy}の選択は圧縮率と速度にのみ影響を与えます。
23382 どの値を選んでも圧縮されたデータは正しく展開できます。
23383 @c COMMON
23384
23385 @c EN
23386 You can give an initial dictionary to the @var{dictionary}
23387 argument to be used in compression.
23388 The compressor and decompressor must use exactly the same dictionary.
23389 See the zlib documentation for the details.
23390 @c JP
23391 @var{dictionary}には圧縮に使う辞書を文字列で与えます。辞書を与える場合、
23392 圧縮と展開で全く同じものを使う必要があります。
23393 辞書の詳細についてはzlibのドキュメントを参照してください。
23394 @c COMMON
23395
23396 @c EN
23397 By default, a deflating port leaves @var{drain} open
23398 after all conversion is done, i.e. the deflating port itself is
23399 closed. If you don't want to bother closing @var{drain},
23400 give a true value to the @var{owner?} argument; then @var{drain}
23401 is closed after the deflating port is closed and all data
23402 is written out.
23403 @c JP
23404 デフォルトでは、deflating portはそれ自身がクローズされても
23405 @var{drain}をクローズしません。@var{drain}の後始末を気にしたくない
23406 場合は@var{owner?}引数に真の値を与えてください。
23407 その場合、deflating portがクローズされすべてのデータが書き出されたのちに
23408 @var{drain}は自動的にクローズされます。
23409 @c COMMON
23410
23411 @c EN
23412 Note: You @emph{must} close a deflating port explicitly,
23413 or the compressed data can be chopped prematurely.
23414 When you leave a deflating port open to be GCed, the
23415 finalizer will close it; however, the order in which
23416 finalizers are called is undeterministic, and it is
23417 possible that the @var{drain} port is closed before
23418 the deflating port is closed. In such cases,
23419 the deflating port's attempt to flush the buffered data
23420 and trailer will fail.
23421 @c JP
23422 注意: deflating portは必ず明示的にクローズしてください。
23423 そうしなければ圧縮データの終わりの部分(バッファされているデータおよびトレイラ)が
23424 @var{drain}に書き出されないかもしれません。
23425 ポートを明示的にクローズせずにガベージ・コレクタに任せた場合、
23426 出力ポートのクローズ手続きはファイナラザから呼び出されることになります。
23427 複数のごみに対してファイナライザの呼ばれる順番は不定なので、
23428 deflating portより先に@var{drain}のファイナライザが呼ばれて
23429 そのポートがクローズされてしまうことがあります。
23430 こうなると、圧縮データの終わりの部分の出力がエラーになってしまいます。
23431 @c COMMON
23432 @end defun
23433
23434 @defun open-inflating-port source :key buffer-size window-bits dictionary owner?
23435 @c MOD rfc.zlib
23436 @c EN
23437 Takes an input port @var{source} from which a compressed data
23438 can be read, and creates and returns a new instance of
23439 @code{<inflating-port>}, that is, a port that allows
23440 decompressed data from it.
23441 This procedure covers zlib's functionality of
23442 @code{inflateInit2()} and @code{inflateSetDictionary()}.
23443 @c JP
23444 圧縮データを読み出せる入力ポート@var{source}を取り、
23445 新たな@code{<inflating-port>}のインスタンス、すなわち
23446 展開されたデータを読み出すことのできる入力ポートを作成し、そのポートを返します。
23447 これはZlibの関数@code{inflateInit2()}、@code{inflateSetDictionary()}
23448 を合わせた手続きです。
23449 @c COMMON
23450
23451 @c EN
23452 The meaning of @var{buffer-size} and @var{owner} are
23453 the same as @code{open-deflating-port}.
23454 @c JP
23455 @var{buffer-size}、@var{owner?}の意味は
23456 @code{open-deflating-port}と同じです。
23457 @c COMMON
23458
23459 @c EN
23460 The meaning of @var{window-bits} is almost the same,
23461 except that if a value increased by 32 is given, the inflating port
23462 automatically detects whether the source stream is
23463 zlib or gzip by its header.
23464
23465 That is, you can specify between 8 to 15 to read zlib,
23466 24 to 31 to read gzip, or 40 to 47 to use automatic detection.
23467
23468 The window bits must be equal to or greater than the window bits
23469 used to compress the source,
23470 or a @code{<zlib-data-error>} condition is thrown.
23471 If you don't know the compression
23472 parameters of the input (which is most likely the case), you need to
23473 specify the maximum value, i.e. 15 for zlib, 31 for gzip, or 47 to
23474 autodetect.
23475 @c JP
23476 @var{window-bits}の意味もほぼ同じですが、
23477 32が足された値が与えられた場合にはzlibとgzipのヘッダ自動判定が有効になります。
23478
23479 すなわち、zlibを読む場合は8から15、gzipを読む場合は24から31、自動判定を使う場合は
23480 40から47の値を指定することになります。
23481
23482 このwindow bitsは、入力が圧縮された時に使われたwindow bits以上でなければならず、
23483 小さいと@code{<zlib-data-error>}コンディションが投げられます。
23484 入力の圧縮時のパラメータを知らない場合(通常そうだと思います)、
23485 最大の値を指定するのが良いでしょう。つまり、
23486 zlibなら15、gzipなら31、自動判定を使うなら47です。
23487 @c COMMON
23488
23489 @c EN
23490 If the input data is compressed with specified dictionary,
23491 the same dictionary must be given to the @var{dictionary} argument.
23492 Otherwise, a compound condition of
23493 @code{<io-read-error>} and @code{<zlib-need-dict-error>} will be raised.
23494 @c JP
23495 @var{dictionary}は圧縮時の辞書と同じものを指定しなければなりません。
23496 辞書を使って圧縮されたデータを展開する際に、@var{dictionary}引数
23497 を指定しなかったり、異なる辞書を与えた場合は
23498 @code{<io-read-error>}と@code{<zlib-need-dict-error>}の
23499 合成コンディションが投げられます。
23500 @c COMMON
23501 @end defun
23502
23503 @subheading Operations on inflating/deflating ports
23504
23505 @defun zstream-total-in xflating-port
23506 @defunx zstream-total-out xflating-port
23507 @defunx zstream-adler32 xflating-port
23508 @defunx zstream-data-type xflating-port
23509 @c MOD rfc.zlib
23510 @c EN
23511 The @var{xflating-port} argument must be either
23512 inflating and deflating port, or an error is raised.
23513
23514 Returns the value of @code{total_in}, @code{total_out},
23515 @var{adler32}, and @code{data_type} fields of the @code{z_stream}
23516 structure associated to the given inflating or deflating port,
23517 respectively.
23518 @c JP
23519 @var{xflating-port}はinflating portかdeflating portでなければ
23520 なりません。さもなくばエラーが通知されます。
23521
23522 @code{z_stream}構造体の@code{total_in}、@code{total_out}、
23523 @code{adlre32}および@code{data_type}フィールドの値を返します。
23524 @c COMMON
23525
23526 @c EN
23527 The value of @code{data_type} can be one of the following
23528 constants:
23529 @c JP
23530 @code{data_type}フィールドの値は以下の定数のうちのいずれかです。
23531 @c COMMON
23532
23533 @defvr {Constant} Z_BINARY
23534 @defvrx {Constant} Z_TEXT
23535 @defvrx {Constant} Z_ASCII
23536 @defvrx {Constant} Z_UNKNOWN
23537 @c MOD rfc.zlib
23538 @end defvr
23539
23540 @end defun
23541
23542 @defun zstream-params-set! deflating-port :key compression-level strategy
23543 @c MOD rfc.zlib
23544 @c EN
23545 Changes compression level and/or strategy during compressing.
23546 @c JP
23547 圧縮率とストラテジを動的に変更するための手続きです。
23548 @c COMMON
23549 @end defun
23550
23551 @defun zstream-dictionary-adler32 deflating-port
23552 @c MOD rfc.zlib
23553 @c EN
23554 When a dictionary is given to @code{open-deflating-port}, the
23555 dictionary's adler32 checksum is calculated. This
23556 procedure returns the checksum. If no dictionary has been given,
23557 this procedure returns @code{#f}.
23558 @c JP
23559 deflating portの作成時に辞書を指定すると、辞書のAdler32チェックサム
23560 が計算されます。この手続きはそのチェックサムを返します。
23561 @code{open-deflating-port}に辞書を与えなかったなら、@code{#f}が返ります。
23562 @c COMMON
23563 @end defun
23564
23565 @defun deflating-port-full-flush deflating-port
23566 @c MOD rfc.zlib
23567 @c EN
23568 Flush the data buffered in the @var{deflating-port}, and
23569 resets compression state. The decompression routine can
23570 skip the data to the full-flush point by @code{inflate-sync}.
23571 @c JP
23572 ポートのデータをフルフラッシュし、圧縮状態をリセットします。
23573 展開ルーチンは@code{inflate-sync}手続きを使って
23574 入力をこの地点までスキップすることができます。
23575 @c COMMON
23576 @end defun
23577
23578 @defun inflate-sync inflating-port
23579 @c MOD rfc.zlib
23580 @c EN
23581 Skip the (possibly corrupted) compressed data up to the
23582 next full-flush point marked by @code{deflating-port-full-flush}.
23583 You may want to use this procedure when you get
23584 @code{<zlib-data-error>}. Returns the number of bytes
23585 skipped when the next full-flush point is found, or
23586 @code{#f} when the input reaches EOF before finding the next point.
23587 @c JP
23588 圧縮データを、@code{deflating-port-full-flush}によって
23589 フルフラッシュしたポイントまで読み飛ばします。
23590 @code{<zlib-data-error>}が投げられたときに使用するとよいでしょう。
23591 フルフラッシュポイントに達したときは読み飛ばしたバイトの数を、EOFまで達
23592 したときは@code{#f}を返します。
23593 @c COMMON
23594 @end defun
23595
23596 @subheading Miscellaneous API
23597
23598 @defun zlib-version
23599 @c MOD rfc.zlib
23600 @c EN
23601 Returns Zlib's version in string.
23602 @c JP
23603 Zlibのバージョンを文字列で返します。
23604 @c COMMON
23605 @end defun
23606
23607 @defun deflate-string string options @dots{}
23608 @c MOD rfc.zlib
23609 @c EN
23610 Compresses the given string and returns zlib-compressed data
23611 in a string. All optional arguments are passed to
23612 @code{open-deflating-port} as they are.
23613 @c JP
23614 与えられた文字列を圧縮し、zlib圧縮されたデータを文字列で返します。
23615 すべてのオプション引数はそのまま@code{open-deflating-port}に渡されます。
23616 @c COMMON
23617 @end defun
23618
23619 @defun inflate-string string options @dots{}
23620 @c MOD rfc.zlib
23621 @c EN
23622 Takes zlib-compressed data in string, and returns decompressed data
23623 in a string. All optional arguments are passed to
23624 @code{open-inflating-port} as they are.
23625 @c JP
23626 Zlib圧縮されたデータを文字列で受け取り、展開されたデータを文字列で
23627 返します。
23628 すべてのオプション引数はそのまま@code{open-deflating-port}に渡されます。
23629 @c COMMON
23630 @end defun
23631
23632 @defun gzip-encode-string string options @dots{}
23633 @defunx gzip-decode-string string options @dots{}
23634 @c MOD rfc.zlib
23635 @c EN
23636 Like @code{deflate-string} and @code{inflate-string}, but
23637 uses the gzip format instead. It is same as giving
23638 more than 15 to the @var{window-bits} argument of @code{deflate-string}
23639 and @code{inflate-string}.
23640 @c JP
23641 @code{deflate-string}および@code{inflate-string}と似ていますが、
23642 GZIPフォーマットを使います。これは
23643 @code{deflate-string}および@code{inflate-string}の
23644 @var{window-bits}に15以上の値指定するのと同じです。
23645 @c COMMON
23646 @end defun
23647
23648 @defun crc32 string :optional checksum
23649 @c MOD rfc.zlib
23650 @c EN
23651 Returns CRC32 checksum of @var{string}. If optional @var{checksum}
23652 is given, the returned checksum is an update of @var{checksum} by
23653 @var{string}.
23654 @c JP
23655 文字列@var{string}のCRC32チェックサムを計算して返します。@var{checksum}
23656 引数が与えられた場合は、それを@var{string}によるチェックサムで更新した
23657 値が返されます。
23658 @c COMMON
23659 @end defun
23660
23661 @defun adler32 string :optional checksum
23662 @c MOD rfc.zlib
23663 @c EN
23664 Returns Adler32 checksum of @var{string}. If optional @var{checksum}
23665 is given, the returned checksum is an update of @var{checksum} by
23666 @var{string}.
23667
23668 Calculating Adler32 is faster than CRC32, but it is known to produce
23669 uneven distribution of hash values for small input.
23670 See RFC3309 for the detailed description. If it matters,
23671 use CRC32 instead.
23672 @c JP
23673 文字列@var{string}のAdler32チェックサムを計算して返します。@var{checksum}
23674 引数が与えられた場合は、それを@var{string}によるチェックサムで更新した
23675 値が返されます。
23676
23677 Adler32はCRC32と比較して高速に計算することが可能なアルゴリズムです
23678 が、小さなデータのチェックサムの信頼性にいくらか問題があることがわ
23679 かっています。詳しくはRFC3309を見てください。これが問題になる場合
23680 はCRC32を使用してください。
23681 @c COMMON
23682 @end defun
23683
23684
23685
23686
23687
23688
23689 @c ----------------------------------------------------------------------
23690 @node SLIB, Functional XML parser, Zlib compression library, Library modules - Utilities
23691 @section @code{slib} - SLIB interface
23692 @c NODE SLIBインタフェース, @code{slib} - SLIBインタフェース
23693
23694 @deftp {Module} slib
23695 @mdindex slib
23696 @c EN
23697 This module is the interface to the Aubrey Jaffer's SLIB.
23698 To use SLIB, say @code{(use slib)}. SLIB itself is not included
23699 in Gauche distribution. If you don't have it on your system,
23700 get it from @uref{http://www-swiss.ai.mit.edu/~jaffer/SLIB.html}.
23701 @c JP
23702 このモジュールはAubrey Jaffer氏のSLIBへのインタフェースです。
23703 SLIBがインストールされている場合、@code{(use slib)} とすれば
23704 SLIBの機能が使えるようになります。
23705 SLIBそのものはGaucheのディストリビューションには含まれていません。
23706 あなたのシステムにまだインストールされていない場合は
23707 @uref{http://www-swiss.ai.mit.edu/~jaffer/SLIB.html}から入手することができます。
23708 @c COMMON
23709
23710 @c EN
23711 By default, the SLIB installation is searched from the directory
23712 specified at the Gauche configuration. If SLIB isn't there, an error
23713 is signaled. In that case, you can set the environment
23714 variable @code{SCHEME_LIBRARY_PATH} to point to the SLIB installation path.
23715 @c JP
23716 デフォルトでは、インストールされたSLIBはGaucheのconfiguration時に指定された
23717 場所から探されます。SLIBがそこになければ、エラーが報告されます。
23718 その場合、環境変数@code{SCHEME_LIBRARY_PATH}でSLIBがインストールされた
23719 パスを指定してください。
23720 @c COMMON
23721
23722 @c EN
23723 This module redefines @code{require}, shadowing the Gauche's original
23724 @code{require}. If it gets a symbol as an argument, it works as
23725 SLIB's @code{require}, while if it gets a string, it works as
23726 Gauche's @code{require}. The same applies to @code{provide} and
23727 @code{provided?}.
23728 @c JP
23729 このモジュールは@code{require}を再定義し、Gaucheオリジナルの@code{require}を
23730 シャドウします。@code{require}にシンボルが渡された場合はSLIBの@code{require}
23731 のように動作します。@code{require}に文字列が渡された場合はGaucheの@code{require}
23732 のように動作します。@code{provide}と@code{provided?}についても同様です。
23733 @c COMMON
23734
23735 @c EN
23736 All SLIB symbol bindings, loaded by @code{require}, stay in the
23737 module @code{slib}.
23738 @c JP
23739 @code{require}でロードされる、SLIBで導入されるすべての定義は、
23740 @code{slib}モジュール内で行われます。
23741 @c COMMON
23742
23743 @c EN
23744 NB: SLIB probes available srfis during initialization, and by the way
23745 it does so, all available srfis are loaded,
23746 regardless of whether you @code{require} it or not. This may
23747 introduce unexpected side effects; for example, Gauche's built-in
23748 @code{regexp-replace} is shadowed by @code{srfi.115}'s one
23749 (@pxref{R7RS regular expressions}), which has slightly different API.
23750 @c JP
23751 註: SLIBは初期化時にサポートされているsrfiを自動的に検出しますが、
23752 その副作用として、@code{require}するか否かにかかわらず
23753 検出されたsrfiが全てロードされてしまいます。
23754 これは思いがけない作用をもたらすことがあります。例えばGaucheの組み込みの
23755 @code{regexp-replace}は、やや異なるAPIを持つ@code{srfi.115}の
23756 同名の手続きによってシャドウされてしまいます
23757 (@ref{R7RS regular expressions}参照)。
23758 @c COMMON
23759 @end deftp
23760
23761 @example
23762 (use slib) ; @r{load and set up slib}
23763 (require 'getopt) ; @r{load SLIB's getopt module}
23764 (require "foo") ; @r{load Gauche's foo module}
23765 @end example
23766
23767 @c ----------------------------------------------------------------------
23768 @node Functional XML parser, SXML query language, SLIB, Library modules - Utilities
23769 @section @code{sxml.ssax} - Functional XML parser
23770 @c NODE 関数的なXMLパーザ, @code{sxml.ssax} - 関数的なXMLパーザ
23771
23772 @deftp {Module} sxml.ssax
23773 @mdindex sxml.ssax
23774 @c EN
23775 @code{sxml.*} modules are the adaptation of
23776 Oleg Kiselyov's SXML framework (@uref{http://okmij.org/ftp/Scheme/xml.html}),
23777 which is based on S-expression representation of XML structure.
23778 @c JP
23779 @code{sxml.*}モジュールは、XML構造のS式表現に基づく
23780 Oleg KiselyovのSXMLフレームワーク(@uref{http://okmij.org/ftp/Scheme/xml.html})の適合です。
23781 @c COMMON
23782
23783 @c EN
23784 SSAX is a parser part of SXML framework.
23785 This is a quote from SSAX webpage:
23786 @c JP
23787 SSAXは、SXMLフレームワークのパーザ部分です。以下は、
23788 SSAXのウェブページからの引用です。
23789 @c COMMON
23790
23791 @quotation
23792 @c EN
23793 A SSAX functional XML parsing framework consists of a DOM/SXML parser,
23794 a SAX parser, and a supporting library of lexing and parsing procedures.
23795 The procedures in the package can be used separately to tokenize or parse
23796 various pieces of XML documents.
23797 The framework supports XML Namespaces, character, internal
23798 and external parsed entities, attribute value normalization,
23799 processing instructions and CDATA sections. The package includes
23800 a semi-validating SXML parser : a DOM-mode parser that is an
23801 instantiation of a SAX parser (called SSAX).
23802 @c JP
23803 SSAXは関数的なXMLパージングフレームワークで、DOM/SXMLパーザ、SAXパーザ、
23804 字句解析・構文解析手続きのサポートライブラリから構成されます。
23805 パッケージ内の手続きは、XML文書の様々な部分をトークナイズ、あるいは
23806 パーズするために独立して使うことができます。
23807 このフレームワークは、XML名前空間、文字、内部および外部解析済み実体、
23808 属性値の正規化、処理命令とCDATAセクションをサポートしています。
23809 パッケージは、ある程度の妥当性検査を行うSXMLパーザ: SAXパーザの
23810 インスタンスであるDOMモードのパーザ(SSAXと呼ばれます)を含んでいます。
23811 @c COMMON
23812 @end quotation
23813
23814 @c EN
23815 The current version is based on the SSAX CVS version newer than
23816 the last 'official' release of SXML toolset (4.9), and
23817 SXML-gauche-0.9 package which was based on SXML-4.9.
23818 There is an important change from that release.
23819 Now the API uses lowercase letter suffix @code{ssax:}
23820 instead of uppercase @code{SSAX:}---the difference matters since
23821 Gauche is case sensitive by default.
23822 Alias names are defined for backward compatibility,
23823 but the use of uppercase suffixed names are deprecated.
23824 @c JP
23825 現在のバージョンは、SXMLツールセットの最新の'公式な'リリース(4.9)よりも
23826 新しい、SSAXのCVSバージョンをベースにしており、パッケージSXML-gauche-0.9は、
23827 SXML-4.9をベースにしています。
23828 SXMLのリリース4.9以降では、重要な変更があります。
23829 現在のAPIでは、大文字の接頭辞@code{SSAX:}の代わりに小文字の@code{ssax:}を
23830 使います。Gaucheはデフォルトで文字の大小を区別するために、この違いは
23831 問題となります。
23832 後方互換性のためにエイリアスされた名前が定義されていますが、
23833 大文字の接頭辞付きの名前の使用は推奨されません。
23834 @c COMMON
23835 @end deftp
23836
23837 @c EN
23838 I derived the content of this part of the manual from SSAX
23839 source code, just by converting its comments into texinfo format.
23840 The original text is by Oleg Kiselyov. Shiro Kawai
23841 should be responsible for any typographical error or formatting error
23842 introduced by conversion.
23843 @c JP
23844 マニュアルのこのパートの内容はSSAXのソースコードから抽出されたもので、
23845 単にそのコメントをTexinfoのフォーマットに変換しただけです。
23846 オリジナルのテキストは、Oleg Kiselyovによるものです。
23847 変換により生じた誤字・誤植やフォーマットエラーの責任は、
23848 Shiro Kawaiにあります。
23849 @c COMMON
23850
23851 @c EN
23852 The manual entries are ordered in "bottom-up" way, beginning from
23853 the lower-level constructs towards the high-level utilities.
23854 If you just want to parse XML document and obtain SXML,
23855 check out @code{ssax:xml->sxml} in @ref{SSAX Highest-level parsers - XML to SXML}.
23856 @c JP
23857 このマニュアルのエントリは、低レベルの構造から高レベルのユーティリティへと
23858 ``ボトムアップ''の方法で並べられています。
23859 もし、あなたが単にXMLドキュメントをパーズしたりSXMLを得たいだけならば、
23860 @ref{SSAX Highest-level parsers - XML to SXML}の@code{ssax:xml->sxml}を
23861 チェックして下さい。
23862 @c COMMON
23863
23864 @c ----------------------------------------------------------------------
23865 @menu
23866 * SSAX data types::
23867 * SSAX low-level parsing code::
23868 * SSAX higher-level parsers and scanners::
23869 * SSAX Highest-level parsers - XML to SXML::
23870 @end menu
23871
23872 @node SSAX data types, SSAX low-level parsing code, Functional XML parser, Functional XML parser
23873 @subsection SSAX data types
23874 @c NODE SSAXデータタイプ
23875
23876 @table @emph
23877 @item TAG-KIND
23878 @c EN
23879 a symbol '@code{START}, '@code{END}, '@code{PI}, '@code{DECL}, '@code{COMMENT}, '@code{CDSECT}
23880 or '@code{ENTITY-REF} that identifies a markup token.
23881 @c JP
23882 シンボル'@code{START}、'@code{END}、'@code{PI}、'@code{DECL}、'@code{COMMENT}、
23883 '@code{CDSECT}は、マークアップトークンを識別するものです。
23884 @c COMMON
23885 @item UNRES-NAME
23886 @c EN
23887 a name (called @code{GI} in the XML Recommendation) as given in an xml
23888 document for a markup token: start-tag, @code{PI} target, attribute name.
23889 If a @code{GI} is an @code{NCName}, @var{UNRES-NAME} is this @code{NCName} converted into
23890 a Scheme symbol. If a @code{GI} is a @code{QName}, @var{UNRES-NAME} is a pair of
23891 symbols: (@var{PREFIX} . @var{LOCALPART})
23892 @c JP
23893 XML文書で、マークアップトークン: 開始タグ、@code{PI}ターゲット、属性名に
23894 与えられる名前(XML勧告では@code{GI}と呼ばれます)です。
23895 @code{GI}が@code{NCName}である場合、@var{UNRES-NAME}はこの@code{NCName}が
23896 Schemeのシンボルに変換されたものになります。
23897 @code{GI}が@code{QName}ならば、@var{UNRES-NAME}は、シンボルのペア、
23898 (@var{PREFIX} . @var{LOCALPART})となります。
23899 @c COMMON
23900 @item RES-NAME
23901 @c EN
23902 An expanded name, a resolved version of an @var{UNRES-NAME}.
23903 For an element or an attribute name with a non-empty namespace URI,
23904 @var{RES-NAME} is a pair of symbols, (@var{URI-SYMB} . @var{LOCALPART}).
23905 Otherwise, it's a single symbol.
23906 @c JP
23907 展開された名前、つまり@var{UNRES-NAME}の解決されたバージョンです。
23908 名前空間URIが空でない場合の要素や属性名では、@var{RES-NAME}はシンボルのペア、
23909 (@var{URI-SYMB} . @var{LOCALPART})です。そうでない場合は、1つのシンボルです。
23910 @c COMMON
23911 @item ELEM-CONTENT-MODEL
23912 @c EN
23913 A symbol:
23914 @c JP
23915 以下のシンボルのうちの1つです。
23916 @c COMMON
23917 @c EN
23918 @multitable @columnfractions .3 .7
23919 @item @code{ANY}
23920 @tab anything goes, expect an END tag.
23921 @item @code{EMPTY-TAG}
23922 @tab no content, and no END-tag is coming.
23923 @item @code{EMPTY}
23924 @tab no content, expect the END-tag as the next token.
23925 @item @code{PCDATA}
23926 @tab expect character data only, and no children elements.
23927 @item @code{MIXED}
23928 @tab
23929 @item @code{ELEM-CONTENT}
23930 @tab
23931 @end multitable
23932 @c JP
23933 @multitable @columnfractions .3 .7
23934 @item @code{ANY}
23935 @tab 何でもよく、ENDタグがあるもの。
23936 @item @code{EMPTY-TAG}
23937 @tab 内容がなく、ENDタグのないもの。
23938 @item @code{EMPTY}
23939 @tab 内容がなく、次のトークンがENDタグであるもの。
23940 @item @code{PCDATA}
23941 @tab 文字データのみで、子要素がないもの。
23942 @item @code{MIXED}
23943 @tab
23944 @item @code{ELEM-CONTENT}
23945 @tab
23946 @end multitable
23947 @c COMMON
23948 @item URI-SYMB
23949 @c EN
23950 A symbol representing a namespace URI -- or other symbol chosen
23951 by the user to represent URI. In the former case,
23952 @var{URI-SYMB} is created by @code{%}-quoting of bad URI characters and
23953 converting the resulting string into a symbol.
23954 @c JP
23955 名前空間を表すシンボル、あるいはURIを表すためにユーザが選んだ他のシンボルです。
23956 前者の場合、@var{URI-SYMB}は不正なURI文字が@code{%}でクォートされた
23957 文字列をシンボルに変換したものです。
23958 @c COMMON
23959 @item NAMESPACES
23960 @c EN
23961 A list representing namespaces in effect. An element of the list
23962 has one of the following forms:
23963 @c JP
23964 効力を持つ名前空間を表すリストです。リストの要素は、以下のフォームのうちの1つです。
23965 @c COMMON
23966
23967 @c EN
23968 @table @code
23969 @item (@var{prefix} @var{uri-symb} . @var{uri-symb})
23970 or,
23971 @item (@var{prefix} @var{user-prefix} . @var{uri-symb})
23972 @var{user-prefix} is a symbol chosen by the user
23973 to represent the URI.
23974 @item (#f @var{user-prefix} . @var{uri-symb})
23975 Specification of the user-chosen prefix and a @var{uri-symbol}.
23976 @item (*DEFAULT* @var{user-prefix} . @var{uri-symb})
23977 Declaration of the default namespace
23978 @item (*DEFAULT* #f . #f)
23979 Un-declaration of the default namespace. This notation
23980 represents overriding of the previous declaration
23981 @end table
23982 @c JP
23983 @table @code
23984 @item (@var{prefix} @var{uri-symb} . @var{uri-symb})
23985 あるいは、
23986 @item (@var{prefix} @var{user-prefix} . @var{uri-symb})
23987 @var{user-prefix}は、そのURIを表現するためにユーザにより選ばれたシンボル。
23988 @item (#f @var{user-prefix} . @var{uri-symb})
23989 ユーザが選んだプリフィックスと@var{uri-symbol}の指定。
23990 @item (*DEFAULT* @var{user-prefix} . @var{uri-symb})
23991 デフォルト名前空間の宣言。
23992 @item (*DEFAULT* #f . #f)
23993 デフォルト名前空間を宣言しない。この記法は、それ以前の宣言を上書き
23994 することを表す。
23995 @end table
23996 @c COMMON
23997
23998 @c EN
23999 A @var{NAMESPACES} list may contain several elements for the same @var{PREFIX}.
24000 The one closest to the beginning of the list takes effect.
24001 @c JP
24002 @var{NAMESPACES}のリストは、同じ@var{PREFIX}についていくつかの要素を含むかも
24003 しれません。リストの先頭に近いものが効力を持ちます。
24004 @c COMMON
24005
24006 @item ATTLIST
24007 @c EN
24008 An ordered collection of (@var{NAME} . @var{VALUE}) pairs, where @var{NAME} is
24009 a @var{RES-NAME} or an @var{UNRES-NAME}. The collection is an ADT.
24010 @c JP
24011 ペア(@var{NAME} . @var{VALUE})の順序付きのコレクションで、@var{NAME}は
24012 @var{RES-NAME}か@var{UNRES-NAME}です。このコレクションはADTです。
24013 @c COMMON
24014 @item STR-HANDLER
24015 @c EN
24016 A procedure of three arguments:
24017 @code{(@var{string1} @var{string2} @var{seed})}
24018 returning a new @var{seed}.
24019 The procedure is supposed to handle a chunk of character data
24020 @var{string1} followed by a chunk of character data @var{string2}.
24021 @var{string2} is a short string, often "\n" and even ""
24022 @c JP
24023 3引数の手続き @code{(@var{string1} @var{string2} @var{seed})}で、
24024 新しい@var{seed}を返します。
24025 この手続きは、文字データ@var{string2}が後に続く、文字データ@var{string1}を
24026 扱うものです。@var{string2}は、``\n''や``''のような短い文字列です。
24027 @c COMMON
24028 @item ENTITIES
24029 @c EN
24030 An assoc list of pairs:
24031 @example
24032 (@var{named-entity-name} . @var{named-entity-body})
24033 @end example
24034 where @var{named-entity-name} is a symbol under which the entity was
24035 declared, @var{named-entity-body} is either a string, or
24036 (for an external entity) a thunk that will return an
24037 input port (from which the entity can be read).
24038 @var{named-entity-body} may also be @code{#f}. This is an indication that a
24039 @var{named-entity-name} is currently being expanded. A reference to
24040 this @var{named-entity-name} will be an error: violation of the
24041 WFC nonrecursion.
24042 @c JP
24043 ペア (@var{named-entity-name} . @var{named-entity-body})の連想リストで、
24044 @var{named-entity-name}はその実体が宣言されたシンボル、
24045 @var{named-entity-body}は文字列か、(外部実体の場合は)
24046 (そこから実体が読み込める)入力ポートを返す手続きです。
24047 @var{named-entity-body}はまた、@code{#f}かも知れません。
24048 これは、@var{named-entity-name}がその時点で展開されていることを
24049 示します。
24050 この@var{named-entity-name}への参照は、WFC非再帰違反としてエラーに
24051 なります。
24052 @c COMMON
24053 @item XML-TOKEN
24054 @c EN
24055 A record with two slots, @var{kind} and @var{token}.
24056 This record represents a markup, which is, according to the XML
24057 Recommendation, "takes the form of start-tags, end-tags, empty-element tags,
24058 entity references, character references, comments, CDATA section delimiters,
24059 document type declarations, and processing instructions."
24060 @c JP
24061 @var{kind}と@var{token}という2つのスロットを持つレコードです。
24062 このレコードは、XML勧告によれば、「開始タグ、終了タグ、空要素タグ、
24063 実体参照、文字参照、コメント、CDATAセクションの区切り、
24064 文書型宣言、処理命令の形を取る」マークアップを表します。
24065 @c COMMON
24066 @table @var
24067 @item kind
24068 @c EN
24069 a @var{TAG-KIND}
24070 @c JP
24071 @var{TAG-KIND}。
24072 @c COMMON
24073 @item head
24074 @c EN
24075 an @var{UNRES-NAME}. For xml-tokens of kinds '@code{COMMENT} and
24076 '@code{CDSECT}, the head is @code{#f}
24077 @c JP
24078 @var{UNRES-NAME}。'@code{COMMENT}と'@code{CDSECT}というkindのXMLトークンでは、
24079 そのheadは@code{#f}になります。
24080 @c COMMON
24081 @end table
24082
24083 @c EN
24084 For example,
24085 @c JP
24086 例を示します。
24087 @c COMMON
24088 @example
24089 <P> => kind='START, head='P
24090 </P> => kind='END, head='P
24091 <BR/> => kind='EMPTY-EL, head='BR
24092 <!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
24093 <?xml version="1.0"?> => kind='PI, head='xml
24094 &my-ent; => kind = 'ENTITY-REF, head='my-ent
24095 @end example
24096 @c EN
24097 Character references are not represented by xml-tokens as these references
24098 are transparently resolved into the corresponding characters.
24099 @c JP
24100 文字参照は、対応する文字へと透過的に解決されるので、XMLトークンとしては
24101 表現されません。
24102 @c COMMON
24103 @item XML-DECL
24104 @c EN
24105 A record with three slots, @var{elems}, @var{entities}, and @var{notations}.
24106
24107 The record represents a datatype of an XML document: the list of
24108 declared elements and their attributes, declared notations, list of
24109 replacement strings or loading procedures for parsed general
24110 entities, etc. Normally an xml-decl record is created from a DTD or
24111 an XML Schema, although it can be created and filled in in many other
24112 ways (e.g., loaded from a file).
24113 @c JP
24114 @var{elems}、@var{entities}、@var{notations}という3つのスロットを持つレコードです。
24115
24116 このレコードは、XML文書のデータタイプを表現します。それは、
24117 宣言された要素とその属性のリスト、宣言された記法、
24118 解析済み一般実体の置換文字列やロードされる手続きのリストなどです。
24119 通常、xml-declレコードは、それを作るには他にたくさんの方法
24120 (例えばファイルからロードするなど)があるにも関わらず、DTDかXML Schemaから
24121 作られます。
24122 @c COMMON
24123
24124 @c EN
24125 @var{elems}: an (assoc) list of decl-elem or @code{#f}. The latter instructs
24126 the parser to do no validation of elements and attributes.
24127 @c JP
24128 @var{elems}: decl-elemか@code{#f}の(連想)リスト。後者は、パーザに、
24129 要素と属性の妥当性検査を行わないように指示します。
24130 @c COMMON
24131
24132 @c EN
24133 @var{decl-elem}: declaration of one element:
24134 @code{(@var{elem-name} @var{elem-content} @var{decl-attrs})};
24135 @var{elem-name} is an @var{UNRES-NAME} for the element.
24136 @var{elem-content} is an @var{ELEM-CONTENT-MODEL}.
24137 @var{decl-attrs} is an @var{ATTLIST},
24138 of @code{(@var{attr-name} . @var{value})} associations.
24139 This element can declare a user procedure to handle parsing of an
24140 element (e.g., to do a custom validation, or to build a hash of
24141 IDs as they're encountered).
24142 @c JP
24143 @var{decl-elem}: 1つの要素の宣言:
24144 @code{(@var{elem-name} @var{elem-content} @var{decl-attrs})};
24145 @var{elem-name}はその要素の@var{UNRES-NAME}。
24146 @var{elem-content}は@var{ELEM-CONTENT-MODEL}。
24147 @var{decl-attrs}は@var{ATTLIST}か、@code{(@var{attr-name} . @var{value})}の
24148 連想リスト。
24149 この要素は、要素のパージングを扱うユーザ手続きを宣言できます。
24150 (例えば、カスタムな妥当性検査を行ったり、タグに出会うたびに
24151 IDのハッシュを構築するなど。)
24152 @c COMMON
24153
24154 @c EN
24155 @var{decl-attr}: an element of an @var{ATTLIST}, declaration of one attribute
24156 @code{(@var{attr-name} @var{content-type} @var{use-type} @var{default-value})}:
24157 @var{attr-name} is an @var{UNRES-NAME} for the declared attribute;
24158 @var{content-type} is a symbol: @code{CDATA}, @var{NMTOKEN}, @var{NMTOKENS}, ...;
24159 or a list of strings for the enumerated type.
24160 @var{use-type} is a symbol: @code{REQUIRED}, @code{IMPLIED}, @code{FIXED}
24161 default-value is a string for the default value, or @code{#f} if not given.
24162 @c JP
24163 @var{decl-attr}: @var{ATTLIST}の要素で、1つの属性
24164 @code{(@var{attr-name} @var{content-type} @var{use-type} @var{default-value})}
24165 の宣言:
24166 @var{attr-name}はその宣言された属性の@var{UNRES-NAME}、
24167 @var{content-type}はシンボル@code{CDATA}、@var{NMTOKEN}、@var{NMTOKENS}、
24168 あるいは列挙されたタイプの文字列のリスト。
24169 @var{use-type}はシンボル@code{REQUIRED}、@code{IMPLIED}、@code{FIXED}。
24170 default-valueは、デフォルト値としての文字列か、与えられなければ@code{#f}。
24171 @c COMMON
24172 @end table
24173
24174 @defun make-empty-attlist
24175 @defunx attlist-add attlist name-value
24176 @defunx attlist-null?
24177 @defunx attlist-remove-top attlist
24178 @defunx attlist->alist attlist
24179 @defunx attlist-fold
24180 @c MOD sxml.ssax
24181 @c EN
24182 Utility procedures to deal with attribute list, which
24183 keeps name-value association.
24184 @c JP
24185 名前-値の属性リストを扱うユーティリティ手続きです。
24186 @c COMMON
24187 @end defun
24188
24189 @defun make-xml-token kind head
24190 @defunx xml-token? token
24191 @c MOD sxml.ssax
24192 @c EN
24193 A constructor and a predicate for a @var{XML-TOKEN} record.
24194 @c JP
24195 @var{XML-TOKEN}レコードのコンストラクタと述語です。
24196 @c COMMON
24197 @end defun
24198
24199 @defmac xml-token-kind token
24200 @defmacx xml-token-head token
24201 @c MOD sxml.ssax
24202 @c EN
24203 Accessor macros of a @var{XML-TOKEN} record.
24204 @c JP
24205 @var{XML-TOKEN}レコードのアクセッサマクロです。
24206 @c COMMON
24207 @end defmac
24208
24209 @c ----------------------------------------------------------------------
24210 @node SSAX low-level parsing code, SSAX higher-level parsers and scanners, SSAX data types, Functional XML parser
24211 @subsection SSAX low-level parsing code
24212 @c NODE SSAXの低レベルパージングコード
24213
24214 @c EN
24215 They deal with primitive lexical units (Names, whitespaces, tags)
24216 and with pieces of more generic productions. Most of these parsers
24217 must be called in appropriate context. For example, @code{ssax:complete-start-tag}
24218 must be called only when the start-tag has been detected and its @code{GI}
24219 has been read.
24220 @c JP
24221 これらは、プリミティブな字句解析ユニット(名前、空白、タグ)や、
24222 より一般的な断片を扱います。
24223 これらのパーザのほとんどは、適切なコンテキストで呼ばれなければなりません。
24224 例えば、@code{ssax:complete-start-tag}は、開始タグが検知されその@code{GI}が
24225 読み込まれたときにのみ呼ばれなければなりません。
24226 @c COMMON
24227
24228 @defun ssax:skip-S port
24229 @c MOD sxml.ssax
24230 @c EN
24231 Skip the S (whitespace) production as defined by
24232 @c JP
24233 次のように定義されるS(空白)をスキップします。
24234 @c COMMON
24235 @example
24236 [3] S ::= (#x20 | #x9 | #xD | #xA)
24237 @end example
24238 @c EN
24239 The procedure returns the first not-whitespace character it
24240 encounters while scanning the @var{port}. This character is left
24241 on the input stream.
24242 @c JP
24243 この手続きは、@var{port}のスキャン中に遭遇した最初の空白ではない文字を
24244 返します。この文字は、入力ストリームに残されます。
24245 @c COMMON
24246 @end defun
24247
24248 @defun ssax:ncname-starting-char? a-char
24249 @c MOD sxml.ssax
24250 @c EN
24251 Check to see if a-char may start a @code{NCName}.
24252 @c JP
24253 @code{NCName}がa-charで始まるかどうかを検査します。
24254 @c COMMON
24255 @end defun
24256
24257 @defun ssax:read-NCName port
24258 @c MOD sxml.ssax
24259 @c EN
24260 Read a @code{NCName} starting from the current position in the @var{port} and
24261 return it as a symbol.
24262 @c JP
24263 @var{port}で現在の位置から始まる@code{NCName}を読み込み、それをシンボルとして
24264 返します。
24265 @c COMMON
24266 @end defun
24267
24268 @defun ssax:read-QName port
24269 @c MOD sxml.ssax
24270 @c EN
24271 Read a (namespace-) Qualified Name, @code{QName}, from the current
24272 position in the @var{port}.
24273
24274 From REC-xml-names:
24275 @c JP
24276 (名前空間)完全修飾名、@code{QName}を@var{port}の現在の位置から読み込みます。
24277
24278 REC-xml-namesは、
24279 @c COMMON
24280 @example
24281 [6] QName ::= (Prefix ':')? LocalPart
24282 [7] Prefix ::= NCName
24283 [8] LocalPart ::= NCName
24284 @end example
24285
24286 @c EN
24287 Return: an @var{UNRES-NAME}.
24288 @c JP
24289 戻り値は、@var{UNRES-NAME}です。
24290 @c COMMON
24291 @end defun
24292
24293 @defvar ssax:Prefix-XML
24294 @c MOD sxml.ssax
24295 @c EN
24296 The prefix of the pre-defined XML namespace, i.e. '@code{xml}.
24297 @c JP
24298 定義済みのXML名前空間の接頭辞、つまり、'@code{xml}です。
24299 @c COMMON
24300 @end defvar
24301
24302 @defun ssax:read-markup-token port
24303 @c MOD sxml.ssax
24304 @c EN
24305 This procedure starts parsing of a markup token. The current position
24306 in the stream must be @code{#\<}. This procedure scans enough of the input stream
24307 to figure out what kind of a markup token it is seeing. The procedure returns
24308 an xml-token structure describing the token. Note, generally reading
24309 of the current markup is not finished! In particular, no attributes of
24310 the start-tag token are scanned.
24311
24312 Here's a detailed break out of the return values and the position in the @var{port}
24313 when that particular value is returned:
24314 @c JP
24315 この手続きは、マークアップトークンのパージングを開始します。
24316 ストリームの現在の位置は、@code{#\<}でなければなりません。
24317 この手続きは、見ているマークアップトークンがどの種類のものか見当を
24318 つけるに十分な程度、入力ストリームをスキャンします。
24319 この手続きは、そのトークンを表現するxml-token構造を返します。
24320 通常、その時点のマークアップの読み込みは完了していないことに注意して下さい。
24321 特に、開始タグトークンの属性はスキャンされていません。
24322
24323 特定の値が返されたときの戻り値と@var{port}での位置を詳細に説明します。
24324 @c COMMON
24325 @table @code
24326 @item PI-token
24327 @c EN
24328 only @code{PI}-target is read.
24329 To finish the Processing Instruction and disregard it,
24330 call @code{ssax:skip-pi}. @code{ssax:read-attributes} may be useful
24331 as well (for @code{PI}s whose content is attribute-value
24332 pairs)
24333 @c JP
24334 @code{PI}ターゲットのみが読み込まれました。
24335 処理命令の読み込みを完了してそれを無視するためには、@code{ssax:skip-pi}を呼びます。
24336 (@code{PI}の内容が、属性-値のペアの場合は、)@code{ssax:read-attributes}も
24337 便利です。
24338 @c COMMON
24339 @item END-token
24340 @c EN
24341 The end tag is read completely; the current position
24342 is right after the terminating @code{#\>} character.
24343 @c JP
24344 終了タグが完全に読み込まれました。
24345 現在の位置は、終了の@code{#\>}文字の直後です。
24346 @c COMMON
24347 @item COMMENT
24348 @c EN
24349 is read and skipped completely. The current position
24350 is right after "@code{-->}" that terminates the comment.
24351 @c JP
24352 コメントが完全に読み込まれスキップされました。
24353 現在の位置は、コメントが終了する``@code{-->}''の直後です。
24354 @c COMMON
24355 @item CDSECT
24356 @c EN
24357 The current position is right after "@code{<!CDATA[}".
24358 Use @code{ssax:read-cdata-body} to read the rest.
24359 @c JP
24360 現在の位置は、"@code{<!CDATA[}"の直後です。
24361 残りを読むためには、@code{ssax:read-cdata-body}を使います。
24362 @c COMMON
24363 @item DECL
24364 @c EN
24365 We have read the keyword (the one that follows "@code{<!}")
24366 identifying this declaration markup. The current
24367 position is after the keyword (usually a
24368 whitespace character)
24369 @c JP
24370 この宣言マークアップを識別するキーワード(``@code{<!}''に続くもの)を
24371 読み込んだところです。現在の位置は、(通常は空白文字である)
24372 そのキーワードの直後です。
24373 @c COMMON
24374 @item START-token
24375 @c EN
24376 We have read the keyword (@code{GI}) of this start tag.
24377 No attributes are scanned yet. We don't know if this
24378 tag has an empty content either.
24379 Use @code{ssax:complete-start-tag} to finish parsing of
24380 the token.
24381 @c JP
24382 この開始タグのキーワード(@code{GI})を読み込んだところです。
24383 属性はまだスキャンされていません。
24384 また、このタグが空の要素を持つかどうかも分かりません。
24385 このトークンのパージングを終了するためには、
24386 @code{ssax:complete-start-tag}を使います。
24387 @c COMMON
24388 @end table
24389 @end defun
24390
24391 @defun ssax:skip-pi port
24392 @c MOD sxml.ssax
24393 @c EN
24394 The current position is inside a @code{PI}. Skip till the rest of the @code{PI}.
24395 @c JP
24396 現在の位置は、@code{PI}の内側です。
24397 @code{PI}の残りをスキップします。
24398 @c COMMON
24399 @end defun
24400
24401 @defun ssax:read-pi-body-as-string port
24402 @c MOD sxml.ssax
24403 @c EN
24404 The current position is right after reading the @code{PITarget}. We read the
24405 body of @code{PI} and return it as a string. The port will point to the
24406 character right after '@code{?>}' combination that terminates @code{PI}.
24407 @c JP
24408 現在の位置は、@code{PITarget}を読み込んだ直後です。
24409 @code{PI}のボディを読み込んで、それを文字列として返します。
24410 ポートでは、@code{PI}を終了する'@code{?>}'の直後の文字を指します。
24411 @c COMMON
24412 @example
24413 [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
24414 @end example
24415 @end defun
24416
24417 @defun ssax:skip-internal-dtd port
24418 @c MOD sxml.ssax
24419 @c EN
24420 The current pos in the port is inside an internal DTD subset
24421 (e.g., after reading @code{#\[ }that begins an internal DTD subset)
24422 Skip until the "@code{]>}" combination that terminates this DTD
24423 @c JP
24424 ポートでの現在の位置は、内部DTDサブセットの内側です
24425 (例えば、内部DTDサブセットの始まりである@code{#\[ }を読み込んだところ)。
24426 このDTDを終了する、組み合わせとなる``@code{]>}''までをスキップします。
24427 @c COMMON
24428 @end defun
24429
24430 @defun ssax:read-cdata-body port str-handler seed
24431 @c MOD sxml.ssax
24432 @c EN
24433 This procedure must be called after we have read a string "@code{<![CDATA[}"
24434 that begins a @code{CDATA} section. The current position must be the first
24435 position of the @code{CDATA} body. This function reads @emph{lines} of the @code{CDATA}
24436 body and passes them to a @var{STR-HANDLER}, a character data consumer.
24437 @c JP
24438 この手続きは、@code{CDATA}セクションを開始する文字列、"@code{<![CDATA[}"を
24439 読み込んだ後に呼ばれなければなりません。
24440 現在の位置は、@code{CDATA}のボディの最初の位置です。
24441 この手続きは、@code{CDATA}のボディの@emph{データ}を読み込み、それらを
24442 @var{STR-HANDLER}(文字データのコンシューマ)へ渡します。
24443 @c COMMON
24444
24445 @c EN
24446 The str-handler is a @var{STR-HANDLER}, a procedure @code{string1} @var{string2} @var{seed}.
24447 The first @var{string1} argument to @var{STR-HANDLER} never contains a newline.
24448 The second @var{string2} argument often will. On the first invocation of
24449 the @var{STR-HANDLER}, the seed is the one passed to @code{ssax:read-cdata-body}
24450 as the third argument. The result of this first invocation will be
24451 passed as the seed argument to the second invocation of the line
24452 consumer, and so on. The result of the last invocation of the
24453 @var{STR-HANDLER} is returned by the @code{ssax:read-cdata-body}. Note a
24454 similarity to the fundamental '@code{fold}' iterator.
24455 @c JP
24456 str-handlerは、@code{string1} @var{string2} @var{seed}を取る手続き
24457 @var{STR-HANDLER}です。
24458 @var{STR-HANDLER}の最初の引数@var{string1}は、改行を含みません。
24459 2番目の引数@var{string2}は、改行を含むことがよくあります。
24460 @var{STR-HANDLER}の最初の呼び出しでは、seedは@code{ssax:read-cdata-body}の
24461 第3引数として渡されるものです。
24462 この最初の呼び出しの結果は、文字データのコンシューマの引数seedとして渡され、
24463 以降同じように続きます。
24464 @var{STR-HANDLER}の最後の呼び出しの結果は、@code{ssax:read-cdata-body}
24465 から返されるものです。
24466 基本的な'@code{fold}'イテレータに似ています。
24467 @c COMMON
24468
24469 @c EN
24470 Within a @code{CDATA} section all characters are taken at their face value,
24471 with only three exceptions:
24472 @c JP
24473 @code{CDATA}セクションでは、以下の3つだけの例外を除いて、全ての文字は
24474 その表面上の値を持ちます。
24475 @c COMMON
24476 @itemize @bullet
24477 @item
24478 @c EN
24479 @code{CR}, @code{LF}, and @code{CRLF} are treated as line delimiters, and passed
24480 as a single @code{#\newline} to the @var{STR-HANDLER}.
24481 @c JP
24482 @code{CR}、@code{LF}、@code{CRLF}は行区切りとして扱われ、@var{STR-HANDLER}へは
24483 1つの@code{#\newline}として渡されます。
24484 @c COMMON
24485 @item
24486 @c EN
24487 "@code{]]>}" combination is the end of the @code{CDATA} section.
24488 @c JP
24489 組み合わせとなる``@code{]]>}''は、@code{CDATA}セクションの終わりであると
24490 されます。
24491 @c COMMON
24492 @item
24493 @c EN
24494 @code{&gt;} is treated as an embedded @code{#\>} character.
24495 Note, @code{&lt;} and @code{&amp;} are not specially recognized (and are not expanded)!
24496 @c JP
24497 @code{&gt;}は、@code{#\>}文字の埋め込みとして扱われます。
24498 @code{&lt;}と@code{&amp;}は特別なものとして認識されない(よって展開されない)ことに
24499 注意が必要です!
24500 @c COMMON
24501 @end itemize
24502 @end defun
24503
24504 @defun ssax:read-char-ref port
24505 @c MOD sxml.ssax
24506 @example
24507 [66] CharRef ::= '&#' [0-9]+ ';'
24508 | '&#x' [0-9a-fA-F]+ ';'
24509 @end example
24510 @c EN
24511 This procedure must be called after we we have read "@code{&#}"
24512 that introduces a char reference.
24513 The procedure reads this reference and returns the corresponding char.
24514 The current position in @var{port} will be after "@code{;}" that terminates
24515 the char reference.
24516 Faults detected: @code{WFC: XML-Spec.html#wf-Legalchar}.
24517 @c JP
24518 この手続きは、文字参照を表す``@code{&#}''を読み込んだ後に呼ばれなければ
24519 なりません。
24520 この手続きは、この参照を読み込んで対応する文字を返します。
24521 @var{port}での現在の位置は、文字参照の終わりとなる``@code{;}''の後と
24522 なります。
24523 @code{WFC: XML-Spec.html#wf-Legalchar}も参照のこと。
24524 @c COMMON
24525
24526 @c EN
24527 According to Section "4.1 Character and Entity References"
24528 of the XML Recommendation:
24529 @c JP
24530 XML勧告のセクション``4.1 文字と実体参照''によると、
24531 @c COMMON
24532 @quotation
24533 @c EN
24534 "[Definition: A character reference refers to a specific character
24535 in the ISO/IEC 10646 character set, for example one not directly
24536 accessible from available input devices.]"
24537 @c JP
24538 ``[定義: 文字参照は、ISO/IEC 10646文字集合にある特定の文字を参照する。
24539 例えば、利用できる入力デバイスからは直接アクセスできないものなど。]''
24540 @c COMMON
24541 @end quotation
24542 @c EN
24543 Therefore, we use a @code{ucscode->char} function to convert a character
24544 code into the character -- @emph{regardless} of the current character
24545 encoding of the input stream.
24546 @c JP
24547 したがって、入力ストリームの現在の文字エンコーディングに@emph{関係なく}、
24548 文字コードを文字に変換するために関数@code{ucscode->char}を使います。
24549 @c COMMON
24550 @end defun
24551
24552 @defun ssax:handle-parsed-entity port name entities content-handler str-handler seed
24553 @c MOD sxml.ssax
24554 @c EN
24555 Expand and handle a parsed-entity reference
24556 @c JP
24557 解析済み実体参照を展開し処理します。
24558 @c COMMON
24559 @itemize @bullet
24560 @item
24561 @c EN
24562 @var{port} - a PORT
24563 @c JP
24564 @var{port} - ポート
24565 @c COMMON
24566 @item
24567 @c EN
24568 @var{name} - the name of the parsed entity to expand, a symbol.
24569 @c JP
24570 @var{name} - 展開する解析済み実体の名前。シンボル。
24571 @c COMMON
24572 @item
24573 @c EN
24574 @var{entities} - see @var{ENTITIES}
24575 @c JP
24576 @var{entities} - @var{ENTITIES}を参照。
24577 @c COMMON
24578 @item
24579 @c EN
24580 @var{content-handler} - procedure @var{port} @var{entities} @var{seed}
24581 that is supposed to return a @var{seed}.
24582 @c JP
24583 @var{content-handler} - @var{port} @var{entities} @var{seed}を取る手続きで、
24584 @var{seed}を返す。
24585 @c COMMON
24586 @item
24587 @c EN
24588 @var{str-handler} - a @var{STR-HANDLER}. It is called if the entity in question
24589 turns out to be a pre-declared entity
24590 @c JP
24591 @var{str-handler} - @var{STR-HANDLER}。対象となる実体が宣言済み実体となった
24592 場合に呼ばれる。
24593 @c COMMON
24594 @end itemize
24595 @c EN
24596 The result is the one returned by @var{content-handler} or @var{str-handler}.
24597 @c JP
24598 戻り値は、@var{content-handler}か@var{str-handler}から返された値です。
24599 @c COMMON
24600
24601 @c EN
24602 Faults detected:
24603 @c JP
24604 こちらも参照のこと。
24605 @c COMMON
24606 @example
24607 WFC: XML-Spec.html#wf-entdeclared
24608 WFC: XML-Spec.html#norecursion
24609 @end example
24610 @end defun
24611
24612 @defun ssax:read-attributes port entities
24613 @c MOD sxml.ssax
24614 @c EN
24615 This procedure reads and parses a production @code{Attribute*}
24616 @c JP
24617 この手続きは、@code{Attribute*}を読み込みパーズします。
24618 @c COMMON
24619 @example
24620 [41] Attribute ::= Name Eq AttValue
24621 [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
24622 | "'" ([^<&'] | Reference)* "'"
24623 [25] Eq ::= S? '=' S?
24624 @end example
24625 @c EN
24626 The procedure returns an @var{ATTLIST}, of @var{Name} (as @var{UNRES-NAME}),
24627 @var{Value} (as string) pairs.
24628 The current character on the @var{port} is a non-whitespace character
24629 that is not an ncname-starting character.
24630 @c JP
24631 この手続きは、@var{Name}(@var{UNRES-NAME})と@var{Value}(文字列)のペアである
24632 @var{ATTLIST}を返します。
24633 @var{port}での現在の文字は、NCNameの開始文字ではなく、空白ではない文字です。
24634 @c COMMON
24635
24636 @c EN
24637 Note the following rules to keep in mind when reading an 'AttValue'
24638 "Before the value of an attribute is passed to the application
24639 or checked for validity, the XML processor must normalize it as follows:
24640 @c JP
24641 'AttValue'を読み込むときには、以下のルールに留意して下さい。
24642 ``属性の値がアプリケーションに渡されるか妥当性が検査される前に、
24643 XMLプロセッサはそれを以下のように正規化しなければならない:
24644 @c COMMON
24645 @itemize @bullet
24646 @item
24647 @c EN
24648 a character reference is processed by appending the referenced
24649 character to the attribute value
24650 @c JP
24651 文字参照は、属性値に参照された文字を追加することで処理される。
24652 @c COMMON
24653 @item
24654 @c EN
24655 an entity reference is processed by recursively processing the
24656 replacement text of the entity [see @var{ENTITIES}]
24657 [named entities amp lt gt quot apos are assumed pre-declared]
24658 @c JP
24659 実体参照は、その実体のテキストの置換を再帰的に行うことにより
24660 処理される。[@var{ENTITIES}参照] [名前付きのエンティティ、amp lt gt
24661 quot aposは定義済みと想定される]
24662 @c COMMON
24663 @item
24664 @c EN
24665 a whitespace character (@code{#x20}, @code{#xD}, @code{#xA}, @code{#x9}) is processed by appending @code{#x20}
24666 to the normalized value, except that only a single @code{#x20} is appended for a
24667 "@code{#xD#xA}" sequence that is part of an external parsed entity or the
24668 literal entity value of an internal parsed entity
24669 @c JP
24670 空白文字(@code{#x20}、@code{#xD}、@code{#xA}、@code{#x9})は、
24671 外部解析済み実体か内部解析済み実体のリテラルの実体の値の一部である
24672 ``@code{#xD#xA}''のシーケンスにただ1つの@code{#x20}が追加されることを
24673 除いて、正規化された値に@code{#x20}を追加することで処理される。
24674 @c COMMON
24675 @item
24676 @c EN
24677 other characters are processed by appending them to the normalized value "
24678 @c JP
24679 他の文字は、正規化された値をそれらに追加することにより処理される''
24680 @c COMMON
24681 @end itemize
24682
24683 @c EN
24684 Faults detected:
24685 @c JP
24686 こちらも参照のこと。
24687 @c COMMON
24688 @example
24689 WFC: XML-Spec.html#CleanAttrVals
24690 WFC: XML-Spec.html#uniqattspec
24691 @end example
24692 @end defun
24693
24694 @defun ssax:resolve-name port unres-name namespaces apply-default-ns?
24695 @c MOD sxml.ssax
24696 @c EN
24697 Convert an @var{unres-name} to a @var{res-name} given the appropriate @var{namespaces}
24698 declarations.
24699 The last parameter @var{apply-default-ns?} determines if the default
24700 namespace applies (for instance, it does not for attribute names)
24701
24702 Per @code{REC-xml-names/#nsc-NSDeclared}, "xml" prefix is considered pre-declared
24703 and bound to the namespace name "@url{http://www.w3.org/XML/1998/namespace}".
24704
24705 This procedure tests for the namespace constraints:
24706 @url{http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared}.
24707 @c JP
24708 与えられた適切な@var{namespaces}の宣言を用いて、@var{unres-name}を
24709 @var{res-name}に変換する。
24710 最後の引数@var{apply-default-ns?}は、デフォルト名前空間の適用を行うか
24711 どうかを決めます(例えば、属性名には適用しないなど)。
24712
24713 @code{REC-xml-names/#nsc-NSDeclared}によれば、接頭辞``xml''は
24714 名前空間名``@url{http://www.w3.org/XML/1998/namespace}''に定義済みで束縛されていると
24715 されます。
24716
24717 この手続きは、名前空間の制約をテストします:
24718 @url{http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared}。
24719 @c COMMON
24720 @end defun
24721
24722 @defun ssax:uri-string->symbol uri-str
24723 @c MOD sxml.ssax
24724 @c EN
24725 Convert a @var{uri-str} to an appropriate symbol.
24726 @c JP
24727 @var{uri-str}を適切なシンボルに変換します。
24728 @c COMMON
24729 @end defun
24730
24731 @defun ssax:complete-start-tag tag port elems entities namespaces
24732 @c MOD sxml.ssax
24733 @c EN
24734 This procedure is to complete parsing of a start-tag markup. The
24735 procedure must be called after the start tag token has been
24736 read. @var{Tag} is an @var{UNRES-NAME}.
24737 @var{Elem
24738 s} is an instance of @code{xml-decl::elems};
24739 it can be @code{#f} to tell the function to do @emph{no} validation of elements
24740 and their attributes.
24741 @c JP
24742 この手続きは、開始タグのマークアップのパージングを完了するためのものです。
24743 この手続きは、開始タグトークンが読み込まれた後に呼ばれなければなりません。
24744 @var{tag}は@var{UNRES-NAME}です。
24745 @var{elems}は@code{xml-decl::elems}のインスタンスで、
24746 手続きに、要素とそれらの属性の妥当性検査を@emph{行わない}ように
24747 指示するために、@code{#f}を指定することができます。
24748 @c COMMON
24749
24750 @c EN
24751 This procedure returns several values:
24752 @c JP
24753 この手続きはいくつかの値を返します。
24754 @c COMMON
24755 @table @var
24756 @item elem-gi
24757 @c EN
24758 a @var{RES-NAME}.
24759 @c JP
24760 @var{RES-NAME}。
24761 @c COMMON
24762 @item attributes
24763 @c EN
24764 element's attributes, an @var{ATTLIST} of @code{(@var{res-name} . @var{string})}
24765 pairs. The list does @emph{not} include @code{xmlns} attributes.
24766 @c JP
24767 要素の属性。@code{(@var{res-name} . @var{string})}というペアの@var{ATTLIST}。
24768 このリストは、@code{xmlns}属性を@emph{含みません}。
24769 @c COMMON
24770 @item namespaces
24771 @c EN
24772 the input list of namespaces amended with namespace
24773 (re-)declarations contained within the start-tag under parsing
24774 @var{ELEM-CONTENT-MODEL}.
24775 @c JP
24776 パージング中の開始タグに含まれる名前空間(再)宣言により修正された後の
24777 名前空間の入力リスト。
24778 @c COMMON
24779 @end table
24780
24781 @c EN
24782 On exit, the current position in @var{port} will be the first character after
24783 @code{#\>} that terminates the start-tag markup.
24784 @c JP
24785 終了時の@var{port}での現在の位置は、開始タグのマークアップを終了する
24786 @code{#\>}の後になります。
24787 @c COMMON
24788
24789 @c EN
24790 Faults detected:
24791 @c JP
24792 こちらも参照のこと。
24793 @c COMMON
24794 @example
24795 VC: XML-Spec.html#enum
24796 VC: XML-Spec.html#RequiredAttr
24797 VC: XML-Spec.html#FixedAttr
24798 VC: XML-Spec.html#ValueType
24799 WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
24800 VC: XML-Spec.html#elementvalid
24801 WFC: REC-xml-names/#dt-NSName
24802 @end example
24803
24804 @c EN
24805 Note, although XML Recommendation does not explicitly say it,
24806 @var{xmlns} and @var{xmlns:} attributes don't have to be declared (although they
24807 can be declared, to specify their default value).
24808 @c JP
24809 XML勧告では明示されていませんが、@var{xmlns}と@var{xmlns:}属性は、
24810 (そのデフォルト値を指定するために宣言されることが出来ますが)
24811 宣言される必要がないことに注意して下さい。
24812 @c COMMON
24813 @end defun
24814
24815 @defun ssax:read-external-id port
24816 @c MOD sxml.ssax
24817 @c EN
24818 This procedure parses an @code{ExternalID} production.
24819 @c JP
24820 この手続きは、@code{ExternalID}をパーズします。
24821 @c COMMON
24822 @example
24823 [75] ExternalID ::= 'SYSTEM' S SystemLiteral
24824 | 'PUBLIC' S PubidLiteral S SystemLiteral
24825 [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
24826 [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
24827 [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]
24828 | [-'()+,./:=?;!*#@@$_%]
24829 @end example
24830 @c EN
24831 This procedure is supposed to be called when an @code{ExternalID} is expected;
24832 that is, the current character must be either @code{#\S} or @code{#\P} that start
24833 correspondingly a @code{SYSTEM} or @code{PUBLIC} token. This procedure returns the
24834 @code{SystemLiteral} as a string. A @code{PubidLiteral} is disregarded if present.
24835 @c JP
24836 この手続きは、@code{ExternalID}が期待されるところで呼ばれます。
24837 つまり、現在の文字は、それぞれ@code{SYSTEM}か@code{PUBLIC}トークンを開始する
24838 @code{#\S}か@code{#\P}でなければなりません。
24839 この手続きは、@code{SystemLiteral}を文字列として返します。
24840 @code{PubidLiteral}は、存在したとしても無視されます。
24841 @c COMMON
24842 @end defun
24843
24844 @c ----------------------------------------------------------------------
24845 @node SSAX higher-level parsers and scanners, SSAX Highest-level parsers - XML to SXML, SSAX low-level parsing code, Functional XML parser
24846 @subsection SSAX higher-level parsers and scanners
24847 @c NODE SSAXの高レベルのパーザとスキャナ
24848
24849 @c EN
24850 They parse productions corresponding to the whole (document) entity
24851 or its higher-level pieces (prolog, root element, etc).
24852 @c JP
24853 これらは、全体的な実体(ドキュメント)あるいはその高レベルな断片
24854 (プロローグ、ルート要素など)をパーズします。
24855 @c COMMON
24856
24857 @defun ssax:scan-Misc port
24858 @c MOD sxml.ssax
24859 @c EN
24860 Scan the @code{Misc} production in the context:
24861 @c JP
24862 そのコンテキストでの@code{Misc}をスキャンします。
24863 @c COMMON
24864 @example
24865 [1] document ::= prolog element Misc*
24866 [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
24867 [27] Misc ::= Comment | PI | S
24868 @end example
24869 @c EN
24870 The following function should be called in the prolog or epilog contexts.
24871 In these contexts, whitespaces are completely ignored.
24872 The return value from @code{ssax:scan-Misc} is either a @code{PI}-token,
24873 a @code{DECL}-token, a @code{START} token, or EOF.
24874 Comments are ignored and not reported.
24875 @c JP
24876 以下の関数は、プロローグかエピローグのコンテキストで呼ばれます。
24877 これらのコンテキストでは、空白文字は完全に無視されます。
24878 @code{ssax:scan-Misc}からの戻り値は、@code{PI}トークンか@code{DECL}トークン、
24879 @code{START}トークン、EOFのいずれかです。
24880 コメントは無視され報告されません。
24881 @c COMMON
24882 @end defun
24883
24884 @defun ssax:read-char-data port expect-eof? str-handler seed
24885 @c MOD sxml.ssax
24886 @c EN
24887 This procedure is to read the character content of an XML document
24888 or an XML element.
24889 @c JP
24890 この手続きは、XML文書かXML要素の文字内容を読むためのものです。
24891 @c COMMON
24892 @example
24893 [43] content ::=
24894 (element | CharData | Reference | CDSect | PI
24895 | Comment)*
24896 @end example
24897 @c EN
24898 To be more precise, the procedure reads @code{CharData}, expands @code{CDSect}
24899 and character entities, and skips comments. The procedure stops
24900 at a named reference, EOF, at the beginning of a @code{PI} or a start/end tag.
24901 @c JP
24902 具体的には、この手続きは@code{CharData}を読み込み、@code{CDSect}と
24903 文字実体を展開し、コメントをスキップします。
24904 この手続きは、名前付き参照、EOF、@code{PI}あるいは開始/終了タグの開始地点で
24905 停止します。
24906 @c COMMON
24907
24908 @table @var
24909 @item port
24910 @c EN
24911 a port to read
24912 @c JP
24913 読み込むポート。
24914 @c COMMON
24915 @item expect-eof?
24916 @c EN
24917 a boolean indicating if EOF is normal, i.e., the character
24918 data may be terminated by the EOF. EOF is normal
24919 while processing a parsed entity.
24920 @c JP
24921 EOFがノーマルかどうか、つまり、文字データがEOFで終わるかどうかを
24922 表す真偽値。解析済み実体を処理している間はEOFはノーマル。
24923 @c COMMON
24924 @item str-handler
24925 @c EN
24926 a @var{STR-HANDLER}.
24927 @c JP
24928 @var{STR-HANDLER}。
24929 @c COMMON
24930 @item seed
24931 @c EN
24932 an argument passed to the first invocation of @var{STR-HANDLER}.
24933 @c JP
24934 @var{STR-HANDLER}の最初の呼び出し時に渡される引数。
24935 @c COMMON
24936 @end table
24937
24938 @c EN
24939 The procedure returns two results: @var{seed} and @var{token}.
24940
24941 The @var{seed} is the result of the last invocation of @var{str-handler}, or the
24942 original seed if @var{str-handler} was never called.
24943 @c JP
24944 この手続きは2つの結果、@var{seed}と@var{token}を返します。
24945
24946 @var{seed}は@var{str-handler}の最後の呼び出しの結果、あるいは
24947 @var{str-handler}が一度も呼ばれなかった場合はオリジナルのseedです。
24948 @c COMMON
24949
24950 @c EN
24951 @var{Token} can be either an eof-object (this can happen only if
24952 @var{expect-eof?} was @code{#t}), or:
24953 @c JP
24954 @var{token}はEOFオブジェクト(これは@var{expect-eof?}が@code{#t}の場合のみ)か、
24955 @c COMMON
24956 @itemize @bullet
24957 @item
24958 @c EN
24959 an xml-token describing a @var{START} tag or an @var{END}-tag;
24960 For a start token, the caller has to finish reading it.
24961 @c JP
24962 @var{START}タグか@var{END}タグを表すxml-token。
24963 開始トークンの場合は、呼び出し側が読み込みを完了する必要がある。
24964 @c COMMON
24965 @item
24966 @c EN
24967 an xml-token describing the beginning of a @code{PI}. It's up to an
24968 application to read or skip through the rest of this @code{PI};
24969 @c JP
24970 @code{PI}の開始を表すxml-token。
24971 この@code{PI}の残りを読み込むかスキップするかはアプリケーションに
24972 任される。
24973 @c COMMON
24974 @item
24975 @c EN
24976 an xml-token describing a named entity reference.
24977 @c JP
24978 名前付き実体参照を表すxml-token。
24979 @c COMMON
24980 @end itemize
24981
24982 @c EN
24983 @code{CDATA} sections and character references are expanded inline and
24984 never returned. Comments are silently disregarded.
24985
24986 As the XML Recommendation requires, all whitespace in character data
24987 must be preserved. However, a @code{CR} character (@code{#xD}) must be disregarded
24988 if it appears before a @code{LF} character (@code{#xA}), or replaced by a @code{#xA} character
24989 otherwise. See Secs. 2.10 and 2.11 of the XML Recommendation. See also
24990 the canonical XML Recommendation.
24991 @c JP
24992 @code{CDATA}セクションと文字参照はインラインで展開され返されません。
24993 コメントは無視されます。
24994
24995 XML勧告が要求するように、文字データ中の全ての空白文字は保存されなければなりません。
24996 しかし、@code{CR}文字(@code{#xD})は、@code{LF}文字(@code{#A})の前に現れるか
24997 @code{#xA}文字で置き換えられた場合は、無視されなければなりません。
24998 XML勧告のセクション2.10と2.11を参照して下さい。
24999 また、正規のXML勧告も参照して下さい。
25000 @c COMMON
25001 @end defun
25002
25003 @defun ssax:assert-token token kind gi error-cont
25004 @c MOD sxml.ssax
25005 @c EN
25006 Make sure that @var{token} is of anticipated @var{kind} and has anticipated @var{gi}.
25007 Note @var{gi} argument may actually be a pair of two symbols, Namespace
25008 URI or the prefix, and of the localname.
25009 If the assertion fails, @var{error-cont} is evaluated by passing it
25010 three arguments: @var{token} @var{kind} @var{gi}.
25011 The result of @var{error-cont} is returned.
25012 @c JP
25013 @var{token}が、予想された@var{kind}のもので、予想された@var{gi}を
25014 持つことを確認します。@var{gi}引数は、実際には2つのシンボル、
25015 名前空間URIかその接頭辞と、そのローカル名のペアでしょう。
25016 アサーションが失敗したら、@var{error-cont}に3つの引数、@var{token} @var{kind} @var{gi}
25017 を渡されて評価されます。
25018 @var{error-cont}の結果が返されます。
25019 @c COMMON
25020 @end defun
25021
25022 @c ----------------------------------------------------------------------
25023 @node SSAX Highest-level parsers - XML to SXML, , SSAX higher-level parsers and scanners, Functional XML parser
25024 @subsection SSAX Highest-level parsers - XML to SXML
25025 @c NODE SSAXの高レベルのパーザ - XMLからSXMLへ
25026
25027 @c EN
25028 These parsers are a set of syntactic forms to instantiate a SSAX parser.
25029 A user can instantiate the parser to do the full validation, or
25030 no validation, or any particular validation. The user specifies
25031 which @code{PI} he wants to be notified about. The user tells what to do
25032 with the parsed character and element data. The latter handlers
25033 determine if the parsing follows a SAX or a DOM model.
25034 @c JP
25035 これらのパーザは、SSAXパーザをインスタンス化するための構文的フォームのセットです。
25036 ユーザは、完全な妥当性検査、妥当性検査なし、特定の妥当性検査を行うために
25037 このパーザをインスタンス化できます。
25038 ユーザは、どの@code{PI}について通知されたいかを指定します。
25039 ユーザは、解析済み文字と要素のデータで何をしたいかを知らせます。
25040 後者のハンドラは、パージングがSAXやDOMモデルに従うかを決定します。
25041 @c COMMON
25042
25043 @defmac ssax:make-pi-parser my-pi-handlers
25044 @c MOD sxml.ssax
25045 @c EN
25046 Create a parser to parse and process one Processing Element (@code{PI}).
25047 @c JP
25048 1つの処理命令(@code{PI})をパーズして処理するパーザを作ります。
25049 @c COMMON
25050
25051 @c EN
25052 @var{My-pi-handlers}:
25053 An assoc list of pairs (@var{PI-TAG} . @var{PI-HANDLER})
25054 where @var{PI-TAG} is an @var{NCName} symbol, the @code{PI} target, and
25055 @var{PI-HANDLER} is a procedure @var{port} @var{pi-tag} @var{seed}
25056 where @var{port} points to the first symbol after the @code{PI} target.
25057 The handler should read the rest of the @code{PI} up to and including
25058 the combination '@code{?>}' that terminates the @code{PI}. The handler should
25059 return a new seed.
25060 One of the @var{PI-TAG}s may be a symbol @code{*DEFAULT*}. The corresponding
25061 handler will handle @code{PI}s that no other handler will. If the
25062 @code{*DEFAULT*} @var{PI-TAG} is not specified,
25063 @code{ssax:make-pi-parser} will make
25064 one, which skips the body of the @code{PI}.
25065 @c JP
25066 @var{my-pi-handlers}:
25067 (@var{PI-TAG} . @var{PI-HANDLER})のペアの連想リスト。
25068 @var{PI-TAG}は@var{NCName}のシンボル、@code{PI}ターゲット。
25069 @var{PI-HANDLER}は@var{port} @var{pi-tag} @var{seed}を引数とする手続きで、
25070 @var{port}では@code{PI}ターゲットの後の最初のシンボルを指しています。
25071 ハンドラは、@code{PI}を終了する組み合わせとなる'@code{?>}'を含む、
25072 @code{PI}の残りを読み込みます。ハンドラは新しいseedを返します。
25073 @var{PI-TAG}の1つは、シンボル@code{*DEFAULT*}でしょう。
25074 これに対応するハンドラは、他のハンドラが扱わない@code{PI}を処理します。
25075 @code{*DEFAULT*} @var{PI-TAG}が指定されていない場合は、
25076 @code{ssax:make-pi-parser}は、@code{PI}のボディをスキップするパーザを
25077 作ります。
25078 @c COMMON
25079
25080 @c EN
25081 The output of the @code{ssax:make-pi-parser} is a procedure
25082 @var{port} @var{pi-tag} @var{seed},
25083 that will parse the current @code{PI} accoding to user-specified handlers.
25084 @c JP
25085 @code{ssax:make-pi-parser}が返すのは、@var{port} @var{pi-tag} @var{seed}を
25086 取る手続きで、ユーザ指定のハンドラに従い現在の@code{PI}をパーズします。
25087 @c COMMON
25088 @end defmac
25089
25090 @defmac ssax:make-elem-parser my-new-level-seed my-finish-element my-char-data-handler my-pi-handlers
25091 @c MOD sxml.ssax
25092 @c EN
25093 Create a parser to parse and process one element, including its
25094 character content or children elements. The parser is typically
25095 applied to the root element of a document.
25096 @c JP
25097 その文字内容や子要素をも含む1つの要素をパーズし処理するパーザを作ります。
25098 このパーザは通常、ドキュメントのルート要素の適用されます。
25099 @c COMMON
25100
25101 @table @var
25102 @item my-new-level-seed
25103 @c EN
25104 procedure @var{elem-gi} @var{attributes} @var{namespaces} @var{expected-content} @var{seed} @*
25105 where @var{elem-gi} is a @var{RES-NAME} of the element
25106 about to be processed.
25107 This procedure is to generate the seed to be passed
25108 to handlers that process the content of the element.
25109 @c JP
25110 @var{elem-gi} @var{attributes} @var{namespaces} @var{expected-content} @var{seed} @*
25111 を引数に取る手続きで、@var{elem-gi}は処理されようとしている要素の@var{RES-NAME}です。
25112 この手続きは、要素の内容を処理するハンドラに渡されるseedを生成します。
25113 @c COMMON
25114 @c This is the function identified as 'fdown' in the denotational
25115 @c semantics of the XML parser given in the title comments to this
25116 @c file.
25117
25118 @item my-finish-element
25119 @c EN
25120 procedure @var{elem-gi} @var{attributes} @var{namespaces} @var{parent-seed} @var{seed} @*
25121 This procedure is called when parsing of @var{elem-gi} is finished.
25122 The @var{seed} is the result from the last content parser (or
25123 from @var{my-new-level-seed} if the element has the empty content).
25124 @var{Parent-seed} is the same seed as was passed to @var{my-new-level-seed}.
25125 The procedure is to generate a seed that will be the result
25126 of the element parser.
25127 @c JP
25128 @var{elem-gi} @var{attributes} @var{namespaces} @var{parent-seed} @var{seed} @*
25129 を引数に取る手続きです。この手続きは、@var{elem-gi}のパージングが完了した時に
25130 呼ばれます。
25131 @var{seed}は、最後に呼ばれたパーザからの(あるいは、
25132 要素が空要素であった場合は、@var{my-new-level-seed}からの)結果です。
25133 @var{parent-seed}は、@var{my-new-level-seed}へ渡されたのと同じseedです。
25134 この手続きは、パーザの結果となるseedを生成するためのものです。
25135 @c COMMON
25136 @c This is the function identified as 'fup' in the denotational
25137 @c semantics of the XML parser given in the title comments to this
25138 @c file.
25139
25140 @item my-char-data-handler
25141 @c EN
25142 A @var{STR-HANDLER}.
25143 @c JP
25144 @var{STR-HANDLER}。
25145 @c COMMON
25146
25147 @item my-pi-handlers
25148 @c EN
25149 See @code{ssax:make-pi-handler} above.
25150 @c JP
25151 @code{ssax:make-pi-handler}を参照して下さい。
25152 @c COMMON
25153 @end table
25154
25155 @c EN
25156 The generated parser is a:
25157 procedure @var{start-tag-head} @var{port} @var{elems} @var{entities}
25158 @var{namespaces} @var{preserve-ws?} @var{seed}. @*
25159 The procedure must be called after the start tag token has been
25160 read. @var{Start-tag-head} is an @var{UNRES-NAME} from the start-element tag.
25161 @var{Elems} is an instance of @code{xml-decl::elems}.
25162 See @code{ssax:complete-start-tag::preserve-ws?}
25163 @c JP
25164 生成されたパーザは:
25165 @var{start-tag-head} @var{port} @var{elems} @var{entities} @var{namespaces}
25166 @var{preserve-ws?} @var{seed} @*
25167 を引数に取る手続きです。
25168 この手続きは、開始タグのトークンが読み込まれた後に呼ばれなければなりません。
25169 @var{start-tag-head}は要素の開始タグの@var{UNRES-NAME}です。
25170 @var{elems}は@code{xml-decl::elems}のインスタンスです。
25171 @code{ssax:complete-start-tag::preserve-ws?}も参照して下さい。
25172 @c COMMON
25173
25174 @c EN
25175 Faults detected:
25176 @c JP
25177 こちらも参照のこと。
25178 @c COMMON
25179 @example
25180 VC: XML-Spec.html#elementvalid
25181 WFC: XML-Spec.html#GIMatch
25182 @end example
25183 @end defmac
25184
25185 @defmac ssax:make-parser user-handler-tag user-handler-proc @dots{}
25186 @c MOD sxml.ssax
25187 @c EN
25188 Create an XML parser, an instance of the XML parsing framework.
25189 This will be a SAX, a DOM, or a specialized parser depending
25190 on the supplied user-handlers.
25191
25192 @var{user-handler-tag} is a symbol that identifies a procedural expression
25193 that follows the tag. Given below are tags and signatures of the
25194 corresponding procedures. Not all tags have to be specified. If some
25195 are omitted, reasonable defaults will apply.
25196 @c JP
25197 XMLパージングフレームワークのインスタンスである、XMLパーザを作ります。
25198 これは、提供されるユーザハンドラによって、SAX、DOM、あるいは特化された
25199 パーザになります。
25200
25201 @var{user-handler-tag}はシンボルで、タグに続く手続き的な式を識別します。
25202 以下にタグと対応する手続きのシグネチャを示します。
25203 全てのタグが指定される必要はありません。
25204 いくつかが省略されると、合理的なデフォルトのものが適用されます。
25205 @c COMMON
25206
25207 @table @code
25208 @item tag: @var{DOCTYPE}
25209 @c EN
25210 handler-procedure: @var{port} @var{docname} @var{systemid} @var{internal-subset?} @var{seed}
25211
25212 If @var{internal-subset?} is @code{#t}, the current position in the port
25213 is right after we have read @code{#\[} that begins the internal DTD subset.
25214 We must finish reading of this subset before we return
25215 (or must call skip-internal-subset if we aren't interested in reading it).
25216 The port at exit must be at the first symbol after the whole
25217 DOCTYPE declaration.
25218
25219 The handler-procedure must generate four values: @*
25220 @var{elems} @var{entities} @var{namespaces} @var{seed}@*
25221 See @code{xml-decl::elems} for @var{elems}.
25222 It may be @code{#f} to switch off the validation.
25223 @var{namespaces} will typically contain @var{USER-PREFIX}es for selected @var{URI-SYMB}s.
25224 The default handler-procedure skips the internal subset,
25225 if any, and returns @code{(values #f '() '() seed)}.
25226 @c JP
25227 ハンドラ手続きの引数: @var{port} @var{docname} @var{systemid} @var{internal-subset?} @var{seed}
25228
25229 @var{internal-subset?}が@code{#t}なら、ポートでの現在の位置は内部DTDサブセットの
25230 開始となる@code{#\[}を読んだ直後です。
25231 手続きから戻る前に、このサブセットの残りの読み込みを完了しなければなりません
25232 (あるいは、それを読むことに興味がなければ、skip-internal-subsetを呼ばなければなりません)。
25233 終了時のポートでの位置は、DOCTYPE宣言全体のあとの最初のシンボルでなければなりません。
25234
25235 ハンドラ手続きは4つの値: @*
25236 @var{elems} @var{entities} @var{namespaces} @var{seed} @*
25237 を生成しなければなりません。
25238 @var{elems}については、@code{xml-decl::elems}を参照して下さい。
25239 妥当性検査をオフにするためには、@code{#f}になるでしょう。
25240 @var{namespaces}は、通常、選択された@var{URI-SYMB}に対して@var{USER-PREFIX}を含む
25241 でしょう。
25242 デフォルトのハンドラ手続きは、内部サブセットがあってもそれをスキップし、
25243 @code{(values #f '() '() seed)}を返します。
25244 @c COMMON
25245
25246 @item tag: @var{UNDECL-ROOT}
25247 @c EN
25248 handler-procedure: @var{elem-gi} @var{seed} @*
25249 where @var{elem-gi} is an @var{UNRES-NAME} of the root element. This procedure
25250 is called when an XML document under parsing contains @emph{no} @code{DOCTYPE}
25251 declaration.
25252 The handler-procedure, as a DOCTYPE handler procedure above,
25253 must generate four values: @*
25254 @var{elems} @var{entities} @var{namespaces} @var{seed}@*
25255 The default handler-procedure returns @code{(values #f '() '() seed)}.
25256 @c JP
25257 ハンドラ手続きの引数: @var{elem-gi} @var{seed} @*
25258 @var{elem-gi}はルート要素の@var{UNRES-NAME}です。
25259 この手続きは、パージング中のXML文書が@code{DOCTYPE}宣言を@emph{含まない}時に
25260 呼ばれます。
25261 ハンドラ手続きは、上ではDOCTYPEハンドラですが、4つの値: @*
25262 @var{elems} @var{entities} @var{namespaces} @var{seed}@*
25263 を生成しなければなりません。
25264 デフォルトのハンドラ手続きは、@code{(values #f '() '() seed)}を返します。
25265 @c COMMON
25266
25267 @item tag: @var{DECL-ROOT}
25268 @c EN
25269 handler-procedure: @var{elem-gi} @var{seed} @*
25270 where @var{elem-gi} is an @var{UNRES-NAME} of the root element. This procedure
25271 is called when an XML document under parsing does contains the @code{DOCTYPE}
25272 declaration.
25273 The handler-procedure must generate a new @code{seed} (and verify
25274 that the name of the root element matches the doctype, if the handler
25275 so wishes).
25276 The default handler-procedure is the identity function.
25277 @c JP
25278 ハンドラ手続きの引数: @var{elem-gi} @var{seed} @*
25279 @var{elem-gi}は、ルート要素の@var{UNRES-NAME}です。
25280 この手続きは、パージング中のXML文書が@code{DOCTYPE}宣言を含む場合に呼ばれます。
25281 このハンドラ手続きは、新しい@code{seed}を生成しなければなりません
25282 (そして、ハンドラが望めば、ルート要素の名前がDOCTYPEにマッチするかを
25283 検証します)。
25284 デフォルトのハンドラ手続きは、それ自身を返す手続きです。
25285 @c COMMON
25286
25287 @item tag: @var{NEW-LEVEL-SEED}
25288 @c EN
25289 handler-procedure: see @code{ssax:make-elem-parser}, @var{my-new-level-seed}
25290 @c JP
25291 ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-new-level-seed}を参照して下さい。
25292 @c COMMON
25293
25294 @item tag: @var{FINISH-ELEMENT}
25295 @c EN
25296 handler-procedure: see @code{ssax:make-elem-parser}, @var{my-finish-element}
25297 @c JP
25298 ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-finish-element}を参照して下さい。
25299 @c COMMON
25300
25301 @item tag: @var{CHAR-DATA-HANDLER}
25302 @c EN
25303 handler-procedure: see @code{ssax:make-elem-parser}, @var{my-char-data-handler}
25304 @c JP
25305 ハンドラ手続きの引数: @code{ssax:make-elem-parser}と@var{my-char-data-handler}を参照して下さい。
25306 @c COMMON
25307
25308 @item tag: @var{PI}
25309 @c EN
25310 handler-procedure: see @code{ssax:make-pi-parser}. @*
25311 The default value is @code{'()}.
25312 @c JP
25313 ハンドラ手続きの引数: @code{ssax:make-pi-parser}を参照して下さい。@*
25314 デフォルトの値は、@code{'()}です。
25315 @c COMMON
25316 @end table
25317
25318 @c EN
25319 The generated parser is a @*
25320 procedure @var{PORT} @var{SEED}
25321
25322 This procedure parses the document prolog and then exits to
25323 an element parser (created by ssax:make-elem-parser) to handle
25324 the rest.
25325 @c JP
25326 生成されるパーザは、@*
25327 @var{PORT} @var{SEED}を取る手続き、@*
25328 です。
25329
25330 この手続きは、ドキュメントのプロローグをパーズして、
25331 その残りを処理するために(ssax:make-elem-parserで作られた)パーザへ
25332 引き継いで終了します。
25333 @c COMMON
25334
25335 @example
25336 [1] document ::= prolog element Misc*
25337 [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
25338 [27] Misc ::= Comment | PI | S
25339
25340 [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
25341 ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
25342 [29] markupdecl ::= elementdecl | AttlistDecl
25343 | EntityDecl
25344 | NotationDecl | PI
25345 | Comment
25346 @end example
25347 @end defmac
25348
25349 @c EN
25350 A few utility procedures that turned out useful.
25351 @c JP
25352 いくつかの便利なユーティリティ手続きがあります。
25353 @c COMMON
25354
25355 @defun ssax:reverse-collect-str fragments
25356 @c MOD sxml.ssax
25357 @c EN
25358 given the list of @var{fragments} (some of which are text strings)
25359 reverse the list and concatenate adjacent text strings.
25360 @c JP
25361 @var{fragments}(そのいくつかはテキスト文字列)のリストを渡すと、
25362 そのリストを逆順にして隣り合ったテキスト文字列を連結します。
25363 @c COMMON
25364 @end defun
25365
25366 @defun ssax:reverse-collect-str-drop-ws fragments
25367 @c MOD sxml.ssax
25368 @c EN
25369 given the list of fragments (some of which are text strings)
25370 reverse the list and concatenate adjacent text strings.
25371 We also drop "unsignificant" whitespace, that is, whitespace
25372 in front, behind and between elements. The whitespace that
25373 is included in character data is not affected.
25374 We use this procedure to "intelligently" drop "insignificant"
25375 whitespace in the parsed SXML. If the strict compliance with
25376 the XML Recommendation regarding the whitespace is desired, please
25377 use the @code{ssax:reverse-collect-str} procedure instead.
25378 @c JP
25379 fragments(そのいくつかはテキスト文字列)のリストを渡すと、
25380 そのリストを逆順にして隣り合ったテキスト文字列を連結します。
25381 ``重要でない''空白文字、つまり、最初や最後、要素の間にある空白文字を
25382 削除します。文字データに含まれる空白文字には影響を与えません。
25383 この手続きは、パーズされたSXMLにある``重要でない''空白文字を
25384 ``知的に''削除するために使います。空白文字に関して、厳密に
25385 XML勧告に準拠したい場合は、代わりに手続き
25386 @code{ssax:reverse-collect-str}を使って下さい。
25387 @c COMMON
25388 @end defun
25389
25390 @defun ssax:xml->sxml port namespace-prefix-assig
25391 @c MOD sxml.ssax
25392 @c EN
25393 This is an instance of a SSAX parser above that returns an SXML
25394 representation of the XML document to be read from @var{port}.
25395 @var{Namespace-prefix-assig} is a list of
25396 @code{(@var{USER-PREFIX} . @var{URI-STRING})}
25397 that assigns @var{USER-PREFIX}es to certain namespaces identified by
25398 particular @var{URI-STRING}s. It may be an empty list.
25399 The procedure returns an SXML tree. The port points out to the
25400 first character after the root element.
25401 @c JP
25402 これは、上のSSAXパーザのインスタンスで、@var{port}から読み込まれる
25403 XMLドキュメントのSXML表現を返します。
25404 @var{namespace-prefix-assig}は、@code{(@var{USER-PREFIX} . @var{URI-STRING})}
25405 のリストで、特定の@var{URI-STRING}で識別されるある名前空間を
25406 @var{USER-PREFIX}に割り当てます。これは空リストでも構いません。
25407 この手続きは、SXMLツリーを返します。
25408 ポートでの位置は、ルート要素の後の最初の文字を指します。
25409 @c COMMON
25410
25411 @c EN
25412 Here's a simple example:
25413 @c JP
25414 簡単な例を示します:
25415 @c COMMON
25416
25417 @example
25418 (call-with-input-string
25419 "<book>
25420 <title>Land of Lisp</title>
25421 <author>Conrad Barski</author>
25422 <publisher>No Starch Press</publisher>
25423 </book>
25424 <book>
25425 <title>Programming Gauche</title>
25426 <author>Kahua Project</author>
25427 <author>Shiro Kawai</author>
25428 <publisher>O'Reilly Japan</publisher>
25429 </book>"
25430 (^p (ssax:xml->sxml p '())))
25431 @result{}
25432 (*TOP*
25433 (book (title "Land of Lisp")
25434 (author "Conrad Barski")
25435 (publisher "No Starch Press"))
25436 (book (title "Programming Gauche")
25437 (author "Kahua Project")
25438 (author "Shiro Kawai")
25439 (publisher "O'Reilly Japan")))
25440 @end example
25441
25442 @c EN
25443 The entire document is put in a pseudo node @code{*TOP*}, since
25444 the document may contain more than one toplevel nodes.
25445 The @code{*TOP*} node can also keep the meta information.
25446 In the following example, the XML declaration is kept under
25447 a pseudo node @code{*PI*} (processing instructions).
25448 @c JP
25449 ドキュメントは複数のトップレベルノードを持っている場合があるので、
25450 ドキュメント全体は擬似ノード@code{*TOP*}の下にまとめられます。
25451 @code{*TOP*}ノードはまたメタ情報を保持するのにも使われます。
25452 次の例ではXML宣言が@code{*PI*} (processing infomation) ノードとして
25453 パーズされています。
25454 @c COMMON
25455
25456 @example
25457 (call-with-input-string
25458 "<?xml version=\"1.0\" encoding=\"utf-8\"?>
25459 <book>
25460 <title>Programming Gauche</title>
25461 <author>Kahua Project</author>
25462 <author>Shiro Kawai</author>
25463 <publisher>O'Reilly Japan</publisher>
25464 </book>"
25465 (^p (ssax:xml->sxml p '())))
25466 @result{}
25467 (*TOP*
25468 (*PI* xml "version=\"1.0\" encoding=\"utf-8\"")
25469 (book (title "Programming Gauche") (author "Kahua Project")
25470 (author "Shiro Kawai") (publisher "O'Reilly Japan")))
25471 @end example
25472
25473 @c EN
25474 Namespaces are recognized, and their aliases are
25475 fully expanded to the URI by default:
25476 @c JP
25477 名前空間も認識されます。デフォルトでは名前空間のエイリアスは全て
25478 完全なURIへと展開されます:
25479 @c COMMON
25480
25481 @example
25482 (call-with-input-string
25483 "<b:book xmlns:b=\"https://example.com/book/\">
25484 <b:title>Programming Gauche</b:title>
25485 <b:author>Kahua Project</b:author>
25486 <b:author>Shiro Kawai</b:author>
25487 <b:publisher>O'Reilly Japan</b:publisher>
25488 </b:book>"
25489 (^p (ssax:xml->sxml p '())))
25490 @result{}
25491 (*TOP*
25492 (https://example.com/book/:book
25493 (https://example.com/book/:title "Programming Gauche")
25494 (https://example.com/book/:author "Kahua Project")
25495 (https://example.com/book/:author "Shiro Kawai")
25496 (https://example.com/book/:publisher "O'Reilly Japan")))
25497 @end example
25498
25499 @c EN
25500 (This is because namespace aliases can have nested scopes,
25501 so just keeping aliases loses information)
25502 @c JP
25503 (名前空間エイリアスは入れ子になったスコープを持つため、
25504 ただエイリアスをそのまま保持するだけでは情報が失われるためです。)
25505 @c COMMON
25506
25507
25508 @c EN
25509 However, tags with fully expanded namespace prefix is cumbersome.
25510 You can provide your own namespace aliases for more compact
25511 output with @var{namespace-prefix-assig} argument.
25512 @c JP
25513 ただ、完全なURIに展開された名前空間プレフィクスは扱い辛いので、
25514 独自の名前空間エイリアスを@var{namespace-prefix-assig}引数で指定できます。
25515 @c COMMON
25516
25517 @example
25518 (call-with-input-string
25519 "<b:book xmlns:b=\"https://example.com/book/\">
25520 <b:title>Programming Gauche</b:title>
25521 <b:author>Kahua Project</b:author>
25522 <b:author>Shiro Kawai</b:author>
25523 <b:publisher>O'Reilly Japan</b:publisher>
25524 </b:book>"
25525 (^p (ssax:xml->sxml p '((Book . "https://example.com/book/")))))
25526 @result{}
25527 (*TOP*
25528 (@@ (*NAMESPACES* (Book "https://example.com/book/")))
25529 (Book:book (Book:title "Programming Gauche")
25530 (Book:author "Kahua Project")
25531 (Book:author "Shiro Kawai")
25532 (Book:publisher "O'Reilly Japan")))
25533 @end example
25534 @end defun
25535
25536 @c ----------------------------------------------------------------------
25537 @node SXML query language, Manipulating SXML structure, Functional XML parser, Library modules - Utilities
25538 @section @code{sxml.sxpath} - SXML query language
25539 @c NODE SXMLクエリ言語, @code{sxml.sxpath} - SXMLクエリ言語
25540
25541 @deftp {Module} sxml.sxpath
25542 @mdindex sxml.sxpath
25543 @c EN
25544 SXPath is a query language for SXML, an instance of XML Information
25545 set (Infoset) in the form of s-expressions.
25546
25547 It is originally written by Oleg Kiselyov, and
25548 improved by Dmitry Lizorkin and Kirill Lisovsky.
25549 This module also incorporates
25550 various procedures written for SXPath by Dmitry Lizorkin and Kirill Lisovsky.
25551
25552 Current version is based on sxpathlib.scm,v 3.915,
25553 sxpath.scm,v 1.1, and sxpath-ext.scm,v 1.911.
25554 @c JP
25555 SXPathは、XML Information set (Infoset)のインスタンスのS式フォームである
25556 SXMLのためのクエリ言語です。
25557
25558 これは最初にOleg Kiselyovによって書かれ、Dmitry LizorkinとKirill Lisovsky
25559 によって改良されました。
25560 このモジュールにはまた、Dmitry LizorkinとKirill LisovskyによりSXPathのために
25561 書かれたたくさんの手続きが盛り込まれています。
25562
25563 現在のバージョンは、sxpathlib.scm v3.915、sxpath.scm v1.1、sxpath-ext.scm v1.911を
25564 ベースにしています。
25565 @c COMMON
25566 @end deftp
25567
25568 @c EN
25569 This manual is mostly derived from the comments in the
25570 original source files.
25571
25572 The module consists of three layers.
25573 @c JP
25574 このマニュアルは、そのほとんどがオリジナルのソースファイルのコメントより
25575 導出されています。
25576
25577 このモジュールは3つのレイヤから構成されます。
25578 @c COMMON
25579 @enumerate
25580 @item
25581 @c EN
25582 Basic converters and applicators, which provides the means to
25583 access and translate SXML tree.
25584 @c JP
25585 SXMLツリーへのアクセスやその変換の手段を提供する基本的なコンバータや
25586 アプリケータ(適用子)。
25587 @c COMMON
25588 @item
25589 @c EN
25590 High-level query language compiler,
25591 which takes abbreviated SXPath and
25592 returns a Scheme function that selects a nodeset
25593 that satisfies the specified path from the given nodeset.
25594 @c JP
25595 省略形のSXPathを取り、与えられたノードセットから指定されたパスを満足する
25596 ノードセットを選択するScheme関数を返す、高レベルなクエリ言語コンパイラ。
25597 @c COMMON
25598 @item
25599 @c EN
25600 Extension libraries, which implements
25601 SXML counterparts to W3C XPath Core Functions Library.
25602 @c JP
25603 W3CのXPathコア関数ライブラリのSXML版を実装する拡張ライブラリ。
25604 @c COMMON
25605 @end enumerate
25606
25607 @c ----------------------------------------------------------------------
25608 @menu
25609 * SXPath basic converters and applicators::
25610 * SXPath query language::
25611 * SXPath extension::
25612 @end menu
25613
25614 @node SXPath basic converters and applicators, SXPath query language, SXML query language, SXML query language
25615 @subsection SXPath basic converters and applicators
25616 @c NODE SXPathの基本的なコンバータとアプリケータ
25617
25618 @c EN
25619 A converter is a function
25620 @c JP
25621 コンバータは、以下を満たす関数です。
25622 @c COMMON
25623 @example
25624 type Converter = Node|Nodeset -> Nodeset
25625 @end example
25626 @c EN
25627 A converter can also play a role of a predicate: in that case, if a
25628 converter, applied to a node or a nodeset, yields a non-empty
25629 nodeset, the converter-predicate is deemed satisfied. Throughout
25630 this file a nil nodeset is equivalent to @code{#f} in denoting a failure.
25631 @c JP
25632 コンバータは、述語としての役割を担うこともあります。
25633 その場合、コンバータが、ノードやノードセットに適用され、空ではないノードセットを
25634 返す場合、述語としてのコンバータは満足したものとみなされます。
25635 このファイルを通して、nilノードセットは失敗を表す@code{#f}と等価です。
25636 @c COMMON
25637
25638 @defun nodeset? x
25639 @c MOD sxml.sxpath
25640 @c EN
25641 Returns @code{#t} if given object is a nodeset.
25642 @c JP
25643 与えられたオブジェクトがノードセットならば、@code{#t}を返します。
25644 @c COMMON
25645 @end defun
25646
25647 @defun as-nodeset x
25648 @c MOD sxml.sxpath
25649 @c EN
25650 If @var{x} is a nodeset - returns it as is, otherwise wrap it in a list.
25651 @c JP
25652 @var{x}がノードセットならば、それをそのまま返し、そうでなければそれを
25653 リストでラップして返します。
25654 @c COMMON
25655 @end defun
25656
25657 @defun sxml:element? obj
25658 @c MOD sxml.sxpath
25659 @c EN
25660 Predicate which returns @code{#t}
25661 if @var{obj} is SXML element, otherwise returns @code{#f}.
25662 @c JP
25663 @var{obj}がSXMLの要素であれば@code{#t}を返し、そうでなければ@code{#f}を
25664 返す述語です。
25665 @c COMMON
25666 @end defun
25667
25668 @defun ntype-names?? crit
25669 @c MOD sxml.sxpath
25670 @c EN
25671 The function @code{ntype-names??} takes a list of acceptable node names as a
25672 criterion and returns a function, which, when applied to a node,
25673 will return @code{#t} if the node name is present in criterion list
25674 and @code{#f} otherwise.
25675 @c JP
25676 関数@code{ntype-names??}は、判定基準として受け付け可能なノード名のリストを取り、
25677 関数を返します。この関数は、ノードに適用された際、そのノード名が判定基準リストに
25678 含まれていれば@code{#t}を、含まれていなければ@code{#f}を返す関数です。
25679 @c COMMON
25680 @example
25681 ntype-names?? :: ListOfNames -> Node -> Boolean
25682 @end example
25683 @end defun
25684
25685 @defun ntype?? crit
25686 @c MOD sxml.sxpath
25687 @c EN
25688 The function @code{ntype??} takes a type criterion and returns
25689 a function, which, when applied to a node, will tell if the node satisfies
25690 the test.
25691 @c JP
25692 関数@code{ntype??}は、型に関する判定基準を取り、関数を返します。
25693 この関数は、ノードに適用された際、そのノードがそのテストを満足するかを
25694 返します。
25695 @c COMMON
25696 @example
25697 ntype?? :: Crit -> Node -> Boolean
25698 @end example
25699
25700 @c EN
25701 The criterion @var{crit} is
25702 one of the following symbols:
25703 @c JP
25704 判定基準@var{crit}は、以下のシンボルのうちの1つです。
25705 @c COMMON
25706 @table @code
25707 @item id
25708 @c EN
25709 tests if the Node has the right name (id)
25710 @c JP
25711 そのノードが正しい名前(id)を持っているかをテストします。
25712 @c COMMON
25713 @item @@
25714 @c EN
25715 tests if the Node is an @var{attributes-list}.
25716 @c JP
25717 そのノードが@var{attributes-list}であるかをテストします。
25718 @c COMMON
25719 @item *
25720 @c EN
25721 tests if the Node is an @var{Element}.
25722 @c JP
25723 そのノードが@var{Element}であるかをテストします。
25724 @c COMMON
25725 @item *text*
25726 @c EN
25727 tests if the Node is a text node.
25728 @c JP
25729 そのノードがテキストノードであるかをテストします。
25730 @c COMMON
25731 @item *data*
25732 @c EN
25733 tests if the Node is a data node
25734 (text, number, boolean, etc., but not pair).
25735 @c JP
25736 そのノードがデータノード(テキスト、数値、真偽値などで、ペアではない)であるか
25737 をテストします。
25738 @c COMMON
25739 @item *PI*
25740 @c EN
25741 tests if the Node is a @code{PI} node.
25742 @c JP
25743 そのノードが@code{PI}ノードであるかをテストします。
25744 @c COMMON
25745 @item *COMMENT*
25746 @c EN
25747 tests if the Node is a @code{COMMENT} node.
25748 @c JP
25749 そのノードが@code{COMMENT}ノードであるかをテストします。
25750 @c COMMON
25751 @item *ENTITY*
25752 @c EN
25753 tests if the Node is a @code{ENTITY} node.
25754 @c JP
25755 そのノードが@code{ENTITY}ノードであるかをテストします。
25756 @c COMMON
25757 @item *any*
25758 @c EN
25759 @code{#t} for any type of Node.
25760 @c JP
25761 どんなタイプのノードに対しても@code{#t}を返します。
25762 @c COMMON
25763 @end table
25764 @end defun
25765
25766 @defun ntype-namespace-id?? ns-id
25767 @c MOD sxml.sxpath
25768 @c EN
25769 This function takes a namespace-id, and returns a predicate
25770 @code{Node -> Boolean}, which is @code{#t}
25771 for nodes with this very namespace-id.
25772 @var{ns-id} is a string.
25773 @code{(ntype-namespace-id?? #f)} will be @code{#t}
25774 for nodes with non-qualified names.
25775 @c JP
25776 この関数は、名前空間IDを取り、述語@code{Node -> Boolean}を
25777 返します。この述語はまさにその名前空間IDを持つノードに対しては
25778 @code{#t}を返します。@var{ns-id}は文字列です。
25779 @code{(ntype-namespace-id?? #f)}は、完全修飾されていない名前を
25780 持つノードに対して@code{#t}を返します。
25781 @c COMMON
25782 @end defun
25783
25784 @defun sxml:invert pred
25785 @c MOD sxml.sxpath
25786 @c EN
25787 This function takes a predicate and returns it inverted .
25788 That is if the given predicate yields @code{#f} or '@code{()} the inverted one
25789 yields the given node (@code{#t}) and vice versa.
25790 @c JP
25791 この関数は、述語を取り、それを反対にして返します。
25792 与えられた述語が@code{#f}や'@code{()}を返す場合、反対にされたものは
25793 与えられたノード(@code{#t})を返します。
25794 @c COMMON
25795 @end defun
25796
25797 @defun node-eq? other
25798 @defunx node-equal? other
25799 @c MOD sxml.sxpath
25800 @c EN
25801 Curried equivalence converter-predicates, i.e.
25802 @c JP
25803 等価な述語としてのコンパータにカリー化します。すなわち、
25804 @c COMMON
25805 @example
25806 ((node-eq? a) b) @equiv{} (eq? a b)
25807 ((node-equal? a) b) @equiv{} (equal? a b)
25808 @end example
25809 @end defun
25810
25811 @defun node-pos n
25812 @c MOD sxml.sxpath
25813
25814 @example
25815 node-pos:: N -> Nodeset -> Nodeset, or
25816 node-pos:: N -> Converter
25817 @end example
25818
25819 @c EN
25820 Select the @var{N}'th element of a Nodeset and return as a singular Nodeset;
25821 Return an empty nodeset if the Nth element does not exist.
25822 @code{((node-pos 1) Nodeset)} selects the node at the head of the Nodeset,
25823 if exists;
25824 @code{((node-pos 2) Nodeset)} selects the Node after that, if
25825 exists.
25826 @var{N} can also be a negative number: in that case the node is picked from
25827 the tail of the list.
25828 @code{((node-pos -1) Nodeset)} selects the last node of a non-empty nodeset;
25829 @code{((node-pos -2) Nodeset)} selects the last but one node, if exists.
25830 @c JP
25831 ノードセットの@var{N}番目の要素を選択し、1つの要素を持つノードセットを返します。
25832 N番目の要素が存在しなければ、空のノードセットを返します。
25833 @code{((node-pos 1) Nodeset)}は、ノードセットの先頭ノードがあればそれを選択します。
25834 @code{((node-pos 2) Nodeset)}は、2番目のノードがあればそれを選択します。
25835 @var{N}は負の数でも構いません。その場合、ノードはリストの末尾から数えられます。
25836 @code{((node-pos -1) Nodeset)}は、空ではないノードセットの最後のノードを選択します。
25837 @code{((node-pos -2) Nodeset)}は、最後から2番目のノードがあればそれを選択します。
25838 @c COMMON
25839 @end defun
25840
25841 @defun sxml:filter pred?
25842 @c MOD sxml.sxpath
25843
25844 @example
25845 filter:: Converter -> Converter
25846 @end example
25847
25848 @c EN
25849 A filter applicator, which introduces a filtering context. The argument
25850 converter is considered a predicate, with either @code{#f}
25851 or nil result meaning failure.
25852 @c JP
25853 フィルタリングを行う、フィルタアプリケータです。
25854 引数のコンバータは、@code{#f}あるいはnilとなることが失敗を意味する述語と
25855 みなされます。
25856 @c COMMON
25857 @end defun
25858
25859 @defun take-until pred?
25860 @c MOD sxml.sxpath
25861
25862 @example
25863 take-until:: Converter -> Converter, or
25864 take-until:: Pred -> Node|Nodeset -> Nodeset
25865 @end example
25866
25867 @c EN
25868 Given a converter-predicate and a nodeset, apply the predicate to
25869 each element of the nodeset, until the predicate yields anything but
25870 @code{#f} or nil. Return the elements of the input nodeset that have
25871 been processed
25872 till that moment (that is, which fail the predicate).
25873 @code{take-until} is a variation of the filter above:
25874 @code{take-until} passes
25875 elements of an ordered input set till (but not including) the first
25876 element that satisfies the predicate.
25877 The nodeset returned by @code{((take-until (not pred)) nset)} is a subset --
25878 to be more precise, a prefix -- of the nodeset returned by
25879 @code{((filter pred) nset)}.
25880 @c JP
25881 述語としてのコンバータとノードセットが与えられると、
25882 ノードセットの各要素に述語を適用し、
25883 述語が@code{#f}あるいはnil以外を返すと、
25884 (その述語が失敗した)その時点までに処理された要素を返します。
25885 @code{take-until}は、上のフィルタのバリエーションの1つです。
25886 @code{take-until}は、その述語を満足する最初の要素(それ自体は含まない)まで、
25887 順序付けられた入力のセットの要素をパスします。
25888 @code{((take-until (not pred)) nset)}により返されるノードセットは、
25889 @code{((filter pred) nset)}により返されるノードセットのサブセット
25890 -- 具体的には接頭辞 --になります。
25891 @c COMMON
25892 @end defun
25893
25894 @defun take-after pred?
25895 @c MOD sxml.sxpath
25896
25897 @example
25898 take-after:: Converter -> Converter, or
25899 take-after:: Pred -> Node|Nodeset -> Nodeset
25900 @end example
25901
25902 @c EN
25903 Given a converter-predicate and a nodeset, apply the predicate to
25904 each element of the nodeset, until the predicate yields anything but
25905 @code{#f} or
25906 nil. Return the elements of the input nodeset that have not been processed:
25907 that is, return the elements of the input nodeset that follow the first
25908 element that satisfied the predicate.
25909 @code{take-after} along with @code{take-until}
25910 partition an input nodeset into three
25911 parts: the first element that satisfies a predicate, all preceding
25912 elements and all following elements.
25913 @c JP
25914 述語としてのコンバータとノードセットを与えると、
25915 述語をノードセットの各要素に適用し、
25916 述語が@code{#f}かnil以外を返すと、
25917 まだ述語が適用されていない要素を返します。
25918 つまり、述語を満足する最初の要素の後に続く要素を返します。
25919 @code{take-after}と@code{take-until}を一緒に使うと、
25920 入力のノードセットを3つのパート:
25921 述語を満足する最初の要素、その要素の前の部分、その要素の後の部分に
25922 分けます。
25923 @c COMMON
25924 @end defun
25925
25926 @defun map-union proc lst
25927 @c MOD sxml.sxpath
25928 @c EN
25929 Apply proc to each element of lst and return the list of results.
25930 If proc returns a nodeset, splice it into the result.
25931
25932 From another point of view,
25933 @code{map-union} is a function Converter->Converter,
25934 which places an argument-converter in a joining context.
25935 @c JP
25936 procをlstの各要素に適用し、結果のリストを返します。
25937 procがノードセットを返す場合、それを結果につなぎ合わせます。
25938
25939 別の観点から見ると、@code{map-union}はConverter->Converter関数で、
25940 結合を行いたいコンテキストでの引数としてのコンバータに
25941 位置します。
25942 @c COMMON
25943 @end defun
25944
25945 @defun node-reverse node-or-nodeset
25946 @c MOD sxml.sxpath
25947
25948 @example
25949 node-reverse :: Converter, or
25950 node-reverse:: Node|Nodeset -> Nodeset
25951 @end example
25952
25953 @c EN
25954 Reverses the order of nodes in the nodeset.
25955 This basic converter is needed to implement a reverse document order
25956 (see the XPath Recommendation).
25957 @c JP
25958 ノードセットでのノードの順番を逆順にします。
25959 この基本的なコンバータは、逆順のドキュメントオーダーを実装するために
25960 必要です。(XPath勧告を参照して下さい。)
25961 @c COMMON
25962 @end defun
25963
25964 @defun node-trace title
25965 @c MOD sxml.sxpath
25966
25967 @example
25968 node-trace:: String -> Converter
25969 @end example
25970
25971 @c EN
25972 @code{(node-trace title)} is an identity converter. In addition it prints out
25973 a node or nodeset it is applied to, prefixed with the 'title'.
25974 This converter is very useful for debugging.
25975 @c JP
25976 @code{(node-trace title)}は、それ自身を返すコンバータです。
25977 また、自身が適用されるノードやノードセットを、'title'という
25978 プリフィックスを付けてプリントします。
25979 このコンバータは、デバッグの際にとても便利です。
25980 @c COMMON
25981 @end defun
25982
25983 @c EN
25984 What follow are Converter combinators,
25985 higher-order functions that transmogrify a converter
25986 or glue a sequence of converters into a single, non-trivial
25987 converter. The goal is to arrive at converters that correspond to
25988 XPath location paths.
25989
25990 From a different point of view, a combinator is a fixed, named
25991 @emph{pattern} of applying converters. Given below is a complete set of
25992 such patterns that together implement XPath location path
25993 specification. As it turns out, all these combinators can be built
25994 from a small number of basic blocks: regular functional composition,
25995 map-union and filter applicators, and the nodeset union.
25996 @c JP
25997 コンバータの組み合わせに続くものは、コンバータを一変させる、
25998 あるいはコンバータのシーケンスを1つの強力なコンバータにつなぎ合わせる
25999 高階関数です。そのゴールは、XPathのロケーションパスに対応する
26000 コンバータとなることです。
26001
26002 別の観点から見ると、コンバータは、コンバータ群の適用の固定され
26003 名前の付いた@emph{パターン}とみなせます。
26004 以下に挙げるのは、XPathのロケーションパスの仕様を実装する
26005 そのようなパターンの完全なセットです。
26006 結局のところ、これら全てのコンビネータはいくつかの基本的なブロック、
26007 通常の関数的なコンポジション、map-unionとfilterアプリケータ、
26008 ノードセットユニオンなどから構築することができます
26009 @c COMMON
26010
26011 @defun select-kids test-pred?
26012 @c MOD sxml.sxpath
26013
26014 @example
26015 select-kids:: Pred -> Node -> Nodeset
26016 @end example
26017 @c EN
26018 Given a Node, return an (ordered) subset its children that satisfy
26019 the Pred (a converter, actually).
26020 @c JP
26021 ノードを与えると、述語(実際はコンバータ)を満足するその子要素の
26022 (順序付けられた)サブセットを返します。
26023 @c COMMON
26024
26025 @example
26026 select-kids:: Pred -> Nodeset -> Nodeset
26027 @end example
26028 @c EN
26029 The same as above, but select among children of all the nodes in
26030 the Nodeset.
26031 @c JP
26032 上と同じですが、ノードセットの全てのノードの子要素から選択します。
26033 @c COMMON
26034 @end defun
26035
26036 @defun node-self pred
26037 @c MOD sxml.sxpath
26038
26039 @example
26040 node-self:: Pred -> Node -> Nodeset, or
26041 node-self:: Converter -> Converter
26042 @end example
26043
26044 @c EN
26045 Similar to select-kids but apply to the Node itself rather
26046 than to its children. The resulting Nodeset will contain either one
26047 component, or will be empty (if the Node failed the Pred).
26048 @c JP
26049 select-kidsに似ていますが、自身をその子要素に適用するのでは
26050 なく、ノードそれ自身に適用します。
26051 結果のノードセットは、1つのコンポーネントを含むか、
26052 空(ノードが述語を満足しない場合)になります。
26053 @c COMMON
26054 @end defun
26055
26056 @defun node-join . selectors
26057 @c MOD sxml.sxpath
26058
26059 @example
26060 node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or
26061 node-join:: [Converter] -> Converter
26062 @end example
26063
26064 @c EN
26065 join the sequence of location steps or paths as described
26066 in the title comments above.
26067 @c JP
26068 上のタイトルコメントで説明されるようなロケーションステップ
26069 あるいはロケーションパスのシーケンスをつなぎ合わせます。
26070 @c COMMON
26071 @end defun
26072
26073 @defun node-reduce . converters
26074 @c MOD sxml.sxpath
26075
26076 @example
26077 node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or
26078 node-reduce:: [Converter] -> Converter
26079 @end example
26080
26081 @c EN
26082 A regular functional composition of converters.
26083 From a different point of view,
26084 @code{((apply node-reduce converters) nodeset)}
26085 is equivalent to
26086 @code{(foldl apply nodeset converters)}
26087 i.e., folding, or reducing, a list of converters with the nodeset
26088 as a seed.
26089 @c JP
26090 コンバータの通常の関数的なコンポジションです。
26091 見方を変えると、@code{((apply node-reduce converters) nodeset)}は
26092 @code{(foldl apply nodeset converters)}と等価です。
26093 すなわち、コンバータのリストをノードセットをseedとして畳み込みや分解
26094 を行うようなものです。
26095 @c COMMON
26096 @end defun
26097
26098 @defun node-or . converters
26099 @c MOD sxml.sxpath
26100
26101 @example
26102 node-or:: [Converter] -> Converter
26103 @end example
26104
26105 @c EN
26106 This combinator applies all converters to a given node and
26107 produces the union of their results.
26108 This combinator corresponds to a union, '@code{|}' operation for XPath
26109 location paths.
26110 @c JP
26111 このコンビネータは、全てのコンバータを与えられたノードに適用し、
26112 それらの結果のユニオンを作ります。
26113 このコンビネータは、XPathのロケーションパスでの'@code{|}'オペレーション
26114 であるユニオンに対応します。
26115 @c COMMON
26116 @end defun
26117
26118 @defun node-closure test-pred?
26119 @c MOD sxml.sxpath
26120
26121 @example
26122 node-closure:: Converter -> Converter
26123 @end example
26124
26125 @c EN
26126 Select all @emph{descendants} of a node that satisfy a converter-predicate.
26127 This combinator is similar to @code{select-kids} but applies to
26128 grand... children as well.
26129 This combinator implements the "@code{descendant::}" XPath axis.
26130 Conceptually, this combinator can be expressed as
26131 @c JP
26132 述語としてのコンバータを満足するノードの全ての@emph{子孫}を選択します。
26133 このコンビネータは@code{select-kids}に似ていますが、孫要素やその
26134 子要素達にも適用を行います。
26135 このコンビネータは、XPathの軸である``@code{descendant::}''を実装します。
26136 概念的には、このコンビネータは以下のように表現することができます。
26137 @c COMMON
26138 @example
26139 (define (node-closure f)
26140 (node-or
26141 (select-kids f)
26142 (node-reduce (select-kids (ntype?? '*)) (node-closure f))))
26143 @end example
26144
26145 @c EN
26146 This definition, as written, looks somewhat like a fixpoint, and it
26147 will run forever. It is obvious however that sooner or later
26148 @code{(select-kids (ntype?? '*))} will return an empty nodeset. At
26149 this point further iterations will no longer affect the result and
26150 can be stopped.
26151 @c JP
26152 この定義は、字面の通り、フィックスポイントのような何かで、
26153 永久に実行し続けます。しかし、いつかは@code{(select-kids (ntype?? '*))}
26154 が空のノードセットを返すことは明白です。その時点では、以降の
26155 イテレーションはその結果に影響を及ぼさず停止されることができます。
26156 @c COMMON
26157 @end defun
26158
26159 @c ----------------------------------------------------------------------
26160 @node SXPath query language, SXPath extension, SXPath basic converters and applicators, SXML query language
26161 @subsection SXPath query language
26162 @c NODE SXPathクエリ言語
26163
26164 @defun sxpath abbrpath . ns-binding
26165 @c MOD sxml.sxpath
26166 Evaluates an abbreviated SXPath. Returns a procedure that when applied
26167 on a node or nodeset will return a nodeset matching the given path.
26168
26169 @example
26170 sxpath:: AbbrPath -> Converter, or
26171 sxpath:: AbbrPath -> Node|Nodeset -> Nodeset
26172 @end example
26173
26174 @c COMMON
26175 @var{AbbrPath} is a list or a string. If it is a list, it is
26176 translated to the full SXPath according to the following rewriting
26177 rules. More informal explanation follows shortly. If it is a string,
26178 it is an XPath query.
26179
26180 Note that these are abstract rules to show how it works, and not the
26181 running code examples. The nonterminals @i{sxpath1} and @i{sxpathr}
26182 don't exist as APIs. The term @i{txpath} is an internal function that
26183 interprets XPath query given as a string.
26184
26185 @c COMMON
26186 @example
26187 (sxpath '()) -> (node-join)
26188 (sxpath '(path-component ...)) ->
26189 (node-join (@i{sxpath1} path-component) (sxpath '(...)))
26190 (@i{sxpath1} '//) -> (node-or
26191 (node-self (ntype?? '*any*))
26192 (node-closure (ntype?? '*any*)))
26193 (@i{sxpath1} '(equal? x)) -> (select-kids (node-equal? x))
26194 (@i{sxpath1} '(eq? x)) -> (select-kids (node-eq? x))
26195 (@i{sxpath1} '(or@@ ...)) -> (select-kids (ntype-names??
26196 (cdr '(or@@ ...))))
26197 (@i{sxpath1} '(not@@ ...)) -> (select-kids (sxml:invert
26198 (ntype-names??
26199 (cdr '(not@@ ...)))))
26200 (@i{sxpath1} '(ns-id:* x)) -> (select-kids
26201 (ntype-namespace-id?? x))
26202 (@i{sxpath1} ?symbol) -> (select-kids (ntype?? ?symbol))
26203 (@i{sxpath1} ?string) -> (@i{txpath} ?string)
26204 (@i{sxpath1} procedure) -> procedure
26205 (@i{sxpath1} '(?symbol ...)) -> (@i{sxpath1} '((?symbol) ...))
26206 (@i{sxpath1} '(path reducer ...)) ->
26207 (node-reduce (sxpath path) (@i{sxpathr} reducer) ...)
26208 (@i{sxpathr} number) -> (node-pos number)
26209 (@i{sxpathr} path-filter) -> (filter (sxpath path-filter))
26210 @end example
26211
26212 @c COMMON
26213
26214 SXPath in its simplest form is a list of path components. The result
26215 procedure will follow the same path and return the matching node
26216 list. For example @code{(one two three)} will find element @code{one}
26217 then @code{two} inside it and @code{three} inside element
26218 @code{two}. The equivalent XPath would be @code{one/two/three}.
26219
26220 There are a few special path components (see @code{ntype??} for the
26221 complete list):
26222
26223 @table @code
26224 @item *
26225 matches an element node.
26226 @item //
26227 matches any one or many consecutive path components.
26228 @item *text*
26229 matches a text node (@code{text()} in XPath).
26230 @item *data*
26231 matches any data node (e.g. text, number, boolean, etc.,
26232 but not pair).
26233 @item @@
26234 selects the attribute list node.
26235 @end table
26236
26237 A path component could be a list in one of these forms:
26238
26239 @table @code
26240 @item (equal? x)
26241 matches if the node under examination matches @var{x} using
26242 @code{node-equal?}
26243 @item (eq? x)
26244 matches if the node under examination matches @var{x} using
26245 @code{node-eq?}
26246 @item (or@@ ...)
26247 matches if the element name is one of the specified symbols.
26248 @item (not@@ ...)
26249 matches if the element name is not one of the specified symbols.
26250 @item (ns-id:* x)
26251 matches the node if it's with namespace @var{x}
26252 @item (<path> n)
26253 matches the @var{n}-th node matching same path component. @var{n}
26254 starts from 1. Negative numbers start from the end of the node list
26255 backward. This is @code{path[n]} syntax in XPath.
26256 @item (<path> (<predicate>...))
26257 matches a path component @var{path} and @code{(sxpath (<predicate>...))}
26258 on those nodes are not empty. This is @code{path[predicate...]} syntax
26259 in XPath.
26260 @end table
26261
26262 If the path component is a string, it is interpreted as an XPath query
26263 string.
26264
26265 If the path component is a procedure, the procedure takes three
26266 arguments: the nodeset being examined, the root node and the variable
26267 bindings.
26268
26269 The root node is usually the entire sxml being applied. However if you
26270 apply the result sxpath procedure with two arguments, root-node will
26271 be the second argument.
26272
26273 When applied with three arguments, the variable bindings are the third
26274 one. This lets you pass arguments to the procedure.
26275
26276 @c COMMON
26277
26278 @smalllisp
26279 ;; select all <book> elements whose style attribute value is equal to
26280 ;; the <bookstore> element's specialty attribute value.
26281 (sxpath "//book[/bookstore/@@specialty=@@style]")
26282 ;; a similar query but this time make sure specialty of _all_
26283 ;; bookstores is matched
26284 (let ([match-specialty
26285 (lambda (node root var-binding)
26286 (let ([style (car ((sxpath '(@@ style *text*)) node))]
26287 [all-specialty ((sxpath '(bookstore @@ specialty *text*)) node)])
26288 (fold (lambda (specialty last-result)
26289 (and last-result (string=? style specialty)))
26290 #t
26291 all-specialty)))])
26292 (sxpath `(// (book (,match-specialty)))))
26293
26294 ;; select all <bookstore> elements that are inside top-level <book>
26295 ;; element
26296 (sxpath '(book bookstore))
26297 ;; select all <bookstore> elements from anywhere
26298 (sxpath '(// bookstore))
26299 ;; select attribute "name" in the top-level <book> element
26300 (sxpath '(book @@ name))
26301 ;; select all <bookstore> and <bookshop> elements that are inside
26302 ;; top-level <book> element
26303 (sxpath '(book (or@@ bookstore bookshop)))
26304 ;; select all elements except <movie> that are inside top-level <book>
26305 ;; element
26306 (sxpath '(book (not@@ movie @@)))
26307 ;; select the attribute "name" of the second <bookstore> element
26308 (sxpath '(book (bookstore 2) @@ name))
26309 ;; select the attribute "name" of all <bookstore> elements that has
26310 ;; attribute "recommended"
26311 (sxpath '(book (bookstore (@@ recommended)) @@ name))
26312 ;; select the attribute "name" of all <bookstore> elements whose
26313 ;; "rating" attribute is 3
26314 (sxpath '(book (bookstore (@@ rating (eq? 3))) @@ name))
26315 ;; select the attribute "rating" whose value is greater than 3 from
26316 ;; all <bookstore> elements
26317 (let ([greater (lambda (nodeset root-node var-binding)
26318 (filter (lambda (node)
26319 (> (string->number (sxml:string-value node))
26320 3))
26321 nodeset))])
26322 (sxpath `(book bookstore @@ rating ,greater)))
26323 @end smalllisp
26324 @end defun
26325
26326 @c EN
26327 Some wrapper functions around @code{sxpath}:
26328 @c JP
26329 @code{sxpath}には、いくつかのラッパ関数があります。
26330 @c COMMON
26331
26332 @defun if-sxpath path
26333 @c MOD sxml.sxpath
26334 @c EN
26335 @code{sxpath} always returns a list, which is @code{#t} in Scheme.
26336 @code{if-sxpath} returns @code{#f} instead of empty list.
26337 @c JP
26338 @code{sxpath}は、常にリストを返し、それはSchemeでは@code{#t}となります。
26339 @code{if-sxpath}は、空リストの代わりに@code{#f}を返します。
26340 @c COMMON
26341 @end defun
26342
26343 @defun if-car-sxpath path
26344 @c MOD sxml.sxpath
26345 @c EN
26346 Returns first node found, if any.
26347 Otherwise returns @code{#f}.
26348 @c JP
26349 もし存在すれば、最初に見つかったノードを返します。
26350 そうでなければ、@code{#f}を返します。
26351 @c COMMON
26352 @end defun
26353
26354 @defun car-sxpath path
26355 @c MOD sxml.sxpath
26356 @c EN
26357 Returns first node found, if any.
26358 Otherwise returns empty list.
26359 @c JP
26360 もし存在すれば、最初に見つかったノードを返します。
26361 そうでなければ、空リストを返します。
26362 @c COMMON
26363 @end defun
26364
26365 @defun sxml:id-alist node . lpaths
26366 @c MOD sxml.sxpath
26367 @c EN
26368 Built an index as a list of
26369 @code{(@var{ID_value} . @var{element})} pairs for given
26370 node. @var{lpaths} are location paths for attributes of type ID.
26371 @c JP
26372 与えられたノードについて、@code{(@var{ID_value} . @var{element})}の
26373 ペアのリストをインデックスとして構築します。
26374 @var{lpaths}は、タイプIDの属性のロケーションパスです。
26375 @c COMMON
26376 @end defun
26377
26378 @c ----------------------------------------------------------------------
26379 @node SXPath extension, , SXPath query language, SXML query language
26380 @subsection SXPath extension
26381 @c NODE SXPathの拡張
26382
26383 @c EN
26384 SXML counterparts to W3C XPath Core Functions Library.
26385 @c JP
26386 W3CのXPathコア関数ライブラリのSXML版です。
26387 @c COMMON
26388
26389 @defun sxml:string object
26390 @c MOD sxml.sxpath
26391 @c EN
26392 The counterpart to XPath @code{string} function (section 4.2 XPath Rec.)
26393 Converts a given object to a string.
26394 NOTE:
26395 @c JP
26396 XPathの@code{string}関数(XPath勧告のセクション4.2)に対応するものです。
26397 与えられたオブジェクトを文字列に変換します。
26398 注意:
26399 @c COMMON
26400 @enumerate
26401 @item
26402 @c EN
26403 When converting a nodeset - a document order is not preserved
26404 @c JP
26405 ノードセットを変換する時は、ドキュメントオーダーは保持されません。
26406 @c COMMON
26407 @item
26408 @c EN
26409 @var{number->string} function returns the result in a form which is slightly
26410 different from XPath Rec. specification
26411 @c JP
26412 @var{number->string}関数は、その結果をXPath勧告の仕様とは少し違った
26413 フォームで返します。
26414 @c COMMON
26415 @end enumerate
26416 @end defun
26417
26418 @defun sxml:boolean object
26419 @c MOD sxml.sxpath
26420 @c EN
26421 The counterpart to XPath @code{boolean} function (section 4.3 XPath Rec.)
26422 Converts its argument to a boolean.
26423 @c JP
26424 XPathの@code{boolean}関数(XPath勧告のセクション4.3)に対応するものです。
26425 引数を真偽値に変換します。
26426 @c COMMON
26427 @end defun
26428
26429 @defun sxml:number obj
26430 @c MOD sxml.sxpath
26431 @c EN
26432 The counterpart to XPath @code{number} function (section 4.4 XPath Rec.)
26433 Converts its argument to a number
26434 NOTE:
26435 @c JP
26436 XPathの@code{number}関数(XPath勧告のセクション4.4)に対応するものです。
26437 引数を数値に変換します。
26438 注意:
26439 @c COMMON
26440 @enumerate
26441 @item
26442 @c EN
26443 The argument is not optional (yet?).
26444 @c JP
26445 引数は(まだ?)オプションではありません。
26446 @c COMMON
26447 @item
26448 @c EN
26449 @code{string->number} conversion is not IEEE 754 round-to-nearest.
26450 @c JP
26451 @code{string->number}の変換は、IEEE 754の四捨五入ではありません。
26452 @c COMMON
26453 @item
26454 @c EN
26455 NaN is represented as 0.
26456 @c JP
26457 NaNは、0として表現されます。
26458 @c COMMON
26459 @end enumerate
26460 @end defun
26461
26462 @defun sxml:string-value node
26463 @c MOD sxml.sxpath
26464 @c EN
26465 Returns a string value for a given node in accordance to
26466 XPath Rec. 5.1 - 5.7
26467 @c JP
26468 XPath勧告のセクション5.1 - 5.7にしたがって、与えられたノードの
26469 文字列値を返します。
26470 @c COMMON
26471 @end defun
26472
26473
26474 @defun sxml:node? node
26475 @c MOD sxml.sxpath
26476 @c EN
26477 According to XPath specification 2.3, this test is true for any
26478 XPath node.
26479 For SXML auxiliary lists and lists of attributes has to be excluded.
26480 @c JP
26481 XPathの仕様2.3にしたがい、このテストはいかなるXPathノードに
26482 対しても真を返します。
26483 SXMLの補助的なリストや属性のリストは除外されます。
26484 @c COMMON
26485 @end defun
26486
26487 @defun sxml:attr-list obj
26488 @c MOD sxml.sxpath
26489 @c EN
26490 Returns the list of attributes for a given SXML node.
26491 Empty list is returned if the given node is not an element,
26492 or if it has no list of attributes
26493 @c JP
26494 与えられたSXMLノードの属性のリストを返します。
26495 与えられたノードが要素ではないか、属性のリストを持っていない場合は、
26496 空リストが返されます。
26497 @c COMMON
26498 @end defun
26499
26500 @defun sxml:id id-index
26501 @c MOD sxml.sxpath
26502 @c EN
26503 Select SXML element by its unique IDs. (XPath Rec. 4.1)
26504 Returns a converter that takes @var{object},
26505 which is a nodeset or a datatype which can be converted to a string by means
26506 of a '@code{string}' function.
26507
26508 @var{id-index} is @code{( (id-value . element) (id-value . element) ... )}.
26509
26510 This index is used for selection of an element by its unique ID.
26511 @c JP
26512 SXML要素を、そのユニークなIDによって選択します(XPath勧告 4.1)。
26513 @var{object}を引数に取るコンバータを返します。
26514 この@var{object}は、ノードセットか、'@code{string}'関数により
26515 文字列に変換できるデータタイプです。
26516
26517 @var{id-index}は、@code{( (id-value . element) (id-value . element) ... )}です。
26518
26519 このインデックスは、要素をそのユニークなIDによって選択するために使われます。
26520 @c COMMON
26521 @end defun
26522
26523 @c EN
26524 Comparators for XPath objects:
26525 @c JP
26526 XPathオブジェクトの比較子:
26527 @c COMMON
26528
26529 @defun sxml:equality-cmp bool-op number-op string-op
26530 @c MOD sxml.sxpath
26531 @c EN
26532 A helper for XPath equality operations: @code{=} , @code{!=}
26533 @var{bool-op}, @var{number-op} and
26534 @var{'string-op} are comparison operations for
26535 a pair of booleans, numbers and strings respectively.
26536 @c JP
26537 XPathの等値比較: @code{=}、@code{!=}のためのヘルパです。
26538 @var{bool-op}、@var{number-op}、@var{'string-op}はそれぞれ、
26539 真偽値、数値、文字列のペアのための比較子です。
26540 @c COMMON
26541 @end defun
26542
26543 @defun sxml:equal? a b
26544 @defunx sxml:not-equal? a b
26545 @c MOD sxml.sxpath
26546 @c EN
26547 Counterparts of XPath equality operations: @code{=} , @code{!=},
26548 using default equality tests.
26549 @c JP
26550 XPathの等値比較: @code{=}、@code{!=}に対応するもので、
26551 デフォルトの等値テストを使います。
26552 @c COMMON
26553 @end defun
26554
26555 @defun sxml:relational-cmp op
26556 @c MOD sxml.sxpath
26557 @c EN
26558 Creates a relational operation ( @code{<} , @code{>} , @code{<=} , @code{>=} )
26559 for two XPath objects.
26560 @code{op} is comparison procedure: @code{<} , @code{>} , @code{<=} or @code{>=}.
26561 @c JP
26562 2つのXPathオブジェクトの関係比較( @code{<}、@code{>}、@code{<=}、@code{>=} )
26563 を作ります。
26564 @code{op}は、比較を行う手続き: @code{<}、@code{>}、@code{<=}、@code{>=}です。
26565 @c COMMON
26566 @end defun
26567
26568 @c EN
26569 XPath axises.
26570 An order in resulting nodeset is preserved.
26571 @c JP
26572 XPathの軸。
26573 結果のノードセットにおける順序は維持されます。
26574 @c COMMON
26575
26576 @defun sxml:attribute test-pred?
26577 @c MOD sxml.sxpath
26578 @c EN
26579 Attribute axis.
26580 @c JP
26581 属性の軸です。
26582 @c COMMON
26583 @end defun
26584
26585 @defun sxml:child test-pred?
26586 @c MOD sxml.sxpath
26587 @c EN
26588 Child axis.
26589 This function is similar to '@code{select-kids}', but it returns an empty
26590 child-list for PI, Comment and Entity nodes.
26591 @c JP
26592 子要素の軸です。
26593 この関数は、'@code{select-kids}'に似ていますが、処理命令やコメント、
26594 実体ノードについては、空の子リストを返します。
26595 @c COMMON
26596 @end defun
26597
26598 @defun sxml:parent test-pred?
26599 @c MOD sxml.sxpath
26600 @c EN
26601 Parent axis.
26602
26603 Given a predicate, it returns a function
26604 @code{RootNode -> Converter}
26605 which yields a
26606 @code{ node -> parent }
26607 converter then applied to a rootnode.
26608
26609 Thus, such a converter may be constructed using
26610 @code{ ((sxml:parent test-pred) rootnode) }
26611 and returns a parent of a node it is applied to.
26612 If applied to a nodeset, it returns the
26613 list of parents of nodes in the nodeset. The rootnode does not have
26614 to be the root node of the whole SXML tree -- it may be a root node
26615 of a branch of interest.
26616 The @code{parent::} axis can be used with any SXML node.
26617 @c JP
26618 親の軸です。
26619
26620 述語を与えると、@code{RootNode -> Converter}関数を返します。
26621 この関数は、rootnodeに適用されると、@code{node -> parent}と
26622 なります。
26623
26624 このようなコンバータは、@code{ ((sxml:parent test-pred) rootnode) }
26625 を使って構築され、それが適用されたノードの親を帰します。
26626 ノードセットに適用された場合、そのノードセットにあるノードの
26627 親のリストを返します。
26628 rootnodeはSXMLツリー全体のルートノードである必要はありません。
26629 興味の対象となるブランチ(枝)のルートノードでも構いません。
26630 @code{parent::}軸は、どんなSXMLノードにも使えます。
26631 @c COMMON
26632 @end defun
26633
26634 @defun sxml:ancestor test-pred?
26635 @c MOD sxml.sxpath
26636 @c EN
26637 Ancestor axis
26638 @c JP
26639 祖先の軸です。
26640 @c COMMON
26641 @end defun
26642
26643 @defun sxml:ancestor-or-self test-pred?
26644 @c MOD sxml.sxpath
26645 @c EN
26646 Ancestor-or-self axis
26647 @c JP
26648 祖先と自分の軸です。
26649 @c COMMON
26650 @end defun
26651
26652 @defun sxml:descendant test-pred?
26653 @c MOD sxml.sxpath
26654 @c EN
26655 Descendant axis
26656 @c JP
26657 子孫の軸です。
26658 @c COMMON
26659 @end defun
26660
26661 @defun sxml:descendant-or-self test-pred?
26662 @c MOD sxml.sxpath
26663 @c EN
26664 Descendant-or-self axis
26665 @c JP
26666 子孫と自分の軸です。
26667 @c COMMON
26668 @end defun
26669
26670 @defun sxml:following test-pred?
26671 @c MOD sxml.sxpath
26672 @c EN
26673 Following axis
26674 @c JP
26675 後続するものの軸です。
26676 @c COMMON
26677 @end defun
26678
26679 @defun sxml:following-sibling test-pred?
26680 @c MOD sxml.sxpath
26681 @c EN
26682 Following-sibling axis
26683 @c JP
26684 後続する兄弟の軸です。
26685 @c COMMON
26686 @end defun
26687
26688 @defun sxml:namespace test-pred?
26689 @c MOD sxml.sxpath
26690 @c EN
26691 Namespace axis
26692 @c JP
26693 名前空間の軸です。
26694 @c COMMON
26695 @end defun
26696
26697 @defun sxml:preceding test-pred?
26698 @c MOD sxml.sxpath
26699 @c EN
26700 Preceding axis
26701 @c JP
26702 先行するものの軸です。
26703 @c COMMON
26704 @end defun
26705
26706 @defun sxml:preceding-sibling test-pred?
26707 @c MOD sxml.sxpath
26708 @c EN
26709 Preceding-sibling axis
26710 @c JP
26711 先行する兄弟の軸です。
26712 @c COMMON
26713 @end defun
26714
26715 @c EN
26716 Popular shortcuts:
26717 @c JP
26718 ポピュラーなショートカット:
26719 @c COMMON
26720
26721 @defun sxml:child-nodes nodeset
26722 @c MOD sxml.sxpath
26723 @example
26724 ((sxml:child sxml:node?) nodeset)
26725 @end example
26726 @end defun
26727
26728 @defun sxml:child-elements nodeset
26729 @c MOD sxml.sxpath
26730 @example
26731 ((select-kids sxml:element?) nodeset)
26732 @end example
26733 @end defun
26734
26735
26736 @c ----------------------------------------------------------------------
26737 @node Manipulating SXML structure, Serializing XML and HTML from SXML, SXML query language, Library modules - Utilities
26738 @section @code{sxml.tools} - Manipulating SXML structure
26739 @c NODE SXML構造を操作する, @code{sxml.tools} - SXML構造を操作する
26740
26741 @deftp {Module} sxml.tools
26742 @mdindex sxml.tools
26743
26744 @c EN
26745 This module is a port of Kirill Lisofsky's sxml-tools,
26746 a collection of convenient procedures that work on
26747 SXML structure.
26748 The current version is derived from sxml-tools CVS revision 3.13.
26749
26750 The manual entry is mainly derived from the comments in the original
26751 source code.
26752 @c JP
26753 現在のバージョンは、sxml-toolsのCVSのリビジョン3.13から導出されています。
26754
26755 マニュアルのエントリは主に、オリジナルのソースコードから導出されています。
26756 @c COMMON
26757 @end deftp
26758
26759 @c ----------------------------------------------------------------------
26760 @menu
26761 * SXML predicates::
26762 * SXML accessors::
26763 * SXML modifiers::
26764 * SXPath auxiliary utilities::
26765 * SXML to markup conversion::
26766 @end menu
26767
26768 @c ----------------------------------------------------------------------
26769 @node SXML predicates, SXML accessors, Manipulating SXML structure, Manipulating SXML structure
26770 @subsection SXML predicates
26771 @c NODE SXMLの述語
26772
26773 @defun sxml:empty-element? obj
26774 @c MOD sxml.tools
26775 @c EN
26776 A predicate which returns @code{#t} if given element @var{obj} is empty.
26777 Empty element has no nested elements, text nodes, @code{PI}s,
26778 Comments or entities
26779 but it may contain attributes or namespace-id.
26780 It is a SXML counterpart of XML @code{empty-element}.
26781 @c JP
26782 与えられた要素@var{obj}が空なら@code{#t}を返す述語です。
26783 空要素は、ネストした要素、テキストノード、@code{PI}、コメントや実体を
26784 持ちませんが、属性や名前空間IDは持つかもしれません。
26785 それは、XMLの@code{empty-element}のSXML版です。
26786 @c COMMON
26787 @end defun
26788
26789 @defun sxml:shallow-normalized? obj
26790 @c MOD sxml.tools
26791 @c EN
26792 Returns @code{#t} if the given @var{obj} is shallow-normalized SXML element.
26793 The element itself has to be normalized but its nested elements are not tested.
26794 @c JP
26795 与えられた@var{obj}が浅く正規化されたSXML要素であれば@code{#t}を返します。
26796 要素それ自体は正規化されていなければなりませんが、ネストした要素は
26797 テストされません。
26798 @c COMMON
26799 @end defun
26800
26801 @defun sxml:normalized? obj
26802 @c MOD sxml.tools
26803 @c EN
26804 Returns @code{#t} if the given @var{obj} is normalized SXML element.
26805 The element itself and all its nested elements have to be normalised.
26806 @c JP
26807 与えられた@var{obj}が正規化されたSXML要素であれば@code{#t}を返します。
26808 要素それ自体とその全てのネストした要素が正規化されていなければなりません。
26809 @c COMMON
26810 @end defun
26811
26812 @defun sxml:shallow-minimized? obj
26813 @c MOD sxml.tools
26814 @c EN
26815 Returns @code{#t} if the given @var{obj} is shallow-minimized SXML element.
26816 The element itself has to be minimised but its nested elements are not tested.
26817 @c JP
26818 与えられた@var{obj}が浅く最小化されたSXML要素であれば@code{#t}を返します。
26819 要素それ自体は最小化されていなければなりませんが、そのネストした要素は
26820 テストされません。
26821 @c COMMON
26822 @end defun
26823
26824 @defun sxml:minimized? obj
26825 @c MOD sxml.tools
26826 @c EN
26827 Returns @code{#t} if the given @var{obj} is minimized SXML element.
26828 The element itself and all its nested elements have to be minimised.
26829 @c JP
26830 与えられた@var{obj}が最小化されたSXML要素であれば@code{#t}が返されます。
26831 要素それ自体とその全てのネストした要素が最小化されていなければなりません。
26832 @c COMMON
26833 @end defun
26834
26835 @c ----------------------------------------------------------------------
26836 @node SXML accessors, SXML modifiers, SXML predicates, Manipulating SXML structure
26837 @subsection SXML accessors
26838 @c NODE SXMLへのアクセッサ
26839
26840 @defun sxml:name obj
26841 @c MOD sxml.tools
26842 @c EN
26843 Returns a name of a given SXML node.
26844 It's just an alias of @code{car}, but introduced for the sake of encapsulation.
26845 @c JP
26846 与えられたSXMLノードの名前を返します。
26847 これは単に@code{car}のエイリアスに過ぎませんが、カプセル化のために導入されています。
26848 @c COMMON
26849 @end defun
26850
26851 @defun sxml:element-name obj
26852 @c MOD sxml.tools
26853 @c EN
26854 A version of @code{sxml:name}, which returns @code{#f}
26855 if the given @var{obj} is not a SXML element.
26856 Otherwise returns its name.
26857 @c JP
26858 @code{sxml:name}の、与えられた@var{obj}がSXML要素ではない場合は@code{#f}を返す
26859 バージョンです。@var{obj}がSXML要素であれば、その名前を返します。
26860 @c COMMON
26861 @end defun
26862
26863 @defun sxml:node-name obj
26864 @c MOD sxml.tools
26865 @c EN
26866 Safe version of @code{sxml:name}, which returns @code{#f}
26867 if the given @var{obj} is not a SXML node.
26868 Otherwise returns its name.
26869 @c JP
26870 @code{sxml:name}の、与えられた@var{obj}がSXMLノードでない場合は@code{#f}を返す、
26871 安全なバージョンです。@var{obj}がSXMLノードであれば、その名前を返します。
26872 @c COMMON
26873 @end defun
26874
26875 @defun sxml:ncname obj
26876 @c MOD sxml.tools
26877 @c EN
26878 Returns Local Part of Qualified Name (Namespaces in XML production [6])
26879 for given obj, which is "@code{:}"-separated suffix of its Qualified Name.
26880 If a name of a node given is @code{NCName} (Namespaces in XML production [4]),
26881 then it is returned as is.
26882 Please note that while SXML name is a symbol this function returns a string.
26883 @c JP
26884 与えられたobjの完全修飾名(Namespaces in XML production [6])のローカルパート、
26885 つまりその完全修飾名を``@code{:}''で分割した後ろの部分を返します。
26886 与えられたノードの名前が@code{NCName}(Namespaces in XML production [4])であれば、
26887 それをそのまま返します。
26888 SXMLの名前はシンボルですが、この関数は文字列を返すことに注意して下さい。
26889 @c COMMON
26890 @end defun
26891
26892 @defun sxml:name->ns-id sxml-name
26893 @c MOD sxml.tools
26894 @c EN
26895 Returns namespace-id part of given name, or @code{#f} if it's LocalName
26896 @c JP
26897 与えられた名前の名前空間ID部分を返します。与えられた名前がLocalNameの
26898 場合は@code{#f}を返します。
26899 @c COMMON
26900 @end defun
26901
26902 @defun sxml:content obj
26903 @c MOD sxml.tools
26904 @c EN
26905 Returns the content of given SXML element or nodeset (just text and element
26906 nodes) representing it as a list of strings and nested elements in document
26907 order. This list is empty if @var{obj} is empty element or empty list.
26908 @c JP
26909 与えられたSXML要素かノードセット(テキストノードと要素ノードのみ)の内容を、
26910 ドキュメントオーダーにしたがった文字列のリストとネストした要素として
26911 返します。このリストは、@var{obj}が空要素や空リストの場合は空です。
26912 @c COMMON
26913 @end defun
26914
26915 @defun sxml:content-raw obj
26916 @c MOD sxml.tools
26917 @c EN
26918 Returns all the content of normalized SXML element except
26919 @var{attr-list} and @var{aux-list}.
26920 Thus it includes @code{PI}, @code{COMMENT} and @code{ENTITY}
26921 nodes as well as @code{TEXT} and @code{ELEMENT} nodes
26922 returned by @code{sxml:content}.
26923 Returns a list of nodes in document order or empty list if @var{obj} is empty
26924 element or empty list.
26925 This function is faster than @code{sxml:content}.
26926 @c JP
26927 正規化されたSXML要素の全ての内容を、@var{attr-list}と@var{aux-list}を除いて
26928 返します。
26929 したがってそれは、@code{PI}、@code{COMMENT}、@code{ENTITY}
26930 ノードとともに、@code{sxml:content}によって返される@code{TEXT}や@code{ELEMENT}も含みます。
26931 戻り値は、ドキュメントオーダーにしたがったノードのリストか、
26932 @var{obj}が空要素や空リストの場合は空リストになります。
26933 この関数は、@code{sxml:content}よりも高速です。
26934 @c COMMON
26935 @end defun
26936
26937 @c EN
26938 In SXML normal form, an element is represented by a list as this:
26939 @c JP
26940 SXMLの通常のフォームでは、1つの要素は次のようなリストで表現されます。
26941 @c COMMON
26942 @example
26943 (@var{name} @var{attr-list} @var{aux-list} @var{content} @dots{})
26944 @end example
26945 @c EN
26946 where @var{attr-list} is a list beginning with @code{@@},
26947 and @var{aux-list} is a list beginning with @code{@@@@}.
26948
26949 In the minimized form,
26950 @var{Aux-list} can be omitted when it is empty.
26951 @var{Attr-list} can be omitted when it is empty @emph{and}
26952 @var{aux-list} is absent.
26953
26954 The following procedures extract @var{attr-list} and @var{aux-list}.
26955 @c JP
26956 @var{attr-list}は@code{@@}で始まるリストで、@var{aux-list}は@code{@@@@}で
26957 始まるリストです。
26958
26959 最小化されたフォームでは、@var{aux-list}は空であれば省略できます。
26960 @var{attr-list}は、それが空で@emph{かつ}@var{aux-list}がなければ省略できます。
26961
26962 以下の手続きは、@var{attr-list}と@var{aux-list}を抽出するものです。
26963 @c COMMON
26964
26965 @defun sxml:attr-list-node obj
26966 @c MOD sxml.tools
26967 @c EN
26968 Returns @var{attr-list} for a given @var{obj},
26969 or @code{#f} if it is absent
26970 @c JP
26971 与えられた@var{obj}の@var{attr-list}を返します。
26972 @var{attr-list}が存在しなければ@code{#f}を返します。
26973 @c COMMON
26974 @end defun
26975
26976 @defun sxml:attr-as-list obj
26977 @c MOD sxml.tools
26978 @c EN
26979 Returns @var{attr-list} wrapped in list,
26980 or '@code{((@@))} if it is absent and @var{aux-list} is present,
26981 or '@code{()} if both lists are absent.
26982 @c JP
26983 @var{attr-list}をリストにラップして返します。
26984 @var{attr-list}が存在せず@var{aun-list}がある場合は'@code{((@@))}を返します。
26985 両方とも存在しない場合には'@code{()}を返します。
26986 @c COMMON
26987 @end defun
26988
26989 @defun sxml:aux-list-node obj
26990 @c MOD sxml.tools
26991 @c EN
26992 Returns @var{aux-list} for a given @var{obj},
26993 or @code{#f} if it is absent.
26994 @c JP
26995 与えられた@var{obj}の@var{aux-list}を返します。
26996 @var{attr-list}が存在しなければ@code{#f}を返します。
26997 @c COMMON
26998 @end defun
26999
27000 @defun sxml:aux-as-list obj
27001 @c MOD sxml.tools
27002 @c EN
27003 Returns @var{aux-list} wrapped in list,
27004 or '@code{()} if it is absent.
27005 @c JP
27006 @var{aux-list}をリストにラップして返します。
27007 @var{aux-list}が存在しなければ'@code{()}を返します。
27008 @c COMMON
27009 @end defun
27010
27011 @defun sxml:attr-list-u obj
27012 @c MOD sxml.tools
27013 @c EN
27014 Returns the list of attributes for given element or nodeset.
27015 Analog of @code{((sxpath '(@@ *)) @var{obj})}.
27016 Empty list is returned if there is no list of attributes.
27017
27018 The @code{-u} suffix indicates it can be used for non-normalized
27019 SXML node. ('u' stands for 'universal').
27020 @c JP
27021 与えられた要素かノードセットの属性のリストを返します。
27022 @code{((sxpath '(@@ *)) @var{obj})}と類似です。
27023 属性のリストがない場合は空リストが返されます。
27024 @c COMMON
27025 @end defun
27026
27027 @defun sxml:aux-list obj
27028 @c MOD sxml.tools
27029 @c EN
27030 Returns the list of auxiliary nodes for given element or nodeset.
27031 Analog of @code{((sxpath '(@@@@ *)) @var{obj})}.
27032 Empty list is returned if a list of auxiliary nodes is absent.
27033 @c JP
27034 与えられた要素かノードセットの補助ノードのリストを返します。
27035 @code{((sxpath '(@@@@ *)) @var{obj})}と類似です。
27036 補助ノードのリストがない場合は空リストが返されます。
27037 @c COMMON
27038 @end defun
27039
27040 @defun sxml:aux-list-u obj
27041 @c MOD sxml.tools
27042 @c EN
27043 Returns the list of auxiliary nodes for given element or nodeset.
27044 Analog of @code{((sxpath '(@@@@ *)) @var{obj})}.
27045 Empty list is returned if a list of auxiliary nodes is absent.
27046
27047 The @code{-u} suffix indicates it can be used for non-normalized
27048 SXML node. ('u' stands for 'universal').
27049 @c JP
27050 与えられた要素かノードセットの補助ノードのリストを返します。
27051 @code{((sxpath '(@@@@ *)) @var{obj})}と類似です。
27052 補助ノードのリストがない場合は空リストが返されます。
27053
27054 @code{-u}が付くものは、正規化されていないSXMLノードに対しても
27055 使えるということを示しています。('u'は'universal'の意味です。)
27056 @c COMMON
27057 @end defun
27058
27059 @defun sxml:aux-node obj aux-name
27060 @c MOD sxml.tools
27061 @c EN
27062 Return the first aux-node with @var{aux-name}
27063 given in SXML element @var{obj}
27064 or @code{#f} is such a node is absent.
27065 Note: it returns just the @emph{first} node found even if multiple nodes are
27066 present, so it's mostly intended for nodes with unique names .
27067 @c JP
27068 与えられたSXML要素@var{obj}で@var{aux-name}という名前の付いている最初の
27069 補助ノードを返します。そのようなノードがない場合は@code{#f}を返します。
27070 注意: 複数のノードがあっても@emph{最初に}見つかったノードのみを
27071 返します。したがって、ユニークな名前を持っているノード群に対して
27072 使われることを意図しています。
27073 @c COMMON
27074 @end defun
27075
27076 @defun sxml:aux-nodes obj aux-name
27077 @c MOD sxml.tools
27078 @c EN
27079 Return a list of aux-node with @var{aux-name}
27080 given in SXML element @var{obj}
27081 or '@code{()} if such a node is absent.
27082 @c JP
27083 与えられたSXML要素@var{obj}で@var{aux-name}とうい名前の付いている補助ノードの
27084 リストを返します。そのようなノードがなければ'@code{()}を返します。
27085 @c COMMON
27086 @end defun
27087
27088 @defun sxml:attr obj attr-name
27089 @c MOD sxml.tools
27090 @c EN
27091 Accessor for an attribute @var{attr-name} of
27092 given SXML element @var{obj}.
27093 It returns:
27094 the value of the attribute if the attribute is present, or
27095 @code{#f} if there is no such an attribute in the given element.
27096 @c JP
27097 与えられたSXML要素@var{obj}の@var{attr-name}という属性へのアクセッサです。
27098 戻り値は、その属性が存在すればその属性の値、与えられた要素に
27099 そのような属性がなければ@code{#f}です。
27100 @c COMMON
27101 @end defun
27102
27103 @defun sxml:num-attr obj attr-name
27104 @c MOD sxml.tools
27105 @c EN
27106 Accessor for a numerical attribute @var{attr-name}
27107 of given SXML element @var{obj}.
27108 It returns:
27109 a value of the attribute as the attribute as a number if the attribute
27110 is present and its value may be converted to number using @code{string->number},
27111 or @code{#f} if there is no such an attribute in the given element or
27112 its value can't be converted to a number.
27113 @c JP
27114 与えられたSXML要素@var{obj}の@var{attr-name}という数値の属性への
27115 アクセッサです。
27116 戻り値は、その属性が存在してその値が@code{string->number}により数値へ
27117 変換できる場合はその属性を数値としてその属性の値、
27118 与えられた要素にそのような属性がないかその値が数値へ変換できない場合は
27119 @code{#f}です。
27120 @c COMMON
27121 @end defun
27122
27123 @defun sxml:attr-u obj attr-name
27124 @c MOD sxml.tools
27125 @c EN
27126 Accessor for an attribute @var{attr-name}
27127 of given SXML element @var{obj} which
27128 may also be an attributes-list or nodeset (usually content of SXML element).
27129
27130 It returns:
27131 the value of the attribute if the attribute is present,
27132 or @code{#f} if there is no such an attribute in the given element.
27133
27134 The @code{-u} suffix indicates it can be used for non-normalized
27135 SXML node. ('u' stands for 'universal').
27136 @c JP
27137 与えられたSXML要素@var{obj}の@var{attr-name}という名前の属性への
27138 アクセッサです。@var{obj}は、(通常はSXML要素の内容である)
27139 属性リストやノードセットでも構いません。
27140
27141 戻り値は、その属性が存在すればその属性の値、与えられた要素に
27142 そのような属性がない場合は@code{#f}です。
27143
27144 @code{-u}が付くものは、正規化されていないSXMLノードに対しても
27145 使えるということを示しています。('u'は'universal'の意味です。)
27146 @c COMMON
27147 @end defun
27148
27149 @defun sxml:ns-list obj
27150 @c MOD sxml.tools
27151 @c EN
27152 Returns the list of namespaces for given element.
27153 Analog of @code{((sxpath '(@@@@ *NAMESPACES* *)) @var{obj})}
27154 Empty list is returned if there is no list of namespaces.
27155 @c JP
27156 与えられた要素の名前空間のリストを返します。
27157 @code{((sxpath '(@@@@ *NAMESPACES* *)) @var{obj})}と類似です。
27158 名前空間のリストがない場合は空リストが返されます。
27159 @c COMMON
27160 @end defun
27161
27162 @defun sxml:ns-id->nodes obj namespace-id
27163 @c MOD sxml.tools
27164 @c EN
27165 Returns the list of namespace-assoc's for given @var{namespace-id} in
27166 SXML element @var{obj}.
27167 Analog of @code{((sxpath '(@@@@ *NAMESPACES* namespace-id)) @var{obj})}.
27168 Empty list is returned if there is no namespace-assoc with
27169 @var{namespace-id} given.
27170 @c JP
27171 SXML要素@var{obj}で、与えられた@var{namespace-id}に対応する名前空間の
27172 連想リストのリストを返します。
27173 @code{((sxpath '(@@@@ *NAMESPACES* namespace-id)) @var{obj})}と類似です。
27174 与えられた@var{namespace-id}に対応する名前空間の連想リストがない場合は
27175 空リストが返されます。
27176 @c COMMON
27177 @end defun
27178
27179 @defun sxml:ns-id->uri obj namespace-id
27180 @c MOD sxml.tools
27181 @c EN
27182 Returns a URI for @var{namespace-id} given, or
27183 @code{#f} if there is no namespace-assoc with @var{namespace-id} given.
27184 @c JP
27185 与えられた@var{namespace-id}に対応するURIを返します。
27186 与えられた@var{namespace-id}に対応する名前空間の連想リストがない場合は
27187 @code{#f}を返します。
27188 @c COMMON
27189 @end defun
27190
27191 @defun sxml:ns-uri->id obj uri
27192 @c MOD sxml.tools
27193 @c EN
27194 Returns a namespace-id for namespace URI given.
27195 @c JP
27196 与えられた名前空間URIに対応する名前空間IDを返します。
27197 @c COMMON
27198 @end defun
27199
27200 @defun sxml:ns-id ns-assoc
27201 @c MOD sxml.tools
27202 @c EN
27203 Returns namespace-id for given namespace-assoc list.
27204 @c JP
27205 与えられた名前空間連想リストに対応する名前空間IDを返します。
27206 @c COMMON
27207 @end defun
27208
27209 @defun sxml:ns-uri ns-assoc
27210 @c MOD sxml.tools
27211 @c EN
27212 Returns URI for given namespace-assoc list.
27213 @c JP
27214 与えられた名前空間連想リストに対応するURIを返します。
27215 @c COMMON
27216 @end defun
27217
27218 @defun sxml:ns-prefix ns-assoc
27219 @c MOD sxml.tools
27220 @c EN
27221 It returns namespace prefix for given namespace-assoc list.
27222 Original (as in XML document) prefix for namespace-id given
27223 has to be strored as the third element in namespace-assoc list
27224 if it is different from namespace-id.
27225 If original prefix is omitted in namespace-assoc then
27226 namespace-id is used instead.
27227 @c JP
27228 与えられた名前空間連想リストに対応する名前空間接頭辞を返します。
27229 与えられた名前空間IDの(XML文書における)オリジナルの接頭辞は、
27230 それが名前空間IDと異なる場合は、名前空間連想リストの3番目の要素として
27231 格納されなければなりません。
27232 名前空間連想リストでオリジナルの接頭辞が省略されている場合は、
27233 代わりに名前空間IDが使われます。
27234 @c COMMON
27235 @end defun
27236
27237 @c ----------------------------------------------------------------------
27238 @node SXML modifiers, SXPath auxiliary utilities, SXML accessors, Manipulating SXML structure
27239 @subsection SXML modifiers
27240 @c NODE SXMLのモディファイヤ
27241
27242 @c EN
27243 Constructors and mutators for normalized SXML data.
27244 These functions are optimized for normalized SXML data.
27245 They are not applicable to arbitrary non-normalized SXML data.
27246
27247 Most of the functions are provided in two variants:
27248 @c JP
27249 正規化されたSXMLデータのコンストラクタやミューテータです。
27250 これらの関数は、正規化されたSXMLデータに最適化されています。
27251 任意の正規化されていないSXMLデータには適用できません。
27252
27253 ほとんどの関数には2つのバージョンがあります。
27254 @c COMMON
27255 @enumerate
27256 @item
27257 @c EN
27258 side-effect intended functions for linear update of given elements.
27259 Their names are ended with exclamation mark.
27260 Note that the returned value of this variant is unspecified,
27261 unless explicitly noted.
27262 An example: @code{sxml:change-content!}.
27263 @c JP
27264 与えられた要素のその場での更新のために副作用が意図された関数。
27265 これらの名前はエクスクラメーションマークで終わっています。
27266 このバージョンの戻り値は、特に断りのない限り未定義です。
27267 例としては、@code{sxml:change-content!}が挙げられます。
27268 @c COMMON
27269 @item
27270 @c EN
27271 pure functions without side-effects which return modified elements.
27272 An example: @code{sxml:change-content}.
27273 @c JP
27274 変更された要素を返す、副作用のない純粋な関数。
27275 例としては、@code{sxml:change-content}が挙げられます。
27276 @c COMMON
27277 @end enumerate
27278
27279 @defun sxml:change-content obj new-content
27280 @defunx sxml:change-content! obj new-content
27281 @c MOD sxml.tools
27282 @c EN
27283 Change the content of given SXML element to @var{new-content}.
27284 If @var{new-content} is an empty list then the @var{obj} is transformed
27285 to an empty element.
27286 The resulting SXML element is normalized.
27287 @c JP
27288 与えられたSXML要素の内容を、@var{new-content}に変更します。
27289 @var{new-content}が空リストの場合は、@var{obj}は空要素に変更されます。
27290 結果のSXML要素は正規化されています。
27291 @c COMMON
27292 @end defun
27293
27294 @defun sxml:change-attrlist obj new-attrlist
27295 @defunx sxml:change-attrlist! obj new-attrlist
27296 @c MOD sxml.tools
27297 @c EN
27298 The resulting SXML element is normalized.
27299 If @var{new-attrlist} is empty,
27300 the cadr of @var{obj} is @code{(@@)}.
27301 @c JP
27302 結果のSXML要素は正規化されています。
27303 @var{new-attrlist}が空の場合は、@var{obj}のcadrは@code{(@@)}になります。
27304 @c COMMON
27305 @end defun
27306
27307 @defun sxml:change-name obj new-name
27308 @defunx sxml:change-name! obj new-name
27309 @c MOD sxml.tools
27310 @c EN
27311 Change a name of SXML element destructively.
27312 @c JP
27313 SXML要素の名前を破壊的に変更します。
27314 @c COMMON
27315 @end defun
27316
27317 @defun sxml:add-attr obj attr
27318 @c MOD sxml.tools
27319 @c EN
27320 Returns SXML element @var{obj} with attribute @var{attr} added,
27321 or @code{#f} if the attribute with given name already exists.
27322 @var{attr} is @code{(@var{attr-name} @var{attr-value})}.
27323 Pure functional counterpart to @code{sxml:add-attr!}.
27324 @c JP
27325 属性@var{attr}が追加されたSXML要素@var{obj}を返します。
27326 与えられた名前の属性がすでに存在する場合は@code{#f}を返します。
27327 @var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
27328 @code{sxml:add-attr!}に対応する純粋関数的な関数です。
27329 @c COMMON
27330 @end defun
27331
27332 @defun sxml:add-attr! obj attr
27333 @c MOD sxml.tools
27334 @c EN
27335 Add an attribute @var{attr} for an element @var{obj}.
27336 Returns @code{#f} if the attribute with given name already exists.
27337 The resulting SXML node is normalized.
27338 Linear update counterpart to @code{sxml:add-attr}.
27339 @c JP
27340 要素@var{obj}に属性@var{attr}を追加します。
27341 与えられた名前の属性がすでに存在する場合は@code{#f}を返します。
27342 結果のSXMLノードは正規化されています。
27343 @code{sxml:add-attr}に対応するその場で更新する関数です。
27344 @c COMMON
27345 @end defun
27346
27347 @defun sxml:change-attr obj attr
27348 @c MOD sxml.tools
27349 @c EN
27350 Returns SXML element @var{obj} with changed value of
27351 attribute @var{attr}, or @code{#f}
27352 if where is no attribute with given name.
27353 @var{attr} is @code{(@var{attr-name} @var{attr-value})}.
27354 @c JP
27355 属性@var{attr}の値が変更されたSXML要素@var{obj}を返します。
27356 与えられた名前の属性がない場合は@code{#f}を返します。
27357 @var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
27358 @c COMMON
27359 @end defun
27360
27361 @defun sxml:change-attr! obj attr
27362 @c MOD sxml.tools
27363 @c EN
27364 Change value of the attribute for element @var{obj}.
27365 @var{attr} is @code{(@var{attr-name} @var{attr-value})}.
27366 Returns @code{#f} if where is no such attribute.
27367 @c JP
27368 要素@var{obj}の属性の値を変更します。
27369 @var{attr}は@code{(@var{attr-name} @var{attr-value})}です。
27370 そのような属性がない場合は@code{#f}を返します。
27371 @c COMMON
27372 @end defun
27373
27374 @defun sxml:set-attr obj attr
27375 @defunx sxml:set-attr! obj attr
27376 @c MOD sxml.tools
27377 @c EN
27378 Set attribute @var{attr} of element @var{obj}.
27379 If there is no such attribute the new one is added.
27380 @c JP
27381 要素@var{obj}の属性@var{attr}をセットします。
27382 そのような属性がない場合は新しい属性として追加されます。
27383 @c COMMON
27384 @end defun
27385
27386 @defun sxml:add-aux obj aux-node
27387 @c MOD sxml.tools
27388 @c EN
27389 Returns SXML element @var{obj}
27390 with an auxiliary node @var{aux-node} added.
27391 @c JP
27392 補助ノード@var{aux-node}が追加されたSXML要素@var{obj}を返します。
27393 @c COMMON
27394 @end defun
27395
27396 @defun sxml:add-aux! obj aux-node
27397 @c MOD sxml.tools
27398 @c EN
27399 Add an auxiliary node @var{aux-node} for an element @var{obj}.
27400 @c JP
27401 要素@var{obj}に補助ノード@var{aux-node}を追加します。
27402 @c COMMON
27403 @end defun
27404
27405 @defun sxml:squeeze obj
27406 @defunx sxml:squeeze! obj
27407 @c MOD sxml.tools
27408 @c EN
27409 Eliminates empty lists of attributes and aux-lists for given SXML element
27410 @var{obj} and its descendants ("minimize" it).
27411 Returns a minimized and normalized SXML element.
27412 @c JP
27413 与えられたSXML要素@var{obj}とその子孫について、空のリストである属性
27414 および補助リストを排除します(最小化)。
27415 最小化され、正規化されたSXML要素が返されます。
27416 @c COMMON
27417 @end defun
27418
27419 @defun sxml:clean obj
27420 @c MOD sxml.tools
27421 @c EN
27422 Eliminates empty lists of attributes and all aux-lists for given SXML element
27423 @var{obj} and its descendants.
27424 Returns a minimized and normalized SXML element.
27425 @c JP
27426 与えられたSXML要素@var{obj}とその子孫について、空リストである属性と、
27427 全ての補助リストを削除します。
27428 最小化され、正規化されたSXML要素が返されます。
27429 @c COMMON
27430 @end defun
27431
27432 @c ----------------------------------------------------------------------
27433 @node SXPath auxiliary utilities, SXML to markup conversion, SXML modifiers, Manipulating SXML structure
27434 @subsection SXPath auxiliary utilities
27435 @c NODE SXPathの補助的ユーティリティ
27436
27437 @c EN
27438 These are convenience utilities to extend SXPath functionalities.
27439 @c JP
27440 これらは、SXPathの機能を拡張する便利なユーティリティです。
27441 @c COMMON
27442
27443 @defun sxml:add-parents obj . top-ptr
27444 @c MOD sxml.tools
27445 @c EN
27446 Returns an SXML nodeset with a 'parent pointer' added.
27447 A parent pointer is an aux node of the form @code{(*PARENT* @var{thunk})},
27448 where @var{thunk} returns the parent element.
27449 @c JP
27450 SXMLノードセットに'親へのポインタ'を追加したものを返します。
27451 親へのポインタは、@code{(*PARENT* @var{thunk})}というフォームを持つ
27452 補助ノードです。@var{thunk}は親要素を返します。
27453 @c COMMON
27454 @end defun
27455
27456 @defun sxml:node-parent rootnode
27457 @c MOD sxml.tools
27458 @c EN
27459 Returns a fast 'node-parent' function, i.e.
27460 a function of one argument - SXML element - which returns its parent
27461 node using @code{*PARENT*} pointer in aux-list.
27462 '@code{*TOP-PTR*} may be used as a pointer to root node.
27463 It return an empty list when applied to root node.
27464 @c JP
27465 高速な'node-parent'関数を返します。
27466 すなわち、SXML要素を1引数として取り、補助リストで
27467 @code{*PARENT*}ポインタを使ってその親ノードを返す関数を返します。
27468 '@code{*TOP-PTR*}はルートノードへのポインタとして使われます。
27469 ルートノードに対して適用されると空リストを返します。
27470 @c COMMON
27471 @end defun
27472
27473 @defun sxml:lookup id index
27474 @c MOD sxml.tools
27475 @c EN
27476 Lookup an element using its ID.
27477 @c JP
27478 要素をそのIDを使って探します。
27479 @c COMMON
27480 @end defun
27481
27482 @c ----------------------------------------------------------------------
27483 @node SXML to markup conversion, , SXPath auxiliary utilities, Manipulating SXML structure
27484 @subsection SXML to markup conversion
27485 @c NODE SXMLからマークアップへの変換
27486
27487 @c EN
27488 Procedures to generate XML or HTML marked up text from SXML.
27489 For more advanced conversion, see the SXML serializer
27490 (@ref{Serializing XML and HTML from SXML}).
27491
27492 @c JP
27493 SXMLからXMLやHTMLなどのマークアップされたテキストを生成する手続き。
27494 もっと高尚な変換器を得たいだけならば、
27495 @ref{Serializing XML and HTML from SXML}をチェックして下さい。
27496 @c COMMON
27497
27498 @defun sxml:clean-feed . fragments
27499 @c MOD sxml.tools
27500 @c EN
27501 Filter the 'fragments'.
27502 The fragments are a list of strings, characters,
27503 numbers, thunks, @code{#f} -- and other fragments.
27504 The function traverses the tree depth-first, and returns a list
27505 of strings, characters and executed thunks,
27506 and ignores @code{#f} and '@code{()}.
27507
27508 If all the meaningful fragments are strings, then
27509 @code{(apply string-append ... )}
27510 to a result of this function will return its string-value.
27511
27512 It may be considered as a variant of Oleg Kiselyov's
27513 @code{SRV:send-reply}:
27514 While @code{SRV:send-reply} displays fragments, this function returns the list
27515 of meaningful fragments and filter out the garbage.
27516 @c JP
27517 'fragments'をフィルタします。
27518 fragmentsは、文字列、文字、数値、手続き、@code{#f}、他のフラグメントの
27519 リストです。
27520 この関数はツリーを深さ優先でトラバースし、
27521 文字列、文字、実行された手続きのリストを返し、
27522 @code{#f}と'@code{()}を無視します。
27523
27524 全ての意味のあるフラグメントは文字列で、
27525 この関数の結果に@code{(apply string-append ... )}を
27526 適用すると、そのstring-valueを返します。
27527
27528 これは、Oleg Kiselyovの@code{SRV:send-reply}の変種であるとみなすことが
27529 できるでしょう。
27530 @code{SRV:send-reply}はフラグメントを印字(display)しますが、
27531 この関数は意味のあるフラグメントのリストを返し、ごみをふるい落とします。
27532 @c COMMON
27533 @end defun
27534
27535 @defun sxml:attr->xml attr :optional namespace-prefix-assig
27536 @defunx sxml:attr->html attr
27537 @c MOD sxml.tools
27538 @c EN
27539 Creates the XML/HTML markup for attributes.
27540 Return a tree of strings, which can be passed to
27541 @code{tree->string} or @code{write-tree} (@pxref{Lazy text construction}).
27542
27543 The argument @var{attr} is a two-element list,
27544 @code{(@var{attr-name} @var{attr-value})}, where
27545 @var{attr-name} is a symbol. @var{Attr-value} can be any value,
27546 and converted to a string with @code{x->string}.
27547 @c JP
27548 属性のXML/HTMLマークアップを作ります。
27549 戻り値は、@code{tree->string}や@code{write-tree}に渡せる
27550 文字列のツリーです(@ref{Lazy text construction}参照)。
27551
27552 @var{attr}は2要素のリスト
27553 @code{(@var{attr-name} @var{attr-value})}で、
27554 @var{attr-name}はシンボルでなければなりません。
27555 @var{attr-value}はどんな値でも良いですが、文字列以外は
27556 @code{x->string}で文字列に変換されます。
27557 @c COMMON
27558
27559 @c EN
27560 The optional @var{namespace-prefix-assig} argument is used to replace
27561 namespace prefix in the attibute name to its alias. See
27562 @code{sxml:sxml->xml} below for the details.
27563 @c JP
27564 省略可能な@var{namespace-prefix-assig}は、属性名の名前空間プレフィクスを
27565 エイリアスに置き換えるのに使われます。
27566 詳しくは下の@code{sxml:sxml->xml}を参照してください。
27567 @c COMMON
27568
27569 @c EN
27570 There's a subtle difference between the two. If the value
27571 is an empty string, @code{sxml:attr->html} omits the attribute
27572 value, while @code{sxml:attr->xml} doesn't.
27573 @c JP
27574 二つの手続きには微妙な差があります。値が空文字列だった場合、
27575 @code{sxml:attr->html}は値を省略しますが、@code{sxml:attr->xml}はしません。
27576 @c COMMON
27577
27578 @example
27579 (use text.tree)
27580
27581 (tree->string (sxml:attr->xml '(name foo)))
27582 @result{} " name=\"foo\""
27583
27584 (tree->string (sxml:attr->html '(value "He said, \"Oops.\"")))
27585 @result{} " value=\"He said, &quot;Oops.&quot;\""
27586
27587 (tree->string (sxml:attr->xml '(download "")))
27588 @result{} " download=\"\""
27589
27590 (tree->string (sxml:attr->html '(download "")))
27591 @result{} " download"
27592 @end example
27593
27594 @c EN
27595 Note: This procedure is slighly modified from the original sxml-tools
27596 to escape special characters in the attribue value,
27597 and recognize namespace prefix.
27598 @c JP
27599 註: この手続きは元のsxml-toolsから、
27600 属性値中の特殊文字をエスケープするのと、名前空間プレフィクスを認識するように変更してあります。
27601 @c COMMON
27602 @end defun
27603
27604 @defun sxml:string->xml string
27605 @defunx sxml:string->html string
27606 @c MOD sxml.tools
27607 @c EN
27608 Return a tree of strings where characters @code{<}, @code{>},
27609 @code{&}, and @code{"} in @var{string}
27610 are replaced by character entity references.
27611 With @code{sxml:string->xml}, @code{'} is also replaced.
27612
27613 The returned string tree can be passed to @code{tree->string}
27614 or @code{write-tree} (@pxref{Lazy text construction}).
27615 @c JP
27616 @var{string}中の文字@code{<}、@code{>}、@code{&}、@code{"}を
27617 対応する文字実体参照に置き換えた文字列のツリーを返します。
27618 @code{sxml:string->xml}では@code{'}も置き換えられます。
27619
27620 戻り値は、@code{tree->string}や@code{write-tree}に渡せます
27621 (@ref{Lazy text construction}参照)。
27622 @c COMMON
27623
27624 @c EN
27625 See also @code{html-escape-string}
27626 in @ref{Simple HTML document construction}.
27627 @c JP
27628 @ref{Simple HTML document construction}の
27629 @code{html-escape-string}も参照して下さい。
27630 @c COMMON
27631 @end defun
27632
27633 @defun sxml:sxml->xml sxml :optional namespace-prefix-assig
27634 @defunx sxml:sxml->html sxml
27635 @c MOD sxml.tools
27636 @c EN
27637 Converts SXML to XML and HTML, respectively. The return value
27638 is a tree of strings to be pased to @code{tree->string} or @code{write-tree}
27639 (@pxref{Lazy text construction}).
27640 @c JP
27641 SXMLをXMLあるいはHTMLにそれぞれ変換します。戻り値は文字列のツリーで、
27642 @code{tree->string}や@code{write-tree}に渡せます
27643 (@ref{Lazy text construction}参照)。
27644 @c COMMON
27645
27646 @c EN
27647 @code{sxml:sxml->xml} can take an optional @var{namespace-prefix-assig},
27648 which is the form @code{((@var{alias-symbol} . @var{namespace-string}) @dots{})}.
27649 It is the same format as the @var{namespace-prefix-assig} argument
27650 of @code{ssax:xml->sxml} (@pxref{SSAX Highest-level parsers - XML to SXML}).
27651 It has two effects:
27652 @c JP
27653 @code{sxml:sxml->xml}は省略可能引数@var{namespace-prefix-assig}を取ります。
27654 これは@code{ssax:xml->sxml}の同名の引数と同じく、
27655 @code{((@var{alias-symbol} . @var{namespace-string}) @dots{})}という形の
27656 リストでなければなりません(@ref{SSAX Highest-level parsers - XML to SXML}参照)。
27657 これは次の二つの効果を持ちます。
27658 @c COMMON
27659
27660 @itemize @bullet
27661 @item
27662 @c EN
27663 It adds @code{xmlns} attributes to the top node of @var{sxml}.
27664 @c JP
27665 @var{sxml}のトップレベルのノードに@code{xmlns}属性を付加
27666 @c COMMON
27667 @item
27668 @c EN
27669 If a node name or an attribute name has a prefix string that matches
27670 @var{namespace-string}, it is replaced with @var{alias-symbol}.
27671 (If its prefix string does not match any of @var{namespace-prefix-assig},
27672 the prefix is left as is.)
27673 @c JP
27674 ノード名や属性名のプリフィクスが@var{namespace-string}のいずれかと一致した場合、
27675 対応する@var{alias-symbol}に置き換えられます
27676 (一致するものがなければプリフィクスはそのまま出力されます)。
27677 @c COMMON
27678 @end itemize
27679
27680 @c EN
27681 Note that @code{sxml:sxml->html} does not take
27682 @var{namespace-prefix-assig}, for HTML doesn't have namespace prefix.
27683 @c JP
27684 @code{sxml:sxml->html}は@var{namespace-prefix-assig}引数を取りません。
27685 HTMLには名前空間プレフィクスは無いからです。
27686 @c COMMON
27687
27688 @c EN
27689 Other differences between XML and HTML version are:
27690
27691 @itemize @bullet
27692 @item
27693 Handling of empty-valueed attribute
27694 (see @code{sxml:attr->xml}/@code{sxml:attr->html} above.)
27695 @item
27696 Characters replaced with character entity references
27697 (see @code{sxml:string->xml}/@code{sxml:string->html} above.)
27698 @item
27699 Non-terminated tags. In HTML, some tags does not have end tags.
27700 In XML, elements with empty content are emitted as self-terminating tags.
27701 @end itemize
27702 @c JP
27703 XML版とHTML版の他の違いは次のとおりです。
27704
27705 @itemize @bullet
27706 @item
27707 空の値を持つ属性の出力
27708 (上の@code{sxml:attr->xml}/@code{sxml:attr->html}参照)
27709 @item
27710 文字実体参照に置き換えられる文字の違い
27711 (上の@code{sxml:string->xml}/@code{sxml:string->html}参照)
27712 @item
27713 終了タグのない要素。HTMLではいくつかの決められたタグは終了タグを持ちません。
27714 XMLでは内容が空の要素は自己終了タグとして出力されます。
27715 @end itemize
27716 @c COMMON
27717
27718 @example
27719 (tree->string (sxml:sxml->xml '(div (@@ (foo "") (bar "'")))))
27720 @result{} "<div foo=\"\" bar=\"&apos;\"/>"
27721 (tree->string (sxml:sxml->html '(div (@@ (foo "") (bar "'")))))
27722 @result{} "<div foo bar=\"'\"/>"
27723
27724 (tree->string (sxml:sxml->xml '(img (@@ (src "foo.png")))))
27725 @result{} "<img src=\"foo.png\"/>"
27726 (tree->string (sxml:sxml->html '(img (@@ (src "foo.png")))))
27727 @result{} "<img src=\"foo.png\">"
27728 @end example
27729 @end defun
27730
27731 @defun sxml:non-terminated-html-tag? tag
27732 @c MOD sxml.tools
27733 @c EN
27734 This predicate yields @code{#t} for "non-terminated" HTML 4.0 tags.
27735 @c JP
27736 この述語は、``終了タグのない''HTML 4.0のタグに対して@code{#t}を
27737 返します。
27738 @c COMMON
27739 @end defun
27740
27741 @c ----------------------------------------------------------------------
27742 @node Serializing XML and HTML from SXML, Text terminal control, Manipulating SXML structure, Library modules - Utilities
27743 @section @code{sxml.serializer} - Serializing XML and HTML from SXML
27744 @c NODE SXMLからXMLとXHTMLのシリアライゼーション, @code{sxml.serializer} - SXMLからXMLとXHTMLのシリアライゼーション
27745
27746 @deftp {Module} sxml.serializer
27747 @mdindex sxml.serializer
27748 @c EN
27749 This module contains a full-featured serializer from SXML into XML and
27750 HTML, partially conforming to XSLT 2.0 and XQuery 1.0 Serialization
27751 (@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/}).
27752 It's more powerful than sxml:sxml->xml and sxml:sxml->html from
27753 sxml.tools.
27754
27755 The manual entry is mainly derived from the comments in the original
27756 source code.
27757 @c JP
27758 このモジュールはSXMLからXMLとHTMLへの変換を行う、様々な機能を持つ
27759 シリアライザを提供します。XSLT2.0とXQuery1.0に部分的に適合しています。
27760 (@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/})。
27761 sxml.toolsのsxml:sxml->xmlとsxml:sxml->htmlよりも強力です。
27762
27763 マニュアルのエントリは主に、オリジナルのソースコードから取られてています。
27764 @c COMMON
27765 @end deftp
27766
27767 @c ----------------------------------------------------------------------
27768 @menu
27769 * Simple SXML serializing::
27770 * Custom SXML serializing::
27771 @end menu
27772
27773 @c ----------------------------------------------------------------------
27774 @node Simple SXML serializing, Custom SXML serializing, Serializing XML and HTML from SXML, Serializing XML and HTML from SXML
27775 @subsection Simple SXML serializing
27776 @c NODE 簡単なSXML変換
27777
27778 @c EN
27779 The SXML serializer provides some convenient high-level converters which
27780 should be enough for most tasks.
27781 @c JP
27782 高レベルの、簡単に使えるシリアライザです。大抵の目的にはこれで十分使えるでしょう。
27783 @c COMMON
27784
27785 @defun srl:sxml->xml sxml-obj :optional port-or-filename
27786 @c MOD sxml.serializer
27787 @c EN
27788 Serializes the @var{sxml-obj} into XML, with indentation to facilitate
27789 readability by a human.
27790
27791 If @var{port-or-filename} is not supplied, the functions return a
27792 string that contains the serialized representation of the
27793 @var{sxml-obj}.
27794
27795 If @var{port-or-filename} is supplied and is a port, the functions
27796 write the serialized representation of @var{sxml-obj} to this port and
27797 return an unspecified result.
27798
27799 If @var{port-or-filename} is supplied and is a string, this string is
27800 treated as an output filename, the serialized representation of
27801 @var{sxml-obj} is written to that filename and an unspecified result
27802 is returned. If a file with the given name already exists, the effect
27803 is unspecified.
27804 @c JP
27805 @var{sxml-obj}をXMLへと変換します。出力は人間が読みやすいように
27806 インデントされます。
27807
27808 @var{port-or-filename}が与えられなければ、
27809 戻り値は@var{sxml-obj}の変換結果の文字列になります。
27810
27811 @var{port-or-filename}がポートならば、そのポートにXMLを書き出します。
27812 戻り値は不定です。
27813
27814 @var{port-or-filename}が文字列ならば、その名のファイルにXMLを書き出し
27815 ます。戻り値は不定です。そのようなファイルが既に存在する場合、
27816 結果は不定です。
27817 @c COMMON
27818
27819 @c EN
27820 Note: Unlike @code{sxml:sxml->xml} in @code{sxml.ssax}, this
27821 procedure requires XML attribute values to be strings.
27822 @c JP
27823 註: @code{sxml.ssax}の@code{sxml:sxml->xml}と異なり、
27824 この手続きはXML属性の値が文字列であることを要求します。
27825 @c COMMON
27826 @end defun
27827
27828 @defun srl:sxml->xml-noindent sxml-obj :optional port-or-filename
27829 @c MOD sxml.serializer
27830 @c EN
27831 Serializes the @var{sxml-obj} into XML, without indentation.
27832
27833 Argument @var{port-or-filename} works like described in
27834 @code{srl:sxml->xml}.
27835 @c JP
27836 @code{srl:sxml->xml}と同じように動作しますが、インデントを行いません。
27837
27838 引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
27839 @c COMMON
27840 @end defun
27841
27842 @defun srl:sxml->html sxml-obj :optional port-or-filename
27843 @c MOD sxml.serializer
27844 @c EN
27845 Serializes the @var{sxml-obj} into HTML, with indentation to
27846 facilitate readability by a human.
27847
27848 Argument @var{port-or-filename} works like described in @code{srl:sxml->xml}.
27849 @c JP
27850 @var{sxml-obj}をHTMLへと変換します。出力は人間が読みやすいように
27851 インデントされます。
27852
27853 引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
27854 @c COMMON
27855
27856 @c EN
27857 Note: Unlike @code{sxml:sxml->html} in @code{sxml.ssax}, this
27858 procedure requires XML attribute values to be strings.
27859 @c JP
27860 註: @code{sxml.ssax}の@code{sxml:sxml->html}と異なり、
27861 この手続きはXML属性の値が文字列であることを要求します。
27862 @c COMMON
27863 @end defun
27864
27865 @defun srl:sxml->html-noindent sxml-obj :optional port-or-filename
27866 @c MOD sxml.serializer
27867 @c EN
27868 Serializes the @var{sxml-obj} into HTML, without indentation.
27869
27870 Argument @var{port-or-filename} works like described in @code{srl:sxml->xml}.
27871 @c JP
27872 @code{srl:sxml->html}と同じように動作しますが、インデントを行いません。
27873
27874 引数@var{port-or-filename}は@code{srl:sxml->xml}と同様に動作します。
27875 @c COMMON
27876 @end defun
27877
27878 @c ----------------------------------------------------------------------
27879 @node Custom SXML serializing, , Simple SXML serializing, Serializing XML and HTML from SXML
27880 @subsection Custom SXML serializing
27881 @c NODE カスタムSXML変換
27882
27883 @c EN
27884 These functions provide full access to all configuration parameters of
27885 the XML serializer.
27886 @c JP
27887 以下の手続きはXMLシリアライザの全ての設定パラメータへのアクセスを提供
27888 します。
27889 @c COMMON
27890
27891 @defun srl:parameterizable sxml-obj :optional port-or-filename params*
27892 @c MOD sxml.serializer
27893 @c EN
27894 Generalized serialization procedure, parameterizable with all the
27895 serialization parameters supported by this implementation.
27896 @c JP
27897 汎用シリアライズ手続、この実装でサポートするすべてのシリアライズパラメー
27898 タのパラメータ化。
27899 @c COMMON
27900
27901 @c EN
27902 @var{sxml-obj} - an SXML object to serialize
27903 @c JP
27904 @var{sxml-obj} - シリアライズするSXMLオブジェクト。
27905 @c COMMON
27906
27907 @c EN
27908 @var{port-or-filename} - either @code{#f}, a port or a string; works
27909 like in srl:sxml->xml (@ref{Simple SXML serializing}).
27910 @c JP
27911 @var{port-or-filename} - @code{#f}あるいはポートあるいは文字列のどれか。
27912 srl:sxml->xmlのものと同じ働きをします(@ref{Simple SXML serializing})。
27913 @c COMMON
27914
27915 @c EN
27916 @var{params} - each parameter is a cons of param-name (a symbol) and
27917 param-value. The available parameter names and their values are
27918 described below:
27919 @c JP
27920 @var{params} - 各パラメータはパラメータ名(シンボル)とパラメータ値との
27921 コンス対。利用可能なパラメータ名とその値については後述。
27922 @c COMMON
27923
27924 @c EN
27925 @code{method} - Either the symbol @code{xml} or @code{html}. For a
27926 detailed explanation of the difference between XML and HTML methods,
27927 see XSLT 2.0 and XQuery 1.0 Serialization (@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/}).
27928 @c JP
27929 @code{method} - シンボル@code{xml}か@code{html}のどちらか。XMLメソッド
27930 とHTMLメソッドの相違についての詳しい説明は、XSLT 2.0 と XQuery
27931 Serialization
27932 (@uref{http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/})
27933 を参照してください。
27934 @c COMMON
27935
27936 @c EN
27937 @code{indent} - Whether the output XML should include whitespace for
27938 human readability (@code{#t} or @code{#f}). You can also supply a
27939 string, which will be used as the indentation unit.
27940 @c JP
27941 @code{indent} - 出力の XML が読みやすさのために空白を含むかどうか
27942 (@code{#t}あるいは@code{#f})。文字列を設定することもでき、その場合
27943 インデント単位に使われます。
27944 @c COMMON
27945
27946 @c EN
27947 @code{omit-xml-declaration} - Whether the XML declaration should be
27948 omitted. Default: @code{#t}.
27949 @c JP
27950 @code{omit-xml-declaration} - XML宣言を省略するかどうか。デフォルトは
27951 @code{#t}。
27952 @c COMMON
27953
27954 @c EN
27955 @code{standalone} - Whether to define the XML document as standalone in
27956 the XML declaration. Should be one of the symbols @code{yes},
27957 @code{no} or @code{omit}, the later causing standalone declaration to
27958 be suppressed. Default: @code{omit}.
27959 @c JP
27960 @code{standalone} - XML ドキュメントを XML 宣言でスタンドアローンとし
27961 て定義するかどうか。@code{yes}、@code{no}、@code{omit}のうちいずれかの
27962 シンボルでなければならない。デフォルトは @code{omit}
27963 @c COMMON
27964
27965 @c EN
27966 @code{version} - The XML version used in the declaration. A string or
27967 a number. Default: @code{"1.0"}.
27968 @c JP
27969 @code{version} - XML宣言中のXMLバージョン。文字列または数。デフォルト
27970 は@code{"1.0"}。
27971 @c COMMON
27972
27973 @c EN
27974 @code{cdata-section-elements} - A list of SXML element names (as
27975 symbols). The contents of those elements will be escaped as CDATA
27976 sections.
27977 @c JP
27978 @code{cdata-section-elements} - SXML要素の名前(シンボル)のリスト。これ
27979 らの要素の中身はCDATAセクションと同様にエスケープされる。
27980 @c COMMON
27981
27982 @c EN
27983 @code{ns-prefix-assig} - A list of @code{(cons prefix namespace-uri)},
27984 where each @code{prefix} is a symbol and each @code{namespace-uri} a
27985 string. Will serialize the given namespaces with the corresponding
27986 prefixes.
27987 @c JP
27988 @code{ns-prefix-assig} - @code{(cons prefix namespace-uri)}のリスト。
27989 各@code{prefix}はシンボルで、@code{namespace-uri}は文字列。
27990 対応する接頭辞をつけて与えられた名前空間をシリアライズする。
27991 @c COMMON
27992
27993 @c EN
27994 ATTENTION: If a parameter name is unexpected or a parameter value is
27995 ill-formed, the parameter is silently ignored!
27996 @c JP
27997 注意: パラメータ名が期待された名前ではない場合、あるいはパラメータ値
27998 が不正な形式である場合にはそのようなパラメータは警告なしで無視されます。
27999 @c COMMON
28000
28001 @c EN
28002 Example usage:
28003
28004 @lisp
28005 (srl:parameterizable
28006 '(tag (@@ (attr "value")) (nested "text node") (empty))
28007 (current-output-port)
28008 '(method . xml) ; XML output method is used by default
28009 '(indent . "\t") ; use a single tabulation to indent
28010 '(omit-xml-declaration . #f) ; add XML declaration
28011 '(standalone . yes) ; denote a standalone XML document
28012 '(version . "1.0")) ; XML version
28013 @end lisp
28014 @c JP
28015 使用実例:
28016 @lisp
28017 (srl:parameterizable
28018 '(tag (@@ (attr "value")) (nested "text node") (empty))
28019 (current-output-port)
28020 '(method . xml) ; XML出力をデフォールト
28021 '(indent . "\t") ; インデントは一つのタブ
28022 '(omit-xml-declaration . #f) ; XML宣言をつける
28023 '(standalone . yes) ; 「standalone」宣言もつける
28024 '(version . "1.0")) ; XMLのバージョン
28025 @end lisp
28026 @c COMMON
28027
28028 @lisp
28029 param ::= (cons param-name param-value)
28030 param-name ::= symbol
28031
28032 cdata-section-elements
28033 value ::= (listof sxml-elem-name)
28034 sxml-elem-name ::= symbol
28035
28036 indent
28037 value ::= 'yes | #t | 'no | #f | whitespace-string
28038
28039 method
28040 value ::= 'xml | 'html
28041
28042 ns-prefix-assig
28043 value ::= (listof (cons prefix namespace-uri))
28044 prefix ::= symbol
28045 namespace-uri ::= string
28046
28047 omit-xml-declaration
28048 value ::= 'yes | #t | 'no | #f
28049
28050 standalone
28051 value ::= 'yes | #t | 'no | #f | 'omit
28052
28053 version
28054 value ::= string | number
28055 @end lisp
28056 @end defun
28057
28058 @defun srl:sxml->string sxml-obj cdata-section-elements indent method ns-prefix-assig omit-xml-declaration? standalone version
28059 @c MOD sxml.serializer
28060 @c EN
28061 Same as @code{srl:parameterizable} returning a string and without the
28062 overhead of parsing parameters. This function interface may change in
28063 future versions of the library.
28064 @c JP
28065 @code{srl:parameterizable}と同様ですが、文字列を返し、パラメータ解析のオーバヘッ
28066 ドはありません。この関数のインタフェースはこのライブラリの将来のバージョ
28067 ンでは変更されるかもしれません。
28068 @c COMMON
28069 @end defun
28070
28071 @defun srl:display-sxml sxml->obj port-or-filename cdata-section-elements indent method ns-prefix-assig omit-xml-declaration? standalone version
28072 @c MOD sxml.serializer
28073 @c EN
28074 Same as @code{srl:parameterizable} writing output to
28075 @var{port-or-filename} and without the overhead of parsing parameters.
28076 This function interface may change in
28077 future versions of the library.
28078 @c JP
28079 @code{srl:parameterizable}と同様ですが、結果を
28080 @var{port-or-filename}に書き出します。パラメータ解析のオーバーヘッドはありません。
28081 この関数のインタフェースはこの
28082 ライブラリの将来のバージョンでは変更されるかもしれません。
28083 @c COMMON
28084 @end defun
28085
28086 @c ----------------------------------------------------------------------
28087 @node Text terminal control, CSV tables, Serializing XML and HTML from SXML, Library modules - Utilities
28088 @section @code{text.console} - Text terminal control
28089 @c NODE テキスト端末制御, @code{text.console} - テキスト端末制御
28090
28091 @deftp {Module} text.console
28092 @mdindex text.console
28093 @c EN
28094 This module provides a simple interface for character terminal control.
28095 Currently we support vt100 compatible terminals and Windows
28096 console.
28097
28098 This module doesn't depend on external library such as @code{curses}
28099 and works with Gauche alone, but
28100 what it can do is limited; for example, you can't get an event
28101 when shift key alone is pressed. For finer controls, you need
28102 some extension libraries.
28103
28104 For an example of the features in this module, see
28105 @file{snake.scm} in the examples directory of Gauche source distribution.
28106 @c JP
28107 このモジュールは文字端末を制御する簡単なインタフェースを提供します。
28108 今のところ、vt100互換端末とWindowsコンソールがサポートされています。
28109
28110 @code{curses}等の外部ライブラリには依存しておらず、Gaucheだけで使うことができますが、
28111 出来ることは限られています。
28112 例えばシフトキーだけが押されたタイミングでイベントを受け取ることはできません。
28113 より細かい制御には、何らかの外部拡張ライブラリが必要になるでしょう。
28114
28115 このモジュールの機能の例としては、
28116 Gaucheソースのexamplesディレクトリにある@file{snake.scm}を見てください。
28117 @c COMMON
28118 @end deftp
28119
28120 @c EN
28121 @subheading Console objects
28122 @c JP
28123 @subheading コンソールオブジェクト
28124 @c COMMON
28125
28126 @deftp {Class} <vt100>
28127 @clindex vt100
28128 @c MOD text.console
28129 @c EN
28130 Represents a vt100-compatible terminal. An instance of this class
28131 can be passed to the ``console'' argument of the following generic
28132 functions.
28133 @c JP
28134 vt100互換端末を表します。このクラスのインスタンスは
28135 以降のジェネリックファンクションの ``console'' 引数に渡せます。
28136 @c COMMON
28137
28138 @defivar {<vt100>} iport
28139 @c EN
28140 Input port connected to the terminal. The default value is
28141 the standard input port.
28142 @c JP
28143 端末に接続されている入力ポートです。デフォルトは標準入力です。
28144 @c COMMON
28145 @end defivar
28146
28147 @defivar {<vt100>} oport
28148 @c EN
28149 Output port connected to the terminal. The default value is
28150 the standard output port.
28151 @c JP
28152 端末に接続されている出力ポートです。デフォルトは標準出力です。
28153 @c COMMON
28154 @end defivar
28155
28156 @defivar {<vt100>} input-delay
28157 @c EN
28158 The terminal send back special keys encoded in an input escape sequence.
28159 In order to distinguish such keys from the actual ESC key, we time the
28160 input---if the subsequent input doesn't come within @code{input-delay}
28161 microseconds, we interpret the input as individual keystroke, rather
28162 than a part of an escape sequence. The default value is @code{1000} (1ms).
28163 @c JP
28164 端末は、特殊キーが押された場合、ESCから始まるエスケープシーケンスを送って来ます。
28165 実際にESCキーが押された場合と区別するために、入力の間隔を測っています。
28166 後続の入力が@code{input-delay}μs以内に来なかった場合はそこでシーケンスが終了したと
28167 みなし、受け取っているシーケンスが有効なエスケープシーケンスを構成しなければ
28168 個別にキー入力されたとみなします。デフォルトは@code{1000}、すなわち1msです。
28169 @c COMMON
28170 @end defivar
28171 @end deftp
28172
28173 @deftp {Class} <windows-console>
28174 @clindex windows-console
28175 @c EN
28176 Represents Windows console. This class is defined on all platforms,
28177 but its useful methods are only available on Windows-native runtime.
28178
28179 It doesn't have public slots.
28180 @c JP
28181 Windowsコンソールを表します。このクラス自体は全てのプラットフォームで
28182 定義されていますが、有用なメソッドはWindowsネイティブのランタイムでしか提供されません。
28183
28184 パブリックなスロットはありません。
28185 @c COMMON
28186 @end deftp
28187
28188 @c EN
28189 The application has to check the runtime to see what kind of console
28190 is available. A suggested flow is as follows.
28191 @c JP
28192 アプリケーションは実行時にどの種類のコンソールが利用可能かを見極めなければなりません。
28193 推奨される手順は次のとおりです。
28194 @c COMMON
28195 @itemize
28196 @item
28197 @c EN
28198 If @code{has-windows-console?} returns true, create @code{<windows-console>}
28199 instance.
28200 You don't need @code{cond-expand}; @code{has-windows-console?} returns
28201 @code{#f} on non-Windows platforms.
28202 @c JP
28203 @code{has-windows-console?}が真の値を返したなら、@code{<windows-console>}の
28204 インスタンスを作ります。
28205 @code{has-windows-console?}はWindowsプラットフォーム以外では常に@code{#f}を
28206 返すので、@code{cond-expand}は不要です。
28207 @c COMMON
28208 @item
28209 @c EN
28210 Check the environment variable @code{TERM}. If it is set and
28211 satisfies @code{vt100-compatible?}, you can create
28212 @code{<vt100>} instance.
28213 (Note: It is possible that you end up using @code{<vt100>} console
28214 on Windows; e.g. @code{gosh} running on MSYS shell.)
28215 @c JP
28216 環境変数@code{TERM}を調べます。それが定義されていて、@code{vt100-compatible?}を
28217 満たすなら、@code{<vt100>}のインスタンスを作ります。
28218 (Windows上でも@code{<vt100>}端末を使うことになる可能性もあります。
28219 例えば@code{gosh}がMSYSシェルから使われている場合です。)
28220 @c COMMON
28221 @item
28222 @c EN
28223 Otherwise, console isn't available.
28224 @c JP
28225 いずれでもなければ、端末は使えません。
28226 @c COMMON
28227 @end itemize
28228
28229 @c EN
28230 The following procedure packages this flow.
28231 @c JP
28232 次の手続きは上の手順を実装しています。
28233 @c COMMON
28234
28235 @defun make-default-console :key if-not-available
28236 @c MOD text.console
28237 @c EN
28238 Determines a suitable console class of the running process and
28239 returns its instance.
28240
28241 If no suitable console is available, the behavior depends on the
28242 @var{if-not-available} keyword argument. If it is @code{:error},
28243 which is default, an error is signalled. If it is @code{#f},
28244 the procedure returns @code{#f}.
28245 @c JP
28246 実行中のプロセスで使える端末のインスタンスを作成して返します。
28247
28248 適切な端末クラスが無い場合、振る舞いは@var{if-not-available}キーワード引数に
28249 依存します。デフォルトである@code{:error}の場合はエラーが報告されます。
28250 @code{#f}の場合はこの手続きが@code{#f}を返します。
28251 @c COMMON
28252 @end defun
28253
28254 @defun vt100-compatible? string
28255 @c MOD text.console
28256 @c EN
28257 Given the string value of the environment variable @code{TERM},
28258 returns @code{#t} if the terminal can be handled by @code{<vt100>} console,
28259 @code{#f} otherwise.
28260 @c JP
28261 環境変数@code{TERM}の値を文字列で受け取り、それが@code{<vt100>}端末として
28262 扱えるなら@code{#t}を、そうでなければ@code{#f}を返します。
28263 @c COMMON
28264 @end defun
28265
28266 @c EN
28267 @subheading Console control
28268 @c JP
28269 @subheading コンソール制御
28270 @c COMMON
28271
28272 @deffn {Generic function} call-with-console console proc :key mode
28273 @c MOD text.console
28274 @c EN
28275 Takes over the control of the console, and calls @var{proc} with
28276 @var{console} as the only argument. The console is set to
28277 the @var{mode}, which must be a symbol @code{with-terminal-mode}
28278 accepts: @code{raw}, @code{rare} or @code{cooked}. By default
28279 the console is set to @code{rare} mode, which turn off the echoing
28280 and passes most of keystrokes to the program, but it intercepts
28281 terminal controls (like @code{Ctrl-C} for interrupt and
28282 @code{Ctrl-Z} for suspend; the actual key depends on terminal
28283 settings, though. @xref{Terminal control}, for the details.)
28284 @c JP
28285 コンソールの制御を取得した状態で、@var{proc}を@var{console}を唯一の引数として
28286 呼び出します。コンソールは@var{mode}で指定されるモードにセットされます。
28287 @var{mode}は@code{with-terminal-mode}が受け付けるシンボル、
28288 すなわち@code{raw}、@code{rare}、@code{cooked}のいずれかでなければなりません。
28289 省略された場合は@code{rare}になります。
28290 このモードは、端末でのエコーを抑止し、ほぼ全てのキーストロークを
28291 プログラムにそのまま渡しますが、端末制御機能はシステム側で処理します
28292 (割り込みの@code{Ctrl-C}、プロセス一時停止の@code{Ctrl-Z}など。実際のキー割り当ては
28293 端末制御で変更可能です。詳しくは@ref{Terminal control}参照。)
28294 @c COMMON
28295
28296 @c EN
28297 If @var{proc} raises an unhandled error, this generic function
28298 resets the terminal mode before returning. It does not clear
28299 the screen.
28300 @c JP
28301 @var{proc}が捕捉されない例外を投げた場合、このジェネリック関数は
28302 端末モードを元に戻します。ただ、スクリーンはクリアされません。
28303 @c COMMON
28304 @end deffn
28305
28306 @deffn {Generic function} putch console char
28307 @c MOD text.console
28308 @c EN
28309 Display a character at the current cursor position, and
28310 move the current cursor position.
28311 @c JP
28312 文字@var{char}をコンソールの現在のカーソル位置に出力し、カーソルをその分進めます。
28313 @c COMMON
28314 @end deffn
28315
28316 @deffn {Generic function} putstr console string
28317 @c MOD text.console
28318 @c EN
28319 Display a string from the current cursor position, and
28320 move the current cursor position.
28321 @c JP
28322 文字列@var{string}コンソールの現在のカーソル位置に出力し、カーソルをその分進めます。
28323 @c COMMON
28324 @end deffn
28325
28326 @deffn {Generic function} beep console
28327 @c MOD text.console
28328 @c EN
28329 Ring the beep, or flash the screen (visible bell) if possible.
28330 @c JP
28331 可能なら、端末のビープ音を鳴らすか、画面をフラッシュさせます(visual bell)。
28332 @c COMMON
28333 @end deffn
28334
28335 @deffn {Generic function} getch console
28336 @c MOD text.console
28337 @c EN
28338 Fetch a keypress from the console. This blocks until
28339 any key is pressed.
28340
28341 The return value may be one of the following values:
28342 @c JP
28343 コンソールからキー入力を読み取ります。何らかのキーが押されるまでブロックします。
28344
28345 戻り値は以下の値のいずれかです。
28346 @c COMMON
28347
28348
28349 @table @asis
28350 @c EN
28351 @item A character
28352 A key for the character is pressed. It may be a control code
28353 if the control key is pressed with the key; that is, if the user
28354 presses Ctrl-A, @code{#\x01} will be returned.
28355 @c JP
28356 @item 文字
28357 その文字に該当するキーが押された場合。
28358 コントロールキーと一緒に押された場合は、制御文字が返ります。
28359 例えばユーザがCtrl-Aをタイプしたら@code{#\x01}が返ります。
28360 @c COMMON
28361 @c EN
28362 @item A symbol
28363 Indicates a special key; the following keys are supported:
28364 @code{KEY_UP}, @code{KEY_DOWN}, @code{KEY_LEFT}, @code{KEY_RIGHT},
28365 @code{KEY_HOME}, @code{KEY_END}, @code{KEY_INS}, @code{KEY_DEL},
28366 @code{KEY_PGDN}, @code{KEY_PGUP}, @code{KEY_F1}, @code{KEY_F2},
28367 @code{KEY_F3}, @code{KEY_F4}, @code{KEY_F5}, @code{KEY_F6},
28368 @code{KEY_F7}, @code{KEY_F8}, @code{KEY_F9}, @code{KEY_F10},
28369 @code{KEY_F11}, @code{KEY_F12}.
28370 (Note: DELETE key is usually mapped to @code{#\x7f}, but it depends on
28371 the terminal).
28372 @c JP
28373 @item シンボル
28374 特殊キーの場合です。以下のキーがサポートされています。
28375 @code{KEY_UP}, @code{KEY_DOWN}, @code{KEY_LEFT}, @code{KEY_RIGHT},
28376 @code{KEY_HOME}, @code{KEY_END}, @code{KEY_INS}, @code{KEY_DEL},
28377 @code{KEY_PGDN}, @code{KEY_PGUP}, @code{KEY_F1}, @code{KEY_F2},
28378 @code{KEY_F3}, @code{KEY_F4}, @code{KEY_F5}, @code{KEY_F6},
28379 @code{KEY_F7}, @code{KEY_F8}, @code{KEY_F9}, @code{KEY_F10},
28380 @code{KEY_F11}, @code{KEY_F12}。
28381 (註: DELETEキーは通常@code{#\x7f}にマップされていますが、
28382 端末設定で変更可能です)。
28383 @c COMMON
28384 @c EN
28385 @item A list of symbol @code{ALT} and a character.
28386 Indicates the character key is pressed with Alt key. For example,
28387 if the user presses Alt-a, @code{(ALT #\a)} is returned.
28388 @c JP
28389 @item シンボル@code{ALT}と文字のリスト
28390 文字キーがAltキーと同時に押されたことを示します。
28391 例えばユーザがAlt-aを押したなら、@code{(ALT #\a)}が返されます。
28392 @c COMMON
28393 @item EOF
28394 @c EN
28395 Indicates the input is closed somehow.
28396 @c JP
28397 入力がクローズされたことを示します。
28398 @c COMMON
28399 @end table
28400
28401 @c EN
28402 Modifier keys except @code{ALT} are not treated separately but
28403 included in the returned keycode. Assuming CAPSLOCK is off,
28404 if the user press @code{a}, @code{Shift}+@code{a}, and @code{Ctrl}+@code{a},
28405 the returned value is @code{#\a}, @code{#\A} and @code{#\x01}, respectively.
28406 @code{Ctrl}+@code{Shift}+@code{a} can't be distinguished from
28407 @code{Ctrl}+@code{a}. @code{ALT}+@code{a}, @code{ALT}+@code{Shift}+@code{a},
28408 and @code{ALT}+@code{Ctrl}+@code{a} will be @code{(ALT #\a)},
28409 @code{(ALT #\A)} and @code{(ALT #\x01)}, respectively.
28410 @c JP
28411 @code{ALT}以外のモディファイアキーは別扱いではなく返される文字コードにエンコードされます。
28412 CAPSLOCKがoffであるとき、ユーザが
28413 @code{a}、@code{Shift}+@code{a}、@code{Ctrl}+@code{a}をタイプしたとすると、
28414 戻り値はそれぞれ@code{#\a}、@code{#\A}、@code{#\x01}となります。
28415 @code{Ctrl}+@code{Shift}+@code{a}は@code{Ctrl}+@code{a}と区別できません。
28416 @code{ALT}+@code{a}、@code{ALT}+@code{Shift}+@code{a}、
28417 @code{ALT}+@code{Ctrl}+@code{a}の戻り値はそれぞれ、
28418 @code{(ALT #\a)}、@code{(ALT #\A)}、@code{(ALT #\x01)}となります。
28419 @c COMMON
28420 @end deffn
28421
28422 @deffn {Generic function} chready? console
28423 @c MOD text.console
28424 Returns true if there's a key sequence to be read in the console's
28425 input.
28426 @end deffn
28427
28428 @deffn {Generic function} query-cursor-position console
28429 @c MOD text.console
28430 Returns two values, the current cursor's x and y position.
28431 The top-left corner is (0,0).
28432 @end deffn
28433
28434 @deffn {Generic function} move-cursor-to console row column
28435 @c MOD text.console
28436 Move cursor to the specified position. The top-left corner is (0,0).
28437 @end deffn
28438
28439 @deffn {Generic function} reset-terminal console
28440 @c MOD text.console
28441 Reset terminal. Usually this sets the
28442 character attributes to the default,
28443 clears the screen, and moves the cursor to (0, 0).
28444 @end deffn
28445
28446 @deffn {Generic function} clear-screen console
28447 @c MOD text.console
28448 Clear entire screen.
28449 @end deffn
28450
28451 @deffn {Generic function} clear-to-eol console
28452 @c MOD text.console
28453 Clear characters from the current cursor position to the
28454 end of the line.
28455 @end deffn
28456
28457 @deffn {Generic function} clear-to-eos console
28458 @c MOD text.console
28459 Clear characters from the current cursor position to the
28460 end of the screen.
28461 @end deffn
28462
28463 @deffn {Generic function} hide-cursor console
28464 @deffnx {Generic function} show-cursor console
28465 @c MOD text.console
28466 Hide/show the cursor.
28467 @end deffn
28468
28469 @deffn {Generic function} cursor-down/scroll-up console
28470 @c MOD text.console
28471 If the cursor is at the bottom line of the screen,
28472 scroll up the contents and clear the bottom line; the cursor stays
28473 the same position. If the cursor is not at the bottom line of
28474 the screen, move the cursor down.
28475 @end deffn
28476
28477 @deffn {Generic function} cursor-up/scroll-down console
28478 @c MOD text.console
28479 If the cursor is at the top line of the screen,
28480 scroll down the contents and clear the top line; the cursor stays
28481 the same position. If the cursor is not at the top line of
28482 the screen, move the cursor up.
28483 @end deffn
28484
28485 @deffn {Generic function} query-screen-size console
28486 @c MOD text.console
28487 Returns two values, the width and height of the screen.
28488
28489 Note: This may affect what's shown in the console.
28490 It is recommended that you only call this before redrawing
28491 the entire screen and save the result.
28492 @end deffn
28493
28494 @deffn {Generic function} set-character-attribute console spec
28495 @c MOD text.console
28496 Set the console so that the subsequent characters will be written
28497 with attributes specified by @var{spec}.
28498
28499 The character attributes spec is a list in the following format:
28500
28501 @example
28502 (<fgcolor> [<bgcolor> . <option> ...])
28503 @end example
28504
28505 where:
28506
28507 @example
28508 <fgcolor> : <color> | #f ; #f means default
28509 <bgcolor> : <color> | #f
28510 <color> : black | red | green | yellow | blue | magenta | cyan | white
28511 <option> : bright | reverse | underscore
28512 @end example
28513
28514 For example, you can set characters to be written in red with
28515 black background and underscore, you can call:
28516
28517 @example
28518 (set-character-attribute con '(red black underscore))
28519 @end example
28520
28521 That the options may seem rather limited in the age of
28522 full-color bitmap displays. That's what it used to be, young lads.
28523 @end deffn
28524
28525 @deffn {Generic function} reset-character-attribute console
28526 @c MOD text.console
28527 Reset character attributes to the default.
28528 @end deffn
28529
28530 @deffn {Generic function} with-character-attribute console attrs thunk
28531 @c MOD text.console
28532 Sets the console's attributes to @var{attrs} and calls @var{thunk},
28533 then restores the attributes. Even if @var{thunk} throws an error,
28534 attributes are restored.
28535
28536 Note: You should be able to nest this, but currently nesting
28537 isn't working.
28538 @end deffn
28539
28540
28541 @c ----------------------------------------------------------------------
28542 @node CSV tables, Calculate difference of text streams, Text terminal control, Library modules - Utilities
28543 @section @code{text.csv} - CSV tables
28544 @c NODE CSVテーブル, @code{text.csv} - CSVテーブル
28545
28546 @deftp {Module} text.csv
28547 @mdindex text.csv
28548 @c EN
28549 Provides a function to parse/generate CSV (comma separated value) tables,
28550 including the format defined in RFC4180. You can customize the
28551 separator and quoter character to deal with variations of CSV formats.
28552
28553 CSV table is consisted by a series of @var{records}, separated by
28554 a newline. Each record contains number of @var{fields}, separated
28555 by a separator character (by default, a comma). A field can contain
28556 comma or newline if quoted, i.e. surrounded by double-quote characters.
28557 To include double-quote character in a quoted field, use two
28558 consecutive double-quote character. Usually, the whitespaces around
28559 the field are ignored.
28560 @c JP
28561 RFC4180に定義されたフォーマットを含む、
28562 CSV (カンマ区切りの値) の表をパーズ/生成するための手続きを提供します。
28563 区切り文字やクオート文字をカスタマイズすることで、CSVに似たフォーマットを
28564 広くカバーすることができます。
28565
28566 CSV の表は、改行で区切られた @var{record} の連続で構成されます。
28567 それぞれのレコードは、区切り文字(デフォルトではカンマ)で区切られた
28568 複数の @var{field} を含みます。フィールドは、クォートされている
28569 (二重引用符で囲まれている)場合は、カンマや改行を含むことができます。
28570 クォートされたフィールドに二重引用符を含めるには、2つの連続する
28571 二重引用符を使います。通常、フィールドの前後の空白は無視されます。
28572 @c COMMON
28573
28574 @c EN
28575 Since use cases of CSV-like files vary, we provide layered API
28576 to be combined flexibly.
28577 @c JP
28578 CSV様のファイルの使われ方は多様なので、このモジュールでは柔軟に組み合わせることが出来る
28579 多層的なAPIを提供します。
28580 @c COMMON
28581 @end deftp
28582
28583 @c EN
28584 @subheading Low-level API
28585 @c JP
28586 @subheading 低レベルAPI
28587 @c COMMON
28588
28589 @c EN
28590 The bottom layer of API is to convert text into list of lists and vice versa.
28591 @c JP
28592 一番下の層のAPIは、テキストとリストのリストとを相互変換するものです。
28593 @c COMMON
28594
28595 @defun make-csv-reader separator :optional (quote-char #\")
28596 @c MOD text.csv
28597 @c EN
28598 Returns a procedure with one optional argument, an input port.
28599 When the procedure is called, it reads one record from the port
28600 (or, if omitted, from the current input port)
28601 and returns a list of fields.
28602 If input reaches EOF, it returns EOF.
28603 @c JP
28604 入力ポートを省略可能引数として取る手続きを返します。
28605 手続きが呼ばれると、ポート(省略された場合は現在の入力ポート)からレコードを1つ読み込み、
28606 フィールドのリストを返します。入力ポートが EOF に達すると、EOF を返します。
28607 @c COMMON
28608 @end defun
28609
28610 @defun make-csv-writer separator :optional newline (quote-char #\") special-char-set
28611 @c MOD text.csv
28612 @c EN
28613 Returns a procedure with two arguments, output port and
28614 a list of fields. When the procedure is called, it
28615 outputs a @var{separator}-separated fields with proper escapes,
28616 to the output port. Each field value must be a string.
28617 The separator argument can be a character or a string.
28618 @c JP
28619 出力ポートとフィールドのリストの2つの引数を取る手続きを返します。
28620 手続きが呼ばれると、@var{separator} で区切られたフィールドを
28621 正しくエスケープして出力ポートに出力します。各フィールドの値は文字列でなければなりません。
28622 @var{separator}は文字または文字列です。
28623 @c COMMON
28624
28625 @c EN
28626 You can also specify the record delimiter
28627 string by @var{newline}; for example, you can pass @code{"\r\n"}
28628 to prepare a file to be read by Windows programs.
28629 @c JP
28630 レコードの区切り文字列を@var{newline} で指定することもできます。例えば、ファイルが Windows の
28631 プログラムでも読めるように、@code{"\r\n"} を渡すことができます。
28632 @c COMMON
28633
28634 @c EN
28635 The output of field is quoted when it contains special characters---
28636 which automatically includes characters
28637 in @var{separator}, @var{quote-char} and @var{newline} argument,
28638 plus the characters in the char-set given to @var{special-char-set};
28639 its default is @code{#[;\s]}.
28640 @c JP
28641 フィールドの出力は、その中に特殊文字が含まれていた場合にクオートされます。
28642 @var{separator}, @var{quote-char}, @var{newline}に含まれる文字は
28643 自動的に特殊文字と認識されます。さらに
28644 @var{special-char-set}に文字集合を渡すと、それも特殊文字として扱われます。
28645 省略時は@code{#[;\s]}が使われます。
28646 @c COMMON
28647 @end defun
28648
28649 @c EN
28650 @subheading Middle-level API
28651 @c JP
28652 @subheading 中レベルAPI
28653 @c COMMON
28654
28655 @c EN
28656 Occasionally, CSV files generated from spreadsheet contains
28657 superfluous rows/columns and we need to make sense of them.
28658 Here are some utilities to help them.
28659 @c JP
28660 スプレッドシート等で作成されたCSVファイルはしばしば、
28661 不要な行や列を含んでいたり、
28662 行や列の内容から有効なデータの場所を探したりする必要があります。
28663 そのために役に立つユーティリティが用意してあります。
28664 @c COMMON
28665
28666 @c EN
28667 A typical format of such spreadsheet-generated CSV file has
28668 the following properties:
28669 @c JP
28670 スプレッドシート等によって生成される典型的なCSVには以下の特徴があります。
28671 @c COMMON
28672
28673 @enumerate
28674 @item
28675 @c EN
28676 There's a ``header row'' near the top; not necessarily the very
28677 first row, but certainly it comes before any real data. It signifies
28678 the meaning of each column of the data.
28679 There may be superfluous columns inserted just for cosmetics,
28680 and sometimes the order of columns are changed when the original spreadsheet
28681 is edited. So we need some
28682 flexibility to interpret the input data.
28683 @c JP
28684 最初の方に、「ヘッダ行」があります。一番最初の行とは限りませんが、
28685 データの実体より前に現れ、データの各列の意味を決めます。
28686 しばしば、見た目のためだけに余分な列が挿入されたり、
28687 編集によって列が入れ替わったりすることもあるので、
28688 ヘッダ行を見てどの列に何があるか判断する必要があります。
28689 @c COMMON
28690
28691 @item
28692 @c EN
28693 ``Record rows'' follow the header row. It contains actual data.
28694 There may be superfluous rows inserted just for cosmetics.
28695 Also, it's often the case that the end of data isn't marked clearly
28696 (you find large number of rows of empty strings, for example).
28697 @c JP
28698 ヘッダ行の後に続く「レコード行」。ここにデータの実体があります。
28699 見た目のためだけに余分な行が挿入されていることもあります。
28700 また、データの終わりがきちんと示されていないことも多いです (例えば、
28701 CSVの末尾に全ての列が空文字列である行がぞろぞろとくっついている、等。)
28702 @c COMMON
28703 @end enumerate
28704
28705 @c EN
28706 The main purpose of middle-level CSV parser is to take the output
28707 of low-level parser, which is a list of lists of strings, and
28708 find the header row, and then convert the subsequent record rows
28709 into tuples according to the header row. A tuple is just a list of
28710 strings, but ordered in the same way as the specified header spec.
28711 @c JP
28712 中レベルCSVパーザの主目的は、低レベルパーザの出力である文字列のリストのリストを
28713 受け取って、ヘッダ行を探し出し、続くレコード行をヘッダ行の内容に沿って
28714 タプルに変換することにあります。ここで、タプルは単なる文字列のリストですが、
28715 指定されたヘッダ仕様に沿った順序で並べてあるものとします。
28716 @c COMMON
28717
28718 @defun csv-rows->tuples rows header-specs :key required-slots allow-gap?
28719 @c MOD text.csv
28720 @c EN
28721 Convert input rows (a list of lists of strings)
28722 to a list of tuples.
28723 A tuple is a list of slot values.
28724
28725 First, it looks for a header row that
28726 matches the given @var{header-spec}. Once the header row is found,
28727 parse the subsequent rows as record row according to the header
28728 and convert them to tuples.
28729 If no header is found, @code{#f} is returned.
28730 @c JP
28731 入力行(文字列のリスト)のリストを、タプルのリストに変換します。
28732 タプルはスロットの値のリストです。
28733
28734 まず@var{header-spec}にマッチするヘッダ行が探されます。ヘッダ行が見つかったら、
28735 それにしたがって後続の行をレコード行として解釈し、各行をタプルへと変換します。
28736 ヘッダ行が見つからなければ、@code{#f}が返されます。
28737 @c COMMON
28738
28739 @c EN
28740 @var{Header-specs} is a list of header spec, each of which can be either
28741 a string, a regexp, or a predicate on a string. If it's a string,
28742 a column that exactly matches the string is picked. If it's a regexp,
28743 a column that matches the regexp is picked. And if it's a predicate,
28744 as you might have already guessed, a column that satisfies the predicate
28745 is picked.
28746
28747 The order fo @var{header-specs} determines the order of columns of
28748 output tuples.
28749 @c JP
28750 @var{header-specs}はヘッダ仕様のリストです。各要素は文字列、正規表現、
28751 あるいは文字列を取る述語手続きのいずれかです。文字列の場合、その文字列と正確に
28752 一致する内容を持つ列が選ばれます。正規表現なら内容がそれと一致する列、
28753 述語手続きなら、内容がその述語を満たすような列がそれぞれ選ばれます。
28754
28755 @var{header-specs}に現れる順番が、出力タプルの列の順番を決めます。
28756 @c COMMON
28757
28758 @c EN
28759 @var{Required-slots} determines if the input row is a valid record row
28760 or not. The structure of @var{required-slots} is as follows:
28761 @c JP
28762 @var{required-slots}は、入力行が有効なレコード行かそうでないかを決めます。
28763 @var{required-slots}の構造は以下のとおりです。
28764 @c COMMON
28765
28766 @example
28767 <required-slots> : (<spec> ...)
28768 <spec> : <header-spec> | (<header-spec> <predicate>)
28769 @end example
28770
28771 @c EN
28772 The @code{<header-spec>} compared to the elements of @var{header-slot}
28773 (by @code{equal?}) to figure out which columns to check. A single
28774 @code{<header-spec>} in @code{<spec>} means that the column shouldn't be
28775 empty for a valid record row. If @var{<spec>} is a list of
28776 @code{<header-spec>} and @code{<predicate>}, then the value of the
28777 column corresponds to the @var{<header-spec>} is passed to @var{<predicate>}
28778 to determine if it's a valid record row.
28779
28780 If @var{required-slots} is omitted or an empty list, any row with
28781 at least one non-empty column to be included in the tuple.
28782 @c JP
28783 @code{<header-spec>}はどの列の要素をチェックすべきかを指定します。
28784 @var{header-slot}に現れる要素のいずれかと@code{equal?}でなければなりません。
28785 @code{<header-spec>}だけが@code{<spec>}として与えられていた場合は、
28786 その列が空であってはいけない、ということを意味します。
28787 @code{<header-spec>}と@code{<predicate>}が与えられた場合は、
28788 レコード行の該当列の値(文字列)が述語手続き@code{<predicate>}に与えられ、
28789 それが偽を返したらその行は有効でないということになります。
28790 @c COMMON
28791
28792 @c EN
28793 If @var{allow-gap?} is @code{#t}, it keeps reading rows until the end,
28794 skipping invalid rows. If @var{allow-gap?} is @code{#f} (default),
28795 it stops reading once it sees an invalid row after headers.
28796 @c JP
28797 @var{allow-gap?}が@code{#t}であった場合、無効な行を飛ばしながら、
28798 入力データは最後まで処理されます。@var{allow-gap?}が@code{#f}であった場合(デフォルト)は、
28799 無効な行が出てきた時点で処理を打ちきります。
28800 @c COMMON
28801
28802 @c EN
28803 Let's see an example. Suppose we have the following CSV file as
28804 @file{data.csv}. It has extra rows and columns, as is often seen
28805 in spreadsheet-exported files.
28806 @c JP
28807 例を見てみましょう。次のデータが@file{data.csv}というファイルに書かれているとします。
28808 スプレッドシートからエクスポートされるデータによくあるように、不要な行や列が混ざっています。
28809 @c COMMON
28810
28811 @smallexample
28812 ,,,,,,,,
28813 "Exported data",,,,,,,,
28814 ,,,,,,,,
28815 ,,Year,Country,,Population,GDP,,Note
28816 ,,1958,"Land of Lisp",,39994,"551,435,453",,
28817 ,,1957,"United States of Formula Translators",,115333,"4,343,225,434",,Estimated
28818 ,,1959,"People's Republic of COBOL",,82524,"3,357,551,143",,
28819 ,,1970,"Kingdom of Pascal",,3785,,,"GDP missing"
28820 ,,,,,,,,
28821 ,,1962,"APL Republic",,1545,"342,335,151",,
28822 @end smallexample
28823
28824 @c EN
28825 You can extract tuples of Country, Year, GDP and Population,
28826 as follows:
28827 @c JP
28828 ここから、Country, Year, GDP, Populationの値からなるタプルのリストを
28829 次のとおり取り出せます。
28830 @c COMMON
28831
28832 @smallexample
28833 (use text.csv)
28834 (use gauche.generator)
28835
28836 (call-with-input-file "data.csv"
28837 (^p (csv-rows->tuples
28838 (generator->list (cute (make-csv-reader #\,) p))
28839 '("Country" "Year" "GDP" "Population"))))
28840 @result{}
28841 (("Land of Lisp" "1958" "551,435,453" "39994")
28842 ("United States of Formula Translators" "1957" "4,343,225,434" "115333")
28843 ("People's Republic of COBOL" "1959" "3,357,551,143" "82524")
28844 ("Kingdom of Pascal" "1970" "" "3785"))
28845 @end smallexample
28846
28847 @c EN
28848 Note that irrelevant rows are skipped, and columns in the results
28849 are ordered as specified in the @var{header-specs}.
28850 @c JP
28851 無関係な行は無視されており、また結果の列は@var{header-specs}に渡した順序に
28852 整列されていることに注目してください。
28853 @c COMMON
28854
28855 @c EN
28856 Since there's a gap (empty row) after the ``Kingdom of Pascal'' entry,
28857 @code{csv-rows->tuples} stops processing there by default. If you want
28858 to include ``APL Republic'', you have to pass @code{:allow-gap? #t}
28859 to @code{csv-rows->tuples}.
28860 @c JP
28861 ``Kingdom of Pascal''の列の後にギャップ(空の列)があるため、
28862 @code{csv-rows->tuples}はそこで処理を打ち切っています。
28863 ギャップの後の``APL Republic''まで含めたければ、@code{csv-rows->tuples}に
28864 @code{:allow-gap? #t}を渡してください。
28865 @c COMMON
28866
28867 @c EN
28868 The next example gives @code{:required-slots} option to eliminate
28869 rows with missing some of Year, Country or GDP---thus ``Kingdom of Pascal''
28870 is omitted from the result, while ``APL Republic'' is included
28871 because of @code{:allow-gap?} argument.
28872 (It also checks Year has exactly 4 digits.)
28873 @c JP
28874 次の例では、@code{:required-slots}引数を与えて、
28875 Year、Country、GDPのデータの一つ以上が欠けている行を除外しています。
28876 したがって``Kingdom of Pascal''は結果から除かれます。一方、
28877 @code{:allow-gap?}引数のために``APL Republic''が含まれます。
28878 (この例ではYearが4桁ぴったりの数値であるかどうかもチェックしています。)
28879 @c COMMON
28880
28881 @smallexample
28882 (call-with-input-file "data.csv"
28883 (^p (csv-rows->tuples
28884 (generator->list (cute (make-csv-reader #\,) p))
28885 '("Country" "Year" "GDP" "Population")
28886 :required-slots '(("Year" #/^\d@{4@}$/) "Country" "GDP")
28887 :allow-gap? #t)))
28888 @result{}
28889 (("Land of Lisp" "1958" "551,435,453" "39994")
28890 ("United States of Formula Translators" "1957" "4,343,225,434" "115333")
28891 ("People's Republic of COBOL" "1959" "3,357,551,143" "82524")
28892 ("APL Republic" "1962" "342,335,151" "1545"))
28893 @end smallexample
28894 @end defun
28895
28896 @c EN
28897 The following two procedures are ingredients of
28898 @code{csv-rows->tuples}:
28899 @c JP
28900 以下の二つの手続きは@code{csv-rows->tuples}の材料です。
28901 @c COMMON
28902
28903
28904 @defun make-csv-header-parser header-specs
28905 @c MOD text.csv
28906 @c EN
28907 Create a procedure that takes a row (a list of strings) and checks if
28908 if it matches the criteria specified by @var{header-specs}.
28909 (See @code{csv-rows->tuples} above about @var{header-specs}.)
28910 If the input satisfies the spec, it returns a permuter vector that maps
28911 the tuple positions to the input column numbers.
28912 Otherwise, it returns @code{#f}.
28913 @c JP
28914 行(文字列のリスト)を受け取り、それが@var{header-specs}で指定される条件に
28915 一致するかどうかを調べます。
28916 (@var{header-specs}については上の@code{csv-rows->tuples}を見てください。)
28917 もし引数が条件を満たしたなら、置換ベクタを返します。
28918 置換ベクタはタプルの位置を入力行の列番号へとマップするもので。
28919 一致しなかった場合は@code{#f}を返します。
28920 @c COMMON
28921
28922 @c EN
28923 The permuter vector is a vector of integers,
28924 where K-th element being I means the K-th item of the tuple should be
28925 taken from I-th column.
28926 @c JP
28927 置換ベクタは整数のベクタです。K番目の要素がIであることは、
28928 タプルのK番目の要素が入力のI番目の列から取られることを示します。
28929 @c COMMON
28930
28931 @c EN
28932 Let's see the example. Suppose we know that the input contains
28933 the following row as the header row:
28934 @c JP
28935 例を見てみましょう。入力に、以下の形の行がヘッダ行として含まれていることが
28936 わかっているとします。
28937 @c COMMON
28938
28939 @example
28940 (define *input-row*
28941 '("" "" "Year" "Country" "" "Population" "GDP" "Notes"))
28942 @end example
28943
28944 @c EN
28945 We want to detect that row, but we only needs
28946 Country, Year, GDP and Population columns, in that order. So we create
28947 a header parser as follows:
28948 @c JP
28949 こういう形の行を見つけたいわけですが、取り出すデータとしては、
28950 @code{Country}、@code{Year}、@code{GDP}、@code{Population}だけが
28951 この順で必要であるとします。この場合、ヘッダパーザを
28952 次のとおり構成できます。
28953 @c COMMON
28954
28955 @example
28956 (define header-parser
28957 (make-csv-header-parser '("Country" "Year" "GDP" "Population")))
28958 @end example
28959
28960 @c EN
28961 Applying this header parser to the input data returns the permuter vector:
28962 @c JP
28963 このヘッダパーザを想定される入力行に適用すれば、置換ベクタが返ってきます:
28964 @c COMMON
28965
28966 @example
28967 (header-parser *input-row*)
28968 @result{} #(3 2 6 5)
28969 @end example
28970
28971 @c EN
28972 It means, the first item of tuple (Country) is in the 3rd column of the input,
28973 the second item of tuple (Year) is in the 2nd column of the input,
28974 and so on. This permuter vector can be used to parse record rows to
28975 get tuples.
28976 @c JP
28977 返り値の意味は、タプルの第0要素(@code{Country})は入力の第3列にあり、
28978 タプルの第1要素(@code{Year})は入力の第2列にある、といった具合です。
28979 置換ベクタはレコード行をパーズしてタプルを生成するのに使えます。
28980 @c COMMON
28981 @end defun
28982
28983 @defun make-csv-record-parser header-slots permuter :optional required-slots
28984 @c MOD text.csv
28985 @c EN
28986 Create a procedure that converts one input row into a tuple.
28987
28988 @var{Permuter} is the vector returned by @code{make-csv-header-parser}.
28989
28990 See @code{cvs-rows->tuples} above for @var{header-slots} and
28991 @var{required-slots} arguments.
28992 @c JP
28993 入力の1行をタプルへと変換する手続きを作って返します。
28994
28995 @var{permuter}は@code{make-csv-header-parser}が返す置換ベクタです。
28996
28997 @var{header-slots}及び@var{required-slots}引数については
28998 上の@code{cvs-rows->tuples}を見てください。
28999 @c COMMON
29000 @end defun
29001
29002
29003 @c ----------------------------------------------------------------------
29004 @node Calculate difference of text streams, EDN parsing and construction, CSV tables, Library modules - Utilities
29005 @section @code{text.diff} - Calculate difference of text streams
29006 @c NODE テキストストリームの相違点を計算する, @code{text.diff} - テキストストリームの相違点を計算する
29007
29008 @deftp {Module} text.diff
29009 @mdindex text.diff
29010 @c EN
29011 This module calculates the difference of two text streams or strings,
29012 using @code{util.lcs} (@pxref{The longest common subsequence}).
29013 @c JP
29014 このモジュールでは、@code{util.lcs} (@ref{The longest common subsequence}参照)を
29015 使って、2つのテキストストリーム、あるいは2つの文字列の相違点を計算します。
29016 @c COMMON
29017 @end deftp
29018
29019 @defun diff src-a src-b :key reader eq-fn
29020 @c MOD text.diff
29021 @c EN
29022 Generates an "edit list" from text sources @var{src-a} and @var{src-b}.
29023
29024 Each of text sources, @var{src-a} and @var{src-b}, can be either an input
29025 port or a string. If it is a string, it is converted to a string input
29026 port internally. Then, the text streams from both sources are converted
29027 to sequences by calling @var{reader} repeatedly on them; the default
29028 of @var{reader} is @code{read-line}, and those sequences are
29029 passed to @code{lcs-edit-list} to calculate the edit list.
29030 The equality function @var{eq-fn} is also passed to @code{lcs-edit-list}.
29031
29032 An edit list is a set of commands that turn the text sequence
29033 from @code{src-a} to the one from @code{src-b}.
29034 See the description of @code{lcs-edit-list} for
29035 the detailed explanation of the edit list.
29036 @c JP
29037 テキストソース@var{src-a}と@var{src-b}から``編集リスト''を生成します。
29038
29039 それぞれのテキストソース、@var{src-a}と@var{src-b}は入力ポートか文字列です。
29040 もし文字列であれば、それは内部的に文字列ポートに変換されます。
29041 そして、2つのソースからのテキストストリームは、それらに対して@var{reader}を繰り返し
29042 呼ぶことによってシーケンスに変換されます。デフォルトの@var{reader}は@var{read-line}で、
29043 2つのシーケンスは編集リストを計算するために@code{lcs-edit-list}に渡されます。
29044 @code{lcs-edit-list}には、等値を検査する関数@var{eq-fn}も渡されます。
29045
29046 編集リストとは、@code{src-a}から@code{src-b}へテキストシーケンスを
29047 変更するためのコマンドのセットです。編集リストの詳細な説明は、
29048 @code{lcs-edit-list}を参照してください。
29049 @c COMMON
29050
29051 @example
29052 (diff "a\nb\nc\nd\n" "b\ne\nd\nf\n")
29053 @result{}
29054 (((- 0 "a"))
29055 ((- 2 "c") (+ 1 "e"))
29056 ((+ 3 "f")))
29057 @end example
29058 @end defun
29059
29060 @defun diff-report src-a src-b :key reader eq-fn writer
29061 @c MOD text.diff
29062 @c EN
29063 A convenience procedure to take the diff of two text sources
29064 and display the result nicely. This procedure calls @code{lcs-fold}
29065 to calculate the difference of two text sources. The meanings of
29066 @var{src-a}, @var{src-b}, @var{reader} and @var{eq-fn} are the
29067 same as @code{diff}'s.
29068 @c JP
29069 2つのテキストソースのdiffをとって、その結果をきれいに表示するための
29070 簡易手続きです。この手続きは、2つのテキストソースの相違点を計算する
29071 ために@code{lcs-fold}を呼び出します。@var{src-a}、@var{src-b}、
29072 @var{reader}、@var{eq-fn}の意味は、@code{diff}の場合と同じです。
29073 @c COMMON
29074
29075 @c EN
29076 @var{Writer} is a procedure that takes two arguments, the text element
29077 and a type, which is either a symbol @code{+},
29078 a symbol @code{-}, or @code{#f}. If the text element is only
29079 in @var{src-a}, @var{writer} is called with the element and
29080 @code{-}. If the text element is only in @var{src-b},
29081 it is called with the element and @code{+}. If the text element
29082 is in both sources, it is called with the element and
29083 @code{#f}. The default procedure of @var{writer} prints
29084 the passed text element to the current output port
29085 in unified-diff-like format:
29086 @c JP
29087 @var{writer}は2つの引数、テキスト要素とタイプ(シンボル@code{+}、
29088 シンボル@code{-}、あるいは@code{#f}のいずれか)を取る手続きです。
29089 テキスト要素が@var{src-a}にしかない場合は、@var{writer}がそのテキスト要素と
29090 @code{-}とともに呼ばれます。テキスト要素が@var{src-b}にしかない場合は、
29091 @var{writer}はそのテキスト要素と@code{+}とともに呼ばれます。
29092 テキスト要素が両方のソースにある場合は、@var{writer}はそのテキスト要素と
29093 @code{#f}とともに呼ばれます。@var{writer}のデフォルトの手続きは、
29094 渡されたテキスト要素を現在の出力ポートにユニファイドdiffのようなフォーマットで
29095 出力します。
29096 @c COMMON
29097 @example
29098 (diff-report "a\nb\nc\nd\n" "b\ne\nd\nf\n")
29099 @end example
29100 displays:
29101 @example
29102 - a
29103 b
29104 - c
29105 + e
29106 d
29107 + f
29108 @end example
29109 @end defun
29110
29111 @defun diff-report/context src-a src-b :key reader eq-fn writer context-size
29112 @c MOD text.diff
29113 @c EN
29114 Produce a human-friendly difference of two text sources like
29115 @code{diff-report}, but in the ``context diff'' format.
29116 @c JP
29117 @code{diff-report}と同じように、二つのテキストソースの差違を出力しますが、
29118 コンテキスト形式を使います。
29119 @c COMMON
29120
29121 @example
29122 (diff-report/context "a\nb\nc\nd\n" "b\ne\nd\nf\n")
29123 @end example
29124 @c EN
29125 displays:
29126 @c JP
29127 は次を出力します:
29128 @c COMMON
29129 @example
29130 ***************
29131 *** 1,4 ****
29132 - a
29133 b
29134 ! c
29135 d
29136 --- 1,4 ----
29137 b
29138 ! e
29139 d
29140 + f
29141 @end example
29142
29143 @c EN
29144 This calls @code{lcs-edit-list/context} to get a context diff of lines,
29145 then format it in the same way as @code{diff -c} output.
29146 (@xref{The longest common subsequence}, for the details of
29147 @code{lcs-edit-list/context}.)
29148 @c JP
29149 この手続きは@code{lcs-edit-list/context}を呼んでコンテキストdiffを得て、
29150 それを@code{diff -c}と同じ形式にして出力します。
29151 @c COMMON
29152
29153 @c EN
29154 Each ``hunk'' (a chunk containing difference)
29155 is preceded by a separater @code{***************},
29156 followed by the excerpt from @var{src-a}, then the excerpt form @var{src-b},
29157 each preceded by the header showing the line number of that excerpts
29158 (start and end line, inclusive, 1-based).
29159 @c JP
29160 各 ``hunk'' (差異を含む塊)はセパレータ@code{***************}で始まり、
29161 その後に@var{src-a}からの抜粋、そして@var{src-b}からの抜粋が続きます。
29162 各抜粋の先頭には、そのhunkの範囲を示す行番号が出力されます
29163 (開始と終了の行番号、どちらも範囲に含まれる、最初の行は1)。
29164 @c COMMON
29165
29166 @c EN
29167 In the excerpts, the line that's deleted from @var{src-a} is prefixed
29168 with @code{-}, the line that's inserted into @var{src-b} is prefixed
29169 with @code{+}, and the line changed is prefixed with @code{!}.
29170 @c JP
29171 抜粋の中では、@var{src-a}から削除された行の前に@code{-}が、
29172 @var{src-b}に挿入された行の前に@code{+}が、そして置き換えられた行の前に@code{!}が、
29173 それぞれ付加されます。
29174 @c COMMON
29175
29176 @c EN
29177 If the hunk only consists of either insertions or deletions, the other
29178 side of excerpt is omitted.
29179 @c JP
29180 1つのhunkが、挿入のみ、または削除のみで構成されている場合、
29181 変更のない方は抜粋が省略されます。
29182 @c COMMON
29183
29184 @example
29185 (diff-report/context "a\nb\nc\n" "a\nc\n")
29186 @r{prints:}
29187 ***************
29188 *** 1,3 ****
29189 a
29190 - b
29191 c
29192 --- 1,2 ----
29193 @end example
29194
29195 @c EN
29196 As a special case, if one of the source is empty, its header is shown
29197 as zero-th line:
29198 @c JP
29199 特別な場合として、一方のソースが空だった場合、その抜粋のヘッダの行番号は0となります。
29200 @c COMMON
29201
29202 @example
29203 (diff-report/context "" "a\nb\nc\n")
29204 @r{prints:}
29205 ***************
29206 *** 0 ****
29207 --- 1,3 ----
29208 + a
29209 + b
29210 + c
29211 @end example
29212
29213 @c EN
29214 The @var{reader}, @var{writer} and @var{eq-fn} keyword arguments are the
29215 same as @code{diff-report}. The @var{context-size} keyword argument
29216 specifies the maximum unchanged lines attached to each hunk to show the
29217 context.
29218 @c JP
29219 @var{reader}、@var{writer}、@var{eq-fn}キーワード引数の意味は
29220 @code{diff-report}と同じです。@var{context-size}キーワード引数は
29221 各hunkの前後に文脈表示のために付加される、変更のなかった行の最大数を指定します。
29222 @c COMMON
29223 @end defun
29224
29225 @defun diff-report/unified src-a src-b :key reader eq-fn writer context-size
29226 @c MOD text.diff
29227 @c EN
29228 Like @code{diff-report/context}, but use ``unified diff'' format,
29229 same as @code{diff -u}.
29230 @c JP
29231 @code{diff-report/context}と似ていますが、@code{diff -u}と同じ
29232 「unified diff」形式で結果を表示します。
29233 @c COMMON
29234
29235 @example
29236 (diff-report/unified "a\nb\nc\nd\n" "a\nx\nd\n")
29237 @r{prints:}
29238 @@@@ -1,4 +1,3 @@@@
29239 a
29240 -b
29241 -c
29242 +x
29243 d
29244 @end example
29245
29246 @c EN
29247 Each ``hunk'' begins with the header:
29248 @c JP
29249 各hunkは次のヘッダで始まります:
29250 @c COMMON
29251 @example
29252 @@@@ -p,q +r,s @@@@
29253 @end example
29254 @c EN
29255 where @var{p} is the start line number in @var{src-a},
29256 @var{q} is the length of the hunk in @var{src-a},
29257 @var{r} is the start line number in @var{src-b},
29258 and @var{s} is the length of the hunk in @var{src-b}.
29259 @c JP
29260 ここで、@var{p}は@var{src-a}におけるhunkの開始行、
29261 @var{q}は@var{src-a}におけるhunkの長さ、
29262 @var{r}は@var{src-b}におけるhunkの開始行、
29263 @var{s}は@var{src-b}におけるhunkの長さです。
29264 @c COMMON
29265
29266 @c EN
29267 The line-number is 1-based.
29268 If the length of the hunk is 1, it is omitted.
29269 @c JP
29270 行番号は1から始まります。また、hunkの長さが1の場合、それは省略されます。
29271 @c COMMON
29272
29273 @c EN
29274 The lines deleted from @var{src-a} has @code{-} prefix,
29275 the ones inserted into @var{src-b} has @code{+} prefix,
29276 and unchanged lines has a space prefix.
29277 @c JP
29278 @var{src-a}から削除された行には@code{-}が、
29279 @var{src-b}に追加された行には@code{+}が、
29280 そして変更のない行にはスペースが付加されます。
29281 @c COMMON
29282
29283 @c EN
29284 As a special case, if either of sources is empty, both of its start index and
29285 length are shown as @code{0}.
29286 @c JP
29287 特別な場合として、どちらかの入力が空だった場合、その開始行と長さはともに0となります。
29288 @c COMMON
29289
29290 @example
29291 (diff-report/unified "a\nb\nc\n" "")
29292 @r{prints:}
29293 @@@@ -1,3 +0,0 @@@@
29294 -a
29295 -b
29296 -c
29297 @end example
29298
29299 @c EN
29300 The @var{reader}, @var{eq-fn}, @code{writer}, and @var{context-size}
29301 keyword arguments are the same as @code{diff-report/context}.
29302 @c JP
29303 @var{reader}、@var{eq-fn}、@var{writer}、@var{context-size}キーワード引数は
29304 @code{diff-report/context}と同じです。
29305 @c COMMON
29306
29307 @c EN
29308 This is used to show the difference of test results in @code{test*/diff}
29309 (@pxref{Unit testing}).
29310 @c JP
29311 この手続きは@code{test*/diff}でテスト結果との差異を示すのに使われています
29312 (@ref{Unit testing}参照)。
29313 @c COMMON
29314 @end defun
29315
29316
29317 @c ----------------------------------------------------------------------
29318 @node EDN parsing and construction, Running external editor, Calculate difference of text streams, Library modules - Utilities
29319 @section @code{text.edn} - EDN parsing and construction
29320 @c NODE EDNのパーズと構築, @code{text.edn} - EDNのパーズと構築
29321
29322 @deftp {Module} text.edn
29323 @mdindex text.edn
29324 @c EN
29325 EDN (Extensible Data Notation) is a subset of Clojure literals
29326 for data exchange. This module provides utilities to read and write EDN
29327 format. See @url{https://github.com/edn-format/edn} for the details of EDN.
29328 @c JP
29329 EDN (Extensible Data Notation)はデータ交換用に定められた、
29330 Clojureのリテラル構文のサブセットです。このモジュールはEDNの読み書きをする
29331 ユーティリティを提供します。EDNの詳細については
29332 @url{https://github.com/edn-format/edn}を参照してください。
29333 @c COMMON
29334
29335 @multitable @columnfractions .2 .2 .6
29336 @item EDN @tab Gauche @tab Note
29337 @item @code{true} @tab @code{#t} @tab
29338 @item @code{false} @tab @code{#f} @tab
29339 @item @code{nil} @tab @code{nil}
29340 @c EN
29341 @tab Clojure's nil is not a symbol but a special value; since Clojure
29342 can't have a symbol named nil, we can map it to Gauche's symbol @code{nil}.
29343 @c JP
29344 @tab Clojureのnilはシンボルではなく特殊な値ですが、
29345 Clojureにはnilというシンボルは存在できないので、
29346 Gaucheのシンボル@code{nil}に対応させています。
29347 @c COMMON
29348 @item number @tab @code{<real>}
29349 @c EN
29350 @tab Integers and floating point numbers.
29351 The @code{N} and @code{M} suffixes in Clojure are ignored.
29352 @c JP
29353 @tab 整数と浮動小数点数。
29354 Clojureの@code{N}と@code{M}サフィックスは無視されます。
29355 @c COMMON
29356 @item symbol @tab @code{<symbol>}
29357 @c EN
29358 @tab Clojure's symbol name has some restrictions, so not all Gauche symbols
29359 map to EDN symbols.
29360 Clojure's namespace-prefixed symbol, e.g. @code{foo/bar} simply maps to
29361 Gauche's symbol @code{foo/bar}; we provide utility procedure to extract
29362 namespace and basename parts.
29363 @c JP
29364 @tab Clojureのシンボル名には制約があるので、
29365 全てのGaucheのシンボルがEDNシンボルとして使えるわけではありません。
29366 Clojureの名前空間つきシンボル(例: @code{foo/bar}) はGauche側では
29367 単に@code{foo/bar}という名前を持つシンボルの扱いになります。
29368 この名前から名前空間とシンボル名を取り出すユーティリティが提供されます。
29369 @c COMMON
29370 @item keyword @tab @code{<keyword>}
29371 @c EN
29372 @tab Clojure has keywords distinct from symbols. They are mapped to Gauche's
29373 keywords (which is a subtype of symbols).
29374 Gauche's keywords can also be symbols, but
29375 no Clojure symbols begin with @code{:} so there won't be a conflict.
29376 @c JP
29377 @tab Clojureはキーワードとシンボルを別の型にしています。
29378 ClojureキーワードはGaucheキーワード(シンボルのサブタイプ)に対応します。
29379 Clojureのシンボルは@code{:}で始まることはないので、混同が起きることはありません。
29380 @c COMMON
29381 @item list @tab @code{<list>}
29382 @c EN
29383 @tab Clojure lists are Gauche lists. Note that Clojure doesn't allow
29384 improper lists.
29385 @c JP
29386 @tab ClojureのリストはGaucheのリストになります。
29387 Clojureにはドットリスト(improper list)が無いことに注意してください。
29388 @c COMMON
29389 @item vector @tab @code{<vector>}
29390 @c EN
29391 @tab Clojure vectors are Gauche vectors.
29392 @c JP
29393 @tab ClojureのベクタはGaucheのベクタになります。
29394 @c COMMON
29395 @item map @tab @code{<hash-table>}
29396 @c EN
29397 @tab Clojure's map becomes Gauche's hashtable with @code{edn-comparator}
29398 for hashing and comparison.
29399 @c JP
29400 @tab Clojureのマップは、Gaucheでは@code{edn-comparator}をハッシュ関数と比較に
29401 使うハッシュテーブルになります。
29402 @c COMMON
29403 @item set @tab @code{<set>}
29404 @c EN
29405 @tab Clojure's set becomes Gauche's set with @code{edn-comparator}
29406 for comparison. @xref{R7RS sets} for interface of sets.
29407 @c JP
29408 @tab Clojureのセットは、Gaucheでは@code{edn-comparator}を比較に使う
29409 @code{<set>}オブジェクトになります。@code{<set>}については@xref{R7RS sets}参照。
29410 @c COMMON
29411 @item tagged object @tab @code{<edn-object>}
29412 @c EN
29413 @tab Tagged objects are mapped to @code{<edn-object>} by default.
29414 You can customize the parser/writer to map tagged objects with a
29415 specific tag to a specific Gauche objects.
29416 @c JP
29417 @tab タグつきオブジェクトはデフォルトで@code{<edn-object>}のインスタンスになります。
29418 タグ付きオブジェクトの解釈をカスタマイズして、特定のGaucheオブジェクトに結びつけることも
29419 できます。
29420 @c COMMON
29421 @end multitable
29422 @end deftp
29423
29424 @c EN
29425 @subheading Parsing
29426 @c JP
29427 @subheading パーザ
29428 @c COMMON
29429
29430 @deftp {Condition Type} <edn-parse-error>
29431 @c EN
29432 When the parser encounters an error, this condition is thrown.
29433 Inherits @code{<error>}.
29434 @c JP
29435 パーザのエラーはこのコンディションで通知されます。@code{<error>}を継承しています。
29436 @c COMMON
29437 @end deftp
29438
29439 @defun parse-edn :optional iport
29440 @c MOD text.edn
29441 @c EN
29442 Read one EDN representation from the given input port, and returns
29443 Gauche object created from it. If @var{iport} is omitted,
29444 current input port is assumed.
29445
29446 When the parser encounters unparsable sequence,
29447 it raises @code{<edn-parse-error>}.
29448
29449 Note that @var{iport} may be read ahead for characters. Suppose
29450 the input consists of @code{abc@{:a b@}}, i.e. a symbol immediately
29451 followed by a map. The parser need to read @code{@{} to know the
29452 end of the symbol. The read-ahead brace isn't pushed back
29453 to the @var{iport}. So it would be a problem if you keep reading
29454 more EDN subsequently. Use @code{parse-edn*} if you want to read
29455 multiple objects.
29456 @c JP
29457 EDN表現を与えられた入力ポートから読み込み、パーズ結果をGaucheオブジェクトとして
29458 返します。@var{iport}が省略された場合は現在の入力ポートが使われます。
29459
29460 パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
29461
29462 @var{iport}から文字が先読みされる可能性があることに注意してください。
29463 例えば入力が@code{abc@{:a b@}}、つまりシンボルの直後にマップが来ていたとします。
29464 パーザは@code{@{}まで読んでシンボルの終了を知り、シンボル@code{abc}を返しますが、
29465 その時点で読まれていた@code{@{}はポートに戻されないので、
29466 続けて@var{iport}からEDNを読む場合に問題となります。
29467 複数のEDNオブジェクトを読み込む場合は@code{parse-edn*}を使ってください。
29468 @c COMMON
29469 @end defun
29470
29471 @defun parse-edn* :optional iport
29472 @c MOD text.edn
29473 @c EN
29474 Read EDN representations repeatedly from the given input port
29475 and returns a list of them. If @var{iport} is omitted,
29476 current input port is assumed.
29477
29478 When the parser encounters unparsable sequence,
29479 it raises @code{<edn-parse-error>}.
29480 @c JP
29481 与えられた入力ポートから、EOFに達するまでEDN表現を読み込み、結果をGaucheオブジェクトの
29482 リストとして返します。@var{iport}が省略された場合は現在の入力ポートが使われます。
29483
29484 パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
29485 @c COMMON
29486 @end defun
29487
29488 @defun parse-edn-string str
29489 @c MOD text.edn
29490 @c EN
29491 A convenience procedure to parse EDN representation in a string @var{str},
29492 and returns the read object.
29493
29494 When the parser encounters unparsable sequence,
29495 it raises @code{<edn-parse-error>}.
29496 @c JP
29497 EDN表現を文字列から読み込む便利手続きです。
29498
29499 パーズが失敗した場合は@code{<edn-parse-error>}が投げられます。
29500 @c COMMON
29501
29502 @example
29503 (parse-edn-string "[1 2 (3 4) @{:a 5@}]")
29504 @result{} #(1 2 (3 4) #<hash-table general 0x1f05780>)
29505 @end example
29506 @end defun
29507
29508 @c EN
29509 @subheading Constructing
29510 @c JP
29511 @subheading 構築
29512 @c COMMON
29513
29514 @defun construct-edn obj :optional oport
29515 @c MOD text.edn
29516 @c EN
29517 Write out an EDN representation of object @var{obj}
29518 to the output port @var{oport}. If @var{oport} is omitted,
29519 current output port is assumed.
29520
29521 If @var{obj} contains an object that doesn't have a defined
29522 EDN representation, a generic function @var{edn-write} is called
29523 on it. See Customization heading below. If no method is defined for
29524 the object, an error is signaled.
29525 @c JP
29526 オブジェクト@var{obj}のEDN表現を出力ポート@var{oport}に書き出します。
29527 @var{oport}が省略された場合は現在の出力ポートが使われます。
29528
29529 @var{obj}中にEDNで表現できないオブジェクトがあった場合、
29530 ジェネリック関数@var{edn-write}が呼ばれます。下のカスタマイズの項を参照してください。
29531 適切なメソッドが定義されていなけばエラーが投げられます。
29532 @c COMMON
29533 @end defun
29534
29535 @defun construct-edn-string obj
29536 @c MOD text.edn
29537 @c EN
29538 Returns an EDN representation of @var{obj} in a string.
29539
29540 If @var{obj} contains an object that doesn't have a defined
29541 EDN representation, a generic function @var{edn-write} is called
29542 on it. See Customization heading below. If no method is defined for
29543 the object, an error is signaled.
29544 @c JP
29545 @var{obj}のEDN表現を文字列で返します。
29546
29547 @var{obj}中にEDNで表現できないオブジェクトがあった場合、
29548 ジェネリック関数@var{edn-write}が呼ばれます。下のカスタマイズの項を参照してください。
29549 適切なメソッドが定義されていなけばエラーが投げられます。
29550 @c COMMON
29551
29552 @example
29553 @end example
29554 (construct-edn-string '#(1 2 "abc"))
29555 @result{} "[1 2 \"abc\"]"
29556 @end defun
29557
29558 @c EN
29559 @subheading Utilities
29560 @c JP
29561 @subheading ユーティリティ
29562 @c COMMON
29563
29564 @defun edn-equal? a b
29565 @c MOD text.edn
29566 @c EN
29567 Test equality of two objects that are read from EDN representation.
29568 @c JP
29569 EDN表現から読まれた二つのオブジェクトが、EDNのセマンティクスで等しいかどうかを調べます。
29570 @c COMMON
29571 @end defun
29572
29573 @defvar edn-comparator
29574 @c MOD text.edn
29575 @c EN
29576 A comparator that uses @code{edn-equal?} for the equality predicate.
29577 Corresponding has function is also included.
29578 EDN maps and sets become Gauche hash-tables and sets with this comparator.
29579 @c JP
29580 @code{edn-equal?}で等価性を判定する比較器です。ハッシュ関数も含まれます。
29581 EDNのマップとセットは、この比較器を使うGaucheのハッシュテーブルとセットになります。
29582 @c COMMON
29583 @end defvar
29584
29585 @defun edn-map key value @dots{}
29586 @defunx edn-set item @dots{}
29587 @c MOD text.edn
29588 @c EN
29589 Convenience procedures to create hash-tables and sets compatible
29590 for EDN.
29591 @c JP
29592 EDNに使えるハッシュテーブルとセットを構築する便利手続きです。
29593 @c COMMON
29594 @end defun
29595
29596 @deftp {Class} <edn-object>
29597 @clindex edn-object
29598 @c MOD text.edn
29599 @c EN
29600 EDN tagged object becomes an instance of this class by default.
29601 The instance has the following slots, both are immutable:
29602 @c JP
29603 EDNのタグつきオブジェクトは、デフォルトではこのクラスのインスタンスになります。
29604 以下のスロットがあります。どちらも変更不可です。
29605 @c COMMON
29606
29607 @defivar <edn-object> tag
29608 @c EN
29609 Object's tag. A symbol.
29610 @c JP
29611 シンボル。オブジェクトのタグです。
29612 @c COMMON
29613 @end defivar
29614
29615 @defivar <edn-object> payload
29616 @c EN
29617 Object's payload. Can be any object that can be representable in EDN.
29618 @c JP
29619 オブジェクトの内容です。EDNで表現可能なオブジェクト。
29620 @c COMMON
29621 @end defivar
29622
29623 @c EN
29624 For example, when you read @code{#myobject @{:a 1 :b 2@}},
29625 the tag is @code{myobject} and the payload is a hashtable
29626 containing mapping @code{@{:a 1 :b 2@}}.
29627 @c JP
29628 例えば、@code{#myobject @{:a 1 :b 2@}}を読んだ場合、
29629 タグは@code{myobject}、内容は@code{@{:a 1 :b 2@}}を読んだ結果のハッシュテーブルに
29630 なります。
29631 @c COMMON
29632 @end deftp
29633
29634 @defun make-edn-object tag payload
29635 @c MOD text.edn
29636 @c EN
29637 Returns a new @code{<edn-object>} instance.
29638 Note: Arguments are not checked. It's caller's responsibility to
29639 pass valid arguments to guarantee it's serializable as EDN.
29640 @c JP
29641 新たな@code{<edn-object>}のインスタンスを作って返します。
29642 引数がEDN表現可能かどうかのチェックはされません。
29643 呼び出し側が有効な引数を渡す必要があります。
29644 @c COMMON
29645 @end defun
29646
29647 @defun edn-object? obj
29648 @c MOD text.edn
29649 @c EN
29650 Returns @code{#t} iff @var{obj} is an instance of @code{<edn-object>}.
29651 @c JP
29652 @var{obj}が@code{<edn-object>}のインスタンスなら@code{#t}を、そうでなければ
29653 @code{#f}を返します。
29654 @c COMMON
29655 @end defun
29656
29657 @defun edn-object-tag edn-object
29658 @defunx edn-object-payload edn-object
29659 @c MOD text.edn
29660 @c EN
29661 Returns the tag and the payload of @var{edn-object}, respectively.
29662 @c JP
29663 @var{edn-object}のタグと内容をそれぞれ返します。
29664 @c COMMON
29665 @end defun
29666
29667 @defun edn-symbol-prefix symbol
29668 @defunx edn-symbol-basename symbol
29669 @c MOD text.edn
29670 @c EN
29671 Return prefix and basename part of the symbol, respectively.
29672 @c JP
29673 シンボルの、プリフィクスとベース名をそれぞれ返します。
29674 @c COMMON
29675
29676 @example
29677 (edn-symbol-prefix 'foo/bar) @result{} foo
29678 (edn-symbol-basename 'foo/bar) @result{} bar
29679
29680 (edn-symbol-prefix 'bar) @result{} #f
29681 (edn-symbol-basename 'bar) @result{} bar
29682 @end example
29683 @end defun
29684
29685 @defun edn-valid-symbol-name? str
29686 @c MOD text.edn
29687 @c EN
29688 Returns @code{#t} iff a string @var{str} can be a valid Clojure symbol name.
29689 It may have namespace prefix.
29690 @c JP
29691 文字列@var{str}がClojureのシンボル名として有効なら@code{#t}を、そうでなければ
29692 @code{#f}を返します。@var{str}には名前空間を含めることもできます。
29693 @c COMMON
29694 @end defun
29695
29696 @c EN
29697 @subheading Customization
29698 @c JP
29699 @subheading カスタマイズ
29700 @c COMMON
29701
29702 @c EN
29703 You can map EDN tagged objects to other Gauche objects.
29704 @c JP
29705 EDNのタグつきオブジェクトを、他のGaucheオブジェクトへとマップすることが出来ます。
29706 @c COMMON
29707
29708 @defun register-edn-object-handler! tag handler
29709 @c MOD text.edn
29710 @c EN
29711 @var{Tag} is a symbol, and @var{handler} is @code{#f} or a procedure
29712 that takes a tag symbol and a payload object.
29713
29714 @var{Tag} must have a name valid as Clojure symbol, or an error
29715 is signaled.
29716
29717 After the parser reads a tagged object with a symbol @var{tag}
29718 and payload, it calls @var{handler}, and the returned object
29719 becomes the result of the parser, instead of @code{<edn-object>}.
29720 Registering @code{#f} removes the previously registered handler.
29721
29722 This procedure is thread-safe.
29723
29724 The following example makes EDN @code{#u8vector[1 2 3 4]} to be read
29725 as @code{#u8(1 2 3 4)}:
29726 @c JP
29727 @var{tag}はシンボル、@var{handler}は@code{#f}もしくは
29728 タグと内容を引数に取る手続きです。
29729
29730 @var{tag}はClojureのシンボルとして有効な名前でなければなりません。
29731 さもなくばエラーが投げられます。
29732
29733 パーザが@var{tag}をタグに持つタグつきオブジェクトを読んだら、
29734 そのタグと内容を引数にして@var{handler}を呼び出し、返り値を
29735 パーズ結果とします。@var{handler}に@code{#f}を渡した場合は
29736 既に登録されたハンドラを(もしあれば)削除します。
29737
29738 この手続きはスレッドセーフです。
29739
29740 以下の例はEDNの@code{#u8vector[1 2 3 4]}を
29741 @code{#u8(1 2 3 4)}として読み込みます。
29742 @c COMMON
29743
29744 @example
29745 (register-edn-object-handler! 'u8vector
29746 (^[tag vec] (vector->u8vector vec)))
29747 @end example
29748 @end defun
29749
29750 @defun edn-object-handler tag
29751 @c MOD text.edn
29752 @c EN
29753 Returns a handler registered with a symbol @var{tag}. If a handler
29754 is not registered for @var{tag}, @code{#f} is returned.
29755 This procedure is thread-safe.
29756 @c JP
29757 @var{tag}に登録されたハンドラを返します。ハンドラが登録されていなければ@code{#f}を返します。
29758 この手続きはスレッドセーフです。
29759 @c COMMON
29760 @end defun
29761
29762 @deffn {Generic Function} edn-write obj
29763 @c MOD text.edn
29764 @c EN
29765 Write EDN representation of @var{obj} to the current output port.
29766 The @code{construct-edn} procedure calls this internally.
29767
29768 To write out a Gauche object as EDN tagged object, define a method to
29769 this generic function. In the method you can call @code{edn-write}
29770 recursively to write out components of the object.
29771
29772 The following example writes @code{#u8(1 2 3 4)} as
29773 EDN @code{#u8vector[1 2 3 4]}:
29774 @c JP
29775 @var{obj}のEDN表現を現在の出力ポートに書き出します。
29776 @code{construct-edn}は内部的にこれを呼んでいます。
29777
29778 GaucheオブジェクトをEDNタグつきオブジェクトとして書き出したい場合に、
29779 このジェネリック関数にメソッドを定義します。メソッド中で、オブジェクトの要素を
29780 再帰的に書き出す場合はそれぞれに@code{edn-write}を呼び出してください。
29781
29782 以下の例は、@code{#u8(1 2 3 4)}をEDNの@code{#u8vector[1 2 3 4]}として
29783 書き出します。
29784 @c COMMON
29785
29786 @example
29787 (define-method edn-write ((x <u8vector>))
29788 (display "#u8vector")
29789 (edn-write (u8vector->vector x)))
29790 @end example
29791 @end deffn
29792
29793 @c ----------------------------------------------------------------------
29794 @node Running external editor, Text filling, EDN parsing and construction, Library modules - Utilities
29795 @section @code{text.external-editor} - Running external editor
29796 @c NODE 外部エディタの起動, @code{text.external-editor} - 外部エディタの起動
29797
29798 @deftp {Module} text.external-editor
29799 @mdindex text.external-editor
29800 @c EN
29801 A convenience module to invoke external editor program.
29802 This is mainly to be used from REPL, but can be useful for
29803 other purposes.
29804 @c JP
29805 外部エディタプログラムを起動するための便利なモジュールです。
29806 もともとREPLで使われることを意図していましたが、他の目的にも有用かもしれません。
29807 @c COMMON
29808 @end deftp
29809
29810 @defun ed path-or-proc :key editor load-after
29811 @c MOD text.external-editor
29812 @c EN
29813 Starts an external editor. The editor program path is determined
29814 in the following order:
29815 @c JP
29816 外部エディタを起動します。起動するエディタのパスは次のように決められます。
29817 @c COMMON
29818
29819 @itemize @bullet
29820 @item
29821 @c EN
29822 The @var{editor} keyword argument, if it's a string.
29823 @c JP
29824 @var{editor}キーワード引数に文字列が与えれれば、それをパスと解釈します。
29825 @c COMMON
29826 @item
29827 @c EN
29828 The value of @code{*editor*} in the user module, if defined.
29829 @c JP
29830 userモジュールに変数@code{*editor*}が定義されていれば、その値。
29831 @c COMMON
29832 @item
29833 @c EN
29834 The value of the environment variable @code{GAUCHE_EDITOR}.
29835 @c JP
29836 環境変数@code{GAUCHE_EDITOR}が定義されていれば、その値。
29837 @c COMMON
29838 @item
29839 @c EN
29840 The value of the environment variable @code{EDITOR}.
29841 @c JP
29842 環境変数@code{EDITOR}が定義されていれば、その値。
29843 @c COMMON
29844 @item
29845 @c EN
29846 If none works, the behavior depends on the value of @var{editor} keyword
29847 argument:
29848 @c JP
29849 どれも該当しなかった場合、@var{editor}キーワード引数によって振る舞いが決まります。
29850 @c COMMON
29851 @table @code
29852 @item #f
29853 @c EN
29854 Just returns @code{#f}.
29855 @c JP
29856 単に@code{#f}を返します。
29857 @c COMMON
29858 @item error
29859 @c EN
29860 Throws an error.
29861 @c JP
29862 エラーを投げます。
29863 @c COMMON
29864 @item ask
29865 @c EN
29866 Asks the user. (default)
29867 @c JP
29868 ユーザに尋ねます。(デフォルト)
29869 @c COMMON
29870 @item message
29871 @c EN
29872 Prints message and returns @code{#f}.
29873 @c JP
29874 メッセージを出して@code{#f}を返します。
29875 @c COMMON
29876 @end table
29877 @end itemize
29878
29879 @c EN
29880 Returns @code{#t} for normal termination.
29881 @c JP
29882 エディタを起動して、それが終了した場合は@code{#t}を返します。
29883 @c COMMON
29884
29885 @c EN
29886 The editor program may be called in one of the following way:
29887 @c JP
29888 エディタプログラムは次のどちらかの形で呼ばれます:
29889 @c COMMON
29890
29891 @example
29892 EDITOR filename
29893 EDITOR +lineno filename
29894 @end example
29895
29896 @c EN
29897 The latter expects to locate the cursor on the specified line number
29898 in the filename.
29899 @c JP
29900 後者の場合、エディタは@var{filename}をオープンした後、
29901 @var{lineno}で示される行にカーソルを移動することが期待されます。
29902 @c COMMON
29903
29904 @c EN
29905 The file to open is determined by calling the generic function
29906 @code{ed-pick-file} on the argument @var{path-or-proc}.
29907 It should return @code{(@var{filename} @var{lineno})},
29908 or @code{#f} to indicate that it couldn't determine the file to edit.
29909 Methods for @code{<string>} and @code{<procedure>} are already defined;
29910 see the entry of @code{ed-pick-file} below.
29911 @c JP
29912 オープンするファイル名は、ジェネリックファンクション@code{ed-pick-file}を
29913 @var{path-or-proc}を引数として起動することで決定されます。
29914 @code{ed-pick-file}は@code{(@var{filename} @var{lineno})}を返すか、
29915 オープンすべきファイル名が決定できない場合は@code{#f}を返します。
29916 @code{<string>}と@code{<procedure>}に対するメソッドは既に定義されています。
29917 詳しくは下の@code{ed-pick-file}を見てください。
29918 @c COMMON
29919
29920 @c EN
29921 @c EN
29922 The @var{load-after} argument controls whether the file is loaded
29923 into the process after the file is modified. It must be one of
29924 the following values:
29925 @c JP
29926 @var{load-after}引数は、ファイルが変更された後でそれを
29927 自動的にロードするかどうかを指定します。以下の値のいずれかでなければなりません。
29928 @c COMMON
29929 @table @code
29930 @item #t
29931 @c EN
29932 Load the file once editor exits and the file is modified.
29933 @c JP
29934 エディタが終了し、その時点でファイルが変更されていた場合は、それをロードします。
29935 @c COMMON
29936 @item #f
29937 @c EN
29938 Do not load the file.
29939 @c JP
29940 ファイルをロードしません。
29941 @c COMMON
29942 @item ask
29943 @c EN
29944 Ask the user if the file should be loaded or not if the file is modified.
29945 (default)
29946 @c JP
29947 ファイルが変更されていた場合に、ロードすべきかどうかをユーザに尋ねます。(デフォルト)
29948 @c COMMON
29949 @end table
29950
29951 @c EN
29952 NB: Common Lisp's @code{ed} can be invoked without argument. For our usage,
29953 though, that feature doesn't seem too useful---it's more likely that
29954 repl IS inside an editor so we only need to open a specific file in
29955 a buffer. Emacsclient requires filename, so it further complicates things.
29956 For now we just require one argument.
29957 @c JP
29958 註: Common Lispの@code{ed}は引数なしで呼び出すこともできます。
29959 しかし我々の用途ではそれはあまり有用でないと判断しました。REPLを走らせている場合、
29960 それが既にエディタの中である可能性は高く、
29961 それなら指定ファイルをバッファで開けばいいわけです。
29962 また、@code{emacsclient}はファイル名を取るので、
29963 ファイル名無しの場合の処理が煩雑になります。なので今のところ、ファイル名を必須としました。
29964 @c COMMON
29965 @end defun
29966
29967 @defun ed-string string :key editor
29968 @c MOD text.external-editor
29969 @c EN
29970 Invoke an external editor (as described in @code{ed}) on a temporary file
29971 whose content is @var{string}.
29972 Once editor exits, returns the edited content as a string.
29973 @c JP
29974 @var{string}を一時ファイルに書き出して、それをオープンするエディタを起動します
29975 (エディタがどう起動されるかについては@code{ed}のエントリを参照)。
29976 エディタが終了したら、編集済の内容を文字列として返します。
29977 @c COMMON
29978 @end defun
29979
29980 @deffn {Generic Function} ed-pick-file obj
29981 @c MOD text.external-editor
29982 @c EN
29983 Determine what to edit. It must return a list of
29984 filename and line number, or @code{#f} if it can't find appropriate file to
29985 edit.
29986 @c JP
29987 何を編集するかを決めるジェネリックファンクションです。
29988 ファイル名と行番号からなるリストか、編集すべきファイル名が見つからなければ@code{#f}を
29989 返します。
29990 @c COMMON
29991
29992 @c EN
29993 Methods for strings, procedures and @code{<top>} are already defined.
29994 If @var{obj} is a string, it is taken as a filename.
29995 If @var{obj} is a procedure and its source location is available,
29996 the source file and the location is returned.
29997 Otherwise, @code{#f} is returned.
29998 @c JP
29999 文字列、@code{<procedure>}、そして@code{<top>}に対するメソッドが既に定義されています。
30000 @var{obj}が文字列なら、それがファイル名です。
30001 @var{obj}が手続きでそのソース位置が分かっていれば、ソースファイル名と定義行を返します。
30002 @var{obj}がそれ以外なら@code{#f}を返します。
30003 @c COMMON
30004 @end deffn
30005
30006 @c ----------------------------------------------------------------------
30007 @node Text filling, Gap buffer, Running external editor, Library modules - Utilities
30008 @section @code{text.fill} - Text filling
30009 @c NODE テキストの再詰め込み, @code{text.fill} - テキストの再詰め込み
30010
30011 @deftp {Module} text.fill
30012 @mdindex text.fill
30013 @c EN
30014 This module provides procedures to fill given text within the
30015 specified width, inserting line breaks
30016 adequately. It is similar to @code{fill-paragraph} of Emacs.
30017 @c JP
30018 このモジュールは、指定の幅にテキストを詰め込む(フィル)ように改行を適宜挿入して表示します。
30019 Emacsの@code{fill-paragraph}のような機能です。
30020 @c COMMON
30021 @end deftp
30022
30023 @defun display-filled-text text :key port indent hanging width start-column lead-in
30024 @c MOD text.fill
30025 @c EN
30026 Output @var{text} to @var{port}, while keeping the line width up to
30027 @var{width} as much as possible by inserting line breaks.
30028 If @var{port} is omitted, the current output port is used.
30029 @c JP
30030 @var{text}を、行の幅がなるべく@var{width}に収まるように改行を挿入しながら
30031 @var{port}に出力します。
30032 @var{port}が省略された場合は現在の出力ポートが使われます。
30033 @c COMMON
30034
30035 @c EN
30036 Two consecutive newlines mark (or, an empty line) a paragraph break.
30037 First, @var{text} is splitted into paragraphs,
30038 then each paragraph is filled.
30039 All other newlines are treated as whitespaces.
30040 @c JP
30041 2つの連続する改行文字(あるいは、ひとつの空行)はパラグラフ境界を示します。
30042 まず@var{text}がパラグラフに分割され、それから各パラグラフがフィルされます。
30043 他の改行文字は空白と同じ扱いになります。
30044 @c COMMON
30045
30046 @c EN
30047 It has a few keyword arguments to control the formatting.
30048 The @var{width} argument specifies the entire width of the filled text.
30049 It tries to keep lines from overflowing the width, but if there's
30050 an unbreakable chunk of text that's wider than the given width,
30051 it lets the line oveflow.
30052 The @var{hanging} specifies the hanging indent width of the paragraph's
30053 first line,
30054 and @var{indent} specifies the indent width of the rest of lines.
30055 They are included in @var{width}. Here's the relations of these
30056 values:
30057 @c JP
30058 いくつかのキーワード引数で出力フォーマットを制御できます。
30059 @var{width}引数はフィルされたテキスト全体の幅を指定します。テキストはこの幅を
30060 越えないように出力されます。
30061 但し、分割できない長い塊があった場合はこの幅を越えることがあります。
30062 @var{hanging}はパラグラフの最初の行のハンギングインデントを、@var{indent}は2行目以降の
30063 インデントを指定します。これらのインデントは@var{width}の一部にカウントされます。
30064 次にこれらの値の関係を示します:
30065 @c COMMON
30066
30067 @example
30068 width
30069 <------------------------------------------------------------------->
30070 hanging
30071 <------>
30072 Lorem ipsum dolor sit amet, consectetur adipiscing elit,
30073 sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
30074 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
30075 nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
30076 in reprehenderit in voluptate velit esse cillum dolore eu fugiat
30077 nulla pariatur. Excepteur sint occaecat cupidatat non proident,
30078 sunt in culpa qui officia deserunt mollit anim id est laborum.
30079 <->
30080 indent
30081 @end example
30082
30083 @c EN
30084 The arguments @var{width}, @var{indent}, and @var{hanging} must be
30085 nonnegative exact integers or @code{#f}, if given.
30086 When omitted or @code{#f},
30087 @var{width} is assumed to be 65, @var{indent} to be 0,
30088 and @var{hanging} to be the same as @var{indent}.
30089 @c JP
30090 @var{width}、@var{indent}、@var{hanging}は与えられたなら
30091 正確な非負整数でなければなりません。省略されるか@code{#f}の場合、
30092 @var{width}は65、@var{indent}は0、@var{hanging}は@var{indent}と同じになります。
30093 @c COMMON
30094
30095 @c EN
30096 If you call this procedure in the middle of the line (that is,
30097 some text is already written to @var{port}), the procedure takes
30098 the current column into account, as shown below:
30099 @c JP
30100 この手続きを、行の途中 (既に@var{port}にいくらか出力されてから改行されていない状態)
30101 で呼び出した場合、この手続きは@var{port}の現在のカラム位置を考慮に入れるので
30102 次のようになります。
30103 @c COMMON
30104
30105 @example
30106 width
30107 <--------------------------------------------------------------------->
30108 start column
30109 | hanging
30110 v<---->
30111 Lorem ipsum dolor sit amet, consectetur
30112 adipiscing elit, sed do eiusmod tempor incididunt ut labore
30113 et dolore magna aliqua. Ut enim ad minim veniam, quis
30114 nostrud exercitation ullamco laboris nisi ut aliquip ex ea
30115 commodo consequat. Duis aute irure dolor in reprehenderit in
30116 voluptate velit esse cillum dolore eu fugiat nulla pariatur.
30117 Excepteur sint occaecat cupidatat non proident, sunt in culpa
30118 qui officia deserunt mollit anim id est laborum.
30119 <-------->
30120 indent
30121 @end example
30122
30123 @c EN
30124 The @var{start-column} keyword argument can override the port's
30125 current column with the given nonnegative exact integer.
30126 It is only considered for the first paragraph; subsequent paragraphs
30127 are formatted as if @var{start-column} is zero.
30128 @c JP
30129 @var{start-column}引数は開始カラム位置を強制的に指定するものです。
30130 与える場合は正確な非負整数でなければなりません。
30131 この機能は最初のパラグラフのみに適用されます。
30132 二番目以降のパラグラフは@var{start-column}が0であるかのようにフォーマットされます。
30133 @c COMMON
30134
30135 @c EN
30136 The last line of the last paragraph is not terminated by a newline,
30137 allowing the caller to continue output in the same line.
30138 @c JP
30139 最後のパラグラフの最後の行の後に改行文字は出力されません。
30140 呼び出し側がこの行の後にさらに続けて出力することもできるようにするためです。
30141 @c COMMON
30142
30143 @c EN
30144 The length of the line is computed by each character's East Asian
30145 Width (@pxref{East asian width property}). The actual display
30146 width depends on the fonts, but it gives a reasonable approximation.
30147 @c JP
30148 行の長さは、East Asian Widthを使って計算されます
30149 (@ref{East asian width property}参照)。実際に表示される行幅は
30150 フォントの設定に影響されますが、それなりの出力は得られます。
30151 @c COMMON
30152
30153 @c EN
30154 Finally, if the @var{lead-in} argument is not @code{#f}, it must be
30155 a string that is output before any @var{text} and indentation is
30156 output. Then, if the column after @var{lead-in} is less than
30157 @var{hanging} minus one, @var{text} will be emitted on the smae
30158 line, starting from @var{hanging} column:
30159 @c JP
30160 最後に、@var{lead-in}引数が与えられて@code{#f}でなければ、
30161 それは文字列でなければならず、@var{text}やインデントの前に出力されます。
30162 そして、もし@var{lead-in}出力後のカラムが@var{hanging}-1カラムより少なければ、
30163 @var{text}は同じ行に出力されます:
30164 @c COMMON
30165
30166 @example
30167 hanging
30168 <------------------>
30169 THIS IS LEAD-IN. Lorem ipsum dolor sit amet, consectetur
30170 adipiscing elit, sed do eiusmod tempor incididunt ut labore
30171 et dolore magna aliqua.
30172 <----------->
30173 indent
30174 @end example
30175
30176 @c EN
30177 If @var{lead-in} text is equal to or longer than the @var{hanging}, @var{text}
30178 is emitted from the next line.
30179 @c JP
30180 @var{lead-in}の幅が@var{hanging}以上であれば、@var{text}は次の行から
30181 出力されます。
30182 @c COMMON
30183
30184 @example
30185 hanging
30186 <------------------>
30187 THIS IS LEAD-IN LONGER THAN HANGING.
30188 Lorem ipsum dolor sit amet, consectetur
30189 adipiscing elit, sed do eiusmod tempor incididunt ut labore
30190 et dolore magna aliqua.
30191 <----------->
30192 indent
30193 @end example
30194
30195 @c EN
30196 Even if @var{text} contains more than one paragraph, @var{lead-in} is
30197 displayed only once, at the beginning.
30198 @c JP
30199 @var{text}が複数パラグラフからなる場合でも、@var{lead-in}は最初に一度だけ
30200 出力されます。
30201 @c COMMON
30202
30203 This is handy when you display definition-list like document, e.g.
30204 command-line option description.
30205 @c JP
30206 これは定義リスト的なドキュメントを表示する時に便利です。
30207 例えばコマンドラインオプションのヘルプ等。
30208 @c COMMON
30209 @end defun
30210
30211 @defun text->filled-stree text :key indent hanging width start-column lead-in
30212 @c MOD text.fill
30213 @c EN
30214 This is a low-level routine to construct a filled text used by
30215 @code{display-filled-text}. It returns a string tree
30216 (@pxref{Lazy text construction}). If you want to add more
30217 text around the filled paragraph, using this procedure can save
30218 constructing intermediate strings.
30219 @c JP
30220 これは@code{display-filled-text}に呼ばれる低レベルルーチンで、
30221 文字列のツリーを返します(@ref{Lazy text construction}参照)。
30222 パラグラフをフィルした後で他のテキストをその周囲に付け足したい場合などに、
30223 中間文字列を作らずに済みます。
30224 @c COMMON
30225
30226 @c EN
30227 The meaning of the keywrd arguments are the same as
30228 @code{display-filled-text}, except that @var{start-column} is
30229 assumed to be 0 if omitted.
30230 @c JP
30231 キーワード引数の意味は@code{display-filled-text}と同じです。
30232 但し@var{start-column}が省略された場合は0とみなされます。
30233 @c COMMON
30234 @end defun
30235
30236
30237 @c ----------------------------------------------------------------------
30238 @node Gap buffer, Localized messages, Text filling, Library modules - Utilities
30239 @section @code{text.gap-buffer} - Gap buffer
30240 @c NODE ギャップバッファ, @code{text.gap-buffer} - ギャップバッファ
30241
30242 @deftp {Module} text.gap-buffer
30243 @mdindex text.gap-buffer
30244 @c EN
30245 This module provides a gap buffer, a data structure useful for
30246 editable text.
30247 @c JP
30248 ギャップバッファは、編集可能なテキストを実装するのに便利なデータ構造です。
30249 @c COMMON
30250
30251 @c EN
30252 A gap buffer is a vector of characters with a ``cursor'', where
30253 you can insert or delete a character in O(1) time. Most of
30254 the editing API operate on the current cursor position.
30255 @c JP
30256 ギャップバッファは、「カーソル」を持つ文字のベクタと考えることができます。
30257 カーソル位置への文字の挿入、もしくはカーソル位置の文字の削除はO(1)時間でできます。
30258 ほとんどの編集APIは現在のカーソル位置を対象にします。
30259 @c COMMON
30260 @end deftp
30261
30262 @defun make-gap-buffer :key initial-capacity
30263 @c MOD text.gap-buffer
30264 @c EN
30265 Creates a fresh gap buffer and returns it. The initial content
30266 is empty.
30267 @c JP
30268 新たなギャップバッファを作って返します。初期状態では中身は空です。
30269 @c COMMON
30270
30271 @c EN
30272 The keyword argument
30273 @var{initial-capacity} must be a positive exact integer if given,
30274 and specifies the initial capacity of the buffer. The buffer is
30275 automatically extended if necessary, so the argument is only a
30276 hint; if you know you'll insert a long string, for example,
30277 you can create a buffer that's large enough to hold it to avoid
30278 reallocation overhead.
30279 @c JP
30280 キーワード引数@var{initial-capacity}は、正の正確な整数でなければならず、
30281 初期状態のバッファの大きさを指定します。バッファは必要に応じて自動的に拡張されるので、
30282 この引数は単なるヒントです。例えば最初に大きな文字列を挿入することがわかっていれば、
30283 あらかじめ大きなバッファを取っておくことで再アロケーションのオーバヘッドを避けることが
30284 できます。
30285 @c COMMON
30286 @end defun
30287
30288 @defun string->gap-buffer string :optional pos whence start end
30289 @c MOD text.gap-buffer
30290 @c EN
30291 Creates a gap buffer that contains the given @var{string},
30292 and returns it.
30293 @c JP
30294 与えられた文字列@var{string}を保持するギャップバッファを作って返します。
30295 @c COMMON
30296
30297 @c EN
30298 The initial cursor position is set at the end of the string by default.
30299 The @var{pos} and @var{whence} argument can set the initial
30300 cursor position. The @var{whence} argument must be either a symbol
30301 @code{beginning} or a symbol @code{end}, and @var{pos} must be an exact
30302 integer offset from the whence. For example, @var{pos} = 10 and
30303 @var{whence} = @code{beginning} sets the cursor at the 10th character
30304 of the string from the beginning, and @var{pos} = -1 and @var{whence} =
30305 @code{end} sets the cursor position at one character before the end
30306 of the string. If the combination of @var{pos} and @var{whence}
30307 points the outside of the string, an error is signaled.
30308 @c JP
30309 カーソルの初期位置は、デフォルトでは文字列の最後です。
30310 @var{pos}と@var{whence}引数で初期位置を変更することができます。
30311 @var{whence}はシンボル@code{beginning}か@code{end}で、@var{pos}は
30312 whenceからのオフセットを表す正確な整数です。例えば@var{pos}が10で
30313 @var{whence}が@code{beginning}なら、文字列の先頭から10番目の文字にカーソルが
30314 置かれます。@var{pos}が-1で@var{whence}が@code{end}なら、文字列の最後から
30315 ひとつ手前の文字にカーソルが置かれます。@var{pos}と@var{whence}の組み合わせが
30316 文字列をはみ出してしまう場合はエラーが投げられます。
30317 @c COMMON
30318
30319 @c EN
30320 The optional @var{start} and @var{end} trims the input string before
30321 creating the gap buffer.
30322 @c JP
30323 省略可能な@var{start}と@var{end}引数は、ギャップバッファを作る前に
30324 入力文字列の範囲を制限します。
30325 @c COMMON
30326 @end defun
30327
30328 @defun gap-buffer? obj
30329 @c MOD text.gap-buffer
30330 @c EN
30331 Returns @code{#t} iff @var{obj} is a gap buffer.
30332 @c JP
30333 @var{obj}がギャップバッファなら@code{#t}を、そうでなければ@code{#f}を返します。
30334 @c COMMON
30335 @end defun
30336
30337 @defun gap-buffer-copy gbuf
30338 @c MOD text.gap-buffer
30339 @c EN
30340 Returns a fresh copy of a gap buffer @var{gbuf}, with the same content
30341 and cursor position.
30342 @c JP
30343 ギャップバッファ@var{gbuf}の新たなコピーを作って返します。内容およびカーソル位置は
30344 @var{gbuf}と同じになります。
30345 @c COMMON
30346 @end defun
30347
30348 @defun gap-buffer->string gbuf :optional start end
30349 @defunx gap-buffer->generator gbuf :optional start end
30350 @c MOD text.gap-buffer
30351 @c EN
30352 Retrieve the content of a gap buffer @var{gbuf} as a string or
30353 a generator of characters, respectively. The optional @var{start} and
30354 @var{end} arguments are nonnegative exact integers of character index
30355 in the content of the buffer, and limits the output within the specified
30356 range.
30357 @c JP
30358 ギャップバッファ@var{gbuf}の内容を文字列もしくは文字のジェネレータとして取り出します。
30359 省略可能な@var{start}と@var{end}はバッファ内の文字インデックスを指定する非負の正確な整数で、
30360 取り出す内容の範囲を制限します。
30361 @c COMMON
30362
30363 @c EN
30364 If you modify the content of gap buffer before the returned generator
30365 is exhausted, consistent behavior isn't guaranteed.
30366 @c JP
30367 返ってきたジェネレータを最後まで読む前にギャップバッファの内容を変えた場合、
30368 一貫性のある振る舞いは保証されません。
30369 @c COMMON
30370 @end defun
30371
30372 @defun gap-buffer-pos gbuf
30373 @c MOD text.gap-buffer
30374 @c EN
30375 Returns the current cursor position of @var{gbuf}, in a nonnegative
30376 exact integer.
30377 @c JP
30378 ギャップバッファ@var{gbuf}の現在のカーソル位置を非負の正確な整数で返します。
30379 @c COMMON
30380 @end defun
30381
30382 @defun gap-buffer-pos-at-end? gbuf pos
30383 @c MOD text.gap-buffer
30384 @c EN
30385 Returns @code{#t} if @var{pos}, a position in nonnegative integer,
30386 is at the end of @var{gbuf}, @code{#f} otherwise.
30387 @c JP
30388 位置を表す非負整数@var{pos}がギャップバッファ@var{gbuf}の末尾を差していれば@code{#t}を、
30389 そうでなければ@code{#f}を返します。
30390 @c COMMON
30391 @end defun
30392
30393 @defun gap-buffer-capacity gbuf
30394 @c MOD text.gap-buffer
30395 @c EN
30396 Returns the currently allocated storage size of @var{gbuf}, in character count.
30397 If you insert more characters into @var{gbuf}, the storage is automatically
30398 expanded.
30399 @c JP
30400 ギャップバッファ@var{gbuf}に現在アロケートされているストレージの大きさを
30401 文字数で返します。@var{gbuf}に格納する文字がそれを越えたら、ストレージは自動的に拡張されます。
30402 @c COMMON
30403 @end defun
30404
30405 @defun gap-buffer-content-length gbuf
30406 @c MOD text.gap-buffer
30407 @c EN
30408 Returns the length of current content of @var{gbuf},
30409 in the number of characters.
30410 @c JP
30411 ギャップバッファ@var{gbuf}に現在格納されている内容の大きさを、文字数で返します。
30412 @c COMMON
30413 @end defun
30414
30415 @defun gap-buffer-gap-at? gbuf whence
30416 @c MOD text.gap-buffer
30417 @c EN
30418 The @var{whence} argument must be either a symbol @code{beginning}
30419 or a symbol @code{end}. Returns @code{#t} iff the current cursor position
30420 of @var{gbuf} is at the beginning or at the end, respectively.
30421 @c JP
30422 @var{whence}引数はシンボル@code{beginning}か@code{end}のいずれかです。
30423 ギャップバッファ@var{gbuf}の現在のカーソル位置がそれぞれバッファの先頭または末尾
30424 である場合に@code{#t},をそうでなければ@code{#f}を返します。
30425 @c COMMON
30426 @end defun
30427
30428 @defun gap-buffer-ref gbuf index :optional fallback
30429 @c MOD text.gap-buffer
30430 @c EN
30431 Returns @var{index}-th character of @var{gbuf}. If @var{index} is
30432 out of range, @var{fallback} is returned if given, or an error
30433 is raised.
30434 @c JP
30435 ギャップバッファ@var{gbuf}の@var{index}番目の文字を返します。@var{index}が
30436 範囲外の場合、@var{fallback}が与えられればそれを返し、無ければエラーが投げられます。
30437 @c COMMON
30438 @end defun
30439
30440 @defun gap-buffer-set! gbuf index char
30441 @c MOD text.gap-buffer
30442 @c EN
30443 Replaces @var{index}-th character of @var{gbuf} with @var{char}.
30444 If @var{index} is out of range, an error is signaled.
30445 @c JP
30446 ギャップバッファ@var{gbuf}の@var{index}番目の文字を@var{char}で置き換えます。
30447 @var{index}が範囲外の場合はエラーが投げられます。
30448 @c COMMON
30449 @end defun
30450
30451 @defun gap-buffer-move! gbuf pos :optional whence
30452 @c MOD text.gap-buffer
30453 @c EN
30454 Moves the cursor position of @var{gbuf} to a position @var{pos}, which
30455 must be an exact integer. The position @var{pos} is relative to
30456 @var{whence}, which must be either one of the symbols @code{beginning},
30457 @code{current} or @code{end}. If omitted, @code{beginning} is assumed.
30458 @c JP
30459 @var{gbuf}のカーソル位置を@var{pos}に移動します。@var{pos}は正確な整数でなければなりません。
30460 @var{pos}は@var{whence}からの相対位置と解釈されます。@var{whence}は
30461 シンボル@code{beginning}、@code{current}、@code{end}のいずれかです。
30462 省略された場合は@code{beginning}と同等です。
30463 @c COMMON
30464 @end defun
30465
30466 @defun gap-buffer-insert! gbuf content
30467 @c MOD text.gap-buffer
30468 @c EN
30469 Inserts @var{content}, which must be a character or a string,
30470 at the current cursor position of @var{gbuf}.
30471 The current cursor position is moved to the end of the inserted content.
30472 @c JP
30473 @var{content}は文字または文字列です。@var{content}wお@var{gbuf}の
30474 現在のカーソル位置に挿入します。
30475 カーソルは、挿入された内容の末尾へと移動します。
30476 @c COMMON
30477 @end defun
30478
30479 @defun gap-buffer-delete! gbuf size
30480 @c MOD text.gap-buffer
30481 @c EN
30482 Delets @var{size} characters from the current cursor position
30483 of @var{gbuf}. The @var{size} argument must be a nonnegative exact integer.
30484 It is an error if @var{size} overruns.
30485 @c JP
30486 @var{gbuf}の現在のカーソル位置から@var{size}文字を削除します。
30487 @var{size}は非負の正確な整数でなければなりません。
30488 @var{size}が現在の内容を越えてしまう場合はエラーとなります。
30489 @c COMMON
30490 @end defun
30491
30492 @defun gap-buffer-clear! gbuf
30493 @c MOD text.gap-buffer
30494 @c EN
30495 Makes @var{gbuf} empty.
30496 @c JP
30497 @var{gbuf}を空にします。
30498 @c COMMON
30499 @end defun
30500
30501 @defun gap-buffer-replace! gbuf size content
30502 @c MOD text.gap-buffer
30503 @c EN
30504 This is a combination of @code{(gap-buffer-delete! gbuf size)} and
30505 @code{(gap-buffer-insert! gbuf content)}.
30506 The @var{size} argument must be a nonnegative exact integer,
30507 and the @var{content} argument must be either a string or a character.
30508 @c JP
30509 これは@code{(gap-buffer-delete! gbuf size)}と
30510 @code{(gap-buffer-insert! gbuf content)}を続けて実行するのと同じです。
30511 @var{size}は非負の正確な整数でなければならず、
30512 @var{content}は文字か文字列でなければなりません。
30513 @c COMMON
30514 @end defun
30515
30516 @defun gap-buffer-contains gbuf str :optional gstart gend sstart send
30517 @c MOD text.gap-buffer
30518 @c EN
30519 Search a string @var{str} in a gap buffer @var{gbuf}. If found,
30520 returns the integer index of the beginning of @var{str} in @var{gbuf}.
30521 If not found, returns @code{#f}.
30522 @c JP
30523 文字列@var{str}をギャップバッファ@var{gbuf}の中から探します。
30524 見つかったら、その先頭の文字インデックスを返します。
30525 見つからなかったら@code{#f}を返します。
30526 @c COMMON
30527
30528 @c EN
30529 The optional arguments @var{gstart} and @var{gend}
30530 restricts the range of @var{gbuf} to be searched, by integer indexes.
30531 The default is the entire buffer.
30532 You can pass @code{#f} to indicate to use the
30533 default value.
30534 @c JP
30535 省略可能引数@var{start}と@var{gend}は、@var{gbuf}内で検索すべき範囲を
30536 制限する整数インデックスです。デフォルトではバッファ全体が検索対象となります。
30537 @code{#f}を渡すことでデフォルトの動作とすることができます。
30538 @c COMMON
30539
30540 @c EN
30541 The optional arguments @var{sstart} and @var{send} restricts
30542 the span of @var{str} to be searched, by integer indexes.
30543 You can pass @code{#f} to indicate to use the
30544 default value.
30545 @c JP
30546 省略可能引数@var{sstart}と@var{send}は、@var{str}から
30547 検索文字列を切り出す整数インデックスです。
30548 @code{#f}を渡すことでデフォルトの動作とすることができます。
30549 @c COMMON
30550 @end defun
30551
30552 @defun gap-buffer-looking-at? gbuf str :optional point
30553 @c MOD text.gap-buffer
30554 @c EN
30555 Returns @code{#t} iff the content immeidately following @var{point}
30556 matches a string @var{str}. If @var{point} is omitted or @code{#f},
30557 the current cursor position is used.
30558 @c JP
30559 整数インデックス@var{point}以降の内容の先頭が文字列@var{str}と一致する場合に
30560 @code{#t}を、そうでなければ@code{#f}を返します。
30561 @var{point}が@code{#f}か省略された場合は現在のカーソル位置が使われます。
30562 @c COMMON
30563 @end defun
30564
30565
30566 @defun gap-buffer-edit! gbuf edit-command
30567 @c MOD text.gap-buffer
30568 @c EN
30569 This is a convenience procedure to ``replay'' editing of the gap buffer
30570 @var{gbuf}. The @var{edit-command} argument must be either one of the
30571 following:
30572 @c JP
30573 これはギャップバッファ@var{gbuf}に対する編集を「リプレイ」するのに便利な手続きです。
30574 @var{edit-command}引数は、次のいずれかの形のフォームです。
30575 @c COMMON
30576
30577 @table @code
30578 @item (i @var{pos} @var{string})
30579 @c EN
30580 Insert @var{string} at a position @var{pos}.
30581 @c JP
30582 @var{string}を@var{pos}位置に挿入 (<b>I</b>nsert)。
30583 @c COMMON
30584 @item (d @var{pos} @var{length})
30585 @c EN
30586 Delete @var{length} characters from a position @var{pos}.
30587 @c JP
30588 @var{pos}位置から@var{length}j文字を削除 (<b>D</b>elete)。
30589 @c COMMON
30590 @item (c @var{pos} @var{length} @var{string})
30591 @c EN
30592 Change: Deletes @var{length} characters from a position @var{pos},
30593 then insert @var{string}.
30594 @c JP
30595 @var{pos}位置からの@var{length}文字を@var{string}へと変更 (<b>C</b>hange)。
30596 @c COMMON
30597 @end table
30598
30599 @c EN
30600 Here, @var{pos} must be a nonnegative exact integer specifying the
30601 position in the gap buffer.
30602 @c JP
30603 ただし、@var{pos}はバッファ先頭からの文字位置を示す非負の正確な整数です。
30604 @c COMMON
30605
30606 @c EN
30607 It returns another edit-command that undo the change.
30608 @c JP
30609 この手続きは、加えた変更を元に戻す編集コマンドを返します。
30610 @c COMMON
30611
30612 @c EN
30613 One of the appliations of this procedure is to handle undo/redo list.
30614 @c JP
30615 この手続きの使用場面のひとつは、undo/redoリストの処理です。
30616 @c COMMON
30617
30618 @example
30619 (define buf (string->gap-buffer "Hello, World!"))
30620
30621 (gap-buffer-edit! buf '(d 0 5))
30622 @result{} (i 0 "Hello")
30623
30624 (gap-buffer-edit! buf '(i 0 "Konnichiwa"))
30625 @result{} (d 0 10)
30626
30627 (gap-buffer->string buf)
30628 @result{} "Aloha, World!"
30629
30630 @c EN
30631 ;; Giving the returned values of gap-buffer-edit! in reverse order,
30632 ;; you can undo the changes:
30633 @c JP
30634 ;; gap-buffer-edit!の戻り値を逆順に適用すると元に戻せる
30635 @c COMMON
30636
30637 (for-each (cut gap-buffer-edit! buf <>) '((d 0 10) (i 0 "Hello")))
30638 (gap-buffer->string buf)
30639 @result{} "Hello, World!"
30640 @end example
30641 @end defun
30642
30643 @c ----------------------------------------------------------------------
30644 @node Localized messages, Simple HTML document construction, Gap buffer, Library modules - Utilities
30645 @section @code{text.gettext} - Localized messages
30646 @c NODE 地域化メッセージ, @code{text.gettext} - 地域化メッセージ
30647
30648 @deftp {Module} text.gettext
30649 @mdindex text.gettext
30650 @c EN
30651 This module provides utilities to deal with localized messages.
30652 The API is compatible to GNU's gettext, and the messages
30653 are read from @file{*.po} and @file{*.mo} files,
30654 so that you can use the GNU gettext
30655 toolchain to prepare localized messages.
30656 However, the code is written from scratch by Alex Shinn and
30657 doesn't depend on GNU's gettext library.
30658 @c JP
30659 このモジュールは地域化メッセージを扱うユーティリティを提供します。
30660 API は GNU の gettext と互換性があり、メッセージは @file{*.po} および
30661 @file{*.mo} ファイルから読み込まれます。それゆえ、GNU の gettext toolchain
30662 をつかって地域化メッセージを準備することができます。しかし、このコードは
30663 Alex Shinn によってスクラッチから書き起こされたものであり、GNU の
30664 gettext ライブラリには依存していません。
30665 @c COMMON
30666
30667 @c EN
30668 This implementation extends GNU's gettext API in the following ways:
30669 @itemize @bullet
30670 @item
30671 It can read from multiple message files in cascaded way,
30672 allowing applications to share a part of message files.
30673 @item
30674 It supports multiple locale/domain simultaneously.
30675 @end itemize
30676 @c JP
30677 この実装は GNU の gettext API を以下のように拡張したものです。
30678 @itemize @bullet
30679 @item
30680 複数のメッセージファイルから、カスケードされた方法で読み込むことができます。
30681 これにより、アプリケーションはメッセージファイルの部分を共有できます。
30682 @item
30683 複数のロケール/ドメインを同時に扱えます。
30684 @end itemize
30685 @c COMMON
30686
30687 @c EN
30688 SRFI-29 (@pxref{Localization}) provides another means of message
30689 localization. A portable program may wish to use SRFI-29, but
30690 generally @code{text.gettext} is recommended in Gauche scripts
30691 because of its flexibility and compatibility to existing message files.
30692 @c JP
30693 SRFI-29 (@ref{Localization}参照) はこれとは別のメッセージの地域化
30694 機構を提供しています。ポータブルなプログラムでは、SRFI-29 の方がよいこと
30695 もありますが、一般には、Gauche スクリプトでは、@code{text.gettext} の
30696 方を推奨します。それは、既存のメッセージファイルとの互換性と柔軟性の
30697 ためです。
30698 @c COMMON
30699 @end deftp
30700
30701 @c EN
30702 @subheading Gettext-compatible API
30703 @c JP
30704 @subheading gettext-互換の API
30705 @c COMMON
30706
30707 @defun textdomain domain-name :optional locale dirs cdir cached? lookup-cached?
30708 @c MOD text.gettext
30709 @c EN
30710 Sets up the default domain and other parameters for
30711 the application. The setting affects to the following @code{gettext}
30712 call.
30713
30714 @var{Domain} is a string or list of strings specifying the domain
30715 (name of @file{.mo} or @file{.po} files) as in C gettext.
30716 You can pass @code{#f} as @var{domain-name} just to get the default
30717 domain accessor procedure.
30718 You can alo pass multiple domains to @var{domain-name}.
30719 @c JP
30720 アプリケーション用に、デフォルトのドメインとそのほかのパラメータを
30721 設定します。この設定は、以降の @code{gettext} の呼出しに影響を与えます。
30722
30723 @var{domain} は文字列または文字列のリストで、ドメイン(@file{.mo} あるいは
30724 @file{.po} ファイル名)を C の gettext と同じように指定します。
30725 @code{#f} を @var{domain-name} として渡すと、デフォルトのドメインアクセサ
30726 手続きが得られます。また、複数のドメインを @var{domain-name}にあたえる
30727 ことができます。
30728 @c COMMON
30729 @example
30730 (textdomain '("myapp" "gimp")) ; search 1st myapp, then gimp
30731 (gettext "/File/Close") ; "Close" from gimp unless overridden
30732 @end example
30733
30734 @c EN
30735 @var{Locale} is a string or list of strings in the standard Unix format of
30736 @code{LANG[_REGION][.ENCODING]}. You can also pass a list of locales
30737 to specify fallbacks.
30738 @c JP
30739 @var{locale} は文字列または文字列のリストで、標準的なUnixのフォーマット
30740 @code{LANG[_REGION][.ENCODING]} です。フォールバックを指定するロケール
30741 のリストを渡すこともできます。
30742 @c COMMON
30743
30744 @example
30745 (textdomain "myapp" '("ru" "uk")) ; search 1st Russian then Ukranian,
30746 (gettext "Hello, World!") ; which are somewhat similar
30747 @end example
30748
30749 @c EN
30750 @var{Dirs} is the search path of directories which should hold the
30751 @file{LOCALE/CDIR/} directories which contain the actual message catalogs.
30752 This is always appended with the system default, e.g.
30753 @file{"/usr/share/locale"}, and may also inherit from the
30754 @code{GETTEXT_PATH} colon-delimited environment variable.
30755
30756 @var{Cdir} is the category directory, defaulting to either the
30757 @code{LC_CATEGORY}
30758 environment variable or the appropriate system default
30759 (e.g. @code{LC_MESSAGES}). You generally won't need this.
30760
30761 @var{Cached?}
30762 means to cache individual messages, and defaults to @code{#t}.
30763
30764 @var{Lookup-cached?}
30765 means to cache the lookup dispatch generated by these
30766 parameters, and defaults to @code{#t}.
30767
30768 @code{Textdomain} just passes these parameters to the internal
30769 @code{make-gettext},
30770 and binds the result to the global dispatch used by @code{gettext}.
30771 You may build these closures manually for convenience in using multiple
30772 separate domains or locales at once (useful for server environments).
30773 See the description of @code{make-gettext} below.
30774
30775 @code{Textdomain} returns an @emph{accessor procedure} which
30776 packages information of the domain. See @code{make-gettext} below
30777 for the details.
30778 @c JP
30779 @var{dirs} は実際のメッセージカタログを含む @file{LOCALE/CDIR/}
30780 ディレクトリのサーチパスです。これは常にシステムのデフォルト(たとえば、
30781 @file{"/usr/share/locale"})に追加されます。そして、コロンで区切られた
30782 @code{GETTEXT_PATH} 環境変数を継承します。
30783
30784 @var{cdir} はカテゴリーディレクトリで、既定値を @code{LC_CATEGORY}
30785 環境変数または、適当なシステム既定値(たとえば @code{LC_MESSAGES})に
30786 設定します。一般にはこれを指定する必要はありません。
30787
30788 @var{cached?} は個別のメッセージをキャッシュするかを意味し、デフォルトは
30789 @code{#t} です。
30790
30791 @var{lookup-cached?}
30792 は、これらのパラメータで生成されるディスパッチをキャッシュするかどうか
30793 を意味し、デフォルトは @code{#t} です。
30794
30795 @code{textdomain} はこれらのパラメータを内部の @code{make-gettext} に
30796 渡し、その結果を、@code{gettext} で使われるグローバルなディスパッチに
30797 束縛します。これらのクロージャを複数の別々のドメインやロケールを一度に
30798 扱うのに便利なように、手で構築することができます。(これらは
30799 サーバ環境で便利です。) 後述の @code{make-gettext} を参照してください。
30800
30801 @code{textdomain} はそのドメインの情報をもつ @emph{アクセサ手続き}を
30802 返します。詳細については、後述の @code{make-gettext} を参照してください。
30803 @c COMMON
30804 @end defun
30805
30806 @defun gettext msg-id
30807 @c MOD text.gettext
30808 @c EN
30809 Returns a translated message of @var{msg-id}. If there's no
30810 translated message, @var{msg-id} itself is returned.
30811 @c JP
30812 @var{msg-id} の翻訳されたメッセージを返します。もし、翻訳された
30813 メッセージがなければ、@var{msg-id} それ自身を返します。
30814 @c COMMON
30815 @end defun
30816
30817 @defun ngettext msg-id :optional msg-id2 num
30818 @c MOD text.gettext
30819 @c EN
30820 Similar to @var{gettext}, but it can be used to handle
30821 plural forms.
30822 Pass a singular form to @var{msg-id}, and plural form to
30823 @code{msg-id2}. The @var{num} argument is used to determine
30824 the plural form. If no message catalog is found, @var{msg-id}
30825 is returned when @var{num} is 1, and @var{msg-id2} otherwise.
30826 @c JP
30827 @var{gettext}と似ていますが、複数形を処理するのに使うことが
30828 できます。単数形のメッセージを @var{msg-id} へ、複数形のメッセージを
30829 @code{msg-id2} に渡します。@var{num} 引数は、複数形を決定
30830 するのに使われます。もし、メッセージカタログが見つからなければ、
30831 @var{num} が 1 のときは、@var{msg-id} が返り、そうでなければ、
30832 @var{msg-id2} が返ります。
30833 @c COMMON
30834 @end defun
30835
30836 @defun bindtextdomain domain dirs
30837 @c MOD text.gettext
30838 @c EN
30839 Sets the search path of domain @var{domain} to @var{dirs}, which
30840 may be just a single directory name or a list of directory names.
30841 @c JP
30842 ドメイン @var{domain} のサーチパスを @var{dirs} に設定します。
30843 単一のディレクトリ名であったり、ディレクトリのリストであったりします。
30844 @c COMMON
30845 @end defun
30846
30847 @defun dgettext domain msg-id
30848 @defunx dcgettext domain msg-id locale
30849 @c MOD text.gettext
30850 @c EN
30851 Returns a translated message of @var{msg-id} in @var{domain}.
30852 @code{Dcgettext} takes @var{locale} as well.
30853 @c JP
30854 @var{domain} 中の @var{msg-id} の翻訳されたメッセージを返します。
30855 @code{dcgettext} は @var{locale} も引数としてとります。
30856 @c COMMON
30857 @end defun
30858
30859 @c EN
30860 @subheading Low-level flexible API
30861 @c JP
30862 @subheading 低水準の柔軟な API
30863 @c COMMON
30864
30865 @c EN
30866 The following procedure is more flexible interface, on top of which
30867 the gettext-compatible APIs are written.
30868 @c JP
30869 以下の手続きはより柔軟性のあるインタフェースで、この上で、gettext-互換の
30870 API が書かれています。
30871 @c COMMON
30872
30873 @defun make-gettext :optional domain locale dirs gettext-cached? lookup-cached?
30874 @c MOD text.gettext
30875 @c EN
30876 Creates and returns an @emph{accessor procedure}, which encapsulates
30877 methods to retrieve localized messages.
30878
30879 The meaning of arguments are the same as @code{textdomain} above.
30880 Indeed, @code{textdomain} just calls @code{make-gettext}, and later
30881 it binds the result to the global parameter. If you wish to have
30882 multiple independent domains within a single program, you can
30883 call @code{make-gettext} directly and manage the created
30884 accessor procedure by yourself.
30885 @c JP
30886 @emph{アクセサ手続き} を生成して返します。返された手続きは、
30887 地域化されたメッセージを検索するメソッドをカプセル化しています。
30888
30889 引数の意味は上述の @code{textdomain} と同じです。
30890 実際は、@code{textdomain} は @code{make-gettext} を呼び、その後、
30891 それは、結果をこのグローバルパラメータに束縛します。@code{make-gettext}
30892 を直接呼んで、自分自身で、アクセサ手続きを管理することもできます。
30893 @c COMMON
30894
30895 @example
30896 (define my-gettext (make-gettext "myapp"))
30897 (define _ (my-gettext 'getter))
30898 (_ "Hello, World!")
30899 @end example
30900 @end defun
30901
30902 @c ----------------------------------------------------------------------
30903 @node Simple HTML document construction, Accessing info document, Localized messages, Library modules - Utilities
30904 @section @code{text.html-lite} - Simple HTML document construction
30905 @c NODE シンプルなHTMLドキュメントの構築, @code{text.html-lite} - シンプルなHTMLドキュメントの構築
30906
30907 @deftp {Module} text.html-lite
30908 @mdindex text.html-lite
30909 @c EN
30910 Provides procedures to construct an HTML document easily.
30911 For example, you can construct an HTML table by the following code:
30912 @c JP
30913 HTML ドキュメントを簡単に構築するための手続きを提供します。
30914 例えば、以下のコードは HTML のテーブルを構築します。
30915 @c COMMON
30916 @example
30917 (html:table
30918 (html:tr (html:th "Item No") (html:th "Quantity"))
30919 (html:tr (html:td 1) (html:td 120))
30920 (html:tr (html:td 2) (html:td 30))
30921 (html:tr (html:td 3) (html:td 215)))
30922 @end example
30923 @c EN
30924 See the description of @code{html:@var{element}} below for details.
30925
30926 This module does little check for the constructed html documents,
30927 such as whether the attributes are valid, and whether the content
30928 of the element matches DTD. It does not provide a feature to parse
30929 the html document neither. Hence the name `lite'.
30930 @c JP
30931 詳細については、以下の @code{html:@var{element}} の説明を見てください。
30932
30933 このモジュールでは生成されたHTMLドキュメントに関して、
30934 例えばアトリビュートに有効な値が入っているか、要素の内容はDTDを満たしているか、
30935 等のチェックをほとんど行いません。また、HTMLをパーズする関数も提供されません。
30936 それが「lite」の名の由来です。
30937 @c COMMON
30938 @end deftp
30939
30940 @defun html-escape
30941 @defunx html-escape-string string
30942 @c MOD text.html-lite
30943 @c EN
30944 Escapes the ``unsafe'' characters in HTML. @code{html-escape}
30945 reads input string from the current input port and writes the result
30946 to the current output port. @code{html-escape-string} takes the
30947 input from @var{string} and returns the result in a string.
30948 @c JP
30949 HTML に含まれる"安全でない"文字をエスケープします。
30950 @code{html-escape} は、現在の入力ポートから文字列を読み込み、
30951 結果を現在の出力ポートへ書き出します。@code{html-escape-string} は
30952 @var{string} を入力とし、文字列を返します。
30953 @c COMMON
30954 @end defun
30955
30956 @defun html-doctype :key type
30957 @c MOD text.html-lite
30958 @c EN
30959 Returns a doctype declaration for an HTML document.
30960 @var{type} can be either one of the followings (default is
30961 @code{:html-4.01-strict}).
30962 @c JP
30963 HTML ドキュメントの文書型宣言を返します。
30964 @var{type} は、以下のいずれかを指定します (デフォルトは@code{:html-4.01-strict}
30965 です)。
30966 @c COMMON
30967 @table @code
30968 @item :html-4.01-strict, :html-4.01, :strict
30969 HTML 4.01 Strict DTD
30970 @item :html-4.01-transitional, :transitional
30971 HTML 4.01 Transitional DTD
30972 @item :html-4.01-frameset, :frameset
30973 HTML 4.01 Frameset DTD
30974 @item :xhtml-1.0-strict, :xhtml-1.0
30975 XHTML 1.0 Strict DTD
30976 @item :xhtml-1.0-transitional
30977 XHTML 1.0 Transitional DTD
30978 @item :xhtml-1.0-frameset
30979 XHTML 1.0 Frameset DTD
30980 @item :xhtml-1.1
30981 XHTML 1.1 DTD
30982 @end table
30983 @end defun
30984
30985 @deftp {Function} html:@var{element} @var{args} @dots{}
30986 @findex html:a
30987 @findex html:abbr
30988 @findex html:acronym
30989 @findex html:address
30990 @findex html:area
30991 @findex html:b
30992 @findex html:base
30993 @findex html:bdo
30994 @findex html:big
30995 @findex html:blockquote
30996 @findex html:body
30997 @findex html:br
30998 @findex html:button
30999 @findex html:caption
31000 @findex html:cite
31001 @findex html:code
31002 @findex html:col
31003 @findex html:colgroup
31004 @findex html:dd
31005 @findex html:del
31006 @findex html:dfn
31007 @findex html:div
31008 @findex html:dl
31009 @findex html:dt
31010 @findex html:em
31011 @findex html:fieldset
31012 @findex html:form
31013 @findex html:frame
31014 @findex html:frameset
31015 @findex html:h1
31016 @findex html:h2
31017 @findex html:h3
31018 @findex html:h4
31019 @findex html:h5
31020 @findex html:h6
31021 @findex html:head
31022 @findex html:hr
31023 @findex html:html
31024 @findex html:i
31025 @findex html:iframe
31026 @findex html:img
31027 @findex html:input
31028 @findex html:ins
31029 @findex html:kbd
31030 @findex html:label
31031 @findex html:legend
31032 @findex html:li
31033 @findex html:link
31034 @findex html:map
31035 @findex html:meta
31036 @findex html:noframes
31037 @findex html:noscript
31038 @findex html:object
31039 @findex html:ol
31040 @findex html:optgroup
31041 @findex html:option
31042 @findex html:p
31043 @findex html:param
31044 @findex html:pre
31045 @findex html:q
31046 @findex html:samp
31047 @findex html:script
31048 @findex html:select
31049 @findex html:small
31050 @findex html:span
31051 @findex html:strong
31052 @findex html:style
31053 @findex html:sub
31054 @findex html:sup
31055 @findex html:table
31056 @findex html:tbody
31057 @findex html:td
31058 @findex html:textarea
31059 @findex html:tfoot
31060 @findex html:th
31061 @findex html:thead
31062 @findex html:title
31063 @findex html:tr
31064 @findex html:tt
31065 @findex html:ul
31066 @findex html:var
31067 @c MOD text.html-lite
31068 @c EN
31069 Construct an HTML element @var{element}. Right now,
31070 the following elements are provided.
31071 (The elements defined in HTML 4.01 DTD,
31072 @uref{http://www.w3.org/TR/html4/sgml/dtd.html}).
31073 @c JP
31074 @var{element} の HTML 要素を構築します。現時点では以下の要素が
31075 サポートされています。
31076 (HTML 4.01 DTD @uref{http://www.w3.org/TR/html4/sgml/dtd.html}
31077 に定義されている要素です)。
31078 @c COMMON
31079 @example
31080 a abbr acronym address area b
31081 base bdo big blockquote body br
31082 button caption cite code col colgroup
31083 dd del dfn div dl dt
31084 em fieldset form frame frameset
31085 h1 h2 h3 h4 h5 h6
31086 head hr html i iframe img
31087 input ins kbd label legend li
31088 link map meta noframes noscript object
31089 ol optgroup option p param pre
31090 q samp script select small span
31091 strong style sub sup table tbody
31092 td textarea tfoot th thead title
31093 tr tt ul var
31094 @end example
31095
31096 @c EN
31097 The result of these functions is a tree of text segments,
31098 which can be written out to a port by @code{write-tree} or
31099 can be converted to a string by @code{tree->string}
31100 (@pxref{Lazy text construction}).
31101
31102 You can specify attributes of the element by using a keyword-value
31103 notation before the actual content.
31104 @c JP
31105 これらの手続きは、テキスト・セグメントのツリーを返すので、
31106 @code{write-tree} でポートに書き出したり、@code{tree->string} で
31107 文字列に変換したりできます
31108 (@ref{Lazy text construction}参照)。
31109
31110 要素のアトリビュートは要素の内容に先立つキーワード-値の表記で指定することができます。
31111 @c COMMON
31112 @example
31113 (tree->string (html:a :href "http://foo/bar" "foobar"))
31114 @result{}
31115 "<a href=\"http://foo/bar\">foobar</a\n>"
31116
31117 (tree->string
31118 (html:table :width "100%" :cellpadding 0 "content here"))
31119 @result{}
31120 "<table width=\"100%\" cellpadding=\"0\">content here</table\n>"
31121 @end example
31122
31123 @c EN
31124 The boolean value given to the attribute has a special meaning.
31125 If @code{#t} is given, the attribute is rendered without a value.
31126 If @code{#f} is given, the attribute is not rendered.
31127 @c JP
31128 属性に与える真偽値は特別な意味を持ちます。
31129 @code{#t} が与えられると、属性は値なしでレンダリングされます。
31130 @code{#f} が与えられると、属性それ自体がレンダリングされません。
31131 @c COMMON
31132 @example
31133 (tree->string (html:table :border #t))
31134 @result{} "<table border></table\n>"
31135
31136 (tree->string (html:table :border #f))
31137 @result{} "<table></table\n>"
31138 @end example
31139
31140 @c EN
31141 Special characters in attribute values are escaped by the function,
31142 but the ones in the content are not. It is caller's responsibility
31143 to escape them.
31144
31145 The functions signal an error if a content is given to the
31146 HTML element that doesn't take a content. They do not
31147 check if the given attribute is valid, neither
31148 if the given content is valid for the element.
31149 @c JP
31150 属性の値における特別な文字は、手続きによってエスケープされますが、
31151 要素の内容にある特別な文字はエスケープされません。それをエスケープ
31152 するのは呼び出し側の責任です。
31153
31154 内容を持たない HTML 要素に内容を与えると手続きはエラーを通知します。
31155 手続きは、与えられた属性が妥当であるか、与えられた内容がその要素に
31156 とって妥当であるかのチェックはしません。
31157 @c COMMON
31158
31159 @c EN
31160 @emph{Note:}
31161 You might have noticed that these procedures insert a newline
31162 before @code{>} of the closing tag. That is, the rendered
31163 HTML would look like this:
31164 @c JP
31165 @emph{注意:}
31166 これらの手続は改行を終了タグの@code{>}の前に挿入することに注意してくだ
31167 さい。つまり、HTMLをレンダリングすると以下のようになります。
31168 @c COMMON
31169
31170 @example
31171 <table><tr><td>foo</td
31172 ><td>bar</td
31173 ></tr
31174 ></table
31175 >
31176 @end example
31177
31178 @c EN
31179 We intentionally avoid inserting newlines after the closing
31180 tag, since @emph{it depends on the surrounding context whether
31181 the newline is significant or not}. We may be able to insert newlines
31182 after the elements directly below a @code{<head>} element,
31183 for example, but we cannot in a @code{<p>} element, without
31184 affecting the content.
31185 @c JP
31186 終了ダグの後に改行をいれないのは意図的なものです。@emph{改行が意味をも
31187 つかどうかは外側の文脈に依存するからです}。たとえば、@code{<head>}要素
31188 の直下にある要素の後に改行を入れてもテキストの内容には影響を与えませんが、
31189 @code{<p>}要素中で改行を入れるとそれは内容の一部となってしまいます。
31190 @c COMMON
31191
31192 @c EN
31193 There are three possible solutions: (1) not to insert newlines
31194 at all, (2) to insert newlines within tags, and (3) to insert
31195 newlines only at the safe position. The first one creates one
31196 long line of HTML, and although it is still valid HTML, it is
31197 inconvenient to handle it with line-oriented tools.
31198 The third one requires the
31199 rendering routine to be aware of DTD. So we took the second
31200 approach.
31201 @c JP
31202 3つ可能性があって、(1) 改行は全く入れない、(2) タグの中だけで改行を入
31203 れる。(3) 安全な場所にのみ改行をいれる。最初の場合はHTMLは一行になり、
31204 正当なHTMLではあるものの、行指向のツールで処理するには不便です。3番目
31205 の場合はレンダリングするのにDTDをちゃんと見るツールが必要になります。
31206 というわけで、ここでは2番目のアプローチを取っています。
31207 @c COMMON
31208 @end deftp
31209
31210 @c ----------------------------------------------------------------------
31211 @node Accessing info document, Multicolumn formatting, Simple HTML document construction, Library modules - Utilities
31212 @section @code{text.info} - Accessing info document
31213 @c NODE infoドキュメントアクセス, @code{text.info} - infoドキュメントアクセス
31214
31215 @deftp {Module} text.info
31216 @mdindex text.info
31217 @c EN
31218 This module provides some basic functionalities to extract information
31219 from @code{info} files, a documentation format defined by
31220 @code{texinfo} system (@url{https://www.gnu.org/software/texinfo/}).
31221 It is used in REPL toplevel commands @code{info}and @code{doc}
31222 (@pxref{Working in REPL}).
31223 It focuses mainly to handle Gauche documents, so it may not handle
31224 all features used in texinfo.
31225 @c JP
31226 このモジュールは、@code{texinfo}システムが生成する
31227 @code{info}ファイルから情報を抜き出す基本的な機能を提供します。
31228 (texinfoについては@url{https://www.gnu.org/software/texinfo/}参照)。
31229 REPLのトップレベルコマンド@code{info}や@code{doc}はこのモジュールを
31230 使っています(@ref{Working in REPL})。
31231 主にGaucheのドキュメントを扱うために作られたので、texinfoの全ての機能はカバーされていません。
31232 @c COMMON
31233 @end deftp
31234
31235 @deftp {Class} <info-document>
31236 @clindex info-file
31237 @c MOD text.info
31238 @c EN
31239 An object for opened info file(s), returned by @code{open-info-document}.
31240 All slots are private.
31241 @c JP
31242 infoファイルの集合であるinfoドキュメントを表すオブジェクトです。
31243 @code{open-info-document}が返します。スロットは全てプライベートです。
31244 @c COMMON
31245 @end deftp
31246
31247 @deftp {Class} <info-node>
31248 @clindex info-node
31249 @c MOD text.info
31250 @c EN
31251 An object for each info node. It keeps the node's content, as well
31252 as links to neighboring nodes. Its instance should be considered
31253 immutable object.
31254
31255 A node can be obtained from an @code{<info-document>} object by
31256 @code{info-get-node}.
31257 @c JP
31258 infoノードを表すオブジェクトです。ノードの内容と他のノードへの参照を持っています。
31259 インスタンスは変更不可なオブジェクトとして扱われなければなりません。
31260
31261 @code{<info-document>}オブジェクトに@code{info-get-node}を適用することで
31262 ノードを得ることができます。
31263 @c COMMON
31264
31265 @defivar <info-node> name
31266 @c EN
31267 A string name of the info node. Every info document has at least
31268 @code{"Top"} node.
31269 @c JP
31270 ノードの名前の文字列です。どのinfoドキュメントにも、最低限@code{"Top"}ノードは
31271 含まれています。
31272 @c COMMON
31273 @end defivar
31274
31275 @defivar <info-node> next
31276 @c EN
31277 The string name of the next node. You can visit all nodes in
31278 the document following the next link.
31279 It may be @code{#f} if the node is the last one of the document.
31280 @c JP
31281 「次」のノードの名前の文字列です。「次」をたどってゆくことで、ドキュメントの全ての
31282 ノードを見ることができます。
31283 ドキュメントの最後のノードでは@code{#f}になっています。
31284 @c COMMON
31285 @end defivar
31286
31287 @defivar <info-node> prev
31288 @c EN
31289 The string name of the previous node. It's a reverse link
31290 of the next node. The previous node of @code{"Top"} is
31291 @code{"(dir)"} by convention, which is a special node
31292 that lists all info documents installed on the system (it is not
31293 included in the info document itself.)
31294 @c JP
31295 「前」のノードの名前の文字列です。「次」のノードとは逆のリンクになっています。
31296 @code{"Top"}のノードの前は慣習により@code{"(dir)"}となっていて、
31297 infoシステムではシステムにインストールされている全てのinfoドキュメントを表示する
31298 特別なノード名となっています。
31299 @c COMMON
31300 @end defivar
31301
31302 @defivar <info-node> up
31303 @c EN
31304 If the node is a subnode, this contains the name of the upper node
31305 (a chapter name for sections, a section name for subsections, etc.)
31306 It is @code{#f} for @code{"Top"} node.
31307 @c JP
31308 このノードが他のノードのサブノードなら、親となるノードの名前の文字列。
31309 例えばこのノードが節(section)なら、親は章(chapter)です。
31310 @code{"Top"}ノードではここは@code{#f}です。
31311 @c COMMON
31312 @end defivar
31313
31314 @defivar <info-node> file
31315 @c EN
31316 An @code{<info-document>} object of the info document this node is contained.
31317 @c JP
31318 このノードが含まれる@code{<info-document>}オブジェクトです。
31319 @c COMMON
31320 @end defivar
31321
31322 @defivar <info-node> content
31323 @c EN
31324 A string content of the node.
31325 @c JP
31326 ノードの内容の文字列です。
31327 @c COMMON
31328 @end defivar
31329 @end deftp
31330
31331 @defun open-info-document info-file-path
31332 @c MOD text.info
31333 @c EN
31334 Open the named info document and returns an @code{<info-document>} instance.
31335 The argument is a pathname to a master info file, usually with
31336 @code{.info} suffix. Depending on the installation, info files
31337 may be compressed with gzip or bzip2, having extensions
31338 @code{.gz} or @code{.bz2} after @code{.info}; you don't need to
31339 specify those extensions. The procedure searches possible compression
31340 options.
31341 @c JP
31342 指定されたパスのinfoドキュメントを読み込んで@code{<info-document>}インスタンスを
31343 返します。引数はマスターinfoファイルのパス名で、通常@code{.info}サフィックスが
31344 ついています。インストール状況によってはinfoファイルはgzipやbzip2で圧縮されていて、
31345 @code{.info}の後に@code{.gz}や@code{.bz2}がついていることもありますが、
31346 これらの圧縮サフィックスはつける必要がありません。この手続きは指定のパス名そのものが
31347 見つからなかったら圧縮サフィックスがついている名前も探します。
31348 @c COMMON
31349
31350 @c EN
31351 A large info document may be splitted into multiple info files,
31352 each with a suffix @code{.info-1}, @code{.info-2} etc. Those are
31353 automatically read, so you only need to give the path to the master file.
31354 @c JP
31355 大きなinfoドキュメントは分割されていて、それぞれに@code{.info-1}、@code{.info-2}
31356 などの名前がついていますが、それらは自動的に読まれるので、マスターとなるinfoファイルだけ
31357 指定すれば良いです。
31358 @c COMMON
31359
31360 @c EN
31361 If it can't find the named document, or can't recognize its format,
31362 an error is thrown.
31363 @c JP
31364 infoドキュメントが見つからなかったり、ファイルフォーマットが認識できなかった場合は
31365 エラーが投げられます。
31366 @c COMMON
31367 @end defun
31368
31369 @defun info-get-node info-doc node-name
31370 @c MOD text.info
31371 @c EN
31372 The @var{info-doc} argument is an @code{<info-document>} instance.
31373 Returns an @code{<info-node>} instance with the string name @var{node-name},
31374 or @code{#f} if no node with the given name is found.
31375 @c JP
31376 @code{<info-document>}のインスタンス@var{info-doc}から、
31377 @var{node-name}を持つノードを探して、その@code{<info-node>}インスタンスを返します。
31378 該当するノードが見つからなければ@code{#f}を返します。
31379 @c COMMON
31380 @end defun
31381
31382 @defun info-index-add! info-doc index-node-name :optional key-modifier
31383 @c MOD text.info
31384 @c EN
31385 Read the node named @var{index-node-name} in the info document
31386 @var{info-doc}, and adds its menu entries into the index table.
31387 @c JP
31388 infoドキュメント@var{info-doc}にある、名前@var{index-node-name}持つノードを
31389 読み取り、そのメニューの内容をインデックステーブルに加えます。
31390 @c COMMON
31391
31392 @c EN
31393 It is particularly useful to give the index page of the info doc,
31394 so that you'll be able to lookup particular term (e.g. function name)
31395 quickly. Typical info document has a node called @code{Index}.
31396 Large documents, such as programming language reference
31397 (Gauche Users' Reference is one of them) may have multiple
31398 index pages for different categories. You can call this procedure
31399 multiple times to add more than one index pages.
31400 @c JP
31401 この手続きは、infoドキュメントの索引ノードを読み込んで索引を作るのに便利です。
31402 例えば関数索引のページを読み込めば、関数名から定義があるノードを探し当てることができます。
31403 典型的なinfoドキュメントでは、索引ページには@code{Index}という名前がついています。
31404 但し、長いドキュメントでは索引がカテゴリごとに分けられていて、
31405 それぞれ違う名前がついているかもしれません (Gaucheのユーザリファレンスもそのひとつです)。
31406 この手続きをそれぞれの索引ノードについて呼び出すことで、複数の索引ノードの内容を
31407 取り込むことができます。
31408 @c COMMON
31409
31410 @c EN
31411 The optional @var{key-modifier} argument is a procedure applied to
31412 the entry-name (string) to obtain a key (string) in the index table.
31413 Sometimes the index uses different entry name
31414 from the actual name; e.g. Gauche's class index lists class names without
31415 surrounding @code{<} and @code{>}, since using the actual name makes all
31416 class names being listed below @code{<} subheading, which isn't very useful.
31417 You can pass @code{(^e #"<~|e|>")} as @var{key-modifier} to recover the actual
31418 class name to be used as the key.
31419 @c JP
31420 省略可能な@var{key-modifier}引数は、索引ノードのテーブルのキー(文字列)を取って
31421 実際の見出しを文字列で返す手続きです。
31422 しばしば索引に示されるキーは、実際の見出しとは異なることがあります。
31423 例えばGaucheのクラス索引は、クラス名を囲む@code{<}と@code{>}を取り除いたものを
31424 キーとしています。実際の名前を使うと、全てのキーが@code{<}の下に集められてしまい
31425 あまり有用ではないからです。この場合は、@var{key-modifier}に
31426 @code{(^e #"<~|e|>")}を渡すことで、実際の名前で索引を引けるようになります。
31427 @c COMMON
31428
31429 @c EN
31430 If there are more than one entries per key, both are saved in the
31431 index table. See @code{info-index-ref} below.
31432 @c JP
31433 同じキーに対応するエントリが複数ある場合、それらは全てテーブルに格納されます。
31434 下の@code{info-index-ref}を参照してください。
31435 @c COMMON
31436 @end defun
31437
31438 @defun info-index-ref info-doc key
31439 @c MOD text.info
31440 @c EN
31441 Lookup index with the given key. Returns a list of
31442 @code{(@var{node-name} @var{line-number})}.
31443
31444 You can use pass @var{node-name} to @code{info-node-get} to obtain the
31445 info node contaning the definition, then pass the node and
31446 @var{line-number} to @code{info-extract-definition}
31447 to obtain the definition as a text.
31448 @c JP
31449 キーに対応するエントリを索引テーブルから探し、
31450 @code{(@var{node-name} @var{line-number})}のリストを返します。
31451
31452 @var{node-name}を@code{info-node-get}に渡せば定義を含んでいるinfoノードを
31453 得られます。また、そのinfoノードと@var{line-number}を
31454 @code{info-extract-definition}に渡せば定義をテキストで得ることができます。
31455 @c COMMON
31456 @end defun
31457
31458 @defun info-index-keys info-doc
31459 @c MOD text.info
31460 @c EN
31461 Returns a list of keys (strings) in the index.
31462 @c JP
31463 infoドキュメントの索引テーブルに登録されているキー(文字列)のリストを返します。
31464 @c COMMON
31465 @end defun
31466
31467 @defun info-index->alist info-doc
31468 @c MOD text.info
31469 @c EN
31470 Returns the content of the index
31471 as @code{((key (node line) ...) ...)}.
31472 @c JP
31473 infoドキュメントの索引テーブルの内容を
31474 @code{((key (node line) ...) ...)}の形で返します。
31475 @c COMMON
31476 @end defun
31477
31478 @defun info-parse-menu info-node
31479 @c MOD text.info
31480 @c EN
31481 This is used in @code{info-index-add!}, but it is generally
31482 useful to parse a menu in an info node. It searches
31483 the @code{* Menu:} line, then gathers menu entry names and
31484 associated node names. Some menus such as index page also
31485 lists line numbers for each entry.
31486 @c JP
31487 これは@code{info-index-add!}の中で使われている手続きですが、
31488 単独でinfoノード中のメニューをパーズするのにも使えます。
31489 @code{* Menu:}という行を探し、見つかったらそれに続く
31490 エントリ名とノード名を集めます。索引ページの場合はノード名だけでなく
31491 定義のある行番号も記されています。
31492 @c COMMON
31493
31494 @c EN
31495 Returns a list of menu entries.
31496 Each menu entry is the following form:
31497 @c JP
31498 見つかったメニューエントリのリストを返します。各エントリは次の形です。
31499 @c COMMON
31500 @example
31501 (<entry-name> <node-name> [<line-number>])
31502 @end example
31503 @end defun
31504
31505 @defun info-extract-definition info-node start-line
31506 @c MOD text.info
31507 @c EN
31508 Extract one definition from the node's content. Assumes the definition
31509 begins from the specified line; then we go forward to find the end of
31510 the definition. The end of definition is when we see the end of content,
31511 or we see a line begins with less than or equal to 3 whitespaces.
31512 (Except the 'defunx'-type multi entry).
31513 @c JP
31514 ノードの内容から、ひとつの定義を抜き出して文字列で返します。
31515 定義は@var{start-line}で示される行から始まっていると解釈されます。
31516 その行から順に見てゆき、定義の終わりを探します。定義の終わりは、
31517 infoノードの終わりか、3つ未満の空白文字で始まっている行の手前までです
31518 (但し、'defunx'形式の複数エントリは定義の終わりとはみなされません)。
31519 @c COMMON
31520
31521 @c EN
31522 Returns a string describing the definition. If no definition is found,
31523 an empty string is returned.
31524 @c JP
31525 定義を記述している文字列を返します。定義が見つからなければ空文字列が返ります。
31526 @c COMMON
31527
31528 @c EN
31529 A typical idiom is to add index node using @code{info-index-add!},
31530 and get the node name and line number of the definition of a specific
31531 item with @code{info-index-ref}, then
31532 then use this procedure to extract the definition.
31533 @c JP
31534 典型的な使いかたは、まず索引ノードを@code{info-index-add!}で登録しておき、
31535 @code{info-index-ref}で知りたい見出しの定義を含むノードと行を入手して、
31536 この手続きで実際の定義を得るというものです。
31537 @c COMMON
31538 @end defun
31539
31540 @c ----------------------------------------------------------------------
31541 @node Multicolumn formatting, Display with pager, Accessing info document, Library modules - Utilities
31542 @section @code{text.multicolumn} - Multicolumn formatting
31543 @c NODE 複数列フォーマット, @code{text.multicolumn} - 複数列フォーマット
31544
31545 @deftp {Module} text.multicolumn
31546 @mdindex text.multicolumn
31547 @c EN
31548 This module provides the means to format a list of words into
31549 a multicolumn text. Think of the output of @code{ls} command.
31550 @c JP
31551 このモジュールは、単語のリストを複数カラム形式に揃えてフォーマットする手段を提供します。
31552 @code{ls}コマンドの出力のようなものを想像してください。
31553 @c COMMON
31554
31555 @example
31556 (display-multicolumn
31557 (string-tokenize "The quick brown fox \
31558 jumps over the lazy dog"))
31559 @result{} @r{prints}
31560 The fox the
31561 quick jumps lazy
31562 brown over dog
31563 @end example
31564
31565 @c EN
31566 Various options are provided to customize the output.
31567 @c JP
31568 出力をカスタマイズできる様々なオプションが提供されます。
31569 @c COMMON
31570 @end deftp
31571
31572 @defun display-multicolumn strs :key width minimum-width max-columns order indent
31573 @c MOD text.multicolumn
31574 @c EN
31575 Display items in a list of strings @var{strs} in multicolumn format,
31576 to the current output port.
31577 The items shouldn't contain newline or tab characters; the procedure
31578 doesn't treat them specially, so the output would be disturbed.
31579
31580 The width of a column is chosen to contain the longest string in @var{strs}
31581 or @var{minimum-width}, whichever greater.
31582 The default of @var{minimum-width} is 8.
31583 @c JP
31584 文字列のリスト@var{strs}の要素を、現在の出力ポートに複数カラム形式に揃えて表示します。
31585 要素中にタブや改行文字があってはなりません。手続きはタブや改行文字を特別扱いしないので、
31586 もし含まれていた場合は出力が乱れます。
31587
31588 カラムの幅は、@var{strs}中の文字列のうち最も長いものか、@var{minimum-width}の
31589 どちらか大きい方で決まります。@var{minimum-width}のデフォルトは8です。
31590 @c COMMON
31591
31592 @c EN
31593 Then as many columns are displayed as fit in @var{width} characters,
31594 whose default is 80. However, the number of columns won't exceed
31595 @var{max-columns} if it is given and not @code{#f}.
31596 @c JP
31597 カラムの幅が決まったら、@var{width}文字の幅にいくつのカラムが収まるかが計算されます。
31598 @var{width}のデフォルトは80です。但し@var{max-columns}が与えられて@code{#f}でなければ、
31599 カラム数は@var{max-column}を越えません。
31600 @c COMMON
31601
31602 @c EN
31603 The @var{order} argument must be either a symbol @code{column} or
31604 @code{row}. If it is @code{column} (default), the items are sorted
31605 column-first; that is, it is filled in the first column from top to
31606 down, then the second column from top to down, and so on.
31607 If it is @code{row}, the items are sorted row-first; it is filled
31608 in the first row from left to right, and then second row, and so on.
31609 @c JP
31610 @var{order}引数はシンボル@code{column}か@code{row}のどちらかです。
31611 @code{column}の場合(デフォルト)、要素はカラムファースト、つまり最初のカラムを
31612 上から下へ、それから第二カラムを上から下へ、という順に並べられます。
31613 @code{row}の場合はロウファースト、つまり最初の行の左から右、次の行の左から右、
31614 という順に並べられます。
31615 @c COMMON
31616
31617 @c EN
31618 The @var{indent} argument must be a nonnegative exact integer. If it is
31619 greater than zero, that number of whitespaces are prepended before
31620 each line. The @var{width} includes this indentation; so the actual
31621 area of text becomes narrower by @var{indent} characters.
31622 @c JP
31623 @var{indent}引数は、与えられたなら非負の正確な整数でなければなりません。
31624 これが1以上の場合、その数の空白文字が各行の先頭に追加されます。
31625 @var{width}で指定される幅はこのインデントを含んだものとなります。つまり
31626 テキストの表示領域の幅はこの引数の分だけ狭くなります。
31627 @c COMMON
31628 @end defun
31629
31630 @defun layout-multicolumn strs :key width minimum-width max-columns order
31631 @c MOD text.multicolumn
31632 @c EN
31633 This is an underlying procedure of @code{display-multicolumn}. It returns
31634 a list of text tree (@pxref{Lazy text construction}). Each text
31635 tree stands for a line, not including the newline character.
31636 This can be handy if you want to modify the layout.
31637 @c JP
31638 この手続きは@code{display-multicolumn}の下請けにあるもので、
31639 テキストツリーのリストを返します (テキストツリーについては
31640 @ref{Lazy text construction}参照)。
31641 各テキストツリーが一行に相当します。改行文字は含まれません。
31642 レイアウトを後から加工したい場合に便利です。
31643 @c COMMON
31644
31645 @example
31646 (layout-multicolumn
31647 (string-tokenize "The quick brown fox \
31648 jumps over the lazy dog"))
31649 @result{}
31650 (("The " "fox " "the")
31651 ("quick " "jumps " "lazy")
31652 ("brown " "over " "dog"))
31653 @end example
31654
31655 @c EN
31656 NB: The actual structure of each text tree may be changed, but
31657 passing it to @code{tree->string} or @code{write-tree} produces
31658 the line.
31659 @c JP
31660 註: テキストツリーの中身はバージョンによって異なるかもしれませんが、
31661 @code{tree->string}や@code{write-tree}に渡した結果は同じになります。
31662 @c COMMON
31663 @end defun
31664
31665
31666 @c ----------------------------------------------------------------------
31667 @node Display with pager, Parsing input stream, Multicolumn formatting, Library modules - Utilities
31668 @section @code{text.pager} - Display with pager
31669 @c NODE ページャーを用いた出力, @code{text.pager} - ページャーを用いた出力
31670
31671 @deftp {Module} text.pager
31672 @mdindex text.pager
31673 @c EN
31674 A convenience module to present long text nicely to the user.
31675 @c JP
31676 長いテキストをユーザに見やすく呈示するための便利モジュールです。
31677 @c COMMON
31678 @end deftp
31679
31680 @deffn {Parameter} pager-program
31681 @c MOD text.pager
31682 @c EN
31683 A parameter containing a list of pager program and its arguments
31684 (e.g. @code{("/usr/bin/less" "-M")}).
31685 @c JP
31686 ページャーとして使うプログラムとその引数のリストを保持するパラメータです。
31687 例: @code{("/usr/bin/less" "-M")}。
31688 @c COMMON
31689
31690 @c EN
31691 The program must take input from the standard input.
31692 @c JP
31693 プログラムは標準入力から入力を取らなければなりません。
31694 @c COMMON
31695
31696 @c EN
31697 The default value is taken from the environment variable @code{PAGER}
31698 if set, or either @code{less} or @code{more} if those programs are
31699 available on the system. If none is found, @code{#f} is set.
31700 @c JP
31701 デフォルトの値は、環境変数@code{PAGER}がセットされていればその値、
31702 そうでなければ、システムに@code{less}または@code{more}があればそれを使います。
31703 いずれにも該当しなければ@code{#f}になっています。
31704 @c COMMON
31705 @end deffn
31706
31707 @defun display/pager string
31708 @c MOD text.pager
31709 @c EN
31710 Display @var{string} by a pager subprocess specified by the parameter
31711 @code{pager-program}. The procedure returns when the subprocess exits.
31712 @c JP
31713 パラメータ@code{pager-program}で指定されるプログラムをサブプロセスとして起動し、
31714 @var{string}を表示させます。サブプロセスが終了するまでこの手続きは返ってきません。
31715 @c COMMON
31716
31717 @c EN
31718 If the terminal is not suitable for control
31719 (e.g. @code{TERM} is @code{dumb} or @code{emacs}), @var{string} is
31720 simply @code{display}ed without a pager.
31721 @c JP
31722 端末がページングに適さない場合 (例えば@code{TERM}が@code{dumb}や@code{emacs}である
31723 場合)は、@var{string}が単に@code{display}で表示されます。
31724 @c COMMON
31725
31726 @c EN
31727 If you're running MinGW version of @code{gosh} on mintty,
31728 calling subprocess pager doesn't work well, so the procedure
31729 emulate the pager behavior (@code{pager-program} is ignored).
31730 @c JP
31731 MinGWバージョンの@code{gosh}をminttyで使っている場合、
31732 サブプロセス経由のページングはうまく動かないので、
31733 この手続きがページャの動作をエミュレートします (@code{pager-program}は無視されます)。
31734 @c COMMON
31735 @end defun
31736
31737 @defun with-output-to-pager thunk
31738 @c MOD text.pager
31739 @c EN
31740 Call @var{thunk} with its current output port to a string buffer,
31741 then show the buffered output using @code{display/pager}.
31742 @c JP
31743 現在の出力ポートを文字列のバッファにして@var{thunk}を呼び出し、
31744 結果を@code{display/pager}で表示します。
31745 @c COMMON
31746 @end defun
31747
31748
31749 @c ----------------------------------------------------------------------
31750 @node Parsing input stream, Showing progress on text terminals, Display with pager, Library modules - Utilities
31751 @section @code{text.parse} - Parsing input stream
31752 @c NODE 入力ストリームのパージング, @code{text.parse} - 入力ストリームのパージング
31753
31754 @deftp {Module} text.parse
31755 @mdindex text.parse
31756 @c EN
31757 A collection of utilities that does simple parsing from
31758 the input port. The API is inspired, and compatible with
31759 Oleg Kiselyov's input parsing library (@uref{http://okmij.org/ftp/Scheme/parsing.html}).
31760 His library is used in lots of other libraries, notably,
31761 a full-Scheme XML parser/generator SSAX (@uref{http://okmij.org/ftp/Scheme/xml.html}).
31762
31763 You can use this module in place of his
31764 @code{input-parse.scm} and @code{look-for-str.scm}.
31765
31766 I reimplemented the functions to be efficient on Gauche.
31767 Especially, usage of @code{string-set!} is totally avoided.
31768 I extended the interface a bit so that they can deal with character sets
31769 and predicates, as well as a list of characters.
31770
31771 These functions work sequentially on the given input port,
31772 that is, they read from the port as much as they need, without
31773 buffering extra characters.
31774 @c JP
31775 入力ポートに対して単純な解析を行うユーティリティのコレクションです。
31776 API は Oleg Kiselyov 氏の入力解析ライブラリ (@uref{http://okmij.org/ftp/Scheme/parsing.html}) に
31777 触発され、互換性を持つものです。氏のライブラリは、他のたくさんの
31778 ライブラリで使われています。特に、Scheme のみで書かれたパーサ/ジェネレータ
31779 である SSAX (@uref{http://okmij.org/ftp/Scheme/xml.html}) が挙げられます。
31780
31781 このモジュールは、氏の @code{input-parse.scm} や @code{look-for-str.scm}
31782 の代わりに使うことができます。
31783
31784 Gauche で効果的になるように手続きを再実装しました。特に、@code{string-set!}
31785 の使用は完全に取り除きました。インターフェースを少し拡張したので、
31786 文字集合や述語、文字のリストにも使うことができます。
31787
31788 これらの手続きは、与えられた入力ポートに対してシーケンシャルに動作します。
31789 それは、ポートから必要なだけ読み、余分な文字をバッファリングしないということです。
31790 @c COMMON
31791 @end deftp
31792
31793 @defun find-string-from-port? str in-port :optional max-no-chars
31794 @c MOD text.parse
31795 @c EN
31796 Looks for a string @var{str} from the input port @var{in-port}.
31797 The optional argument @var{max-no-chars} limits the maximum number of
31798 characters to be read from the port; if omitted, the search span is
31799 until EOF.
31800
31801 If @var{str} is found, this function returns the number of characters
31802 it has read. The next read from @var{in-port} returns the next char
31803 of @var{str}. If @var{str} is not found, it returns @code{#f}.
31804
31805 Note: Although this procedure has `@code{?}' in its name,
31806 it may return non-boolean value, contrary to the Scheme convention.
31807 @c JP
31808 入力ポート @var{in-port} から、文字列 @var{str} を探します。
31809 オプショナル引数 @var{max-no-chars} は、ポートから読み込まれる最大文字数を
31810 制限します。省略されると、検索する範囲は EOF までとなります。
31811
31812 @var{str} が見つかると、手続きはすでに読み込んだ文字の数を返します。
31813 @var{in-port} の次回の読み込みは、@var{str} の次の文字を返します。
31814 @var{str} が見つからない場合、@code{#f} が返ります。
31815
31816 注意: この手続きはその名前に「@code{?}」がつきますが、Scheme の慣習に反し、
31817 真偽値ではない値を返すことがあります。
31818 @c COMMON
31819 @end defun
31820
31821 @defun peek-next-char :optional port
31822 @c MOD text.parse
31823 @c EN
31824 Discards the current character and peeks the next character from @var{port}.
31825 Useful to look ahead one character.
31826 If @var{port} is omitted, the current input port is used.
31827 @c JP
31828 現在の文字を破棄し、@var{port} から次の文字を読みます。一文字先読みするのに
31829 便利です。@var{port} が省略されると、現在の入力ポートが使われます。
31830 @c COMMON
31831 @end defun
31832
31833 @c EN
31834 In the following functions, @var{char-list} refers to one of the
31835 followings:
31836 @itemize @bullet
31837 @item
31838 A character set.
31839 @item
31840 A list of characters, character sets and/or symbol @code{*eof*}.
31841 @end itemize
31842 That denotes a set of characters. If a symbol @code{*eof*} is
31843 included, the EOF condition is also included. Without @code{*eof*},
31844 the EOF condition is regarded as an error.
31845 @c JP
31846 以下の手続きでは、@var{char-list} は次のどれかを意味します。
31847 @itemize @bullet
31848 @item
31849 文字集合。
31850 @item
31851 文字、文字集合、シンボル @code{*eof*} の任意の組み合わせのリスト。
31852 @end itemize
31853 これらにより文字の集合が表現されます。シンボル @code{*eof*} が含まれる場合、
31854 EOF の条件もまた含まれます。@code{*eof*} が含まれない場合、EOF の条件は
31855 エラーとして扱われます。
31856 @c COMMON
31857
31858 @defun assert-curr-char char-list string :optional port
31859 @c MOD text.parse
31860 @c EN
31861 Reads a character from @var{port}. If it is included in @var{char-list},
31862 returns the character. Otherwise, signals an error with a message
31863 containing @var{string}.
31864 If @var{port} is omitted, the current input port is used.
31865 @c JP
31866 @var{port} から文字を読みます。その文字が @var{char-list} に含まれている場合は
31867 その文字を返します。そうでなければ、@var{string} を含むメッセージとともに
31868 エラーを通知します。
31869 @c COMMON
31870 @end defun
31871
31872 @defun skip-until char-list/number :optional port
31873 @c MOD text.parse
31874 @c EN
31875 @var{char-list/number} is either a char-list or a number.
31876 If it is a number; it reads that many characters and returns @code{#f}.
31877 If the input is not long enough, an error is signaled.
31878 If @var{char-list/number} is a char-list, it reads from @var{port}
31879 until it sees a character that belongs to the char-list.
31880 Then the character is returned.
31881 If @var{port} is omitted, the current input port is used.
31882 @c JP
31883 @var{char-list/number} は、文字のリストか数です。
31884 数の場合、たくさんの文字を読んで、@code{#f} を返します。
31885 入力が十分に長くない場合は、エラーが通知されます。
31886 @var{char-list/number} が文字のリストの場合、その文字リストに属する文字に
31887 出会うまで @var{port} を読み込み、その文字を返します。
31888 @var{port} が省略された場合、現在の入力ポートが使われます。
31889 @c COMMON
31890 @end defun
31891
31892 @defun skip-while char-list :optional port
31893 @c MOD text.parse
31894 @c EN
31895 Reads from @var{port} until it sees a character that does not
31896 belong to @var{char-list}. The character remains in the stream.
31897 If it reaches EOF, an EOF is returned.
31898 If @var{port} is omitted, the current input port is used.
31899
31900 This example skips whitespaces from input. Next read from
31901 port returns the first non-whitespace character.
31902 @c JP
31903 @var{char-list} に属しない文字に出会うまで、@var{port} を読み込みます。
31904 文字はストリームに残されます。EOF に達したら EOF が返されます。
31905 @var{port} が省略された場合、現在の入力ポートが使われます。
31906
31907 この例では、入力から空白スペースをスキップしています。ポートからの次の
31908 読み込みは、最初の空白スペースでない文字を返します。
31909 @c COMMON
31910 @example
31911 (skip-while #[\s] port)
31912 @end example
31913 @end defun
31914
31915 @defun next-token prefix-char-list break-char-list :optional comment port
31916 @c MOD text.parse
31917 @c EN
31918 Skips any number of characters in @var{prefix-char-list},
31919 then collects the characters until it sees @var{break-char-list}.
31920 The collected characters are returned as a string.
31921 The break character remains in the @var{port}.
31922
31923 If the function encounters EOF and @code{*eof*} is not included in
31924 @var{break-char-list}, an error is signaled with @var{comment} is
31925 included in the message.
31926 @c JP
31927 @var{prefix-char-list} に含まれる文字はいくつでもスキップします。
31928 そして、@var{break-char-list} に含まれる文字に出会うまで、文字を
31929 蓄積します。蓄積された文字群は文字列として返されます。
31930 中断文字は @var{port} に残されます。
31931
31932 手続きが EOF に達し、@code{*eof*} が @var{break-char-list} に含まれていない
31933 場合、@var{comment} が含まれたメッセージとともにエラーが通知されます。
31934 @c COMMON
31935 @end defun
31936
31937 @defun next-token-of char-list/pred :optional port
31938 @c MOD text.parse
31939 @c EN
31940 Reads and collects the characters as far as
31941 it belongs to @var{char-list/pred}, then returns them as a string.
31942 The first character that doesn't belong to @var{char-list/pred} remains
31943 on the port.
31944
31945 @var{char-list/pred} may be a char-list or a predicate that takes
31946 a character. If it is a predicate, each character is passed to it,
31947 and the character is regarded to ``belong to'' @var{char-list/pred}
31948 when it returns a true value.
31949 @c JP
31950 読み込んだ文字が @var{char-list/pred} にある限り蓄積し、文字列として
31951 返します。@var{char-list/pred} に含まれない最初の文字はポートに残されます。
31952
31953 @var{char-list/pred} は文字のリストか文字を取る述語です。述語の場合、
31954 それぞれの文字がその述語に渡され、真の値が返る場合はその文字は
31955 @var{char-list/pred} に属するとみなされます。
31956 @c COMMON
31957 @end defun
31958
31959 @defun read-string n :optional port
31960 @c MOD text.parse
31961 @c EN
31962 This is like built-in @code{read-string} (@pxref{Reading data}),
31963 except that this returns @code{""} when the input already reached EOF.
31964
31965 Provided for the compatibility for the code that depends Oleg's library.
31966 @c JP
31967 組み込みの@code{read-string} (@ref{Reading data}参照) とほぼ同じですが、
31968 入力が既にEOFに達していた場合は@code{""}を返します。
31969
31970 Olegのライブラリに依存しているコードの互換性のために用意されています。
31971 @c COMMON
31972 @end defun
31973
31974 @c ----------------------------------------------------------------------
31975 @node Showing progress on text terminals, Segmented string matching, Parsing input stream, Library modules - Utilities
31976 @section @code{text.progress} - Showing progress on text terminals
31977 @c NODE テキスト端末上で進捗を表示する, @code{text.progress} - テキスト端末上で進捗を表示する
31978
31979 @deftp {Module} text.progress
31980 @mdindex text.progress
31981 @c EN
31982 This module provides a utility to report a progress of processing
31983 on a text terminal, using characters to display bar chart.
31984 @c JP
31985 このモジュールはバーチャートを文字を用いて表示し、テキスト端末上に処理
31986 の進行状況を出すためのユーティリティです。
31987 @c COMMON
31988
31989 @c EN
31990 The generic format of a progress bar consists of a single line
31991 of text, which is splitted into several parts; a header, which
31992 displays the title; followed by a bar, a numeric part, and a time part,
31993 as shown in the following example (only the line beginning with ``foo''
31994 is actually displayed).
31995 @c JP
31996 進捗を示すプログレスバーの汎用的なフォーマットは1行のテキストで構成されます。
31997 この1行はいくつかの部分に分解できます。タイトルを表示するヘッダ部、その後に
31998 プログレスバーがあって、数値部、時間部と続きます。以下がその例です(foo
31999 からはじまる1行だけが実際に表示されます。
32000 @c COMMON
32001 @example
32002 <-header-> <-------bar---------> <-num-><-time-> <---info---->
32003 foo |############# |123/211 01:21 ETA compiling...
32004 ^
32005 separator
32006 @end example
32007
32008 @c EN
32009 Various things like the character used in the bar chart or
32010 the format of the numeric progress can be configured.
32011 @c JP
32012 バーチャートに使う文字などのいろいろなバリエーションや、数値で表わす
32013 進捗のフォーマットなども設定可能です。
32014 @c COMMON
32015
32016 @c EN
32017 Internally a progress bar maintains two numbers, the maximum (goal)
32018 value and the current value. The bar shows the proportion of
32019 the current value relative to the maximum value. The numeric progress
32020 shows the current value over the maximum value by default, but you
32021 can configure it to show only the current value or percentage, for example.
32022 @c JP
32023 内部的にはプログレスバーは2つの数値、最大値(ゴール)と現在の値を保持し
32024 ています。バーは最大値に対する現在の値の比を示すものです。数値で表わす
32025 進捗はデフォルトでは最大値の上に現在の値を表示します。しかし、たとえば、
32026 現在の値だけを表示するとか、100分率で表示するなどの設定が可能です。
32027 @c COMMON
32028
32029 @c EN
32030 A progress bar also has two states, ``in progress'' and ``finished''.
32031 When it is in progress, every time the text is displayed it is
32032 followed by @code{#\return}, so that the next display overwrites
32033 the bar, and the time part shows ETA (estimated time of arrival).
32034 Once it becomes finished, the last line of text is displayed
32035 with @code{#\newline}, and the time part shows the actual time
32036 it took to finish.
32037 @c JP
32038 プログレスバーは2つの状態「進捗中」および「終了」のどちらかの状態を保
32039 持しています。「進捗中」なら、どの時点でも表示されるテキストには
32040 @code{#\return}が続きます。これにより次の表示が前の表示を上書きするこ
32041 とになります。時間部はETA(残り時間)を表示します。終了してしまえば、最
32042 後の行の後に@code{#\newline}が続きます。時間部には終了までにかかった時
32043 間が表示されます。
32044 @c COMMON
32045 @end deftp
32046
32047 @c EN
32048 This module provides only one procedure, @code{make-text-progress-bar},
32049 which packages the progress bar feature in a closure and returns it.
32050 @c JP
32051 このモジュールは@code{make-text-progress-bar}という手続きを1つだけ提供
32052 します。この手続きはプログレスバーの機能をクロージャに包んでそれを返し
32053 ます。
32054 @c COMMON
32055
32056 @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
32057 @c MOD text.progress
32058 @c EN
32059 Returns a procedure that packages operations on the progress bar.
32060 The procedure can be called with a symbol indicating an operation,
32061 and an optional numeric argument.
32062 @c JP
32063 プログレスバー上の操作を包んだ手続きを返します。返された手続きに操作を
32064 示すシンボルとオプションで数値を引数として渡して使います。
32065 @c COMMON
32066
32067 @table @code
32068 @item @var{proc} 'show
32069 @c EN
32070 Redisplays the progress bar. All other operations implies redisplay,
32071 so you don't need to use this unless you have a specific reason to
32072 redisplay the current state.
32073 @c JP
32074 プログレスバーを再表示する。他のどの操作も状態の再表示を行います。
32075 したがって、現在のステータスを再表示しなければない特別な理由がないかぎ
32076 りこれを使う必要はありません。
32077 @c COMMON
32078
32079 @item @var{proc} 'set @var{value}
32080 @c EN
32081 Sets the current value to @var{value}, then redisplays the progress bar.
32082 If @var{value} exceeds the max value, it is clipped by the max value.
32083 @c JP
32084 現在の値を@var{value}にセットし、プログレスバーを再表示します。
32085 @var{value}が最大値を超えていたら、超過分を切り捨て最大値にします。
32086 @c COMMON
32087
32088 @item @var{proc} 'inc @var{value}
32089 @c EN
32090 Increments the current value by @var{value}, then redisplays the progress bar.
32091 If the current value exceeds the max value, it is clipped by the max value.
32092 @c JP
32093 @var{value}分だけ現在の値を増し、プログレスバーを再表示します。現在の
32094 値が最大値を超えたら、超過分を切り捨て最大値にします。
32095 @c COMMON
32096
32097 @item @var{proc} 'finish
32098 @c EN
32099 Puts the progress bar to the ``finished'' state, then redisplays it.
32100 The time part shows the total elapsed time, and the line is terminated
32101 by @code{#\newline} so that it won't be clobbered. Once a progress
32102 bar becomes ``finished'', there's no way to put it back ``in progress''.
32103 @c JP
32104 プログレスバーを「終了」状態にし、再表示します。時間部はトータルの経過
32105 時間を表示します。また、表示行末は@code{#\newline}とし、上書きされない
32106 ようにします。プログレスバーはいったん「終了」状態になれば、「進捗中」
32107 状態に戻す方法はありません。
32108 @c COMMON
32109
32110 @item @var{proc} 'set-info @var{text}
32111 @c EN
32112 Changes the text displayed in the ``info'' part. To use the info part,
32113 you have to give a positive value to @var{info-width} keyword argument
32114 of @code{make-text-progress-bar}.
32115 @c JP
32116 ``info''部に表示されるテキストを変更します。
32117 info部を使うには、@code{make-text-progress-bar}の@var{info-width}キーワード
32118 引数に正の値が指定されている必要があります。
32119 @c COMMON
32120
32121
32122 @item @var{proc} 'set-header @var{text}
32123 @c EN
32124 Changes the text displayed in the ``header' area.
32125 @c JP
32126 ``header''部に表示されるテキストを変更します。
32127 @c COMMON
32128 @end table
32129
32130 @c EN
32131 The keyword arguments are used to customize the display:
32132 @c JP
32133 キーワード引数を使って表示をカスタマイズできます。
32134 @c COMMON
32135 @table @var
32136 @item header
32137 @c EN
32138 The text to be displayed in the header part.
32139 This can be changed later, by sending @code{set-header} message
32140 to the created progress bar.
32141 @c JP
32142 ヘッダ部に表示するテキスト。このテキストは、作られたプログレスバーに
32143 @code{set-header}メッセージを送ることで後で変更可能です。
32144 @c COMMON
32145
32146 @item header-width
32147 @c EN
32148 The width of the header part, in number of characters.
32149 The header text is displayed left-aligned in the part.
32150 If the header text is longer than the width, the excess characters
32151 are omitted. The default is 14.
32152 @c JP
32153 ヘッダ部の幅、文字数で指定します。ヘッダ部のテキストは左詰めです。ヘッ
32154 ダ部に置くテキストが幅よりも長い場合には超過分の文字は切り捨てられます。
32155 デフォルトは14文字です。
32156 @c COMMON
32157
32158 @item bar-char
32159 @c EN
32160 A character used to draw a bar chart. The default is @code{#\#}.
32161 @c JP
32162 バーチャートを描くのに使う文字。デフォルトは@code{#\#}です。
32163 @c COMMON
32164
32165 @item bar-width
32166 @c EN
32167 The width of the bar chart part, in number of characters.
32168 The default is 40.
32169 @c JP
32170 バーチャート部の幅で、文字数で指定します。デフォルトでは40文字です。
32171 @c COMMON
32172
32173 @item num-width
32174 @c EN
32175 The width of the numeric part, in number of characters.
32176 The default is 9. Setting this to 0 hides the numeric part.
32177 @c JP
32178 数値部の幅で、文字数で指定します。デフォルトでは9で、これを0に設定する
32179 と数値部を隠せます。
32180 @c COMMON
32181
32182 @item num-format
32183 @c EN
32184 A procedure to format the numeric part. Two arguments are
32185 passed; the current value and the maximum value. It must return
32186 a string. The default is the following procedure.
32187 @c JP
32188 数値部を整形する手続き。引数が2つ渡されます。ひとつは現在の値、もうひ
32189 とつは最大値です。この手続きは文字列を返さなければなりません。デフォル
32190 トでは以下の手続きです。
32191 @c COMMON
32192 @example
32193 (lambda (cur max)
32194 (format "~d/~d" cur max))
32195 @end example
32196
32197 @item time-width
32198 @c EN
32199 The width of the time part, in number of characters.
32200 The default is 7. Settings this to 0 hides the time part.
32201 @c JP
32202 時間部の幅で、文字数で指定します。デフォルトでは7文字で、これを0に設定
32203 すると時間部を隠せます。
32204 @c COMMON
32205
32206 @item info
32207 @c EN
32208 The text to be displayed in the info part. This text can be
32209 changed later by sending @code{set-info} message to the created
32210 progress bar. Note that you have to give a positive number
32211 to @var{info-width} keyword argument to enable the info part.
32212 @c JP
32213 info部に表示されるテキストです。このテキストは、作られたプログレスバーに
32214 @code{set-info}メッセージを送ることで後から変更できます。
32215 info部を表示するには、@var{info-width}キーワード引数に正の値を
32216 与えておく必要があります。
32217 @c COMMON
32218
32219 @item info-width
32220 @c EN
32221 The width of the info part. The default value is zero,
32222 which means the info part is not displayed.
32223 @c JP
32224 info部の表示幅です。デフォルトは0で、info部は表示されません。
32225 @c COMMON
32226
32227 @item separator-char
32228 @c EN
32229 A character put around the bar part. Default is @code{#\|}.
32230 You can pass @code{#f} not to display the separators.
32231 @c JP
32232 バー部分の前後に置く文字です。デフォルトでは@code{#\|}です。
32233 セパレータを表示したくなければ、@code{#f}を渡します。
32234 @c COMMON
32235
32236 @item max-value
32237 @c EN
32238 The maximum value of the progress bar. Must be a positive real number.
32239 Default is 100.
32240 @c JP
32241 プログレスバーの最大値です。正の実数でなければなりません。デフォルトでは100です。
32242 @c COMMON
32243
32244 @item port
32245 @c EN
32246 An output port to which the progress bar is displayed. The default value
32247 is the current output port when @code{make-text-progress-bar} is called.
32248 @c JP
32249 プログレスバーを表示する出力ポートです。デフォルト値は
32250 @code{make-text-progress-bar}が呼ばれた時点での現在の出力ポートです。
32251 @c COMMON
32252 @end table
32253 @end defun
32254
32255 @c EN
32256 Here's a simple example, using customized numeric part:
32257 @c JP
32258 以下は簡単なカスタマイズをした例です。
32259 @c COMMON
32260
32261 @example
32262 (use text.progress)
32263
32264 (define (main args)
32265 (define (num-format cur max)
32266 (format "~d/~d(~3d%)" cur max
32267 (round->exact (/. (* cur 100) max))))
32268
32269 (let ((p (make-text-progress-bar :header "Example"
32270 :header-width 10
32271 :bar-char #\o
32272 :num-format num-format
32273 :num-width 13
32274 :max-value 256)))
32275 (do ((i 0 (+ i 1)))
32276 ((= i 256) (p 'finish))
32277 (p 'inc 1)
32278 (sys-select #f #f #f 50000))))
32279 @end example
32280
32281 @c ----------------------------------------------------------------------
32282 @node Segmented string matching, Shell text utilities, Showing progress on text terminals, Library modules - Utilities
32283 @section @code{text.segmented-match} - Segmented string matching
32284 @c NODE 区切られた文字列のマッチ, @code{text.segmented-match} - 区切られた文字列のマッチ
32285
32286 @deftp {Module} text.segmented-match
32287 @mdindex text.segmented-match
32288 @c EN
32289 Sometimes you want to search for a group of words concatenated with
32290 a delimiter, using only the prefixes of each words. For example:
32291 you want to search @code{call-with-current-continuation} using
32292 @code{c-w-c-c}. One of its popular applications is symbol completion,
32293 which Gauche provides on REPL (@pxref{Input editing}).
32294 @c JP
32295 しばしば、複数の単語をデリミタでつないだ文字列を、各単語のプレフィクスだけを指定して
32296 サーチしたいことがあります。例えば@code{c-w-c-c}を指定して
32297 @code{call-with-current-continuation}を探す、というようなことです。
32298 これはシンボルの補完などによく使われ、
32299 GaucheのREPLでも採用しています (@ref{Input editing}参照)。
32300 @c COMMON
32301
32302 @c EN
32303 This module provides basic parts to perform such searching.
32304 @c JP
32305 このモジュールは、そういうサーチをするための基本的な部品を提供します。
32306 @c COMMON
32307 @end deftp
32308
32309 @defun segmented-prefix? pattern word :optional separator
32310 @c MOD text.segmented-match
32311 @c EN
32312 The @var{pattern} and @var{word} arguments must be a string, and
32313 @var{separator} must be either a character, a character set,
32314 a regexp, a predicate taking a character, or a string.
32315 When @var{separator} is omitted, @code{#\-} is assumed.
32316 @c JP
32317 @var{pattern}と@var{word}はともに文字列、@var{separator}は
32318 文字、文字集合、正規表現、文字を取る述語、あるいは文字列のいずれかでなければなりません。
32319 @var{separator}が省略された場合は@code{#\-}が使われます。
32320 @c COMMON
32321
32322 @c EN
32323 First, @var{pattern} and @var{word} are splitted into segments
32324 by @var{separator},
32325 using @code{string-split} (@pxref{String utilities}). If every
32326 segments from @var{pattern} consist a prefix of the corresponding
32327 segments from @var{word}, it returns @code{#t}. It is allowed
32328 for @var{word} to have more segments than @var{pattern}.
32329 @c JP
32330 まず@var{pattern}と@var{word}が@var{separator}を区切りとして
32331 @code{string-split}により分割されます (@ref{String utilities}参照)。
32332 そして、@var{pattern}の分割されたそれぞれの断片が全て@var{word}の分割された対応する
32333 断片のプレフィクスになっている場合に@code{#t}が、そうでなければ@code{#f}が返されます。
32334 @var{word}の断片の方が@var{pattern}の断片より多い場合は、余った分は無視されます。
32335 @c COMMON
32336
32337 @example
32338 (segmented-match? "a-b-c" "alpha-bravo-charlie") @result{} #t
32339 (segmented-match? "a-b" "alpha-bravo-charlie") @result{} #t
32340 (segmented-match? "al-br-char" "alpha-bravo-charlie") @result{} #t
32341 (segmented-match? "a-b" "alpha-delta-charlie") @result{} #t
32342 @end example
32343 @end defun
32344
32345 @defun make-segmented-prefix-matcher pattern separator
32346 @c MOD text.segmented-match
32347 @c EN
32348 This is a subfunction of @code{segmented-match?}.
32349 @c JP
32350 @code{segmented-match?}の下請け手続きです。
32351 @c COMMON
32352
32353 @c EN
32354 Returns a procedure that takes a string @var{word}, and sees if
32355 each segment of @var{pattern} is a prefix of corresponding segment
32356 of @var{word}. If any of the @var{pattern}'s segment is not a
32357 prefix of the corresponding @var{word}'s segment, @code{#f} is
32358 returned. Otherwise, it returns a true value: If the number of
32359 @var{word}'s segments is the same as the @var{pattern}'s, @code{#t}
32360 is retured; if @var{word} has more segments, the remaining part
32361 of the @var{word} (exclusing leading separator) is returned.
32362 @c JP
32363 一つの文字列引数@var{word}を取る述語関数を返します。その関数は、
32364 @var{pattern}のそれぞれの断片のうち、@var{word}の対応する断片の
32365 プレフィクスになっていないものがひとつでもあれば@code{#f}を返します。
32366 そうでない場合、@var{word}の断片の数と@var{pattern}の断片の数が同じであれば
32367 @code{#t}が、@var{word}の断片の数が多ければ、@var{word}のマッチしなかった
32368 残りの部分 (先頭の@var{separator}は除く) が返されます。
32369 @c COMMON
32370
32371 @example
32372 ((make-segmented-prefix-matcher "a-b-c" #\-) "alpha-bravo-charlie")
32373 @result{} #t
32374 ((make-segmented-prefix-matcher "a-b" #\-) "alpha-bravo-charlie-delta")
32375 @result{} "charlie-delta"
32376 ((make-segmented-prefix-matcher "a-b" #\-) "alpha-charlie-delta")
32377 @result{} #f
32378 @end example
32379
32380 @c EN
32381 This preprocesses @var{pattern}, so if you want to match
32382 many words against a single pattern, it is faster to get
32383 predicates with this procedure than applying @code{segmented-prefix?}
32384 repeatedly.
32385 @c JP
32386 この手続きは@var{pattern}をプリプロセスするので、一つのパターンに対して
32387 多くの単語をマッチさせたい場合は、毎回@code{segmented-prefix?}を呼び出すより
32388 効率的です。
32389 @c COMMON
32390 @end defun
32391
32392 @c ----------------------------------------------------------------------
32393 @node Shell text utilities, SQL parsing and construction, Segmented string matching, Library modules - Utilities
32394 @section @code{text.sh} - Shell text utilities
32395 @c NODE シェルのテキストユーティリティ, @code{text.sh} - シェルのテキストユーティリティ
32396
32397 @deftp {Module} text.sh
32398 @mdindex text.sh
32399 @c EN
32400 This module provides several utilities useful when you're writing
32401 shell-like scripts.
32402 @c JP
32403 このモジュールは、シェルスクリプト風のスクリプトを書いている時に便利な
32404 いくつかのユーティリティを提供します。
32405 @c COMMON
32406 @end deftp
32407
32408 @defun shell-escape-string str :optional flavor
32409 @c MOD text.sh
32410 @c EN
32411 If @var{str} contains characters that affects shell's command-line
32412 argument parsing, escape @var{str} to avoid shell's interpretation.
32413 Otherwise, returns @var{str} itself.
32414
32415 The optional @var{flavor} argument takes a symbol to
32416 specify the platform; currently @code{windows} and
32417 @code{posix} can be specified. The way shell handles
32418 the escape and quotation differ a lot between these platforms;
32419 the @code{windows} flavor uses MSVC runtime argument parsing behavior,
32420 while the @code{posix} flavor assumes IEEE Std 1003.1.
32421 When omitted, the default
32422 value is chosen according to the running platform.
32423 (Note: Cygwin is regarded as @code{posix}.)
32424
32425 Use this procedure when you need to build a command-line string by yourself.
32426 (If you pass a command-line argument list, instead of a single
32427 command-line string, you don't need to escape them since we
32428 bypass the shell.)
32429
32430 (NB: Use this with caution on Windows; if you run a batch file
32431 (@file{*.bat} or @file{*.cmd}), its command-line arguments are
32432 parsed differently, and it is known that there's no safe escaping
32433 way that works for all the cases. It's up to you to ensure
32434 all arugments are safe when you run those files. See also
32435 @code{sys-exec} (@pxref{Process management})).
32436 @c JP
32437 @var{str}がシェルのコマンドライン引数解析に影響を与える文字を含んでいる場合、
32438 それらがシェルによって解釈されないようにエスケープされた文字列を返します。
32439 そうでなければ@var{str}自体を返します。
32440
32441 省略可能な@var{flavor}引数はシンボルを取り、プラットフォームを指定します。
32442 現在は@code{windows}か@code{posix}が指定可能です。シェルが
32443 エスケープやクオートを処理する方法がこの二つのプラットフォームで大きく
32444 異なるからです。@code{windows}フレーバーの場合はMVCSランタイムの
32445 引数パージングに合わせ、@code{posix}フレーバーの場合はIEEE Std 1003.1に
32446 合わせます。
32447 省略された場合は、プロセスが走っているプラットフォームが
32448 デフォルトの値となります。(Cygwinは@code{posix}とみなされます。)
32449
32450 自分でコマンドライン文字列を組み立てる必要がある場合に使ってください。
32451 (単一のコマンドライン文字列でなく、コマンドライン引数のリストを渡す場合は
32452 エスケープの必要はありません。引数はシェルを通さずに子プロセスに渡される
32453 からです。)
32454
32455 (註: Windowsでバッチファイル(@file{*.bat}、@file{*.cmd})を起動する場合は、
32456 コマンドラインが異なる方法でパーズされることに注意してください。
32457 特に、あらゆる場合に対して安全に引数をエスケープする方法が無いことが
32458 知られています。バッチファイルに渡す引数を用意する場合は独自にそれが
32459 安全であることを確かめて下さい。@code{sys-exec}のエントリも参照のこと
32460 (@ref{Process management}))。
32461 @c COMMON
32462 @end defun
32463
32464 @defun shell-tokenize-string str :optional flavor
32465 @c MOD text.sh
32466 @c EN
32467 Split a string @var{str} into arguments as the shell does.
32468 @c JP
32469 シェルがやるように、文字列@var{str}を引数リストに分割します。
32470 @c COMMON
32471
32472 @example
32473 (shell-tokenize-string "grep -n -e \"foo bar\" log")
32474 @result{} ("grep" "-n" "-e" "foo bar" "log")
32475 @end example
32476
32477 @c EN
32478 The optional @var{flavor} arguments can be a symbol either
32479 @code{windows} or @code{posix} to specify the syntax.
32480 If it's @code{windows}, we follow MSVC runtime command-line
32481 argument parser behavior. If it's @code{posix}, we follow
32482 IEEE Std 1003.1 Shell Command Language. When omitted,
32483 the default value is chosen according to the running platform.
32484 (Note: Cygwin is regarded as @code{posix}.)
32485 @c JP
32486 省略可能な@var{flavor}引数はシンボル@code{windows}か@code{posix}を取り、
32487 構文を指定します。@code{windows}の場合はMVCSランタイムの
32488 引数パージングに合わせ、@code{posix}フレーバーの場合はIEEE Std 1003.1
32489 Shell Command Languageに合わせます。
32490 省略された場合は、プロセスが走っているプラットフォームが
32491 デフォルトの値となります。(Cygwinは@code{posix}とみなされます。)
32492 @c COMMON
32493
32494 @c EN
32495 This procedure does not handle fancier shell features such
32496 as variable substitution. If it encounters a metacharacter
32497 that requires such interpretation, an error is signaled.
32498 In other words, metacharacters must be properly quoted
32499 in @var{str}.
32500 @c JP
32501 この手続きはシェルの変数置換のような高度な機能は持っていません。
32502 もしそういった解釈が必要なメタ文字に出会った場合はエラーが投げられます。
32503 言い換えれば、メタ文字は@var{str}の中で全て適切にクオートされている
32504 必要があります。
32505 @c COMMON
32506
32507 @example
32508 (shell-tokenize-string "echo $foo" 'posix)
32509 @result{} @r{signals error}
32510
32511 (shell-tokenize-string "echo \"$foo\"" 'posix)
32512 @result{} @r{still signals error}
32513
32514 (shell-tokenize-string "echo '$foo'" 'posix)
32515 @result{} ("echo" "$foo")
32516
32517 (shell-tokenize-string "echo \\$foo" 'posix)
32518 @result{} ("echo" "$foo")
32519 @end example
32520 @end defun
32521
32522 @defmac shell-case expr clause @dots{}
32523 @c MOD text.sh
32524 @c EN
32525 This macro implements shell's @code{case} built-in command.
32526 Each @var{clause} must be one fo the following forms:
32527 @c JP
32528 このマクロは、シェルの@code{case}組み込みコマンドを実装します。
32529 各@var{clause}は次の形式のいずれかでなければなりません。
32530 @c COMMON
32531
32532 @itemize @bullet
32533 @item
32534 @code{(@var{pattern} @var{body} @dots{})}
32535 @item
32536 @code{((@var{pattern} @dots{}) @var{body} @dots{})}
32537 @item
32538 @code{(else @var{body} @dots{})}
32539 @end itemize
32540
32541 @c EN
32542 The @code{else} form must appear as the last @var{clause}, if there's any.
32543 @c JP
32544 また、@code{else}フォームはあるなら最後の@var{clause}でなければなりません。
32545 @c COMMON
32546
32547 @c EN
32548 First, @var{expr} is evaluated. It must produce a string.
32549 Then, each @var{clause} is examined, and the value of @var{expr}
32550 matches one of the @var{pattern}s, then @var{body} @dots{} of the
32551 clause is evaluated, and the last result is returned.
32552 @c JP
32553 まず@var{expr}が評価されます。値は文字列でなければなりません。
32554 次に各@var{clause}が順番に吟味され、@var{expr}の値が@var{pattern}にマッチした
32555 場合にその@var{clause}が選ばれて@var{body} @dots{}が評価され、
32556 最後の式の値が全体の値となります。
32557 @c COMMON
32558
32559 @c EN
32560 When none of @var{clause} has matching @var{pattern}, if @code{else}
32561 clause is provided its @var{body} @dots{} is evaluated, otherwise
32562 an undefined value is returned.
32563 @c JP
32564 いずれの@var{pattern}もマッチしなかった場合、@code{else}節が与えられていれば
32565 その@var{body} @dots{}が評価されて最後の式の値が全体の値となり、
32566 @code{else}節がなければ未定義値が返されます。
32567 @c COMMON
32568
32569 @c EN
32570 The matching is done as @code{glob} (@pxref{Directories}) does.
32571 That is, if a @var{pattern} is @code{"abc*"}, then the value
32572 @code{"abc"}, @code{"abcd"}, @code{"abccc"}, etc. match,
32573 and if a @var{pattern} is @code{"a[bcd]"}, then the value
32574 @code{"ab"}, @code{"ac"} and @code{"ad"} match.
32575 @c JP
32576 マッチは@code{glob}と同じ方法で行われます (@ref{Directories}参照)。
32577 例えば、@var{pattern}が@code{"abc*"}であれば、
32578 @var{expr}の値が@code{"abc"}、@code{"abcd"}、@code{"abccc"}等である
32579 場合にマッチし、@var{pattern}が@code{"a[bcd]"}であれば、
32580 @code{"ab"}、@code{"ac"}、@code{"ad"}がマッチします。
32581 @c COMMON
32582
32583 @c EN
32584 For example, the following shell @code{case} command:
32585 @c JP
32586 次のシェルの@code{case}コマンドは:
32587 @c COMMON
32588
32589 @example
32590 case $arg in
32591 foo*) process_foo $arg;;
32592 ba[rz]|quux) process_bar $arg;;
32593 *) process_other $arg;;
32594 esac
32595 @end example
32596
32597 @c EN
32598 can be translated as follows:
32599 @c JP
32600 次のように書き直せるでしょう。
32601 @c COMMON
32602
32603 @example
32604 (shell-case arg
32605 ["foo*" (process-foo arg)]
32606 [("ba[rz]" "quux") (process-bar arg)]
32607 [else (process-other arg)])
32608 @end example
32609
32610 @c EN
32611 The same thing can be achieved with @code{rxmatch-case}, for example,
32612 but manually translating shell glob pattern to regexp can be tedious
32613 and error-prone. This is particulary useful when you're rewriting
32614 existing shell scripts in Gauche.
32615 @c JP
32616 同等の処理は例えば@code{rxmatch-case}を使って書くこともできますが、
32617 シェルのglobパターンを正規表現に置き換えてゆくのは面倒ですし
32618 ミスが入り込む余地もあります。
32619 既存のシェルスクリプトをGaucheで最実装する場合には@code{shell-case}は非常に便利な
32620 ツールになるでしょう。
32621 @c COMMON
32622 @end defmac
32623
32624 @defun shell-match pattern str
32625 @c MOD text.sh
32626 @c EN
32627 This extract the matching function of @code{shell-case} to be used
32628 independently. The @var{pattern} argument must be a glob pattern
32629 string, or a list of glob pattern strings.
32630 The @var{str} argument must be a string.
32631 @c JP
32632 これは@code{shell-case}のマッチ部分の機能だけを独立して取り出したものです。
32633 @var{pattern}はglobパターンを表す文字列、もしくは
32634 globパターンを表す文字列のリストで、
32635 @var{str}は文字列でなければなりません。
32636 @c COMMON
32637
32638 @c EN
32639 If the value of @var{str} matches @var{pattern} (or one of @var{pattern}s
32640 in the second form), it returns @code{#t}. Otherwise, it returns @code{#f}.
32641 @c JP
32642 @var{str}の値が@var{pattern} (もしくは、2番めの形式の場合は@var{pattern}のいずれかに)
32643 マッチしたら@code{#t}を、そうでなければ@code{#f}を返します。
32644 @c COMMON
32645 @end defun
32646
32647 @c ----------------------------------------------------------------------
32648 @node SQL parsing and construction, Simple template expander, Shell text utilities, Library modules - Utilities
32649 @section @code{text.sql} - SQL parsing and construction
32650 @c NODE SQLのパーズと構築, @code{text.sql} - SQLのパーズと構築
32651
32652 @deftp {Module} text.sql
32653 @mdindex text.sql
32654 @c EN
32655 This module provides a utility to parse and construct SQL statement.
32656 @c JP
32657 このモジュールはSQL文のパーズと構築のためのユーティリティを提供します。
32658 @c COMMON
32659
32660 @c EN
32661 It is currently under development, and we only have a tokenization routine.
32662 The plan is to define S-expression syntax of SQL and provides a routine
32663 to translate one form to the other.
32664 @c JP
32665 このモジュールは現在まだ開発途上にあります。まだトークン列を生成するルー
32666 チンしかありません。SQLのS式構文を定義して、SQLとその構文との間の変換
32667 ルーチンを提供する計画です。
32668 @c COMMON
32669
32670 @c EN
32671 Note: If you're looking for a routine to escape strings to be
32672 safe in SQL, see @code{dbi-escape-sql} in @ref{DBI user API}.
32673 @c JP
32674 註: SQLに安全に渡せるように文字列をエスケープするルーチンをお探しなら、
32675 @ref{DBI user API}の@code{dbi-escape-sql}を見てください。
32676 @c COMMON
32677 @end deftp
32678
32679 @defun sql-tokenize sql-string
32680 @c MOD text.sql
32681 @c EN
32682 Tokenize a SQL statement @var{sql-string}. The return value is
32683 a list of tokens, where each token is
32684 represented by one of the following forms.
32685 @c JP
32686 SQL文@var{sql-string}をトークン列に分解します。返り値はトークンのリス
32687 トで、各トークンは以下の形式のひとつで表現されます。
32688 @c COMMON
32689
32690 @c EN
32691 @example
32692 <symbol> Special delimiter. One of the followings:
32693 + - * / < = > <> <= >= ||
32694 <character> Special delimiter. One of the followings:
32695 #\, #\. #\( #\) #\;
32696 <string> Regular identifier
32697 (delimited <string>) Delimited identifier
32698 (parameter <num>) Positional parameter (?)
32699 (parameter <string>) Named parameter (:foo)
32700 (string <string>) Character string literal
32701 (number <string>) Numeric literal
32702 (bitstring <string>) Binary string. <string> is like "01101"
32703 (hexstring <string>) Binary string. <string> is like "3AD20"
32704 @end example
32705 @c JP
32706 @example
32707 <symbol> 特殊区切り子、以下のどれか
32708 + - * / < = > <> <= >= ||
32709 <character> 特殊区切り子、以下のどれか
32710 #\, #\. #\( #\) #\;
32711 <string> 通常の識別子
32712 (delimited <string>) 区切られた識別子
32713 (parameter <num>) 位置パラメータ (?)
32714 (parameter <string>) 名前つきパラメータ (:foo)
32715 (string <string>) 文字列リテラル
32716 (number <string>) 数値リテラル
32717 (bitstring <string>) バイナリ文字列 <string> は "01101" な感じ
32718 (hexstring <string>) Binary string. <string> は "3AD20" な感じ
32719 @end example
32720 @c COMMON
32721
32722 @c EN
32723 If it encounters an untokenizable string, it raises an
32724 @code{<sql-parse-error>} condition.
32725 @c JP
32726 トークンに分解できない文字列がくると@code{<sql-parse-error>}コンディショ
32727 ンがあがります。
32728 @c COMMON
32729 @end defun
32730
32731 @deftp {Condition Type} <sql-parse-error>
32732 @c MOD text.sql
32733 @c EN
32734 A condition to indicate an SQL parse error. Inherits @code{<error>}.
32735 @c JP
32736 SQLパーズエラーを示すコンディション。@code{<error>}を継承。
32737 @c COMMON
32738 @defivar <sql-parse-error> sql-string
32739 @c EN
32740 Holds the source SQL string.
32741 @c JP
32742 元のSQL文字列を保持。
32743 @c COMMON
32744 @end defivar
32745 @end deftp
32746
32747 @c ----------------------------------------------------------------------
32748 @node Simple template expander, Transliterate characters, SQL parsing and construction, Library modules - Utilities
32749 @section @code{text.template} - Simple template expander
32750 @c NODE 簡単なテンプレート拡張, @code{text.template} - 簡単なテンプレート拡張
32751
32752 @deftp {Module} text.template
32753 @mdindex text.template
32754 @c EN
32755 This module lifts Gauche's built-in string interpolation feature
32756 to be more general template engine.
32757 @c JP
32758 このモジュールは、Gauche組み込みの文字列補間機能をより一般的なテンプレートエンジンとして
32759 使えるようにするものです。
32760 @c COMMON
32761
32762 @c EN
32763 Gauche's string interpolation syntax is expanded at read time and then
32764 handled by macro expanders, and
32765 becomes a simple Scheme code fragment.
32766 For example, if you have this:
32767 @c JP
32768 Gaucheの文字列補間構文はソース読み込み時にマクロ呼び出しへと展開され、
32769 さらにマクロ展開器により展開されて単純なSchemeコード片となります。
32770 例えば、次のソースコードがある場合:
32771 @c COMMON
32772 @example
32773 (let ([x 10])
32774 #"The square of x is ~(* x x).")
32775 @end example
32776
32777 @c EN
32778 It is eventually converted to this after macro expansion:
32779 @c JP
32780 マクロ展開後の最終形は次のコードになります:
32781 @c COMMON
32782 @example
32783 (let ([x 10])
32784 (string-append '"The square of x is " (x->string (* x.0 x.0)) '"."))
32785 @end example
32786
32787 @c EN
32788 It is a kind of template expansion, but you have to have the template string
32789 as a literal, so it's restricted. With this module, you can feed template
32790 string and the bindings of the value at the runtime:
32791 @c JP
32792 これも一種のテンプレート展開と言えるのですが、文字列補間ではテンプレート文字列が
32793 文字列リテラルとしてソースコード上に現れていなければならないという制限があります。
32794 このモジュールでは、文字列と束縛を実行時に与えることができます:
32795 @c COMMON
32796
32797 @example
32798 (define *template* "The square of x is ~(* x x).")
32799
32800 (expand-template-string *template*
32801 (make-template-environment :bindings '(x 10)))
32802 @result{} "The square of x is 100."
32803 @end example
32804
32805 @c EN
32806 The syntax of template strings is the same as string interpolation
32807 (@pxref{String interpolation}); that is, tokens following @code{~}
32808 is read as a Scheme expression. In case if the token is a symbol
32809 and you need to delimit it from subsequent characters, you can use
32810 symbol escape by @code{|}.
32811 @c JP
32812 テンプレート文字列の構文は文字列補間のそれと同じです(@ref{String interpolation}参照)。
32813 すなわち、@code{~}に続くトークンがScheme式として呼ばれます。もしトークンがシンボルで、
32814 その後の続く文字から区切る必要がある場合は、@code{|}によるシンボルエスケープが使えます。
32815 @c COMMON
32816
32817 @c EN
32818 You also need to provide a @emph{template environment}, where the
32819 expressions in the template is evaluated. Note that,
32820 unlike string interpolation,
32821 those expressions can't refer to the local bindings.
32822 @c JP
32823 また、テンプレート展開時には、テンプレート中の式を評価するための
32824 @emph{テンプレート環境}を与える必要があります。
32825 文字列補間と違って、テンプレート中の式がローカル束縛を参照することはできません。
32826 @c COMMON
32827 @end deftp
32828
32829 @defun expand-template-string template env
32830 @c EN
32831 Expands a template string @var{template} with a template environment
32832 @var{env}, and returns the result string.
32833 @c JP
32834 テンプレート文字列@var{template}を、テンプレート環境@var{env}のもとで展開し、
32835 結果の文字列を返します。
32836 @c COMMON
32837 @end defun
32838
32839 @defun expand-template-file filename env :optional paths
32840 @c EN
32841 Reads a template string from a file named by @var{filename}, expands
32842 it with a template environment @var{env}, and returns the result string.
32843
32844 If @var{filename} is not an absolute path, it is looked in the directories
32845 listed in @var{paths}.
32846 @c JP
32847 テンプレート文字列を@var{filename}で指定されるファイルから読み込み、
32848 テンプレート環境@var{env}のもとでそれを展開し、結果の文字列を返します。
32849
32850 @var{filename}が絶対パスでない場合は、@var{paths}中のディレクトリからの相対パスで
32851 探されます。
32852 @c COMMON
32853 @end defun
32854
32855 @defun make-template-environment :key extends imports bindings
32856 @c EN
32857 Creates and returns a template environment. A template environment
32858 is like a module (@pxref{Modules}): It maps symbols to values, and
32859 it can import bindings from other modules, or extend other modules.
32860 @c JP
32861 テンプレート環境を作成して返します。テンプレート環境はモジュールのようなものです
32862 (@ref{Modules}参照)。それはシンボルを値にマップし、
32863 また他のモジュールから束縛をインポートしたり、他のモジュールをextendしたりできます。
32864 @c COMMON
32865
32866 @c EN
32867 The keyword arguments @var{extends} and @var{imports} must be a list
32868 of symbols; they specify names of modules to inherit from or to import from.
32869 @c JP
32870 キーワード引数@var{extends}と@var{imports}はシンボルのリストを取り、
32871 それぞれ継承元のモジュール、あるいはインポート元のモジュールを指定します。
32872 @c COMMON
32873
32874 @c EN
32875 The keyword arguments @var{bindings} must either be a dictionary
32876 (anything that inherits @code{<dictionary>}), or a key-value list.
32877 The mappings represented by it are incorporated to the environment.
32878 @c JP
32879 キーワード引数@var{bindings}はディクショナリ(@code{<dictionary>}のサブクラスの
32880 インスタンス)か、key-valueリストでなければなりません。
32881 それにより表される束縛が環境に取り込まれます。
32882 @c COMMON
32883 @end defun
32884
32885 @c ----------------------------------------------------------------------
32886 @node Transliterate characters, Lazy text construction, Simple template expander, Library modules - Utilities
32887 @section @code{text.tr} - Transliterate characters
32888 @c NODE 文字変換, @code{text.tr} - 文字変換
32889
32890 @deftp {Module} text.tr
32891 @mdindex text.tr
32892 @c EN
32893 This module implements a transliterate function,
32894 that substitutes characters of the input string.
32895 This functionality is realized in Unix @code{tr(1)} command,
32896 and incorporated in various programs such as @code{sed(1)}
32897 and @code{perl}.
32898
32899 Gauche's @code{tr} is aware of multibyte characters.
32900 @c JP
32901 このモジュールは、入力ストリームから指定の文字を置き換えて出力する、
32902 文字変換(transliterate)機能を提供します。
32903 Unixの@code{tr(1)}コマンドで実装され、@code{sed}や@code{perl}にも
32904 採り入れられている機能です。
32905
32906 Gaucheの@code{tr}はマルチバイト文字/文字列を正しく扱います。
32907 @c COMMON
32908 @end deftp
32909
32910 @defun tr from-list to-list :key :complement :delete :squeeze :table-size :input :output
32911 @c MOD text.tr
32912 @c EN
32913 Reads from @var{input} and writes to @var{output},
32914 with transliterating characters in @var{from-list} to the
32915 corresponding ones in @var{to-list}. Characters that doesn't
32916 appear in @var{from-list} are passed through.
32917 @c JP
32918 @var{input}から文字を読み込み、その文字が@var{from-list}内にあれば
32919 対応する@var{to-list}内の文字に置き換えて、@var{output}へと書き出します。
32920 @var{from-list}に無い文字はそのまま@var{output}へと渡されます。
32921 @c COMMON
32922
32923 @c EN
32924 The default values of @var{input} and @var{output} are
32925 current input port and current output port, respectively.
32926 @c JP
32927 @var{input}と@var{output}の既定値はそれぞれ現在の入力ポートと
32928 出力ポートです。
32929 @c COMMON
32930
32931 @c EN
32932 Both @var{from-list} and @var{to-list} must be strings.
32933 They may contain the following special syntax.
32934 Other characters that doesn't fits in the syntax are taken as they are.
32935 @c JP
32936 @var{from-list}と@var{to-list}は文字列でなければなりません。
32937 その中には次のような表記を使うことができます。それ以外の文字はそのまま使われます。
32938 @c COMMON
32939
32940 @table @code
32941 @item @b{x-y}
32942 @c EN
32943 Expanded to the increasing sequence of characters from @code{x} to @code{y},
32944 inclusive. The order is determined by the internal character
32945 encoding system; generally it is safer to limit use of this within
32946 the range of the same character class. The character @code{x}
32947 must be before @code{y}.
32948 @c JP
32949 文字@code{x}から文字@code{y}までの文字の昇順の並びと解釈されます。
32950 @code{x}と@code{y}は含まれます。文字の並びはGaucheの内部文字エンコーディングに
32951 よって決定されるので、一般には@code{x}と@code{y}は同じキャラクタクラスの中に
32952 止めておいた方が安全でしょう。@code{x}は@code{y}より小さくなければなりません。
32953 @c COMMON
32954
32955 @item @b{x*n}
32956 @c EN
32957 Repeat @code{x} for @code{n} times. @code{n} is a decimal number notation.
32958 Meaningful only in
32959 @var{to-list}; it is an error to use this form in @var{from-list}.
32960 If @code{n} is omitted or zero, @code{x} is repeated until @var{to-list}
32961 matches the length of @var{from-list} (any character after it is ignored).
32962 @c JP
32963 文字@code{x}の@code{n}個の並び。@code{n}は10進数で表記された数値です。
32964 これは@var{to-list}でのみ有効で、@var{from-list}で使うとエラーになります。
32965 @code{n}が省略されるか0の場合、@code{x}は@var{to-list}の長さが@var{from-list}
32966 の長さに達するまで繰り返されます(その場合、@var{to-list}の残りは無視されます)。
32967 @c COMMON
32968
32969 @item @b{@code{\}x}
32970 @c EN
32971 Represents @code{x} itself. Use this escape to avoid a special
32972 character to be interpreted as itself. Note that if you place
32973 a backslash in a string, you must write @code{\\}, for the Scheme
32974 reader also interprets backslash as a special character.
32975
32976 There's no special sequence to represent non-graphical characters,
32977 for you can put such characters by the string syntax.
32978 @c JP
32979 文字@code{x}それ自身。特殊文字そのものを埋め込みたい場合に使います。
32980 文字列のリーダも@code{\}を解釈するので、@code{\\}と書かねばならないことに注意
32981 して下さい。
32982
32983 グラフィカルでない文字のための構文はありません。文字列リーダの構文を使って
32984 そのような文字を文字列に含めることができます。
32985 @c COMMON
32986 @end table
32987
32988 @c EN
32989 Here's some basic examples.
32990 @example
32991 ;; @r{swaps case of input}
32992 (tr "A-Za-z" "a-zA-Z")
32993
32994 ;; @r{replaces 7-bit non-graphical characters to `?'}
32995 (tr "\x00-\x19\x7f" "?*")
32996 @end example
32997 @c JP
32998 いくつか例を挙げます。
32999 @example
33000 ;; @r{大文字と小文字を交換します}
33001 (tr "A-Za-z" "a-zA-Z")
33002
33003 ;; @r{ひらがなとかたかなを交換します}
33004 (tr "ぁ-んァ-ン" "ァ-ンぁ-ん")
33005
33006 ;; @r{7ビットのノングラフィカルな文字を`?'に変換します}
33007 (tr "\x00-\x19\x7f" "?*")
33008 @end example
33009 @c COMMON
33010
33011 @c EN
33012 If @var{from-list} contains duplicated characters, the first correspondence
33013 is used, and the subsequent correspondences are ignored.
33014 @c JP
33015 @var{from-list}に文字の重複があった場合、最初の出現位置との対応が使われ、
33016 以降の同じ文字の対応は無視されます。
33017 @c COMMON
33018
33019 @example
33020 (string-tr "abc" "aabbcc" "123456")
33021 @result{} "135"
33022 @end example
33023
33024 @c EN
33025 If @var{to-list} is shorter than @var{from-list}, the behavior
33026 depends on the keyword argument @var{delete}. If a true value is
33027 given, characters that appear in @var{from-list} but not
33028 in @var{to-list} are deleted. Otherwise,
33029 the extra characters in @var{from-list} are just passed through.
33030 @c JP
33031 @var{to-list}が@var{from-list}より短い場合、動作はキーワード引数@var{delete}に
33032 依存します。もし真の値が@var{delete}に与えられれば、@var{from-list}に現われて
33033 @var{to-list}に対応するものがない文字は入力から取り除かれます。そうでなければ
33034 そのような文字はそのまま出力されます。
33035 @c COMMON
33036
33037 @example
33038 (string-tr "abracadabra" "abc" "" :delete #t)
33039 @result{} "rdr"
33040 @end example
33041
33042
33043 @c EN
33044 When a true value is specified to @var{complement},
33045 the character set in @var{from-list} is complemented.
33046 Note that it implies @emph{huge} set of characters,
33047 so it is not very useful unless either output character
33048 set is a single character (using `*') or used with
33049 @code{delete} keyword.
33050 @c JP
33051 真の値が@var{complement}に与えられた場合、@var{from-list}の文字の
33052 補集合が@var{from-list}として使われます。この文字集合は極めて大きくなる
33053 可能性があることに注意してください。従って、一般にこのオプションは
33054 @var{to-list}に`*'を使ってそれらの文字を一文字にマッピングするか、
33055 @code{delete}オプションと併用するかしないとあまり意味がありません。
33056 @c COMMON
33057
33058 @c EN
33059 When a true value is specified to @var{squeeze},
33060 the sequence of the same replaced characters is squeezed to one.
33061 If @var{to-list} is empty, the sequence of the same characters
33062 in @var{from-list} is squeezed.
33063 @c JP
33064 真の値が@var{squeeze}に与えられた場合、同じ文字への置換が2つ以上並ぶ場合に
33065 2つめ以降の文字が削除されます。@var{to-list}が空の場合は、@var{from-list}
33066 に含まれる文字で同一文字が並んだ場合に2つめ以降の文字が削除されます。
33067 @c COMMON
33068
33069 @c EN
33070 Internally, @code{tr} builds a table to map the characters for
33071 efficiency. Since Gauche can deal with potentially huge set
33072 of characters, it limits the use of the table for only smaller
33073 characters (<256 by default). If you want to transliterate
33074 multibyte characters on the large text, however, you might want
33075 to use larger table, trading off the memory usage. You can specify
33076 the internal table size by @var{table-size} keyword argument.
33077 For example, if you transliterate lots of EUC-JP hiragana text
33078 to katakana, you may want to set table size greater than 42483
33079 (the character code of the last katakana).
33080 @c JP
33081 内部的に、@code{tr}はキャラクタのマッピングのためにテーブルを使用します。
33082 但し、Gaucheでは極めて大きな文字集合を扱うため、テーブルはキャラクタコードの
33083 小さい文字のみに対して使われます(デフォルトではコード255以下の文字)。
33084 もし、より大きな文字を頻繁に変換することが分かっていて、メモリを余分に使っても
33085 速度を上げたい場合は、このテーブルの大きさを@var{table-size}キーワード引数で
33086 指定することができます。例えばEUC-JPコードで大量の平仮名と片仮名を変換する場合は、
33087 @var{table-size}を42483以上にすると、全ての変換がテーブルルックアップで
33088 行われます。
33089 @c COMMON
33090
33091 @c EN
33092 Note that the pre-calculation to build the transliterate table
33093 needs some overhead. If you want to call @code{tr} many times
33094 inside loop, consider to use @code{build-transliterator} described below.
33095 @c JP
33096 @code{tr}が変換テーブルを計算するのにいくらかオーバーヘッドがあることに
33097 注意して下さい。内側のループで@code{tr}を繰り返し呼ぶような場合は
33098 下に示す@code{build-transliterator}を使った方が良いでしょう。
33099 @c COMMON
33100 @end defun
33101
33102 @defun string-tr string from-list to-list :key :complement :delete :squeeze :table-size
33103 @c MOD text.tr
33104 @c EN
33105 Works like @code{tr}, except that input is taken from a string @var{string}.
33106 @c JP
33107 入力を@var{string}から取って変換結果を文字列で返す以外は@code{tr}と同じです。
33108 @c COMMON
33109 @end defun
33110
33111 @defun build-transliterator from-list to-list :key :complement :delete :squeeze :table-size :input :output
33112 @c MOD text.tr
33113 @c EN
33114 Returns a procedure that does the actual transliteration. This effectively
33115 ``pre-compiles'' the internal data structure. If you want to run
33116 @code{tr} with the same sets repeatedly, you may build the procedure
33117 once and apply it repeatedly, saving the overhead of initialization.
33118 @c JP
33119 実際の変換動作をする手続きを作成して返します。内部データのセットアップを済ませるため、
33120 同じ文字変換セットに対して@code{tr}を繰り返し呼ぶような場合は、この手続きを用いることで
33121 初期化のオーバヘッドを軽減することができます。
33122 @c COMMON
33123
33124 @c EN
33125 A note for an edge case:
33126 When @var{input} and/or @var{output} keyword arguments are omitted,
33127 the created transliterator is set up to use current-input-port and/or
33128 current-output-port at the time transliterator is called.
33129 @c JP
33130 註記:@var{input}や@var{output}キーワード引数が省略された場合、
33131 作成される変換手続きは、それが使用された時点でのカレント入出力ポート
33132 を参照します。
33133 @c COMMON
33134
33135 @example
33136 (with-input-from-file "huge-file.txt"
33137 (lambda ()
33138 (let loop ((line (read-line)))
33139 (unless (eof-object? line) (tr "A-Za-z" "a-zA-Z")))))
33140
33141 @c EN
33142 ;; @r{runs more efficiently...}
33143 @c JP
33144 ;; @r{以下の方が効率良く動作します...}
33145 @c COMMON
33146
33147 (with-input-from-file "huge-file.txt"
33148 (lambda ()
33149 (let ((ptr (build-transliterator "A-Za-z" "a-zA-Z")))
33150 (let loop ((line (read-line)))
33151 (unless (eof-object? line) (ptr))))))
33152 @end example
33153
33154 @end defun
33155
33156 @c ----------------------------------------------------------------------
33157 @node Lazy text construction, Combination library, Transliterate characters, Library modules - Utilities
33158 @section @code{text.tree} - Lazy text construction
33159 @c NODE 怠惰なテキスト構築, @code{text.tree} - 怠惰なテキスト構築
33160
33161 @deftp {Module} text.tree
33162 @mdindex text.tree
33163 @c EN
33164 Defines simple but commonly used functions for a text construction.
33165
33166 When you generate a text by a program,
33167 It is a very common operation to concatenate text segments.
33168 However, using string-append repeatedly causes unnecessary
33169 copying of intermediate strings, and sometimes such intermediate
33170 strings are discarded due to the error situation (for example,
33171 think about constructing an HTML document in the CGI script).
33172
33173 The efficient technique is to delay concatenation of those
33174 text segments until it is needed. In Scheme it is done very
33175 easily by just consing the text segments together, thus forming
33176 a tree of text, and then traverse the tree to construct a text.
33177 You can even directly writes out the text during traversal,
33178 avoiding intermediate string buffer.
33179 (Hans Boehm's ``cord'' library, which comes with his garbage
33180 collector library, uses this technique and proves it is very
33181 efficient for editor-type application).
33182
33183 Although the traversal of the tree can be written in a
33184 few lines of Scheme, I provide this module in the spirits
33185 of OnceAndOnlyOnce. Also it's easier if we have a common interface.
33186 @c JP
33187 テキストを生成する場合によく使われるシンプルな手続きを定義します。
33188
33189 プログラムでテキストを生成する場合、テキストの断片をつなぎ合わせて行く操作が
33190 非常に多く現われます。しかし単純に@code{string-append}を繰り返し
33191 呼んでしまうと、中間結果の文字列を保持するためだけにメモリアロケーションが多発しますし、
33192 途中でエラーが発生した場合にその中間結果は結局捨てられてしまうかもしれません
33193 (例えば、CGIスクリプト中でHTMLドキュメントを構築してゆくような場合を考えてみて下さい)。
33194
33195 よく知られた効率の良い方法は、テキストの断片をつなぎ合わせるのを本当に必要に
33196 なるまで遅らせることです。Schemeではそれは非常に簡単です。単に断片をコンス
33197 していって木構造を作り、最後にそれをトラバースしてテキストを作成するのです。
33198 場合によっては、トラバースしながらテキストを出力すれば事足りてしまうので、
33199 中間結果のバッファを持つ必要さえありません。
33200 (Hans Boehmのガベージコレクションライブラリに附属している ``cord'' ライブラリ
33201 はこのテクニックを実装したもので、エディタ等のアプリケーションで非常に効率良く
33202 動作することが知られています)。
33203
33204 木構造をトラバースする手続きなどほんの2〜3行で書けてしまいますが、
33205 「一度、そして一度だけ」の精神の下に、このモジュールを提供します。
33206 インタフェースが統一されてたほうが便利ですしね。
33207 @c COMMON
33208 @end deftp
33209
33210 @deffn {Generic Function} write-tree tree :optional out
33211 @c MOD text.tree
33212 @c EN
33213 Writes out an @var{tree} as a tree of text, to the output port @var{out}.
33214 If @var{out} is omitted, the current output port is used.
33215
33216 Two methods are defined for this generic function, as shown below.
33217 If you have more complex behavior, you can define more methods
33218 to customize the behavior.
33219 @c JP
33220 @var{tree}をテキストの木構造とみなして、出力ポート@var{out}に出力します。
33221 @var{out}が省略された場合は現在の出力ポートが使われます。
33222
33223 下に示す2つのメソッドが定義されています。より複雑な動作をさせたい場合は、
33224 単純なリストの替わりにノードとなるクラスを定義して、それにメソッドを定義するようにすれば
33225 動作をカスタマイズできます。
33226 @c COMMON
33227 @end deffn
33228
33229 @deffn {Method} write-tree ((tree <list>) out)
33230 @deffnx {Method} write-tree ((tree <top>) out)
33231 @c MOD text.tree
33232 @c EN
33233 Default methods. For a list, @code{write-tree} is recursively
33234 called for each element. Any objects other than list is written out
33235 using @code{display}.
33236 @c JP
33237 @code{write-tree}の既定の動作です。@var{tree}がリストなら、その要素それぞれに
33238 ついて@code{write-tree}を呼び出します。それ以外のオブジェクトに関しては
33239 @code{display}を呼んで出力します。
33240 @c COMMON
33241 @end deffn
33242
33243 @defun tree->string tree
33244 @c MOD text.tree
33245 @c EN
33246 Just calls the @code{write-tree} method for @var{tree} using
33247 an output string port, and returns the result string.
33248 @c JP
33249 出力文字列ポートを作成して@code{write-tree}を呼び、生成された文字列を返します。
33250 @c COMMON
33251 @end defun
33252
33253
33254 @c ----------------------------------------------------------------------
33255 @node Combination library, Message digester framework, Lazy text construction, Library modules - Utilities
33256 @section @code{util.combinations} - Combination library
33257 @c NODE 組み合わせ, @code{util.combinations} - 組み合わせ
33258
33259 @deftp {Module} util.combinations
33260 @mdindex util.combinations
33261 @c EN
33262 This module implements several useful procedures of
33263 combinations, permutations and related operations.
33264
33265 Most procedures in the module have two variants: a procedure without
33266 star (e.g. @code{permutations}) treats all elements in the given
33267 set distinct, while a procedure with star (e.g. @code{permutations*})
33268 considers duplication. The procedures with star take optional @var{eq}
33269 argument that is used to test equality, which defaults to @code{eqv?}.
33270 @c JP
33271 このモジュールは、いくつかの便利なコンビネーションや順列とそれに関連する
33272 操作の手続きを実装しています。
33273
33274 このモジュールのほとんどの手続きは2つのバージョンを持っています。
33275 1つはアスタリスクの付かない手続き(例えば、@code{permutations})で、
33276 与えられたセットにある全ての要素を区別して扱います。もう1つは、
33277 アスタリスクの付く手続き(例えば、@code{permutations*})で、重複を
33278 考慮します。アスタリスクの付く手続きは、オプショナルな@var{eq}引数を取り
33279 ます。それは等値性のテストに使われ、デフォルトは@code{eqv?}です。
33280 @c COMMON
33281 @end deftp
33282
33283 @defun permutations set
33284 @defunx permutations* set :optional eq
33285 @c MOD util.combinations
33286 @c EN
33287 Returns a list of all permutations of a list @var{set}.
33288 @c JP
33289 リスト@var{set}の全ての順列のリストを返します。
33290 @c COMMON
33291
33292 @example
33293 (permutations '(a b c))
33294 @result{} ((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))
33295
33296 (permutations '(a a b))
33297 @result{} ((a a b) (a b a) (a a b) (a b a) (b a a) (b a a))
33298
33299 (permutations* '(a a b))
33300 @result{} ((a a b) (a b a) (b a a))
33301 @end example
33302
33303 @c EN
33304 The number of possible permutations explodes if @var{set} has
33305 more than several elements. Use with care. If you want to process
33306 each permutation at a time, consider @code{permutations-for-each} below.
33307 @c JP
33308 @var{set}がある程度の要素を持っている場合、可能性のある順列の数は
33309 爆発的に大きくなります。注意して使って下さい。
33310 一度にそれぞれの順列を処理したい場合は、下記の@code{permutations-for-each}の
33311 使用を考慮して下さい。
33312 @c COMMON
33313 @end defun
33314
33315 @defun permutations-for-each proc set
33316 @defunx permutations*-for-each proc set :optional eq
33317 @c MOD util.combinations
33318 @c EN
33319 For each permutation of a list @var{set}, calls @var{proc}.
33320 Returns an undefined value.
33321 @c JP
33322 リスト@var{set}のそれぞれの順列に対して、@var{proc}を呼び出します。
33323 戻り値は未定義値です。
33324 @c COMMON
33325 @end defun
33326
33327 @defun combinations set n
33328 @defunx combinations* set n :optional eq
33329 @c MOD util.combinations
33330 @c EN
33331 Returns a list of all possible combinations of @var{n} elements out
33332 of a list @var{set}.
33333 @c JP
33334 リスト@var{set}の@var{n}個の要素の可能性のある全ての順列のリストを
33335 返します。
33336 @c COMMON
33337
33338 @example
33339 (combinations '(a b c) 2)
33340 @result{} ((a b) (a c) (b c))
33341
33342 (combinations '(a a b) 2)
33343 @result{} ((a a) (a b) (a b))
33344
33345 (combinations* '(a a b) 2)
33346 @result{} ((a a) (a b))
33347 @end example
33348
33349 @c EN
33350 Watch out the explosion of combinations when @var{set} is large.
33351 @c JP
33352 @var{set}が大きいときは、組み合わせの爆発について注意して下さい。
33353 @c COMMON
33354 @end defun
33355
33356 @defun combinations-for-each proc set n
33357 @defunx combinations*-for-each proc set n :optional eq
33358 @c MOD util.combinations
33359 @c EN
33360 Calls @var{proc} for each combination of @var{n} elements out of @var{set}.
33361 Returns an undefined value.
33362 @c JP
33363 @var{set}の@var{n}個の要素のそれぞれの組み合わせについて@var{proc}を
33364 呼び出します。戻り値は未定義値です。
33365 @c COMMON
33366 @end defun
33367
33368 @defun power-set set
33369 @defunx power-set* set :optional eq
33370 @c MOD util.combinations
33371 @c EN
33372 Returns power set (all subsets) of a list @var{set}.
33373 @c JP
33374 リスト@var{set}の累乗集合(全てのサブセット)を返します。
33375 @c COMMON
33376
33377 @example
33378 (power-set '(a b c))
33379 @result{} (() (a) (b) (c) (a b) (a c) (b c) (a b c))
33380
33381 (power-set* '(a a b)
33382 @result{} (() (a) (b) (a a) (a b) (a a b))
33383 @end example
33384 @end defun
33385
33386 @defun power-set-for-each proc set
33387 @defunx power-set*-for-each proc set :optional eq
33388 @c MOD util.combinations
33389 @c EN
33390 Calls @var{proc} for each subset of @var{set}.
33391 @c JP
33392 @var{set}のそれぞれのサブセットについて@var{proc}を呼び出す。
33393 @c COMMON
33394 @end defun
33395
33396 @defun power-set-binary set
33397 @c MOD util.combinations
33398 @c EN
33399 Returns power set of @var{set}, like @code{power-set}, but in different order.
33400 @code{Power-set-binary} traverses subset space in depth-first order,
33401 while @code{power-set} in breadth-first order.
33402 @c JP
33403 @code{power-set}のように、@var{set}の累乗集合を返しますが、順番が異なります。
33404 @code{power-set-binary}はサブセットの空間を深さ優先でトラバースしますが、
33405 @code{power-set}は横型探索を行います。
33406 @c COMMON
33407
33408 @example
33409 (power-set-binary '(a b c))
33410 @result{} (() (c) (b) (b c) (a) (a c) (a b) (a b c))
33411 @end example
33412 @end defun
33413
33414 @defun cartesian-product list-of-sets
33415 @defunx cartesian-product-right list-of-sets
33416 @c MOD util.combinations
33417 @c EN
33418 Returns a cartesian product of sets in @var{list-of-sets}.
33419 @code{Cartesian-product} construct the result in left fixed order
33420 (the rightmost element varies first), while
33421 @code{cartesian-product-right} in right fixed order
33422 (the leftmost element varies first).
33423 @c JP
33424 @var{list-of-sets}にあるセットのデカルト積を返します。
33425 @code{cartesian-product}は左固定順で結果を構築しますが
33426 (一番右の要素がまず異なる)、
33427 @code{cartesian-product-right}は右固定順で行います
33428 (一番左の要素がまず異なる)。
33429 @c COMMON
33430
33431 @example
33432 (cartesian-product '((a b c) (0 1)))
33433 @result{} ((a 0) (a 1) (b 0) (b 1) (c 0) (c 1))
33434
33435 (cartesian-product-right '((a b c) (0 1)))
33436 @result{} ((a 0) (b 0) (c 0) (a 1) (b 1) (c 1))
33437 @end example
33438 @end defun
33439
33440 @c ----------------------------------------------------------------------
33441 @node Message digester framework, Calculate dominator tree, Combination library, Library modules - Utilities
33442 @section @code{util.digest} - Message digester framework
33443 @c NODE メッセージダイジェストフレームワーク, @code{util.digest} - メッセージダイジェストフレームワーク
33444
33445 @deftp {Module} util.digest
33446 @mdindex util.digest
33447 @c EN
33448 This module provides a base class and common interface for
33449 message digest algorithms, such as MD5 (@pxref{MD5 message digest})
33450 and SHA (@pxref{SHA message digest}).
33451 @c JP
33452 このモジュールは、MD5 (@ref{MD5 message digest}参照)や
33453 SHA (@ref{SHA message digest}参照)などの、メッセージ
33454 ダイジェストアルゴリズムのためのベースクラスと一般的なインターフェースを
33455 提供します。
33456 @c COMMON
33457
33458 @c EN
33459 A typical way to compute a message digest would be as follows:
33460 @c JP
33461 メッセージダイジェストを計算する典型的なコードは次のとおりです:
33462 @c COMMON
33463
33464 @example
33465 (use rfc.sha) ; import actual digest implementation
33466 (use util.digest)
33467
33468 (digest-message-to 'base64url <sha256> "message")
33469 @end example
33470
33471 @c EN
33472 You can use different algorithms, and choose different output
33473 format (e.g. u8vector, hexadecimal string, etc.)
33474 If you need to digest with a secret key, @pxref{HMAC keyed-hashing}.
33475 @c JP
33476 異なるアルゴリズムを選んだり、異なる出力形式を選ぶこともできます
33477 (例: u8vector, 16進数文字列など)。
33478 秘密鍵を用いたダイジェストについては@ref{HMAC keyed-hashing}を参照してください。
33479 @c COMMON
33480 @end deftp
33481
33482 @c EN
33483 @subheading User API
33484 @c JP
33485 @subheading ユーザ向けAPI
33486 @c COMMON
33487
33488 @c EN
33489 To digest a message, you can use the following API.
33490 @c JP
33491 メッセージダイジェストを計算するには、以下のAPIが使えます。
33492 @c COMMON
33493
33494 @deffn {Generic Function} digest-message-to target digester message
33495 @c MOD util.digest
33496 @c EN
33497 Compute a digest of @var{message} using algorithm implemented by @var{digester},
33498 and returns as an instance of class @var{target}.
33499 @c JP
33500 @var{message}のダイジェストを、@var{digester}で指定されるアルゴリズムを使って
33501 計算し、@var{target}クラスのインスタンスで結果を返します。
33502 @c COMMON
33503
33504 @c EN
33505 The @var{message} argument may be a string or a u8vector.
33506 @c JP
33507 @var{message}引数は文字列かu8vectorです。
33508 @c COMMON
33509
33510 @c EN
33511 The @var{digester} argument must be a class inheriting
33512 @code{<message-digest-algorithm>} and implementing the digester protocol
33513 described below. Gauche provides SHA
33514 (@pxref{SHA message digest}) and MD5 (@pxref{MD5 message digest}) by
33515 default.
33516 @c JP
33517 @var{digester}引数は@code{<message-digest-algorithm>}を継承し、
33518 後で述べるダイジェストプロトコルを実装しているクラスです。
33519 Gaucheにデフォルトでついてくるものとしては、SHA
33520 (@ref{SHA message digest}参照)とMD5(@ref{MD5 message digest}参照)があります。
33521 @c COMMON
33522
33523 @c EN
33524 The supported @var{target} class is @code{<u8vector>} and @code{<string>}.
33525 Digest result is a bytestring in general, so using @code{<u8vector>}
33526 is recommended; if you give @code{<string>}, the result
33527 is likely to be an incomplete string.
33528 @c JP
33529 @var{target}には@code{<u8vector>}か@code{<string>}を指定できます。
33530 ダイジェスト結果は一般にバイト列になるので、@code{<u8vector>}が推奨です。
33531 @code{<string>}を指定した場合は、不完全文字列が返ってくることが多いでしょう。
33532 @c COMMON
33533
33534 @c EN
33535 For the convnience, the following symbols are also allowed as @var{target},
33536 in which case the output byte sequence is encoded to a readable string
33537 For the details of those encodings, @pxref{Base64 encoding/decoding}.
33538 @c JP
33539 簡便のために、@var{target}には以下のシンボルのいずれかを渡すこともできます。
33540 その場合、ダイジェスト結果が指定の形式で可読文字列にエンコードされて返されます。
33541 これらのエンコーディングの詳細については@ref{Base64 encoding/decoding}を参照してください。
33542 @c COMMON
33543
33544 @table @code
33545 @item base64
33546 @c EN
33547 Base64 encoding (original).
33548 @c JP
33549 オリジナルのBase64エンコーディング
33550 @c COMMON
33551 @item base64url
33552 @c EN
33553 URL-safe Base64 encoding.
33554 @c JP
33555 URL安全なBase64エンコーディング
33556 @c COMMON
33557 @item base64url-nopad
33558 @c EN
33559 URL-safe Base64 encoding and omitting trailing padding character (@code{=})
33560 @c JP
33561 URL安全なBase64で、末尾のパディング文字(@code{=})を省略したもの
33562 @c COMMON
33563 @item base32
33564 @c EN
33565 Base32 encoding.
33566 @c JP
33567 Base32エンコーディング
33568 @c COMMON
33569 @item base32hex
33570 @c EN
33571 Base32hex encoding.
33572 @c JP
33573 Base32hexエンコーディング
33574 @c COMMON
33575 @item base16
33576 @c EN
33577 Base16 encoding, a.k.a. hexadecimal encoding (using @code{#[0-9A-F]}.
33578 @c JP
33579 Base16エンコーディング、あるいは16進数形式。@code{#[0-9A-F]}が使われます。
33580 @c COMMON
33581 @item hex
33582 @c EN
33583 Base16 encoding but use lowercase letters (using @code{#[0-9a-f]}.
33584 @c JP
33585 16進数形式、アルファベットに小文字が使われます。
33586 @c COMMON
33587 @end table
33588 @end deffn
33589
33590 @deffn {Generic Function} digest-to target digester
33591 @c EN
33592 Read input from the current input port until EOF, compute
33593 its digest using the algorithm specified by @var{digester},
33594 and returns result in an instance of a class given to @var{target}.
33595 You can also give some symbols to specify encodings as @var{target}.
33596 See @code{digest-message-to} above for the details of
33597 @var{target} and @var{digester}.
33598 @c JP
33599 入力を現在の入力ポートから読んで、@var{digester}で指定されるアルゴリズムで
33600 ダイジェストを計算し、結果を@var{target}クラスのインスタンスで返します。
33601 @var{target}には可読文字列へのエンコーディングを指定するシンボルを与えることもできます。
33602 @var{target}と@var{digester}引数について詳しくは、上の
33603 @code{digest-message-to}の項目を参照してください。
33604 @c COMMON
33605 @c MOD util.digest
33606
33607 @end deffn
33608
33609 @c EN
33610 @subheading Implementer API
33611 @c JP
33612 @subheading 実装者向けAPI
33613 @c COMMON
33614
33615 @c EN
33616 The following API is for the impelmenter of the actual
33617 digest aglrithms.
33618 @c JP
33619 以下のAPIはダイジェストアルゴリズムを実装する人向けです。
33620 @c COMMON
33621
33622 @deftp {Class} <message-digest-algorithm-meta>
33623 @clindex message-digest-algorithm-meta
33624 @c MOD util.digest
33625 @c EN
33626 A metaclass of message digest algorithm implementation.
33627 @c JP
33628 メッセージダイジェストアルゴリズムの実装のメタクラスです。
33629 @c COMMON
33630
33631 @defivar {<message-digest-algorithm-meta>} hmac-block-size
33632 @c EN
33633 Specifies the block size (in bytes), which is specific to each algorithm.
33634 (This is a slot for each @emph{class} object that implements the algorithm,
33635 not for instance of such classes. Only the author of such digest classes
33636 needs to care. See @file{ext/digest/sha.scm} in the source tree
33637 for more details.)
33638 @c JP
33639 各アルゴリズムに固有のブロックサイズをバイト数で指定します。
33640 (これはアルゴリズムを実装する各クラスオブジェクトのスロットで、
33641 それらのクラスのインスタンスのスロットではありません。通常、新たなダイジェストアルゴリズム
33642 クラスを実装する人のみが気にすれば良いスロットです。具体例は
33643 ソースツリーの@file{ext/digest/sha.scm}を見てください。)
33644 @c COMMON
33645 @end defivar
33646 @end deftp
33647
33648 @deftp {Class} <message-digest-algorithm>
33649 @clindex message-digest-algorithm
33650 @c MOD util.digest
33651 @c EN
33652 A base class of message digest algorithm implementation.
33653 @c JP
33654 メッセージダイジェストアルゴリズムの実装のベースクラスです。
33655 @c COMMON
33656 @end deftp
33657
33658 @c EN
33659 The concrete subclass of message digest algorithm has to
33660 implement the following methods.
33661 @c JP
33662 メッセージダイジェストアルゴリズムの具体サブクラスは、以下のメソッドを
33663 実装しなければなりません。
33664 @c COMMON
33665
33666 @deffn {Generic function} digest-update! algorithm data
33667 @c MOD util.digest
33668 @c EN
33669 Takes the instance of massage-digest algorithm, and updates it
33670 with the data @var{data}, which can be either a u8vector
33671 or a (possibly incomplete) string.
33672 @c JP
33673 メッセージダイジェストアルゴリズムのインスタンスを取り、
33674 それをu8vectorか(不完全な可能性のある)文字列のデータ@var{data}で
33675 更新します。
33676 @c COMMON
33677 @end deffn
33678
33679 @deffn {Generic function} digest-final! algorithm
33680 @c MOD util.digest
33681 @c EN
33682 Finalizes the instance of message-digest algorithm, and
33683 returns the digest result in an incomplete string.
33684 @c JP
33685 メッセージダイジェストアルゴリズムのインスタンスを終了させ、
33686 そのダイジェストの結果を不完全文字列で返します。
33687 @c COMMON
33688 @end deffn
33689
33690 @deffn {Generic function} digest class
33691 @c MOD util.digest
33692 @c EN
33693 A wrapper of digest routines. Given message-digest algorithm @var{class},
33694 this function reads the input data from current input port until EOF,
33695 and returns the digest result in an incomplete string.
33696 @c JP
33697 ダイジェストルーチンのラッパです。メッセージダイジェストアルゴリズム
33698 @var{class}を与え、現在の入力ポートから入力データをEOFまで読み込み、
33699 そのダイジェストの結果を不完全文字列で返します。
33700 @c COMMON
33701 @end deffn
33702
33703 @c EN
33704 @subheading Deprecated API
33705 @c JP
33706 @subheading 非推奨API
33707 @c COMMON
33708
33709
33710 @deffn {Generic function} digest-string class string
33711 @c MOD util.digest
33712 @c DEPRECATED
33713 @c EN
33714 Use @code{digest-message-to} for the new code.
33715
33716 Same as @code{(digest-message-to <string> @var{class} @var{string})},
33717 where only a string is allowed to the @var{string} argument.
33718 @c JP
33719 新たなコードではより柔軟な@code{digest-message-to}を使ってください。
33720
33721 @code{(digest-message-to <string> @var{class} @var{string})}と同じです。
33722 ただし@var{string}引数は文字列でなければなりません。
33723 @c COMMON
33724 @end deffn
33725
33726 @defun digest-hexify digest-result
33727 @c MOD util.digest
33728 @c DEPRECATED
33729 @c EN
33730 Same as @code{(base16-encode-message digest-result :lowercase #t)}
33731 (@pxref{Base64 encoding/decoding}). In typical case, you can pass
33732 @code{hex} as the target to @code{digest-message-to} to get
33733 the hexified output directly. This procedure is only kept for
33734 the backward compatibility.
33735 @c JP
33736 @code{(base16-encode-message digest-result :lowercase #t)}と同じです
33737 (@ref{Base64 encoding/decoding}参照)。通常は@code{digest-message-to}の
33738 @var{target}引数に@code{hex}を渡すことで直接16進数表記の結果が得られます。
33739 この手続きは互換性のためだけに残されています。
33740 @c COMMON
33741 @end defun
33742
33743 @c ----------------------------------------------------------------------
33744 @node Calculate dominator tree, R6RS identifier syntax, Message digester framework, Library modules - Utilities
33745 @section @code{util.dominator} - Calculate dominator tree
33746 @c NODE 支配木, @code{util.dominator} - 支配木
33747
33748 @deftp {Module} util.dominator
33749 @mdindex util.dominator
33750 @c EN
33751 Dominator tree is an auxiliary structure for control flow graphs.
33752 It is frequently used in the flow analysis of compilers, but
33753 also useful for handling general directed graphs.
33754 @c JP
33755 支配木(dominator tree)は制御フローグラフで補助的に使われる構造です。
33756 コンパイラのフロー解析によく使われることが多いですが、一般の有向グラフでも有用です。
33757 @c COMMON
33758 @end deftp
33759
33760 @defun calculate-dominators start upstreams downstreams node-comparator
33761 @c MOD util.dominator
33762 @c EN
33763 The four arguments represent a directed, possibly cyclic, graph.
33764 Here, we use @code{Node} to denote an abstract type of a node
33765 of the graph. It can be anything---the algorithm is oblivious on
33766 the actual type of nodes.
33767 @c JP
33768 4つの引数で有向グラフが表現されます。循環があっても構いません。
33769 以下ではグラフのノードが@code{Node}という型を持つとして説明します。
33770 実際にはノードの型は何であっても構いません。
33771 アルゴリズムはノードの実際の型とは無関係に動作します。
33772 @c COMMON
33773
33774 @table @asis
33775 @item @var{start} @code{:: Node}
33776 @c EN
33777 The start node, or the enter node, of the graph.
33778 @c JP
33779 フローの起点となるノード。startノードとかenterノードとも呼ばれます。
33780 @c COMMON
33781 @item @var{upstreams} @code{:: Node -> (Node @dots{})}
33782 @c EN
33783 A procedure that takes a node, and returns its upstream
33784 (immediate ancestor) nodes.
33785 @c JP
33786 ノードを取り、その直接の上流ノードのリストを返す関数。
33787 @c COMMON
33788 @item @var{downstreams} @code{:: Node -> (Node @dots{})}
33789 @c EN
33790 A procedure that takes a node, and returns its downstream
33791 (immediate descendant) nodes.
33792 @c JP
33793 ノードを取り、その直接の下流ノードのリストを返す関数。
33794 @c COMMON
33795 @item @var{node-comparator}
33796 @c EN
33797 A comparator that is used to determine if two nodes are equal to each other.
33798 It doesn't need to have comparison procedure (we don't need to see
33799 which is smaller than the other), but it has to have hash function,
33800 for we use hashtables internally. (@xref{Basic comparators}, for the details
33801 of comparators.)
33802 @c JP
33803 二つのノードが等しいかどうかを決定する比較器。大小比較関数を持っている必要はありませんが、
33804 アルゴリズム内部でハッシュテーブルを使うので、ハッシュ関数は持っている必要があります。
33805 比較器について詳しくは@ref{Basic comparators}を参照してください。
33806 @c COMMON
33807 @end table
33808
33809 @c EN
33810 The procedure returns a list of @code{(node1 node2)}, where
33811 @code{node2} is the immediate dominator of @code{node1}.
33812 @c JP
33813 返り値は@code{(node1 node2)}を要素に持つリストです。ここで、
33814 @code{node2}は@code{node1}の直接支配ノード(immediate dominator)です。
33815 @c COMMON
33816
33817 @c EN
33818 If there are node in the given graph that are unreachable
33819 from @var{start}, such nodes are ignored and not included
33820 in the result.
33821 @c JP
33822 与えられたグラフの中に@var{start}から到達不可能なノードがあった場合、
33823 それは単に無視され、結果に含まれません。
33824 @c COMMON
33825
33826 @c EN
33827 (A bit of explanation: Suppose you want to go to node X from @var{start}.
33828 There may be multiple routes, but if you have to pass node Y no matter
33829 which route you take, then Y is a dominator of X. There may be
33830 many dominators of X. Among them, there's
33831 always one dominator such that all other X's dominators are also
33832 its dominators---in other words, the closest dominator of X---which
33833 is called the immediate dominator of X.)
33834 @c JP
33835 (ちょっとした説明: @var{start}からノードXに行きたいとします。
33836 複数の経路がありえますが、どの経路を取っても必ずノードYを通らないと
33837 Xに行けない場合、YをXの支配ノード(dominator)と呼びます。
33838 支配ノードは複数ありえますが、その中で一つだけ、他のXの支配ノード全てが
33839 そのノードの支配ノードでもあるようなノードがあります(言い換えれば、
33840 Xに一番「近い」支配ノードです)。それをXの直接支配ノードと呼びます。)
33841 @c COMMON
33842
33843 @c EN
33844 Let's see an example. You have this directed graph:
33845 @c JP
33846 例を見てみましょう。こんな有向グラフがあるとします。
33847 @c COMMON
33848
33849 @example
33850 A (start)
33851 |
33852 v
33853 B <-------+
33854 | |
33855 ------+----- |
33856 | | |
33857 v v |
33858 C -------> D ---+
33859 | |
33860 v v
33861 E <------- F
33862 @end example
33863
33864 @c EN
33865 Let's represent the graph by a list of @code{(x y z ...)} where @code{x}
33866 can directly go to either @code{y z ...}.
33867 @c JP
33868 このグラフをリストのリストで表現してみましょう。
33869 ここで、内側のリスト@code{(x y z ...)}は、@code{x}からは@code{y}や@code{z}に
33870 直接行ける、ということを表します。
33871 @c COMMON
33872
33873 @example
33874 (define *graph* '((A B)
33875 (B C D)
33876 (C D E)
33877 (D F B)
33878 (F E)))
33879 @end example
33880
33881 @c EN
33882 Then you can calculate the immediate dominator of each node as follows:
33883 @c JP
33884 すると、各ノードの直接支配ノードが次の通り計算できます。
33885 @c COMMON
33886
33887 @example
33888 (calculate-dominators 'A
33889 (^n (filter-map (^g (and (memq n (cdr g)) (car g))) *graph*))
33890 (^n (assoc-ref *graph* n '()))
33891 eq-comparator)
33892 @result{} ((E B) (F D) (D B) (C B) (B A))
33893 @end example
33894
33895 @c EN
33896 That is, @code{E}'s immediate dominator is @code{B},
33897 @code{F}'s is @code{D}, and so on.
33898 @c JP
33899 つまり、@code{E}の直接支配ノードは@code{B}であり、
33900 @code{F}のは@code{D}である、という具合です。
33901 @c COMMON
33902
33903 @c EN
33904 The result itself can be viewed as a tree. It is called a dominator tree.
33905 @c JP
33906 この結果自体を木と解釈することができます。これを支配木(dominator tree)と呼びます。
33907 @c COMMON
33908
33909 @example
33910 F
33911 |
33912 v
33913 E D C
33914 | | |
33915 | v |
33916 +---> B <---+
33917 |
33918 v
33919 A
33920 @end example
33921 @end defun
33922
33923 @c ----------------------------------------------------------------------
33924 @node R6RS identifier syntax, Determine isomorphism, Calculate dominator tree, Library modules - Utilities
33925 @section @code{util.identifier-syntax} - R6RS identifier syntax
33926 @c NODE R6RS識別子マクロ, @code{util.identifier-syntax} - R6RS識別子マクロ
33927
33928 @deftp {Module} util.identifier-syntax
33929 @mdindex util.identifier-syntax
33930 @c EN
33931 Provide R6RS's @code{identifier-syntax} form.
33932 @c JP
33933 R6RSの@code{identifier-syntax}フォームを提供します。
33934 @c COMMON
33935 @end deftp
33936
33937 @defmac identifier-syntax template
33938 @defmacx identifier-syntax (id1 template1) ((@code{set!} id2 pattern) template2)
33939 [R6RS]
33940 @c MOD util.identifier-syntax
33941 @c EN
33942 Creates an idendifier macro transformer in the way R6RS specifies.
33943 For identifier transformers, @pxref{Identifier transformer}. This macro
33944 is built on top of @code{make-id-transformer}.
33945 We provide this to ease porting R6RS code to Gauche.
33946 @c JP
33947 R6RSで規定されている方法で識別子マクロ変換器を作ります。
33948 識別子マクロについては@ref{Identifier transformer}を参照してください。
33949 このマクロは@code{make-id-transformer}を使って作られています。
33950 R6RSコードをGaucheにポートする際に便利でしょう。
33951 @c COMMON
33952
33953 @c EN
33954 This form must appear as @var{transformer-spec} in macro definitions
33955 (@pxref{Hygienic macros}). The behavior is undefined if this is
33956 used in other places.
33957 @c JP
33958 このフォームはマクロ定義の@var{transformer-spec}として使うことができます
33959 (@ref{Hygienic macros}参照)。それ以外の部分に現れた場合の動作は未定義です。
33960 @c COMMON
33961
33962 @c EN
33963 The first form creates an identifier macro that expands to @var{template}.
33964 Suppose you define a macro with this:
33965 @c JP
33966 最初の形式は、識別子マクロを@var{template}へと展開します。
33967 例えば次の定義があったとします:
33968 @c COMMON
33969
33970 @example
33971 (define-syntax now (identifier-syntax (sys-time)))
33972 @end example
33973
33974 @c EN
33975 Then, any use of @code{now} is expanded to @code{(sys-time)}; however,
33976 @code{(set! now expr)} will raise an error.
33977 @c JP
33978 すると、@code{now}が現れたらそれは全て@code{(sys-time)}へと展開されます。
33979 ただし@code{(set! now expr)}はエラーになります。
33980 @c COMMON
33981
33982 @c EN
33983 The second form allows @code{set!} as well. The following is a contrived
33984 example:
33985 @c JP
33986 二番目の形式は@code{set!}に使われた場合の展開も定義します。
33987 次はちょっとわざとらしい例ですが:
33988 @c COMMON
33989
33990 @example
33991 (define-syntax foo
33992 (identifier-syntax
33993 [_ (get-foo)]
33994 [(set! _ expr) (set-foo! expr)]))
33995 @end example
33996
33997 @c EN
33998 Any use of @code{foo} is expanded to @code{(get-foo)}, except
33999 @code{(set! foo something)}, which is expanded to @code{(set-foo! something)}.
34000 @c JP
34001 @code{foo}が出現するとそれは@code{(get-foo)}に置き換えられます。
34002 ただし@code{(set! foo something)}の場合はそれが
34003 @code{(set-foo! something)}となります。
34004 @c COMMON
34005
34006 @c EN
34007 (Unlike using @code{make-id-transformer} and @code{syntax-rules} combination,
34008 the @code{set!} matching clause can come later.)
34009 @c JP
34010 (@code{make-id-transformer}と@code{syntax-rules}の組み合わせとは違って、
34011 @code{set!}とマッチする節を後に置きます。)
34012 @c COMMON
34013
34014 @c EN
34015 The expansion is hygienic. The identifiers used in @var{template} captures
34016 meaning in the scope where @code{identifier-syntax} appears, and won't
34017 be affected by the scope where the macro is used.
34018 @c JP
34019 展開は衛生的です。@var{template}に現れる識別子は@code{identifier-syntax}が現れた
34020 環境での意味を捕捉し、マクロが使われる環境に影響されません。
34021 @c COMMON
34022 @end defmac
34023
34024 @c ----------------------------------------------------------------------
34025 @node Determine isomorphism, The longest common subsequence, R6RS identifier syntax, Library modules - Utilities
34026 @section @code{util.isomorph} - Determine isomorphism
34027 @c NODE 同型判定, @code{util.isomorph} - 同型判定
34028
34029 @deftp {Module} util.isomorph
34030 @mdindex util.isomorph
34031 @c EN
34032 Provides a procedure that determines whether two structures are
34033 isomorphic.
34034 @c JP
34035 二つの構造が同型かどうかを判定する手続きを提供するモジュールです。
34036 @c COMMON
34037 @end deftp
34038
34039 @defun isomorphic? obj1 obj2 :optional context
34040 @c MOD util.isomorph
34041 @c EN
34042 Returns @code{#t} if @var{obj1} and @var{obj2} are isomorphic.
34043
34044 @var{context} is used if you want to call @code{isomorphic?}
34045 recursively inside @code{object-isomorphic?} described below.
34046 @c JP
34047 @var{obj1}と@var{obj2}が同型であれば@code{#t}を返します。
34048
34049 省略可能な引数@var{context}は、下で説明する@code{object-isomorphic?}
34050 の中から@code{isomorphic?}を再帰的に呼び出す場合に使います。
34051 @c COMMON
34052
34053 @example
34054 (isomorphic? '(a b) '(a b)) @result{} #t
34055
34056 (define x (cons 0 0))
34057 (define y (cons 0 0))
34058 (isomorphic? (cons x x)
34059 (cons x y))
34060 @result{} #f
34061 (isomorphic? (cons x x)
34062 (cons y y))
34063 @result{} #t
34064 @end example
34065 @end defun
34066
34067 @deffn {Generic Function} object-isomorphic? obj1 obj2 context
34068 @c MOD util.isomorph
34069 @c EN
34070 With this method, you can customize how to determine isomorphism of
34071 two objects. Basically, you will call @code{isomorphic?} recursively
34072 for each slots of object you want to traverse; the method should return
34073 @code{#t} if all of the test succeeds, or return @code{#f} otherwise.
34074 @var{context} is an opaque structure
34075 that keeps the traversal context, and you should pass it to
34076 @code{isomorphic?} as is.
34077
34078 The default method returns @code{#t} if @var{obj1} and @var{obj2} are
34079 equal (in the sense of @code{equal?}).
34080 @c JP
34081 このメソッドで、二つのオブジェクトの同型判定処理をカスタマイズできます。
34082 基本的には、オブジェクトのトラバースしたいスロットに対して@code{isomorphic?}を順に適用し、
34083 全てが成功すれば@code{#t}を、一つでも失敗すれば@code{#f}を返すようにします。
34084 @var{context}はトラバースのコンテクストを保持しているオブジェクトです。そのまま
34085 @code{isomorphic?}に渡して下さい。
34086
34087 デフォルトメソッドは、@var{obj1}と@var{obj2}が@code{equal?}の意味で等しければ
34088 @code{#t}を返します。
34089 @c COMMON
34090 @end deffn
34091
34092 @c ----------------------------------------------------------------------
34093 @node The longest common subsequence, Levenshtein edit distance, Determine isomorphism, Library modules - Utilities
34094 @section @code{util.lcs} - The longest common subsequence
34095 @c NODE 最長共通サブシーケンス, @code{util.lcs} - 最長共通サブシーケンス
34096
34097 @deftp {Module} util.lcs
34098 @mdindex util.lcs
34099 @c EN
34100 This module implements the algorithm to find the longest common subsequence
34101 of two given sequences. The implemented algorithm is based on
34102 Eugene Myers' O(ND) algorithm
34103 (Eugene Myers, An O(ND) Difference Algorithm and Its Variations,
34104 @i{Algorithmica} Vol. 1 No. 2, pp. 251-266, 1986.).
34105
34106 One of the applications of this algorithm is to calculate
34107 the difference of two text streams;
34108 @pxref{Calculate difference of text streams}.
34109 @c JP
34110 このモジュールは、与えられた2つのシーケンスの最長共通サブシーケンスを見つける
34111 アルゴリズムを実装しています。アルゴリズムは、Eugene Myersの
34112 O(ND)アルゴリズムに基づいています
34113 (Eugene Myers, An O(ND) Difference Algorithm and Its Variations,
34114 @i{Algorithmica} Vol. 1 No. 2, pp. 251-266, 1986.)。
34115
34116 このアルゴリズムを使うアプリケーションの1つは、2つのテキストストリームの
34117 相違点を計算する@code{test.diff}モジュールです
34118 (@ref{Calculate difference of text streams}参照)。
34119 @c COMMON
34120 @end deftp
34121
34122 @defun lcs seq-a seq-b :optional eq-fn
34123 @c MOD util.lcs
34124 @c EN
34125 Calculates and returns the longest common sequence of
34126 two lists, @var{seq-a} and @var{seq-b}.
34127 Optional @var{eq-fn} specifies
34128 the comparison predicate; if omitted, @code{equal?} is used.
34129 @c JP
34130 2つのリスト、@var{seq-a}と@var{seq-b}の最長共通シーケンスを計算して
34131 返します。オプションの@var{eq-fn}では、比較を行う述語を指定します。
34132 省略されると、@code{equal?}が使われます。
34133 @c COMMON
34134
34135 @example
34136 (lcs '(x a b y) '(p a q b))
34137 @result{} (a b)
34138 @end example
34139 @end defun
34140
34141 @defun lcs-with-positions seq-a seq-b :optional eq-fn
34142 @c MOD util.lcs
34143 @c EN
34144 This is the detailed version of @code{lcs}.
34145 The arguments are the same.
34146
34147 Returns a list of the following structure:
34148 @c JP
34149 @code{lcs}の詳細バージョンです。引数は同じです。
34150
34151 以下の構造のリストを返します。
34152 @c COMMON
34153
34154 @example
34155 (@var{length} ((@var{elt} @var{a-pos} @var{b-pos}) @dots{}))
34156 @end example
34157
34158 @c EN
34159 @var{Length} is an integer showing the length of the found LCS.
34160 What follows is a list of elements of LCS; each sublist
34161 consists of the element, the integer position of the element
34162 in @var{seq-a}, then the integer position of the element in @var{seq-b}.
34163 @c JP
34164 @var{length}は、見つかったLCS(最長共通サブシーケンス)の長さを表す整数です。
34165 それに続くのは、LCSの要素のリストで、その要素を構成するそれぞれのサブリスト、
34166 @var{seq-a}の中での要素の位置(整数)、@var{seq-b}の中での要素の位置(整数)
34167 となります。
34168 @c COMMON
34169
34170 @example
34171 (lcs-with-positions '(a) '(a))
34172 @result{} (1 ((a 0 0)))
34173
34174 (lcs-with-positions '(x a b y) '(p q a b))
34175 @result{} (2 ((a 1 2) (b 2 3)))
34176
34177 (lcs-with-positions '(x a b y) '(p a q b))
34178 @result{} (2 ((a 1 1) (b 2 3)))
34179
34180 (lcs-with-positions '(x y) '(p q))
34181 @result{} (0 ())
34182 @end example
34183 @end defun
34184
34185 @defun lcs-fold a-proc b-proc both-proc seed a b :optional eq-fn
34186 @c MOD util.lcs
34187 @c EN
34188 A fundamental iterator over the "edit list" derived from
34189 two lists @var{a} and @var{b}.
34190
34191 @var{A-proc}, @var{b-proc}, @var{both-proc} are all procedures
34192 that take two arguments. The second argument is a intermediate
34193 state value of the calculation. The first value is an element
34194 only in @var{a} for @var{a-proc}, or an element only in @var{b}
34195 for @var{b-proc}, or an element in both @var{a} and @var{b}
34196 for @var{both-proc}. The return value of each procedure is used
34197 as the state value of the next call of either one of the procedures.
34198 @var{Seed} is used as the initial value of the state value.
34199 The last state value is returned from @code{lcs-fold}.
34200
34201 The three procedures are called in the following order: Suppose the sequence
34202 @var{a} consists of @var{a'}@var{c}@var{a''}, and @var{b} consists of
34203 @var{b'}@var{c}@var{b''}, where @var{a'}, @var{b'}, @var{a''}, and @var{b''}
34204 are subsequences, and @var{c} is the head of the
34205 LCS of @var{a} and @var{b}. Then @var{a-proc} is called first on
34206 each element in @var{a'}, @var{b-proc} is called second on
34207 each element in @var{b'}, then @var{both-proc} is called on @var{c}.
34208 Afterwards, the process is repeated using @var{a''} and @var{b''}.
34209 @c JP
34210 2つのリスト@var{a}と@var{b}から引き出された``編集リスト''に対する
34211 基本的なイテレータです。
34212
34213 @var{a-proc}、@var{b-proc}、@var{both-proc}は全て2引数を取る手続きです。
34214 2番目の引数は、計算の中間の値です。最初の値は、@var{a-proc}では@var{a}にしかない要素、
34215 @var{b-proc}では@var{b}にしかない要素、@var{both-proc}では@var{a}と@var{b}の両方に
34216 ある要素となります。それぞれの手続きが返す値は、次に呼び出される手続きのうちの1つの
34217 状態を表す値として使われます。@var{seed}は、状態を表す値の初期値として使われます。
34218 @code{lcs-fold}が返す値は、最後の状態を表す値です。
34219
34220 これらの3つの手続きは、以下の順番で呼ばれます。ここでは、シーケンス@var{a}は
34221 @var{a'}@var{c}@var{a''}、@var{b}は@var{b'}@var{c}@var{b''}となっているとすると、
34222 ここでは@var{a'}、@var{b'}、@var{a''}、@var{b''}はサブシーケンスで、
34223 @var{c}は@var{a}と@var{b}のLCSの先頭になります。そして、@var{a-proc}はまず
34224 @var{a'}のそれぞれの要素に対して呼ばれ、@var{b-proc}が@var{b'}のそれぞれの
34225 要素に対して呼ばれ、@var{both-proc}が@var{c}に対して呼ばれます。
34226 その後、このプロセスは@var{a''}と@var{b''}を使って繰り返されます。
34227 @c COMMON
34228 @end defun
34229
34230 @defun lcs-edit-list a b :optional eq-fn
34231 @c MOD util.lcs
34232 @c EN
34233 Calculates 'edit-list' from two lists @var{a} and @var{b}, which is
34234 the smallest set of commands (additions and deletions) that changes
34235 @var{a} into @var{b}.
34236 This procedure is built on top of @code{lcs-fold} above.
34237
34238 Returns a list of @emph{hunk}s, which is a contiguous section of
34239 additions and deletions. Each hunk consists of a list of
34240 directives, which is a form of:
34241 @c JP
34242 2つのリスト@var{a}と@var{b}から``編集リスト''を計算します。それは、
34243 @var{a}を@var{b}に変更するためのコマンド(追加と削除)の最小セットです。
34244 この手続きは、上の@code{lcs-fold}の上に構築されています。
34245 @c COMMON
34246 @example
34247 (@var{+}|@var{-} @var{position} @var{element})
34248 @end example
34249
34250 @c EN
34251 Here's an example. Suppose @var{a} and @var{b} are the following
34252 lists, respectively.
34253 @c JP
34254 例を挙げます。@var{a}と@var{b}がそれぞれ以下のようなリストだとします。
34255 @c COMMON
34256
34257 @example
34258 @var{a} @equiv{} ("A" "B" "C" "E" "H" "J" "L" "M" "N" "P")
34259 @var{b} @equiv{} ("B" "C" "D" "E" "F" "J" "K" "L" "M" "R" "S" "T")
34260 @end example
34261
34262 @c EN
34263 Then, @code{(lcs-edit-list a b equal?)} returns the following list.
34264 @c JP
34265 すると、@code{(lcs-edit-list a b equal?)}は以下のリストを返します。
34266 @c COMMON
34267 @example
34268 (((- 0 "A"))
34269 ((+ 2 "D"))
34270 ((- 4 "H") (+ 4 "F"))
34271 ((+ 6 "K"))
34272 ((- 8 "N") (- 9 "P") (+ 9 "R") (+ 10 "S") (+ 11 "T"))
34273 )
34274 @end example
34275 @c EN
34276 The result consists of five hunks. The first hunk consists of
34277 one directive, @code{(- 0 "A")}, which means the element @code{"A"}
34278 at the position 0 of list @var{a} has to be deleted.
34279 The second hunk also consists of one directive, @code{(+ 2 "D")},
34280 meaning the element @code{"D"} at the position 2 of list @var{b}
34281 has to be added. The third hunk means @code{"H"} at the position
34282 4 of list @var{a} should be removed and @code{"F"} at the position
34283 4 of list @var{b} should be added, and so on.
34284
34285 If you are familiar with Perl's Algorithm::Diff module, you may
34286 notice that this is the same structure that its @code{diff} procedure
34287 returns.
34288 @c JP
34289 結果は5つの片からなります。最初のものは1つのディレクティブ、@code{(- 0 ``A'')}から
34290 なり、これはリスト@var{a}の位置0にある要素@code{``A''}が削除されることを意味します。
34291 2番目のものはまた1つのディレクティブ、@code{(+ 2 ``D'')}からなり、これは
34292 リスト@var{b}の位置2にある要素@code{``D''}が追加されることを意味します。
34293 3番目のものは、リスト@var{a}の位置4にある@code{``H''}は削除され、リスト@var{b}の
34294 位置4にある@code{``F''}が追加される、などとなります。
34295
34296 もしあなたがPerlのAlgorithm::Diffモジュールを良く知っていれば、
34297 その@code{diff}手続きが返すものと同じ構造だということが分かるでしょう。
34298 @c COMMON
34299 @end defun
34300
34301 @defun lcs-edit-list/context a b :optional eq-fn :key context-size
34302 @defunx lcs-edit-list/unified a b :optional eq-fn :key context-size
34303 @c MOD util.lcs
34304 @c EN
34305 Calculates edit list of two sequences @var{a} and @var{b}, including
34306 context surrounding the changes.
34307 It is similar to what you get with @code{diff -c} and @code{diff -u}
34308 commands, respectively.
34309 The @code{text.diff} module provides context diff on top of
34310 this procedure (@pxref{Calculate difference of text streams}).
34311 @c JP
34312 二つのシーケンス@var{a}と@var{b}から、変更の文脈を含めた編集リストを計算します。
34313 @code{diff -c}および@code{diff -u}コマンドの出力と似たようなものです。
34314 @code{text.diff}モジュールではこの手続きの上に、コンテクストdiff出力を得る
34315 ユーティリティを提供しています
34316 (@ref{Calculate difference of text streams}参照)。
34317 @c COMMON
34318
34319 @c EN
34320 The @var{eq-fn} argument specifies the equality predicate on the elements.
34321 Its default is @code{equal?}.
34322 The @var{context-size} keyword argument specifies the maximum
34323 size of the unchanged elements surrounding each edits. It must be
34324 an exact positive integer. Its default is 3.
34325 @c JP
34326 @var{eq-fn}引数はシーケンスの各要素を比較する述語で、デフォルトは@code{equal?}です。
34327 @var{context-size}引数は、文脈を示すために変更点の前後に付加される変更のない
34328 要素の最大数で、正の正確な整数でなければなりません。デフォルトは3です。
34329 @c COMMON
34330
34331 @c EN
34332 Returns a list of @emph{hunk}s. Each hunk represents a chunk of
34333 difference between @var{a} and @var{b}. The format of hunk
34334 differs between @code{lcs-edit-list/context} and
34335 @code{lcs-edit-list/unified}.
34336 @c JP
34337 戻り値は@emph{hunk}のリストです。各hunkが@var{a}と@var{b}の相違点を示します。
34338 hunkのフォーマットは@code{lcs-edit-list/context}と@code{lcs-edit-list/unified}で
34339 異なります。
34340 @c COMMON
34341
34342 @c EN
34343 @strong{A hunk of @code{lcs-edit-list/context}} has the following form:
34344 @c JP
34345 @strong{@code{lcs-edit-list/context}のhunk}は次のとおりです。
34346 @c COMMON
34347
34348 @example
34349 <hunk> : #(<a-edits> <b-edits>)
34350
34351 <a-edits> : <edits>
34352 <b-edits> : <edits>
34353
34354 <edits> : (<start-pos> <end-pos> <edit> ...)
34355
34356 <edit> : (= <element>) ; same in both a and b
34357 | (- <element>) ; deleted: only in a
34358 | (+ <element>) ; inserted: only in b
34359 | (! <element>) ; changed
34360 @end example
34361
34362 @c EN
34363 The @var{<start-pos>} and @var{<end-pos>} are exact integer indexes
34364 of the sequence the hunk is covering; the start position inclusive,
34365 the end position exclusive, and 0-based.
34366 @c JP
34367 @var{<start-pos>}と@var{<end-pos>}は正確な整数のインデックスで、
34368 シーケンス中でhunkがカバーする範囲を示します (@var{<start-pos>}は含まれ、
34369 @var{<end-pos>}は含まれません)。
34370 @c COMMON
34371
34372 @c EN
34373 Each @var{<edit>} shows the element in that range, and whether the
34374 element is to be unchanged, deleted, inserted or changed, to edit
34375 the sequence @var{a} to make @var{b}.
34376 @c JP
34377 各@var{<edit>}はその範囲の要素と、それが両シーケンスで同じなのか、
34378 削除された(@var{a}だけに存在)か、挿入された(@var{b}だけに存在)か、
34379 あるいは置き換えられたかを示します。
34380 @c COMMON
34381
34382 @c EN
34383 Here's an example:
34384 @c JP
34385 これが例です:
34386 @c COMMON
34387
34388 @example
34389 (lcs-edit-list/context '(a b c) '(a B c d))
34390 @result{}
34391 (#((0 3 (= a) (! b) (= c))
34392 ((0 4 (= a) (! B) (= c) (+ d)))))
34393 @end example
34394
34395 @c EN
34396 The result contains one hunk. It shows that you should change @code{b}
34397 to @code{B}, and insert @code{d}.
34398 @c JP
34399 結果には1つのhunkが含まれ、それは@code{b}を@code{B}に置き換えて@code{d}を追加することを
34400 指示しています。
34401 @c COMMON
34402
34403 @c EN
34404 @strong{A hunk of @code{lcs-edit-list/unified}} has the following form:
34405 @c JP
34406 @strong{@code{lcs-edit-list/unified}のhunk}は次のとおりです:
34407 @c COMMON
34408
34409 @example
34410 <hunk> : #(<a-start> <a-size> <b-start> <b-size> (<edit> ...))
34411
34412 <edit> : (= <element>) ; unchanged
34413 | (- <element>) ; deleted
34414 | (+ <element>) ; inserted
34415 @end example
34416
34417 @c EN
34418 Each @var{start} and @var{size} in the hunk specifies
34419 the start position within the sequence (0-based) and
34420 the length of the hunk in the sequence, respectively.
34421 @c JP
34422 各@var{start}と@var{size}はそれぞれのシーケンス中での、
34423 hunkの開始位置(0起点)とその長さを示します。
34424 @c COMMON
34425
34426 @example
34427 (lcs-edit-list/unified '(a b c) '(a B c d))
34428 @result{}
34429 (#(0 3 0 4 ((= a) (- b) (+ B) (= c) (+ d))))
34430 @end example
34431
34432 @c EN
34433 @strong{Context size:}
34434 In each hunk, up to @var{context-size} unchanged elements are attached
34435 before and after the inserted/delete/changed elements, to show the
34436 context. If there's less than @code{(+ 1 (* conext-size 2))} elements
34437 between two changes, they are merged into one hunk. In the followig
34438 example, the change of @code{b} to @code{B} and @code{e} to @code{E}
34439 are merged into one hunk for they're not far enough, while
34440 the change of @code{i} to @code{I} is in a separate hunk:
34441 @c JP
34442 @strong{コンテキストの大きさ}:
34443 各hunkの前後には、文脈を示すために、
34444 最大で@var{context-size}の、変更のない要素が付加されています。
34445 もし変更のあった二ヶ所の間の要素が@code{(+ 1 (* conext-size 2))}より少なければ、
34446 二つの変更箇所は一つのhunkにまとめられます。
34447 次の例では、@code{b}から@code{B}、@code{e}から@code{E}への変更は
34448 十分に離れていないのでひとつのhunkになり、一方@code{i}から@code{I}への変更は
34449 別のhunkになっています:
34450 @c COMMON
34451
34452 @example
34453 (lcs-edit-list/context '(a b c d e f g h i j)
34454 '(a B c d E f g h I j)
34455 equal? :context-size 1)
34456 @result{}
34457 (#((0 6 (= a) (! b) (= c) (= d) (! e) (= f))
34458 (0 6 (= a) (! B) (= c) (= d) (! E) (= f)))
34459 #((7 10 (= h) (! i) (= j))
34460 (7 10 (= h) (! I) (= j))))
34461
34462 (lcs-edit-list/unified '(a b c d e f g h i j)
34463 '(a B c d E f g h I j)
34464 equal? :context-size 1)
34465 @result{}
34466 (#(0 6 0 6 ((= a) (- b) (+ B) (= c) (= d) (- e) (+ E) (= f)))
34467 #(7 3 7 3 ((= h) (- i) (+ I) (= j))))
34468 @end example
34469 @end defun
34470
34471
34472 @c ----------------------------------------------------------------------
34473 @node Levenshtein edit distance, Pattern matching, The longest common subsequence, Library modules - Utilities
34474 @section @code{util.levenshtein} - Levenshtein edit distance
34475 @c NODE Levenshtein編集距離, @code{util.levenshtein} - Levenshtein編集距離
34476
34477 @deftp {Module} util.levenshtein
34478 @mdindex util.levenshtein
34479 @c EN
34480 This module provides procedures to calculate edit distance between
34481 two sequences. Edit distance is the minimum number of edit operations
34482 required to match one sequence to another.
34483 Three algorithms are implemented:
34484 @c JP
34485 このモジュールは二つのシーケンスの間の編集距離を計算する手続きを提供します。
34486 編集距離とは、ひとつのシーケンスからもうひとつのシーケンスへと変更する
34487 編集操作の数です。3つのアルゴリズムが実装されています。
34488 @c COMMON
34489
34490 @table @asis
34491 @item Levenshtein distance
34492 @c EN
34493 Count deletion of one element, insertion of one element,
34494 and substitution of one element.
34495 @c JP
34496 1要素の削除、1要素の追加、1要素の置き換えそれぞれを1操作と数えます。
34497 @c COMMON
34498 @item Damerau-Levenshtein distance
34499 @c EN
34500 Besides deletion, insertion and substitution, we allow transposition
34501 of adjacent elements.
34502 @c JP
34503 削除、追加、置き換えに加え、隣合った要素の入れ替えも1操作と数えます。
34504 @c COMMON
34505 @item Restricted edit distance
34506 @c EN
34507 Also called optimal string alignment distance. Like Damerau-Levenshtein,
34508 but once transposition is applied, no further editing on those elements
34509 are allowed.
34510 @c JP
34511 Optimal string alignmentとも呼ばれます。Damerau-Levenshteinと似ていますが、
34512 隣合った要素の入れ替えを行った場合、それらの要素は以降の編集を受けません。
34513 @c COMMON
34514 @end table
34515
34516 @c EN
34517 These algorithms are often used to compare strings, but the procedures
34518 in this module can handle any type of sequence (@pxref{Sequence framework}).
34519 @c JP
34520 これらのアルゴリズムは文字列に対して使われることが多いですが、
34521 このモジュールの手続きはシーケンスになら何でも使えます
34522 (@ref{Sequence framework}参照)。
34523 @c COMMON
34524 @end deftp
34525
34526 @defun l-distance seq-A seq-B :key elt= cutoff
34527 @defunx l-distances seq-A seq-Bs :key elt= cutoff
34528 @defunx re-distance seq-A seq-B :key elt= cutoff
34529 @defunx re-distances seq-A seq-Bs :key elt= cutoff
34530 @defunx dl-distance seq-A seq-B :key elt= cutoff
34531 @defunx dl-distances seq-A seq-Bs :key elt= cutoff
34532 @c MOD util.levenshtein
34533 @c EN
34534 Calculates Levenshtein distance (@code{l-*}), restricted edit
34535 distance (@code{re-*}) and Damerau-Levenshtein distance (@code{dl-*})
34536 between sequences, respectively. Each algorithm comes in two
34537 flavors: The singular form @code{*-distance} takes two sequences,
34538 @var{seq-A} and @var{seq-B}, and calculates distance between them.
34539 The plural form @code{*-distances} takes a sequence @var{seq-A}
34540 and a list of sequences @var{seq-Bs}, and calculates distances
34541 between @var{seq-A} and each in @var{seq-Bs}.
34542 @c JP
34543 それぞれ、与えられたシーケンス間のLevenshtein距離(@code{l-*})、
34544 Restricted edit距離(@code{re-*})およびDamerau-Levenshtein距離(@code{dl-*})を
34545 計算します。アルゴリズム毎にふたつのAPIが提供されます。
34546 単数形の@code{*-distance}は、二つのシーケンス@var{seq-A}と@var{seq-B}を取り、
34547 両者の間の距離を計算します。
34548 複数形の@code{*-distances}は、一つのシーケンス@var{seq-A}と
34549 シーケンスのリスト@var{seq-Bs}をとり、@var{seq-Bs}の各シーケンスと
34550 @var{seq-A}との距離を計算します。
34551 @c COMMON
34552
34553 @c EN
34554 If you need to calculate distances from a single sequence to many
34555 sequences, using the plural version is much faster than repeatedly
34556 calling the singular version, for the plural version can reuse internal
34557 data structures and save allocation and setup time.
34558 @c JP
34559 あるシーケンスと、多数のシーケンスとの間の距離を計算したいなら、
34560 単数形のAPIを繰り返し呼ぶより複数形のAPIを使う方が効率的です。
34561 複数形のAPIでは内部で使うデータ構造を再利用するので、
34562 重複するアロケーションと初期化の時間を節約できます。
34563 @c COMMON
34564
34565 @c EN
34566 Sequences can be any object that satisfy the @code{<sequence>} protocol
34567 (@pxref{Sequence framework}).
34568 @c JP
34569 シーケンスは、@code{<sequence>}プロトコルを満足するオブジェクトであれば
34570 何でも構いません (@ref{Sequence framework}参照)。
34571 @c COMMON
34572
34573 @c EN
34574 The keyword argument @var{elt=} is used to compare elements in
34575 the sequences. Its default is @code{eqv?}.
34576 @c JP
34577 キーワード引数@var{elt=}はシーケンスの要素同士を比較するのに使われます。
34578 デフォルトは@code{eqv?}です。
34579 @c COMMON
34580
34581 @c EN
34582 The keyword argument @var{cutoff} must be, if given, a nonnegative
34583 exact integer. Once the possible minimum distance between two sequences
34584 becomes greater than this number, the algorithm stops and gives @code{#f}
34585 as the result, and moves on to the next calculation.
34586 This is useful when you run the algorithm on large set of sequences
34587 and you only need to look for the pairs closer than the certain limit.
34588 @c JP
34589 キーワード引数@var{cutoff}は非負の正確な整数でなければなりません。与えられた場合、
34590 二つのシーケンスの距離を比較していて、それが@var{cutoff}以上になることがわかったら、
34591 それ以上の計算を打ち切り@code{#f}を結果とします。
34592 これは、特にたくさんのシーケンスから、ごく限られた限度以下の距離を持つものを探す
34593 場合に便利です。
34594 @c COMMON
34595
34596 @c EN
34597 In our implementation, Levenshtein is the fastest, Damerau-Levenshtein
34598 is the slowest and Restricted edit is somewhere inbetween. If you don't
34599 need to take into account of transpositions, use Levenshtein; it counts
34600 2 for @code{cat} -> @code{act}, while other algorithms yield 1 for it.
34601 If you need to consider transpositions, choose either
34602 @code{re-} or @code{dl-}. The catch in @code{re-} is that it does not
34603 satisfy triangular inequality, i.e. for given three sequences X, Y and Z,
34604 (Damerau-)Levenshtein distance L always satisfy
34605 L(X;Z) <= L(X;Y) + L(Y;Z), but restricted edit distance doesn't
34606 guarantee that.
34607 @c JP
34608 現在の実装ではだいたい、Levenshteinが最も速く、Damerau-Levenshteinが最も遅く、
34609 Restricted editがその中間です。置換を1操作と考える必要がなければ、
34610 Levenshteinを使うのが良いでしょう。@code{cat}から@code{act}は
34611 Levenshtein距離では2ですが他の距離では1です。
34612 置換を1操作とする必要があれば、@code{re-}か@code{dl-}を
34613 使うことになります。@code{re-}の落とし穴は、それが三角不等式を満たさないことです。
34614 つまり、3つのシーケンスX, Y, Zがある時、
34615 (Damerau-)Levenshtein距離Lは常に
34616 L(X;Z) <= L(X;Y) + L(Y;Z) を満たしますが、Restricted edit距離には
34617 その保証がありません。
34618 @c COMMON
34619
34620 @example
34621 (l-distance "cat" "act") @result{} 2
34622 (l-distances "cat" '("Cathy" "scathe" "stack")
34623 :elt= char-ci=?)
34624 @result{} (2 3 4)
34625
34626 (re-distance "cat" "act") @result{} 1
34627
34628 (re-distances "pepper"
34629 '("peter" "piper" "picked" "peck" "pickled" "peppers")
34630 :cutoff 4)
34631 @result{} (2 2 4 4 #f 1)
34632
34633 (dl-distance '(a b c d e) '(c d a b e)) @result{} 4
34634 @end example
34635
34636 @c EN
34637 Note: If you pass a list of sequences to the second argument
34638 of the singular version by accident, you might not get an error immediately
34639 because a list is also a sequence.
34640 @c JP
34641 註: 単数形のAPIの第2引数にうっかりシーケンスのリストを渡してしまった場合でも、
34642 直ちにエラーになるとは限らないことに注意。リスト自体もシーケンスだからです。
34643 @c COMMON
34644 @end defun
34645
34646 @c ----------------------------------------------------------------------
34647 @node Pattern matching, SLIB-compatible record type, Levenshtein edit distance, Library modules - Utilities
34648 @section @code{util.match} - Pattern matching
34649 @c NODE パターンマッチング, @code{util.match} - パターンマッチング
34650
34651 @deftp {Module} util.match
34652 @mdindex util.match
34653 @c EN
34654 This module is a port of Andrew Wright's pattern matching macro library.
34655 It is widely used in the Scheme world, and ported to various Scheme
34656 implementations, including Chez Scheme, PLT Scheme, Scheme48, Chicken,
34657 and SLIB.
34658 It is similar to, but more powerful than
34659 Common Lisp's @code{destructuring-bind}.
34660 @c JP
34661 このモジュールは Andrew Wright のパターンマッチングマクロライブラリを
34662 ポートしたものです。このライブラリは Scheme 界では広くつかわれており、
34663 Chez Scheme、PLT Scheme、Scheme48、Chicken および SLIB を含む、様々な
34664 Scheme の実装にポートされています。この機能は Common Lisp の
34665 @code{destructuring-bind} に似ていますがより強力です。
34666 @c COMMON
34667
34668 @c EN
34669 This version retains compatibility of the original Wright's macro,
34670 except (1) @var{box} is not supported since Gauche doesn't have one,
34671 and (2) structure matching is integrated to Gauche's object system.
34672 @c JP
34673 この版では、オリジナルの Wright's macro のマクロとの互換性が保たれて
34674 います。ただし、例外がふたつあって、それは、(1) @var{box} はサポートされて
34675 いません。Gauche にそれがないからです。(2) 構造のマッチングは Gauche の
34676 オブジェクトシステムに統合されています。
34677 @c COMMON
34678 @end deftp
34679
34680 @c EN
34681 We show a list of APIs first, then the table of complete syntax of
34682 patterns, followed by examples.
34683 @c JP
34684 まず API のリストを示し、それからパターンの完全な構文のテーブルを示し、
34685 そして例を示します。
34686 @c COMMON
34687
34688 @c EN
34689 @subheading Pattern matching API
34690 @c JP
34691 @subheading パターンマッチング API
34692 @c COMMON
34693
34694 @defmac match expr clause @dots{}
34695 @c MOD util.match
34696 @c EN
34697 Each @var{clause} is either one of the followings:
34698 @c JP
34699 それぞれの @var{clause} は以下のうちどちらかです。
34700 @c COMMON
34701 @example
34702 (@var{pat} @var{body} @dots{})
34703 (@var{pat} (=> @var{identifier}) @var{body} @dots{})
34704 @end example
34705
34706 @c EN
34707 First, the @var{expr} is matched against @var{pat} of each clauses.
34708 The detailed syntax of the pattern is explained below.
34709 @c JP
34710 まず、@var{expr} を各節の @var{pat} に照合します。パターンの詳しい
34711 構文については後述します。
34712 @c COMMON
34713
34714 @c EN
34715 If a matching @var{pat} is found, the @emph{pattern variables} in
34716 @var{pat} are bound to the corresponding elements in @var{expr}, then
34717 @var{body} @dots{} are evaluated. Then @code{match} returns the value(s)
34718 of the last expression of @var{body} @dots{}.
34719 @c JP
34720 @var{pat} にマッチする部分が見つかれば、@var{pat} 中の @emph{パターン変数}
34721 は、@var{expr} 中の対応する要素に束縛され、その後、@var{body} @dots{}
34722 が評価されます。@code{match}は@var{body} @dots{}の最後の式の値を返します。
34723 @c COMMON
34724
34725 @c EN
34726 If the clause is the second form, @var{identifier} is also bound
34727 to the failure continuation of the @var{clause}. It is a
34728 procedure with no arguments, and when called, it jumps back to
34729 the matcher as if the matching of @var{pat} is failed, and
34730 @code{match} continues to try the rest of clauses.
34731 So you can perform extra tests
34732 within @var{body} @dots{} and if you're not satisfied you can reject
34733 the match by calling @code{(@var{identifier})}. See the examples
34734 below for more details.
34735 @c JP
34736 節が 2つ目の形式である場合、@var{identifier} は @var{clause} の失敗継続
34737 に束縛されます。これは引数をもたない手続きで、呼ばれると、あたかも、
34738 @var{pat} の照合に失敗したかの如くマッチャーに戻り、@code{match} が
34739 残りの節について試行を続けます。それゆえ、@var{body} @dots{} 内部で
34740 追加のテストを実行することが可能で、もし、満足いくものでなければ、
34741 @code{(@var{identifier})} を呼ぶことで、照合結果を拒絶することができます。
34742 より詳しくは、後述の例を見てください。
34743 @c COMMON
34744
34745 @c EN
34746 If no @var{pat} matches, @code{match} reports an error.
34747 @c JP
34748 どの @var{pat} もマッチしなければ、@code{match} はエラーを報告します。
34749 @c COMMON
34750 @end defmac
34751
34752 @defmac match-lambda clause @dots{}
34753 @c MOD util.match
34754 @c EN
34755 Creates a function that takes one argument and performs @code{match} on it,
34756 using @var{clause} @dots{}. It's functionally equivalent to the following
34757 expression:
34758 @c JP
34759 ひとつの引数をとり、それに対して @var{clause} @dots{} を用いて、
34760 @code{match} を実行する関数を生成します。機能としては以下の式と同等です。
34761 @c COMMON
34762 @example
34763 (lambda (expr) (match expr @var{clause} @dots{}))
34764 @end example
34765
34766 @c EN
34767 Example:
34768 @c JP
34769 例:
34770 @c COMMON
34771
34772 @example
34773 (map (match-lambda
34774 ((item price-per-lb (quantity 'lbs))
34775 (cons item (* price-per-lb quantity)))
34776 ((item price-per-lb (quantity 'kg))
34777 (cons item (* price-per-lb quantity 2.204))))
34778 '((apple 1.23 (1.1 lbs))
34779 (orange 0.68 (1.4 lbs))
34780 (cantaloupe 0.53 (2.1 kg))))
34781 @result{} ((apple . 1.353) (orange . 0.952)
34782 (cantaloupe . 2.4530520000000005))
34783 @end example
34784 @end defmac
34785
34786 @defmac match-lambda* clause @dots{}
34787 @c MOD util.match
34788 @c EN
34789 Like @code{match-lambda}, but performs @code{match} on the list of
34790 whole arguments.
34791 It's functionally equivalent to the following expression:
34792 @c JP
34793 @code{match-lambda} と同じですが、@code{match} をすべての引数のリスト
34794 に対して実行します。機能としては以下の式と同等です。
34795 @c COMMON
34796 @example
34797 (lambda expr (match expr @var{clause} @dots{}))
34798 @end example
34799 @end defmac
34800
34801 @defmac match-let ((pat expr) @dots{}) body-expr @dots{}
34802 @defmacx match-let name ((pat expr) @dots{}) body-expr @dots{}
34803 @defmacx match-let* ((pat expr) @dots{}) body-expr @dots{}
34804 @defmacx match-letrec ((pat expr) @dots{}) body-expr @dots{}
34805 @c MOD util.match
34806 @c EN
34807 Generalize @code{let}, @code{let*}, and @code{letrec} to allow
34808 patterns in the binding position rather than just variables.
34809 Each @var{expr} is evaluated, and then matched to @var{pat},
34810 and the bound pattern variables are visible in
34811 @var{body-expr} @dots{}.
34812 @c JP
34813 束縛部分が単なる変数ではなく、パターンを許す、一般化された @code{let}、
34814 @code{let*} および @code{letrec} です。
34815 各 @var{expr} が評価され、その後、@var{pat} と照合され、束縛された
34816 パターン変数が @var{body-expr} @dots{} から見えるようになります。
34817 @c COMMON
34818
34819 @example
34820 (match-let (
34821 (((ca . cd) ...) '((a . 0) (b . 1) (c . 2)))
34822 )
34823 (list ca cd))
34824 @result{} ((a b c) (0 1 2))
34825 @end example
34826
34827 @c EN
34828 If you're sick of parenthesis, try @code{match-let1} below.
34829 @c JP
34830 括弧はうんざりという向きには、以下の @code{match-let1} をおためしあれ。
34831 @c COMMON
34832 @end defmac
34833
34834 @defmac match-let1 pat expr body-expr @dots{}
34835 @c MOD util.match
34836 @c EN
34837 This is a Gauche extension and isn't found in the original Wright's code.
34838 This one is equivalent to the following code:
34839 @c JP
34840 これは Gauche での拡張で、オリジナルの Wright のコードにはありません。
34841 これは以下のコードと同等です。
34842 @c COMMON
34843 @example
34844 (match-let ((@var{pat} @var{expr})) @var{body-expr} @dots{})
34845 @end example
34846
34847 @c EN
34848 Syntactically, @code{match-let1} is very close to the Common Lisp's
34849 @code{destructuring-bind}.
34850 @c JP
34851 構文としては @code{match-let1} は Common Lisp の @code{destructuring-bind}
34852 に非常によく似ています。
34853 @c COMMON
34854
34855 @example
34856 (match-let1 ('let ((var val) ...) body ...)
34857 '(let ((a b) (c d)) foo bar baz)
34858 (list var val body))
34859 @result{} ((a c) (b d) (foo bar baz))
34860 @end example
34861 @end defmac
34862
34863 @defmac match-define pat expr
34864 @c MOD util.match
34865 @c EN
34866 Like toplevel @code{define}, but allows a pattern instead of variables.
34867 @c JP
34868 トップレベルの @code{define} と同様ですが、変数の代りにパターンが許されます。
34869 @c COMMON
34870
34871 @example
34872 (match-define (x . xs) (list 1 2 3))
34873
34874 x @result{} 1
34875 xs @result{} (2 3)
34876 @end example
34877
34878 @end defmac
34879
34880 @c EN
34881 @subheading Pattern syntax
34882 @c JP
34883 @subheading パターンの構文
34884 @c COMMON
34885
34886 @c EN
34887 Here's a summary of pattern syntax. The asterisk @code{(*)}
34888 after explanation means Gauche's extension which does not present
34889 in the original Wright's code.
34890 @c JP
34891 ここにあるのはパターンの構文の要約です。説明の後にあるアスタリスク
34892 @code{(*)} はオリジナルの Wright のコードにはない、Gauche の拡張で
34893 あることを意味します。
34894 @c COMMON
34895
34896 @c EN
34897 @example
34898 pat : @var{patvar} ;; anything, and binds pattern var
34899 | @b{_} ;; anything
34900 | () ;; the empty list
34901 | #t ;; #t
34902 | #f ;; #f
34903 | @var{string} ;; a string
34904 | @var{number} ;; a number
34905 | @var{character} ;; a character
34906 | '@var{sexp} ;; an s-expression
34907 | '@var{symbol} ;; a symbol (special case of s-expr)
34908 | (@var{pat1} ... @var{patN}) ;; list of n elements
34909 | (@var{pat1} ... @var{patN} . @var{patN+1}) ;; list of n or more
34910 | (@var{pat1} ... @var{patN} @var{patN+1} ooo) ;; list of n or more, each element
34911 ;; of remainder must match @var{patN+1}
34912 | #(@var{pat1} ... @var{patN}) ;; vector of n elements
34913 | #(@var{pat1} ... @var{patN} @var{patN+1} ooo) ;; vector of n or more, each element
34914 ;; of remainder must match @var{patN+1}
34915 | (@b{$} @var{class} @var{pat1} ... @var{patN}) ;; an object (@var{patK} matches in slot order)
34916 | (@b{struct} @var{class} @var{pat1} ... @var{patN}) ;; ditto (*)
34917 | (@b{@@} @var{class} (@var{slot1} @var{pat1}) ...) ;; an object (using slot names) (*)
34918 | (@b{object} @var{class} (@var{slot1} @var{pat1}) ...) ;; ditto (*)
34919 | (@b{=} @var{proc} @var{pat}) ;; apply proc, match the result to pat
34920 | (@b{and} @var{pat} ...) ;; if all of pats match
34921 | (@b{or} @var{pat} ...) ;; if any of pats match
34922 | (@b{not} @var{pat} ...) ;; if all pats don't match at all
34923 | (@b{?} @var{predicate} @var{pat} ...) ;; if predicate true and all pats match
34924 | (@b{set!} @var{patvar}) ;; anything, and binds setter
34925 | (@b{get!} @var{patvar}) ;; anything, and binds getter
34926 | `qp ;; a quasi-pattern
34927
34928 patvar : a symbol except @b{_}, @b{quote}, @b{$}, @b{struct}, @b{@@}, @b{object}, @b{=}, @b{and}, @b{or},
34929 @b{not}, @b{?}, @b{set!}, @b{get!}, @b{quasiquote}, @b{...}, @b{___}, @b{..@i{k}}, @b{__@i{k}}.
34930
34931 @c @b doesn't work well in pdf version, so we conditionalize...
34932 @ifnottex
34933 ooo : @b{...} ;; zero or more
34934 | @b{___} ;; zero or more
34935 | @b{..@i{k}} ;; @i{k} or more, where @i{k} is an integer.
34936 ;; Example: @b{..1}, @b{..2} ...
34937 | @b{__@i{k}} ;; @i{k} or more, where @i{k} is an integer.
34938 ;; Example: @b{__1}, @b{__2} ...
34939 @end ifnottex
34940 @iftex
34941 ooo : ... ;; zero or more
34942 | ___ ;; zero or more
34943 | ..@slanted{k} ;; @i{k} or more, where @i{k} is an integer.
34944 ;; Example: ..1, ..2 ...
34945 | __@slanted{k} ;; @i{k} or more, where @i{k} is an integer.
34946 ;; Example: __1, __2 ...
34947 @end iftex
34948
34949 @end example
34950 @c JP
34951 @example
34952 pat : @var{patvar} ;; 任意のオブジェクトにマッチし、patvarを束縛
34953 | @b{_} ;; 任意のオブジェクト
34954 | () ;; 空リスト
34955 | #t ;; #t
34956 | #f ;; #f
34957 | @var{string} ;; 文字列
34958 | @var{number} ;; 数
34959 | @var{character} ;; 文字
34960 | @var{keyword} ;; キーワード (*)
34961 | '@var{sexp} ;; S式
34962 | '@var{symbol} ;; シンボル(S式の特殊ケース)
34963 | (@var{pat1} ... @var{patN}) ;; n 要素のリスト
34964 | (@var{pat1} ... @var{patN} . @var{patN+1}) ;; n 以上の要素を含むリスト
34965 | (@var{pat1} ... @var{patN} @var{patN+1} ooo) ;; n 以上の要素を含むリスト、残りの各要素は
34966 ;; @var{patN+1} にマッチしなければならない
34967 | #(@var{pat1} ... @var{patN}) ;; n 要素のベクタ
34968 | #(@var{pat1} ... @var{patN} @var{patN+1} ooo) ;; n 以上の要素を含むベクタ、残りの各要素は
34969 ;; @var{patN+1} にマッチしなければならない
34970 | (@b{$} @var{class} @var{pat1} ... @var{patN}) ;; オブジェクト (@var{patK} はスロット順でマッチ)
34971 | (@b{struct} @var{class} @var{pat1} ... @var{patN}) ;; 同上 (*)
34972 | (@b{@@} @var{class} (@var{slot1} @var{pat1}) ...) ;; オブジェクト (スロット名を使う) (*)
34973 | (@b{object} @var{class} (@var{slot1} @var{pat1}) ...) ;; 同上 (*)
34974 | (@b{=} @var{proc} @var{pat}) ;; procを適用し、結果を pat にマッチさせる
34975 | (@b{and} @var{pat} ...) ;; すべての pat にマッチするか
34976 | (@b{or} @var{pat} ...) ;; マッチする pat があるか
34977 | (@b{not} @var{pat} ...) ;; どの pat もマッチしないか
34978 | (@b{?} @var{predicate} @var{pat} ...) ;; predicate が真、かつ、全 pat がマッチ
34979 | (@b{set!} @var{patvar}) ;; 任意のオブジェクトにマッチし、セッタを束縛
34980 | (@b{get!} @var{patvar}) ;; 任意のオブジェクトにマッチし、ゲッタを束縛
34981 | `qp ;; 擬似パターン
34982
34983 patvar : a symbol except @b{_}, @b{quote}, @b{$}, @b{struct}, @b{@@}, @b{object}, @b{=}, @b{and}, @b{or},
34984 @b{not}, @b{?}, @b{set!}, @b{get!}, @b{quasiquote}, @b{...}, @b{___}, @b{..k}, @b{__k}.
34985
34986 @c @b doesn't work well in pdf version, so we conditionalize...
34987 @ifnottex
34988 ooo : @b{...} ;; ゼロまたはそれ以上
34989 | @b{___} ;; ゼロまたはそれ以上
34990 | @b{..@i{k}} ;; @i{k} またはそれ以上。@i{k}は整数。
34991 ;; 例: @b{..1}, @b{..2} ...
34992 | @b{__@i{k}} ;; @i{k} またはそれ以上。@i{k}は整数。
34993 ;; 例: @b{__1}, @b{__2} ...
34994 @end ifnottex
34995 @iftex
34996 ooo : ... ;; ゼロまたはそれ以上
34997 | ___ ;; ゼロまたはそれ以上
34998 | ..@slanted{k} ;; @i{k} またはそれ以上。@i{k}は整数。
34999 ;; 例: ..1, ..2 ...
35000 | __@slanted{k} ;; @i{k} またはそれ以上。@i{k}は整数。
35001 ;; 例: __1, __2 ...
35002 @end iftex
35003
35004 @end example
35005 @c COMMON
35006
35007 @itemize @bullet
35008 @item
35009 @c EN
35010 A bare symbol is a "pattern variable"; it matches anything, and
35011 the matched part of the expression is bound to the symbol.
35012 The following symbols have special meanings and cannot be used
35013 as a pattern variable: @code{_}, @code{quote}, @code{$}, @code{struct},
35014 @code{@@}, @code{object}, @code{=}, @code{and}, @code{or},
35015 @code{not}, @code{?}, @code{set!}, @code{get!}, @code{quasiquote},
35016 @code{...}, @code{___}, and @code{..k} and @code{__k} where @emph{k} is
35017 an integer.
35018 @c JP
35019 素のシンボルは「パターン変数」で、あらゆるものとマッチし、
35020 式のマッチした部分がそのシンボルに束縛されます。
35021 以下のシンボルは特別な意味をもち、パターン変数としては使えません。
35022 @code{_}、@code{quote}、@code{$}、@code{struct}、@code{@@}、@code{object}、
35023 @code{=}、@code{and}、@code{or}、@code{not}、@code{?}、@code{set!}、
35024 @code{get!}、@code{quasiquote}、@code{...}、@code{___} および
35025 @code{..k} と @code{__k} (ここで、@emph{k} は整数)。
35026 @c COMMON
35027
35028 @item
35029 @c EN
35030 A symbol @code{_} matches anything, without binding a pattern variable.
35031 It can be used to show "don't care" placeholder.
35032 @c JP
35033 シンボル @code{_} はあらゆるものマッチし、パターン変数は束縛しません。
35034 プレースホルダであることを示すのに用います。
35035 @c COMMON
35036
35037 @item
35038 @c EN
35039 Literals such as emptylist, booleans, strings, numbers, characters and
35040 keywords match the same object (in the sense of @code{equal?}).
35041 @c JP
35042 空リスト、真偽値、文字列、数、文字およびキーワードのリテラルは
35043 (@code{equal?}という意味で)同じオブジェクトとマッチします。
35044 @c COMMON
35045
35046 @item
35047 @c EN
35048 Quoted expression matches the same expression (in the sense of @code{equal?}).
35049 You can use a quoted symbol to match the symbol itself.
35050 @c JP
35051 クウォートされた式は(@code{equal?} という意味で)同じ式とマッチします。
35052 クウォートされたシンボルをそれ自身とマッチさせるのに使えます。
35053 @c COMMON
35054
35055 @item
35056 @c EN
35057 A keyword, without a quote, used to match the same keyword object.
35058 Since we're in the process of unifying keywords and symbols, the user is
35059 recommended to write keywords with a quote in a pattern in order to match
35060 the keyword in the input. @xref{Keyword and symbol integration}, for
35061 the details.
35062 @c JP
35063 キーワードは、以前はクオート無しで同じキーワードにマッチしていました。
35064 しかし現在は、キーワードとシンボルの統合に移行中なので、キーワードにマッチさせるために
35065 パターンにキーワードを含める際には常にクオートしてください。
35066 詳しくは@ref{Keyword and symbol integration}参照。
35067 @c COMMON
35068
35069 @item
35070 @c EN
35071 A list and a vector in general match a list or a vector whose elements
35072 matches the elements in the pattern recursively, unless the first element
35073 of the list is one of the special symbols listed above, it has a special
35074 meaning.
35075 @c JP
35076 通常リストおよびベクタは、それぞれ、パターン中の要素にマッチする要素を
35077 もつリストまたはベクタとマッチします。ただし、最初の要素が上であげた
35078 特別なシンボルではない限りです。そのような場合には特別な意味を持ちます。
35079 @c COMMON
35080
35081 @c EN
35082 As a special case, the last element of a vector or a list can be
35083 followed by a symbol @code{...}. In that case, the pattern just before
35084 the symbol @code{...} can be applied repeatedly until it consumes all the
35085 elements in the given expression. A symbol @code{___} can be used
35086 in place of @code{...}; it is useful when you want to produce a pattern
35087 by syntax-rules macro.
35088 @c JP
35089 特別な場合として、ベクタあるいはリストの最後の要素のあとにシンボル
35090 @code{...} を付加することができます。この場合には、@code{...} シンボル
35091 直前のパターンが与えられた式のすべての要素を尽すまで繰り返し適用されます。
35092 シンボル @code{___} は @code{...} の場所で使えます。構文規則マクロによって
35093 パターンを生成したいときに便利です。
35094 @c COMMON
35095
35096 @c EN
35097 For a list pattern, you can also use a symbol @code{..1}, @code{..2},
35098 @dots{}, which specifies the minimum number of repetition.
35099 @c JP
35100 リストのパターンに対しては、シンボル @code{..1}、@code{..2}、@dots{} が
35101 使えます。これは繰り返しの最小値を指定するものです。
35102 @c COMMON
35103
35104 @item
35105 @c EN
35106 @code{($ class pat1 @dots{})} matches an instance of a class @code{class}.
35107 Each pattern @code{pat1} @dots{} matches each value of slots,
35108 in order of @code{(class-slots class)} by default.
35109 (Records are exception; they match the same order as their
35110 default constructor since 0.9.6.)
35111 @c JP
35112 @code{($ class pat1 @dots{})} は @code{class} クラスのインスタンスと
35113 マッチします。各パターン @code{pat1} @dots{} はデフォルトではスロットの各値と
35114 @code{(class-slots class)} の順にマッチします。
35115 (レコードは例外で、0.9.6からデフォルトコンストラクタの順序と同じ順序になりました。)
35116 @c COMMON
35117
35118 @c EN
35119 @code{(struct class pat1 @dots{})} has the same meaning. Although
35120 the original Wright's code doesn't have @code{struct}, PLT Scheme has
35121 it in its extended match feature, and it is more descriptive.
35122 @c JP
35123 @code{(struct class pat1 @dots{})} は同じ意味です。オリジナルの
35124 Wright のコードには、@code{struct} はありませんが、PLT Scheme の拡張
35125 照合機能にはそなわっています。こちらの方がより説明的です。
35126 @c COMMON
35127
35128 @c EN
35129 This is an adaptation of the original feature that can match structures.
35130 It is useful to match a simple instance that you know the order of
35131 slots; for example, a simple record created by @code{define-record-type}
35132 (@pxref{Record types}) would be easy to match by positioned values.
35133 @c JP
35134 これはオリジナルの機能を構造(structure)にもマッチするように調整した
35135 ものです。スロットの順番が予め分るような単純なインスタンスをマッチする
35136 のに便利です。たとえば、@code{define-record-type} (@ref{Record types}参照)で作成した
35137 簡単なレコードは簡単に位置指定された値でマッチすることができます。
35138 @c COMMON
35139
35140 @c EN
35141 If the instance's class uses inheritances, it is a bit difficult to
35142 match by positions. You can use @code{@@} or @code{object} pattern
35143 below to match using slot names.
35144 @c JP
35145 インスタンスのクラスが継承を使っている場合、位置によるマッチを
35146 おこなうのは少々難しくなります。以下の @code{@@} あるいは @code{object}
35147 パターンを使って、スロット名でマッチを行うことができます。
35148 @c COMMON
35149
35150 @item
35151 @c EN
35152 @code{(object class (slot1 pat1) @dots{})} matches an instance
35153 of a class @code{class} whose value of @var{slot1} @dots{} matches
35154 @var{pat1} @dots{}. This is Gauche's extension. @code{@@} can be
35155 used in place of @code{object}, but @code{object} is recommended
35156 because of descriptiveness.
35157 @c JP
35158 @code{(object class (slot1 pat1) @dots{})} は
35159 @var{slot1} @dots{} の値が @var{pat1} @dots{} にマッチするような
35160 @code{class} クラスのインスタンスとマッチします。これは、
35161 Gauche の拡張です。@code{@@} は @code{object} と同じ場所で使えます。
35162 ただし、@code{object} の方が説明的でわかりやすいので、こちらを
35163 推奨します。
35164 @c COMMON
35165
35166 @item
35167 @c EN
35168 @code{(= proc pat)} first applies @var{proc} to the corresponding
35169 expression, then match the result with @var{pat}.
35170 @c JP
35171 @code{(= proc pat)} は最初に @var{proc} を対応する式に適用し、
35172 その結果と @var{pat} をマッチさせます。
35173 @c COMMON
35174
35175 @item
35176 @c EN
35177 @code{(and pat @dots{})} matches when all @var{pat} matches the
35178 corresponding subtree. A common idiom to realize ``as'' matching,
35179 with which you can bind the entire tree as well as its substrees,
35180 can be written with @code{and} operator. For example,
35181 @code{(and (x . y) p)} matches a pair, binding its cdr to @var{x},
35182 its car to @var{y}, and the entire pair to @var{p}.
35183 @c JP
35184 @code{(and pat @dots{})}は、対応する式が全ての@var{pat}にマッチした時に
35185 マッチに成功します。よく使われるイディオムとして、@code{and}で「asマッチング」、
35186 つまり部分式ごとにマッチした全体を別の変数にマッチさせることができます。
35187 例えば@code{(and (x . y) p)}はペアにマッチし、そのcarを@var{x}に、
35188 cdrを@var{y}に、そしてペア全体を@var{p}に束縛します。
35189 @c COMMON
35190
35191 @item
35192 @c EN
35193 @code{(or pat @dots{})} tries to match each @var{pat} against
35194 the corresponding subtree, and if any succeeds, the entire @code{or}
35195 pattern succeeds. If no @var{pat} matches the subtree, the entire
35196 @code{or} pattern fails.
35197 If there're pattern variables in @var{pat}, the set of variables
35198 in each @var{pat} must be the same: That is,
35199 @code{(or (_ x y) (_ x y _))} is ok but @code{(or (_ x _) (_ x y _))} is not.
35200 It is because the latter may leave some of pattern variables
35201 unbound even match succeeds.
35202 @c JP
35203 @code{(or pat @dots{})}は対応する式に対して@var{pat}を順に試し、
35204 マッチするものがあればそこで成功、ひとつもマッチしなければ失敗とします。
35205 パターン変数を使う場合、各@var{pat}中のパターン変数は同じでなければなりません。
35206 つまり@code{(or (_ x y) (_ x y _))} はokですが、
35207 @code{(or (_ x _) (_ x y _))} は許されません。
35208 マッチする@var{pat}によっては束縛されないパターン変数が出てしまうからです。
35209 @c COMMON
35210
35211 @item
35212 @c EN
35213 @code{(not pat @dots{})} matches when none of @var{pat} matches
35214 the corresponding subtree.
35215 @c JP
35216 @code{(not pat @dots{})} はどの@var{pat}も式にマッチしない場合に
35217 マッチ成功となります。
35218 @c COMMON
35219
35220 @item
35221 @c EN
35222 @code{(? predicate pat @dots{})} first applies a predicate to the
35223 corresponding expression, and if it returns true, applies each
35224 @code{pat} @dots{} to the expression.
35225 @c JP
35226 @code{(? predicate pat @dots{})} は最初、述語を対応する式に適用し、
35227 真が返れば、各 @code{pat} @dots{} をその式に適用します。
35228 @c COMMON
35229
35230 @item
35231 @c EN
35232 @code{(set! patvar)} matches anything, and binds an one-argument
35233 procedure to a pattern variable @var{patvar}. If the procedure is
35234 called, it replaces the value of matched pattern for the given argument.
35235 @c JP
35236 @code{(set! patvar)} はあらゆるものにマッチし、一引数の手続きを
35237 パターン変数 @var{patvar} に束縛します。その手続きが呼ばれると、
35238 マッチしたパターンの値を与えられた引数で置き換えます。
35239 @c COMMON
35240
35241 @item
35242 @c EN
35243 @code{(get! patvar)} matches anything, and binds a zero-argument
35244 procedure to a pattern variable @var{patvar}. If the procedure is
35245 called, it returns the matched value.
35246 @c JP
35247 @code{(get! patvar)} はあらゆるものにマッチし、引数なしの手続きを
35248 パターン変数 @var{patvar} に束縛します。その手続きが呼ばれると、
35249 マッチしたパターンの値を返します。
35250 @c COMMON
35251
35252 @item
35253 @c EN
35254 @code{`qp} is a quasipattern. @var{qp} is quoted, in the sense
35255 that it matches itself, @emph{except} the pattern that is unquoted.
35256 (Don't confuse quasipattern to quasiquote, though the functions are
35257 similar. Quasiquote turns off evaluation except unquoted subtree.
35258 Quasiquote turns off the special pattern syntax except unquoted subtree.
35259 See the examples below).
35260 @c JP
35261 @code{`qp}はquasipatternです。@var{qp}は、クオートされたパターンと同様、
35262 それそのものにマッチしますが、その中にアンクオートされているパターンがあると、
35263 その部分だけは通常のパターンとして解釈されます。
35264 (準クオート(quasiquote)とquasipatternを混同しないようにしてください。
35265 機能的に両者は似ていますが、準クオートがアンクオートされた部分木以外の
35266 部分の評価をoffにするのに対し、quasipatternはアンクオートされた部分木
35267 以外の部分のパターン構文を無効にします。下の例も参照して下さい。)
35268 @c COMMON
35269 @end itemize
35270
35271 @c EN
35272 @subheading Pattern examples
35273 @c JP
35274 @subheading パターン例
35275 @c COMMON
35276
35277 @c EN
35278 A simple structure decomposition:
35279 @c JP
35280 単純な構造の分解
35281 @c COMMON
35282 @example
35283 (match '(0 (1 2) (3 4 5))
35284 [(a (b c) (d e f))
35285 (list a b c d e f)])
35286 @result{} (0 1 2 3 4 5)
35287 @end example
35288
35289 @c EN
35290 Using predicate patterns:
35291 @c JP
35292 述語パターンの使用
35293 @c COMMON
35294 @example
35295 (match 123
35296 [(? string? x) (list 'string x)]
35297 [(? number? x) (list 'number x)])
35298 @result{} (number 123)
35299 @end example
35300
35301 @c EN
35302 Extracting variables and expressions from @code{let}.
35303 Uses repetition and predicate patterns:
35304 @c JP
35305 @code{let} から変数と式を取り出す
35306 反復および述語パターンの利用
35307 @c COMMON
35308 @example
35309 (define let-analyzer
35310 (match-lambda
35311 [('let (? symbol?)
35312 ((var expr) ...)
35313 body ...)
35314 (format "named let, vars=~s exprs=~s" var expr)]
35315 [('let ((var expr) ...)
35316 body ...)
35317 (format "normal let, vars=~s exprs=~s" var expr)]
35318 [_
35319 (format "malformed let")]))
35320
35321 (let-analyzer '(let ((a b) (c d)) e f g))
35322 @result{} "normal let, vars=(a c) exprs=(b d)"
35323
35324 (let-analyzer '(let foo ((x (f a b)) (y (f c d))) e f g))
35325 @result{} "named let, vars=(x y) exprs=((f a b) (f c d))"
35326
35327 (let-analyzer '(let (a) b c d))
35328 @result{} "malformed let"
35329 @end example
35330
35331 @c EN
35332 Using @code{=} function application. The pattern variable @var{m}
35333 is matched to the result of application of the regular expression.
35334 @c JP
35335 @code{=} 関数適用。パターン変数 @var{m} は正規表現の適用結果にマッチする
35336 @c COMMON
35337 @example
35338 (match "gauche-ref.texi"
35339 ((? string? (= #/(.*)\.([^.]+)$/ m))
35340 (format "base=~a suffix=~a" (m 1) (m 2))))
35341 @result{} "base=gauche-ref suffix=texi"
35342 @end example
35343
35344 @c EN
35345 An example of quasipattern. In the first expression, the
35346 pattern except @code{value} is quoted, so the symbols @code{the},
35347 @code{answer}, and @code{is} are not pattern variables but literal
35348 symbols. The second expression shows that; input symbol @code{was}
35349 does not match the literal symbol @code{is} in the pattern.
35350 If we don't use quasiquote, all symbols in the pattern are pattern
35351 variables, so any four-element list matches as the third expression shows.
35352 @c JP
35353 quasipatternの例です。最初の式では、パターンのうち@code{value}以外の
35354 部分がクオートされたことになり、従ってシンボル@code{the}, @code{answer},
35355 @code{is}はパターン変数ではなくリテラルシンボルとなります。
35356 2番目の式がそのことを示しています。入力にあるシンボル@code{was}は
35357 パターンの@code{is}とマッチしません。もしクオートを行わないと、
35358 全てのシンボルはパターン変数となるので、3番目の例に示すように
35359 任意の4つの要素を持つリストとマッチしてしまいます。
35360 @c COMMON
35361 @example
35362 (match '(the answer is 42)
35363 [`(the answer is ,value) value]
35364 [_ #f])
35365 @result{} 42
35366
35367 (match '(the answer was 42)
35368 [`(the answer is ,value) value]
35369 [_ #f])
35370 @result{} #f
35371
35372 (match '(a b c d)
35373 [(the answer is value) value]
35374 [_ #f])
35375 @result{} d
35376 @end example
35377
35378 @c EN
35379 An example of matching records.
35380 The following code implements ``rotation''
35381 operation to balance a red-black tree.
35382 @c JP
35383 レコードのマッチングの例です。
35384 次のコードは赤黒木をバランスさせる「ローテーション」操作を実装しています。
35385 @c COMMON
35386
35387 @example
35388 (define-record-type T #t #t
35389 color left value right)
35390
35391 (define (rbtree-rotate t)
35392 (match t
35393 [(or ($ T 'B ($ T 'R ($ T 'R a x b) y c) z d)
35394 ($ T 'B ($ T 'R a x ($ T 'R b y c)) z d)
35395 ($ T 'B a x ($ T 'R ($ T 'R b y c) z d))
35396 ($ T 'B a x ($ T 'R b y ($ T 'R c z d))))
35397 (make-T 'R (make-T 'B a x b) y (make-T 'B c z d))]
35398 [_ t]))
35399 @end example
35400
35401 @c ----------------------------------------------------------------------
35402 @node SLIB-compatible record type, Relation framework, Pattern matching, Library modules - Utilities
35403 @section @code{util.record} - SLIB-compatible record type
35404 @c NODE SLIB-互換のレコード型, @code{util.record} - SLIB-互換のレコード型
35405
35406 @deftp {Module} util.record
35407 @mdindex util.record
35408 @c EN
35409 This module provides a Guile and SLIB compatible record type API.
35410 It is built on top of Gauche's object system.
35411
35412 See also @ref{Record types}, which provides a convenience macro
35413 @code{define-record-type}.
35414 @c JP
35415 このモジュールは、Guile と SLIB とに互換性のあるレコード型 API を提供します。
35416 これは、Gauche のオブジェクトシステム上に構築されています。
35417
35418 便利なマクロ @code{define-record-type} を提供する @ref{Record types} も
35419 参照してください。
35420 @c COMMON
35421 @end deftp
35422
35423 @defun make-record-type type-name field-names
35424 @c MOD util.record
35425 @c EN
35426 Returns a new class which represents a new record type.
35427 (It is what is called @emph{record-type descriptor} in SLIB).
35428 In Gauche, the new class is a subclass of @code{<record>}
35429 (see @ref{Record types}).
35430
35431 @var{type-name} is a string that is used for debugging purposes.
35432 It is converted to a symbol and set as the name of the new class.
35433 @var{field-names} is a list of symbols of the names of fields.
35434 Each field is implemented as a slot of the new class.
35435 @c JP
35436 あらしいレコード型を表わす新しいクラスを返します。
35437 (これは SLIB では @emph{レコード型記述子}とよばれているものです。)
35438 Gauche では、この新しいクラスは @code{<record>} のサブクラスです
35439 (@ref{Record types} 参照)。
35440
35441 @var{type-name} はデバッグの目的で使われる文字列です。
35442 これは、シンボルに変換され、この新しいクラスの名前として設定されます。
35443 @var{field-names} はフィールド名のシンボルのリストです。
35444 各々のフィールドはこの新しいクラスのスロットとして実装されます。
35445 @c COMMON
35446 @end defun
35447
35448 @c EN
35449 In the following procedures, @var{rtd} is the record class
35450 created by @code{make-record-type}.
35451 @c JP
35452 以下の手続きでは、@var{rtd} は @code{make-record-type} によって
35453 生成されたクラスです。
35454 @c COMMON
35455
35456 @defun record-constructor rtd :optional field-names
35457 @c MOD util.record
35458 @c EN
35459 Returns a procedure that constructs an instance
35460 of the record type of given @var{rtd}. The returned
35461 procedure takes exactly as many arguments as @var{field-names},
35462 which defaults to @code{'()}. Each argument sets the initial
35463 value of the corresponding field in @var{field-names}.
35464 @c JP
35465 与えられた @var{rtd} レコード型のインスタンスを構築する手続きを
35466 返します。返された手続きは @var{field-names} とちょうど同じ数の
35467 引数をとります。@var{field-names} のデフォルトは @code{'()} です。
35468 それぞれの引数は @var{field-names} の対応するフィールドの初期値を
35469 設定します。
35470 @c COMMON
35471 @end defun
35472
35473 @defun record-predicate rtd
35474 @c MOD util.record
35475 @c EN
35476 Returns a procedure that takes one argument, which returns @code{#t}
35477 iff the given argument is of type of @var{rtd}.
35478 @c JP
35479 一つの引数をとり、与えられた引数が @var{rtd} と同じ型であり、その場合に
35480 限り @code{#t} を返す手続きを返します。
35481 @c COMMON
35482 @end defun
35483
35484 @defun record-accessor rtd field-name
35485 @c MOD util.record
35486 @c EN
35487 Returns an accessor procedure for the field named by @var{field-name}
35488 of type @var{rtd}. The accessor procedure takes an instance of
35489 @var{rtd}, and returns the value of the field.
35490 @c JP
35491 @var{rtd} 型の @var{field-name} によって名付けられたフィールドへの
35492 アクセサ手続きを返します。このアクセサ手続きは、@var{rtd} のインスタンスを
35493 一つとり、そのフィールドの値を返します。
35494 @c COMMON
35495 @end defun
35496
35497 @defun record-modifier rtd field-name
35498 @c MOD util.record
35499 @c EN
35500 Returns a modifier procedure for the field named by @var{field-name}
35501 of type @var{rtd}. The modifier procedure takes two arguments,
35502 an instance of @var{rtd} and a value, and sets the value to
35503 the specified field.
35504 @c JP
35505 @var{rtd} 型の @var{field-name} によって名付けられたフィールドへの
35506 モディファイア手続きを返します。このモディファイア手続きは、
35507 @var{rtd} のインスタンスと値のふたつの引数をとり、その引数を
35508 指定されたフィールドに設定します。
35509 @c COMMON
35510 @end defun
35511
35512 @example
35513 (define rtd (make-record-type "my-record" '(a b c)))
35514
35515 rtd @result{} #<class my-record>
35516
35517 (define make-my-record (record-constructor rtd '(a b c)))
35518
35519 (define obj (make-my-record 1 2 3))
35520
35521 obj @result{} #<my-record 0x819d9b0>
35522
35523 ((record-predicate? rtd) obj) @result{} #t
35524
35525 ((record-accessor rtd 'a) obj) @result{} 1
35526 ((record-accessor rtd 'b) obj) @result{} 2
35527 ((record-accessor rtd 'c) obj) @result{} 3
35528
35529 ((record-modifier rtd 'a) obj -1)
35530
35531 ((record-accessor rtd 'a) obj) @result{} -1
35532 @end example
35533
35534 @c ----------------------------------------------------------------------
35535 @node Relation framework, Stream library, SLIB-compatible record type, Library modules - Utilities
35536 @section @code{util.relation} - Relation framework
35537 @c NODE リレーションフレームワーク, @code{util.relation} - リレーションフレームワーク
35538
35539 @deftp {Module} util.relation
35540 @mdindex util.relation
35541 @c EN
35542 Provides a set of common operations for relations.
35543 @c JP
35544 リレーションに対する共通の操作を提供します。
35545 @c COMMON
35546
35547 @c EN
35548 Given set of values S1, S2, ..., Sn, a relation R is a set of tuples
35549 such that the first element of a tuple is from S1, the second from
35550 S2, ..., and the n-th from Sn. In another word, R is a subset of
35551 Cartesian product of S1, ..., Sn.
35552 (The definition, as well as the term @emph{relation}, is taken
35553 from the Codd's 1970 paper,
35554 "A Relational Model of Data for Large Shared Data Banks", in
35555 CACM 13(6) pp.377--387.)
35556 @c JP
35557 値の集合を S1, S2, ..., Sn とするとリレーション R はタプルの集合で、
35558 タプルの最初の要素は S1 からの値で、2番目は S2 から、で n 番目は
35559 Sn からとなっている。いいかえれば、R は S1, ..., Sn の直積です。
35560 (この定義と@emph{リレーション}という用語は 1970年のCoddのペーパー
35561 "A Relational Model of Data for Large Shared Data Banks", in
35562 CACM 13(6) pp.377--387.によるものです。)
35563 @c COMMON
35564
35565 @c EN
35566 This definition can be applied to various datasets: A set of Gauche
35567 object system instances is a relation, if you view each instance as
35568 a tuple and each slot value as the actual values. A list of lists can be a
35569 relation. A stream that reads from CSV table produces a relation.
35570 Thus it would be useful to provide a module that implements generic
35571 operations on relations, no matter how the actual representation is.
35572 @c JP
35573 この定義はいろいろなデータベースセットにあてはまります。各インスタンス
35574 をタプルとみなし、各スロット値を実際の値と見ると、Gaucheのオブジェクト
35575 システムの集合はリレーションです。リストのリストもリレーションです。
35576 CSVテーブルからの読み出しストリームはリレーションを生成します。このよ
35577 うことから、表現に依存しないリレーション上のジェネリックな操作を実装す
35578 るモジュールを用意することは有意義です。
35579 @c COMMON
35580
35581 @c EN
35582 From the operational point of view, we can treat any datastructure
35583 that provides the following four methods; @code{relation-rows},
35584 which retrieves a collection of tuples (rows);
35585 @code{relation-column-names}, @code{relation-accessor}, and
35586 @code{relation-modifier}, which provide the means to access
35587 meta-information.
35588 All the rest of relational operations are built on top of
35589 those primitive methods.
35590 @c JP
35591 操作という観点からいえば、以下の4つのメソッドがあれば、どのようなデー
35592 タ構造もあつかえます。タプルのコレクション(行)を取り出す
35593 @code{relation-rows}、それから、@code{relation-column-names}、
35594 @code{relation-accessor}、@code{relation-modifier}、これらはメタ情報に
35595 アクセスする方法を提供しています。これ以外のすべてのリレーション操作は
35596 上のプリミティブメソッドを使って組まれています。
35597 @c COMMON
35598
35599 @c EN
35600 A concrete implementation of relation can use duck typing,
35601 i.e. it doesn't need to inherit a particular base class to
35602 use the relation methods. However, for the convenience,
35603 a base class @code{<relation>} is provided in this module.
35604 It works as a mixin class---a concrete class typically wants
35605 to inherit @code{<relation>} and @code{<collection>} or
35606 @code{<sequence>}. Check out the sample implementations
35607 in the @file{lib/util/relation.scm} in the source tree, if
35608 you're curious.
35609 @c JP
35610 リレーションの具体的な実装にはダックタイピングが適用できます。
35611 すなわち、リレーションメソッドを使うのに特定のベースクラスを継承する必
35612 要はありません。しかし、利便のためにこのモジュールには、ベースクラス
35613 @code{<relation>}が用意されています。これは、ミックスインクラスのよう
35614 な働きをします。具象クラスは典型的には@code{<relation>}および
35615 @code{<collection>}または@code{<sequence>}を継承することになるでしょう。
35616 興味があれば、ソースツリーにある@file{lib/util/relation.scm}に含まれる
35617 サンプル実装をチェックするとよいでしょう。
35618 @c COMMON
35619
35620 @c EN
35621 This module is still under development.
35622 The plan is to build useful relational operations on top of the
35623 common methods.
35624 @c JP
35625 このモジュールは現時点では開発途上にあります。計画では共通メソッド上に
35626 有用なリレーション操作関数群を構築することになっています。
35627 @c COMMON
35628 @end deftp
35629
35630 @c EN
35631 @subheading Basic class and methods
35632 @c JP
35633 @subheading 基本となるクラスとメソッド
35634 @c COMMON
35635
35636 @deftp {Class} <relation>
35637 @clindex relation
35638 @c MOD util.relation
35639 @c EN
35640 An abstract base class of relations.
35641 @c JP
35642 リレーションの抽象ベースクラス
35643 @c COMMON
35644 @end deftp
35645
35646 @deffn {Method} relation-column-names (r <relation>)
35647 @c MOD util.relation
35648 @c EN
35649 A subclass must implement this method.
35650 It should return a sequence of names of the columns.
35651 The type of column names is up to the relation; we don't
35652 place any restriction on it, as far as they are different
35653 each other in terms of @code{equal?}.
35654 @end deffn
35655 @c JP
35656 サブクラスではこのメソッドを必ず実装しなければなりません。
35657 カラムの名前のシーケンスを返す必要があります。カラム名の型はリレーショ
35658 ンによります。@code{equal?}の意味で相互に異っているかぎり、カラム名に
35659 ついて特に制限はありません。
35660 @end deffn
35661 @c COMMON
35662
35663 @deffn {Method} relation-accessor (r <relation>)
35664 @c MOD util.relation
35665 @c EN
35666 A subclass must implement this method.
35667 It should return a procedure that takes two arguments, a row from
35668 the relation @var{r} and a column name, and returns the value
35669 of the specified column.
35670 @c JP
35671 サブクラスではこのメソッドは必ず実装しなければなりまん。2つの引数をと
35672 り、リレーション@var{r}の行とカラム名をとり、指定したカラムの値を返す
35673 手続を返さなければなりません。
35674 @c COMMON
35675 @end deffn
35676
35677 @deffn {Method} relation-modifier (r <relation>)
35678 @c MOD util.relation
35679 @c EN
35680 A subclass must implement this method. It should returns a procedure
35681 that takes three arguments, a row from the relation @var{r}, a column
35682 name, and a value to set.
35683 @c JP
35684 サブクラスではこのメソッドは必ず実装しなければなりまん。
35685 3つの引数、リレーション@var{r}の行、カラム名、値をとり、その値をセット
35686 する手続を返さなければなりません。
35687 @c COMMON
35688
35689 @c EN
35690 If the relation is read-only, this method returns @code{#f}.
35691 @c JP
35692 リレーションが読み込み専用の場合はこのメソッドは@code{#f}を返します。
35693 @c COMMON
35694 @end deffn
35695
35696 @deffn {Method} relation-rows (r <relation>)
35697 @c MOD util.relation
35698 @c EN
35699 A subclass must implement this method.
35700 It should return the underlying instance of @code{<collection>} or
35701 its subclass (e.g. @code{<sequence>})
35702 @c JP
35703 サブクラスではこのメソッドは必ず実装しなければなりまん。
35704 基盤となっている@code{<collection>}クラスまたはそのサブクラス(たとえば
35705 @code{<sequence>})のインスタンスを返さなければなりません。
35706 @c COMMON
35707 @end deffn
35708
35709 @c EN
35710 The rest of method are built on top of the above four methods.
35711 A subclass of @code{<relation>} may overload some of the
35712 methods below for better performance, though.
35713 @c JP
35714 のこりのメソッドは上の4つのメソッドを使って組まれています。とはいえ、
35715 @code{<relation>} のサブクラスでは以下のメソッドを性能を得るためにオー
35716 バーロードすることもできます。
35717 @c COMMON
35718
35719 @deffn {Method} relation-column-name? (r <relation>) column
35720 @c MOD util.relation
35721 @c EN
35722 Returns true iff @var{column} is a valid column name for the relation
35723 @var{r}.
35724 @c JP
35725 @var{column}がリレーション@var{r}において有効なカラム名である場合にの
35726 み真を返します。
35727 @c COMMON
35728 @end deffn
35729
35730 @deffn {Method} relation-column-getter (r <relation>) column
35731 @deffnx {Method} relation-column-setter (r <relation>) column
35732 @c MOD util.relation
35733 @c EN
35734 Returns a procedure to access the specified column of a row
35735 from the relation @var{r}. @code{Relation-column-getter}
35736 should return a procedure that takes one argument, a row.
35737 @code{Relation-column-setter} should return a procedure that
35738 takes two arguments, a row and a new value to set.
35739 @c JP
35740 リレーション@var{r}の行の指定したカラムにアクセスする手続を返します。
35741 @code{Relation-column-getter}は、1つの引数、行をとる手続きを返さなけれ
35742 ばなりません。@code{Relation-column-setter}は2つの引数、行と新しくセッ
35743 トする値を取る手続きを返さなければなりません。
35744 @c COMMON
35745
35746 @c EN
35747 If the relation is read-only, @code{relation-column-setter}
35748 returns @code{#f}.
35749 @c JP
35750 リレーションが読み込み専用の場合は@code{relation-column-setter}
35751 は@code{#f}を返します。
35752 @c COMMON
35753 @end deffn
35754
35755 @deffn {Method} relation-ref (r <relation>) row column :optional default
35756 @c MOD util.relation
35757 @c EN
35758 @var{Row} is a row from the relation @var{r}. Returns value of
35759 the @var{column} in @var{row}. If @var{column} is not a valid
35760 column name, @var{default} is returned if it is given, otherwise
35761 an error is signaled.
35762 @c JP
35763 @var{row}はリレーション@var{r}の行です。@var{row}の@var{column}の値を
35764 返します。@var{column}が不正なカラム名である場合、@var{default}が与え
35765 られていればそれを返し、そうでなければ、エラーを示すシグナルがあがりま
35766 す。
35767 @c COMMON
35768 @end deffn
35769
35770 @deffn {Method} relation-set! (r <relation>) row column value
35771 @c MOD util.relation
35772 @c EN
35773 @var{Row} is a row from the relation @var{r}. Sets @var{value}
35774 as the value of @var{column} in @var{row}. This may signal
35775 an error if the relation is read-only.
35776 @c JP
35777 @var{row}はリレーション@var{r}の行です。@var{value}を@var{row}の
35778 @var{column}に設定します。リレーションが読み込み専用の場合には
35779 エラーを示すシグナルがあがります。
35780 @c COMMON
35781 @end deffn
35782
35783 @deffn {Method} relation-column-getters (r <relation>)
35784 @deffnx {Method} relation-column-setters (r <relation>)
35785 @c MOD util.relation
35786 @c EN
35787 Returns full list of getters and setters. Usually the default
35788 method is sufficient, but the implementation may want to cache
35789 the list of getters, for example.
35790 @c JP
35791 ゲッタとセッタの完全なリストを返します。通常はデフォルトのメソッドで十
35792 分ですが、たとえばゲッタのリストをキャッシュしたいときもあるでしょう。
35793 @c COMMON
35794 @end deffn
35795
35796 @deffn {Method} relation-coercer (r <relation>)
35797 @c MOD util.relation
35798 @c EN
35799 Returns a procedure that coerces a row into a sequence.
35800 If the relation already uses a sequence to represent a row,
35801 it can return row as is.
35802 @c JP
35803 行をシーケンスに変換する手続きを返します。行がすでにシーケンスで表現さ
35804 れているリレーションであれば、行をそのまま返す手続きです。
35805 @c COMMON
35806 @end deffn
35807
35808 @deffn {Method} relation-insertable? (r <relation>)
35809 @c MOD util.relation
35810 @c EN
35811 Returns true iff new rows can be inserted to the relation @var{r}.
35812 @c JP
35813 リレーション@var{r}に新しい行を挿入可能な場合にのみ真を返します。
35814 @c COMMON
35815 @end deffn
35816
35817 @deffn {Method} relation-insert! (r <relation>) row
35818 @c MOD util.relation
35819 @c EN
35820 Insert a row @var{row} to the relation @var{r}.
35821 @c JP
35822 リレーション@var{r}に行@var{row}を挿入します。
35823 @c COMMON
35824 @end deffn
35825
35826 @deffn {Method} relation-deletable? (r <relation>)
35827 @c MOD util.relation
35828 @c EN
35829 Returns true iff rows can be deleted from the relation @var{r}.
35830 @c JP
35831 リレーション@var{r}から行を削除可能である場合にのみ真を返します。
35832 @c COMMON
35833 @end deffn
35834
35835 @deffn {Method} relation-delete! (r <relation>) row
35836 @c MOD util.relation
35837 @c EN
35838 Deletes a row @var{row} from the relation @var{r}.
35839 @c JP
35840 リレーション@var{r}から行@var{row}を削除します。
35841 @c COMMON
35842 @end deffn
35843
35844 @deffn {Method} relation-fold (r <relation>) proc seed column @dots{}
35845 @c MOD util.relation
35846 @c EN
35847 Applies @var{proc} to the values of @var{column} @dots{} of each row,
35848 passing @var{seed} as the state value. That is, for each row in
35849 @var{r}, @var{proc} is called as follows:
35850 @c JP
35851 @var{proc}を各行のカラム@var{column} @dots{} の値に適用します。
35852 @var{seed}は状態の値として渡されます。すなわち、リレーション@var{r}の
35853 各行ごとに以下のように@var{proc}を呼びます。
35854 @c COMMON
35855 @example
35856
35857 (@var{proc} @var{v_0} @var{v_1} @dots{} @var{v_i} @var{seed})
35858
35859 where @var{v_k} = (relation-ref @var{r} @var{row} @var{column_k})
35860
35861 @end example
35862
35863 @c EN
35864 The result of the call becomes a new seed value, and the final result
35865 is returned from @var{relation-fold}.
35866 @c JP
35867 呼び出しの結果があたらしいシードの値となり、最終の結果が
35868 @var{relation-fold}から返ります。
35869 @c COMMON
35870
35871 @c EN
35872 For example, if a relation has a column named @code{amount},
35873 and you want to sum up all of them in a relation @var{r},
35874 you can write like this:
35875 @c JP
35876 たとえば、リレーションが @code{amount} という名前のカラムをもつものと
35877 し、リレーション @var{r} 内にあるそのカラムをすべて足しあわせたいとす
35878 ると以下のように書けます。
35879 @c COMMON
35880 @example
35881 (relation-fold r + 0 'amount)
35882 @end example
35883 @end deffn
35884
35885 @c EN
35886 @subheading Concrete classes
35887 @c JP
35888 @subheading 具象クラス
35889 @c COMMON
35890
35891 @deftp {Class} <simple-relation>
35892 @clindex simple-relation
35893 @c MOD util.relation
35894 @end deftp
35895
35896 @deftp {Class} <object-set-relation>
35897 @clindex object-set-relation
35898 @c MOD util.relation
35899 @end deftp
35900
35901 @c ----------------------------------------------------------------------
35902 @node Stream library, Temporal relation, Relation framework, Library modules - Utilities
35903 @section @code{util.stream} - Stream library
35904 @c NODE ストリームライブラリ, @code{util.stream} - ストリームライブラリ
35905
35906 @deftp {Module} util.stream
35907 @mdindex util.stream
35908 @c EN
35909 This module provides a library of lazy streams, including the
35910 functions and syntaxes defined in SRFI-40 and SRFI-41,
35911 the latter of which became a part of R7RS large (as @code{(scheme stream)},
35912
35913 Gauche has a built-in lazy sequences (@pxref{Lazy sequences}), which is
35914 a lazy stream integrated to a list so that you can use all list procedures
35915 on it. Lazy streams provided in this module are somewhat heavier than
35916 lazy sequences and you need to use special procedures,
35917 but it is strictly lazy (while a lazy sequence evaluates one element ahead)
35918 and portable.
35919 @c JP
35920 このモジュールは遅延ストリームのライブラリを提供します。このモジュール
35921 にはSRFI-40とSRFI-41で定義されている関数および構文が含まれています。
35922 後者は@code{(scheme stream)}としてR7RS largeの一部になっています。
35923
35924 Gaucheには遅延ストリームとリストを統合したような、組み込みの遅延シーケンスがあります
35925 (@ref{Lazy sequences})参照。そちらは通常のリスト手続きを使って扱うことができます。
35926 このモジュールで提供される遅延ストームは、遅延シーケンスより重く、
35927 扱うために専用の手続きが必要です。ただ、要素の評価は必要になるぎりぎりまで遅延され
35928 (遅延シーケンスでは必要な要素のひとつ先まで評価されます)、またポータブルです。
35929 @c COMMON
35930 @end deftp
35931
35932 @menu
35933 * Stream primitives::
35934 * Stream constructors::
35935 * Stream binding::
35936 * Stream consumers::
35937 * Stream operations::
35938 @end menu
35939
35940 @node Stream primitives, Stream constructors, Stream library, Stream library
35941 @subsection Stream primitives
35942
35943 @defun stream? obj
35944 [R7RS stream]
35945 @c MOD util.stream
35946 @c EN
35947 Returns @code{#t} iff @var{obj} is a stream created by a procedure
35948 of @code{util.stream}.
35949 @c JP
35950 @var{obj}が@code{util.stream}の手続きによって作成されたストリームであ
35951 る場合にかぎり@code{#t}を返します。
35952 @c COMMON
35953 @end defun
35954
35955 @defvar stream-null
35956 [R7RS stream]
35957 @c MOD util.stream
35958 @c EN
35959 The singleton instance of NULL stream.
35960 @c JP
35961 NULLストリームのシングルトンインスタンス。
35962 @c COMMON
35963 @end defvar
35964
35965 @defmac stream-cons object stream
35966 [R7RS stream]
35967 @c MOD util.stream
35968 @c EN
35969 A fundamental constructor of a stream. Adds @var{object} to the
35970 head of a @var{stream}, and returns a new stream.
35971 @c JP
35972 ストリームの基本構成子。@var{object}を@var{stream}の先頭に追加し、新し
35973 いストリームを返します。
35974 @c COMMON
35975 @end defmac
35976
35977 @defun stream-null? obj
35978 [R7RS stream]
35979 @c MOD util.stream
35980 @c EN
35981 Returns @code{#t} iff @var{obj} is the null stream.
35982 @c JP
35983 @var{obj}がNULLストリームの場合にのみ@code{#t}を返します。
35984 @c COMMON
35985 @end defun
35986
35987 @defun stream-pair? obj
35988 [R7RS stream]
35989 @c MOD util.stream
35990 @c EN
35991 Returns @code{#t} iff @var{obj} is a non-null stream.
35992 @c JP
35993 @var{obj}がNULLストリームではないストリームのときにのみ@code{#t}を返します。
35994 @c COMMON
35995 @end defun
35996
35997 @defun stream-car s
35998 [R7RS stream]
35999 @c MOD util.stream
36000 @c EN
36001 Returns the first element of the stream @var{s}.
36002 @c JP
36003 ストリーム@var{s}の最初の要素を返します。
36004 @c COMMON
36005 @end defun
36006
36007 @defun stream-cdr s
36008 [R7RS stream]
36009 @c MOD util.stream
36010 @c EN
36011 Returns the remaining elements of the stream @var{s}, as a stream.
36012 @c JP
36013 ストリーム@var{s}の最初の要素を除いた残りの要素をストリームとして
36014 返します。
36015 @c COMMON
36016 @end defun
36017
36018 @defmac stream-delay expr
36019 [SRFI-40]
36020 @c MOD util.stream
36021 @c EN
36022 Returns a stream which is a delayed form of @var{expr}.
36023 @c JP
36024 @var{expr}の遅延形式であるストリームを返します。
36025 @c COMMON
36026
36027 @c EN
36028 As a rule of thumb, any stream-producing functions should
36029 wrap the resulting expression by @code{stream-delay}.
36030 (Or you can use @code{stream-lambda}, @code{stream-let} or @code{stream-define},
36031 described below.)
36032 @c JP
36033 原則として、ストリームを生成する関数はすべからく結果を
36034 @code{stream-delay}でラップすべきです。
36035 (以下に述べる@code{stream-lambda}, @code{stream-let}, @code{stream-define}を
36036 使う手もあります)。
36037 @c COMMON
36038 @end defmac
36039
36040 @defmac stream-lambda formals body body2 @dots{}
36041 [R7RS stream]
36042 @c MOD util.stream
36043 @c EN
36044 A convenience macro to create a function that returns a stream.
36045 Effectively, @code{(stream-lambda formals body body2 @dots{})} is the same
36046 as @code{(lambda formals (stream-delay body body2 @dots{}))}.
36047 @c JP
36048 ストリームを返す関数を作る簡易マクロです。
36049 @code{(stream-lambda formals body body2 @dots{})}は
36050 @code{(lambda formals (stream-delay body body2 @dots{}))}と同じです。
36051 @c COMMON
36052 @end defmac
36053
36054 @node Stream constructors, Stream binding, Stream primitives, Stream library
36055 @subsection Stream constructors
36056
36057 @defun stream obj @dots{}
36058 [SRFI-40]
36059 @c MOD util.stream
36060 @c EN
36061 Returns a new stream whose elements are @var{obj} @dots{}.
36062 @c JP
36063 要素が@var{obj} @dots{}であるような新しいストリームを返します。
36064 @c COMMON
36065
36066 @c EN
36067 Note: This differs from SRFI-41's (@code{scheme.stream}'s) @code{stream},
36068 which is a macro so that arguments are lazily evaluated. SRFI-41's
36069 @code{stream} is provided as @code{stream+} in this module.
36070 @c JP
36071 註:これはSRFI-41 (@code{scheme.stream})の@code{stream}とは異なります。
36072 SRFI-41の方はマクロで、引数の評価が遅延されます。SRFI-41版はこのモジュールでは
36073 @code{stream+}と言う名前で提供されます。
36074 @c COMMON
36075
36076 @example
36077 (stream 1 2 3)) @result{} @r{a stream that contains} (1 2 3)
36078 (stream 1 (/ 1 0))) @result{} @r{error}
36079 @end example
36080 @end defun
36081
36082 @defmac stream+ expr @dots{}
36083 @c MOD util.stream
36084 @c EN
36085 Returns a new stream whose elements are the result of @var{expr} @dots{}.
36086
36087 This is the same as SRFI-41(@code{scheme.stream})'s @code{stream}.
36088 Each @var{expr} isn't evaluated until it is accessed.
36089 @c JP
36090 要素が@var{expr} @dots{}の結果であるような新たなストリームを作って返します。
36091
36092 これはSRFI-41(@code{scheme.stream})の@code{stream}と同じです。
36093 各@var{expr}はアクセスされるまで評価されません。
36094 @c COMMON
36095
36096 @example
36097 (define s (stream+ 1 (/ 1 0))) ;; doesn't yield an error
36098
36099 (stream-car s) @result{} 1
36100
36101 (stream-cadr s) @result{} @r{error}
36102 @end example
36103 @end defmac
36104
36105 @defun stream-unfold f p g seed
36106 [R7RS stream]
36107 @c MOD util.stream
36108 @c EN
36109 Creates a new stream whose element is determined as follows:
36110
36111 @itemize
36112 @item
36113 A ``go'' predicate @var{p} is called on the current seed value.
36114 If it yields @code{#f}, the stream terminates.
36115 @item
36116 Otherwise, @code{(f s)} is the element of the stream,
36117 and @code{(g s)} becomes the next seed value, where
36118 @code{s} is the current seed value. The initial seed value
36119 is given by @var{seed}.
36120 @end itemize
36121
36122 Note: Unfortunately, the order of arguments differs from
36123 other @code{*-unfold} procedures, which takes @code{p f g}
36124 (predicate, value-generator and seed-generator). Furthermore,
36125 the predicate is stop-predicate (returning true stops iteration).
36126 @c JP
36127 次の手順で生成される要素をもつ新たなストリームを作成して返します。
36128
36129 @itemize
36130 @item
36131 「続行」述語@var{p}が現在のシード値を引数として呼ばれます。
36132 もし@code{#f}が返されたら、ストリームはそこで終了です。
36133 @item
36134 そうでなければ、@code{s}を現在のシード値として、@code{(f s)}をストリームの
36135 現在の要素とし、@code{(g s)}を次のシード値とします。
36136 @var{seed}はシード値の初期値を与えます。
36137 @end itemize
36138
36139 註:残念なことに、この手続きは他の @code{*-unfold} 系手続きと異なる順序で
36140 引数を取ります。他の手続きは@code{p f g} (述語、値生成、シード生成) の順です。
36141 さらに、他の手続きでは述語は停止する時に真を返します。
36142 @c COMMON
36143
36144 @example
36145 (stream->list
36146 (stream-unfold integer->char (cut < <> 58) (cut + 1 <>) 48))
36147 @result{} (#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
36148 @end example
36149 @end defun
36150
36151 @defun stream-unfoldn f seed n
36152 [SRFI-40]
36153 @c MOD util.stream
36154 @c EN
36155 Creates @var{n} streams related each other, whose contents are
36156 generated by @var{f} and @var{seed}.
36157 @c JP
36158 互いに関連する @var{n} 本のストリームを生成します。それぞれの内容は
36159 @var{f}および@var{seed}を使って生成します。
36160 @c COMMON
36161
36162 @c EN
36163 The @var{f} is called with the current seed value,
36164 and returns @code{@var{n}+1} values:
36165 @c JP
36166 @var{f}は現在のシード値とともに呼ばれ、@code{@var{n}+1}個の値
36167 を返します。
36168 @c COMMON
36169 @example
36170 (@var{f} @var{seed})
36171 => seed result_0 result_1 @dots{} result_n-1
36172 @end example
36173
36174 @c EN
36175 The first value is to be the next seed value.
36176 @var{Result_k} must be one of the following forms:
36177 @table @code
36178 @item (val)
36179 @var{val} will be the next car of @var{k}-th stream.
36180 @item #f
36181 No new information for @var{k}-th stream.
36182 @item ()
36183 The end of @var{k}-th stream has been reached.
36184 @end table
36185 @c JP
36186 最初の値は次のシード値になります。@var{Result_k}は以下の形式のどれかで
36187 なければなりません。
36188 @table @code
36189 @item (val)
36190 @var{val}は@var{k}-番目のストリームの次のcar部になります。
36191 @item #f
36192 @var{k}-番目のストリームの新しい情報はありません。
36193 @item ()
36194 @var{k}-番目のストリームの最後に到達しました。
36195 @end table
36196 @c COMMON
36197
36198 @c EN
36199 The following example creates two streams, the first one produces
36200 an infinite series of odd numbers and the second produces evens.
36201 @c JP
36202 以下の例では2つのストリームが作られます。最初のものは奇数の無限ストリー
36203 ムで、2つめのものは偶数の無限ストリームです。
36204 @c COMMON
36205
36206 @example
36207 gosh> (define-values (s0 s1)
36208 (stream-unfoldn (lambda (i)
36209 (values (+ i 2) ;; next seed
36210 (list i) ;; for the first stream
36211 (list (+ i 1)))) ;; for the second stream
36212 0 2))
36213 #<undef>
36214 gosh> (stream->list (stream-take s0 10))
36215 (0 2 4 6 8 10 12 14 16 18)
36216 gosh> (stream->list (stream-take s1 10))
36217 (1 3 5 7 9 11 13 15 17 19)
36218 @end example
36219 @end defun
36220
36221 @defun stream-unfolds f seed
36222 [R7RS stream]
36223 @c MOD util.stream
36224 @c EN
36225 Like @code{stream-unfoldn}, but the number of created streams is
36226 determined by the number fo return values from @var{f}. See
36227 @code{stream-unfoldn} above for the details.
36228 @c JP
36229 @code{stream-unfoldn}と似ていますが、結果のストリームの数は
36230 @var{f}の戻り値の数により決定されます。詳しくは
36231 上の@code{stream-unfoldn}の説明を参照してください。
36232 @c COMMON
36233 @end defun
36234
36235 @defun stream-constant obj @dots{}
36236 [R7RS stream]
36237 @c MOD util.stream
36238 @c EN
36239 Returns an infinite stream that repeats @var{obj} @dots{}.
36240 @c JP
36241 @var{obj} @dots{}を繰り返す無限ストリームを返します。
36242 @c COMMON
36243
36244 @example
36245 (stream->list 10 (stream-constant 1 2))
36246 @result{} (1 2 1 2 1 2 1 2 1 2)
36247 @end example
36248 @end defun
36249
36250 @defun make-stream n :optional init
36251 @c MOD util.stream
36252 @c EN
36253 Creates a new stream of @var{n} elements of @var{init}.
36254 If @var{init} is omitted, @code{#f} is used.
36255 Specifying a negative number to @var{n} creates an infinite stream.
36256 @c JP
36257 @var{n}個の@var{init}を要素とする新しいストリームを生成します。
36258 @var{init}が省略された場合@code{#f}が使われます。@var{n}を負の値にする
36259 と無限ストリームが生成されます。
36260 @c COMMON
36261 @end defun
36262
36263 @defun stream-tabulate n init-proc
36264 @c MOD util.stream
36265 @c EN
36266 Creates a new stream of @var{n} elements.
36267 The @var{k}-th element is obtained by applying @var{init-proc}
36268 to @var{k}. Specifying a negative number to @var{n} creates
36269 an infinite stream.
36270 @c JP
36271 @var{n}個の要素をもつ新しいストリームを生成します。@var{k}-番目の要素
36272 は @var{init-proc} を @var{k} に適用して得られます。@var{n}を負の値にする
36273 と無限ストリームが生成されます。
36274 @c COMMON
36275 @end defun
36276
36277 @defun stream-iota :optional count start step
36278 @c MOD util.stream
36279 @c EN
36280 Creates a new stream of numbers, starting from @var{start}
36281 and incrementing @var{step}. The length of stream is maximum
36282 integer not greater than nonnegative real number @var{count}.
36283 The default values of @code{count}, @var{start} and @var{step} are
36284 @code{+inf.0}, 0 and 1, respectively.
36285
36286 If @var{start} and @var{step} are exact, and @var{count} is exact or
36287 infinite, a sequence of exact numbers are created. Otherwise,
36288 a sequence of inexact numbers are created.
36289 @c JP
36290 @var{start}からはじまり、@var{step}ずつ要素が増加する数値のストリーム
36291 を生成します。ストリームの長さは非負の実数@var{count}を越えない最大の整数値です。
36292 @var{count}, @var{start}, @var{step}のデフォルト値はそれぞれ
36293 @code{+inf.0}, 0 および 1です。
36294
36295 @var{start}と@var{step}が正確数で、@var{count}が正確数か無限大の場合、
36296 正確数のストリームが作られます。そうでなければ非正確数のストリームになります。
36297 @c COMMON
36298 @end defun
36299
36300 @defun stream-range start :optional end step
36301 [R7RS stream]
36302 @c MOD util.stream
36303 @c EN
36304 Creates a new stream of real numbers, starting from @var{start}
36305 and stops before @var{end}, stepping by @var{step}.
36306 If @var{end} is omitted, positive infinity is assumed.
36307 If @var{step} is omitted, @code{1} is assumed if @var{end} is greater
36308 than @var{start}, and @code{-1} if @var{end} is less than @var{start}.
36309
36310 The generated numbers are exact if @var{start} and @var{step} are exact
36311 and @var{end} is either exact or infinite. Otherwise, inexact numbers
36312 are generated.
36313
36314 In R7RS @code{scheme.stream}, @var{end} argument is required.
36315 @c JP
36316 @var{start}から始まり@var{step}おきに@var{end}の手前まで続く実数のストリームを
36317 作って返します。@var{end}が省略された場合は正の無限大が使われます。
36318 @var{step}が省略された場合、@var{start}が@var{end}より小さければ@code{1}が、
36319 大きければ@var{-1}が使われます。
36320
36321 @var{start}と@var{step}が正確数で、@var{end}が正確数か無限大の場合は、
36322 正確数のシーケンスが、そうでない場合は非正確数のシーケンスが生成されます。
36323
36324 R7RSの@code{scheme.stream}では、@var{end}引数は必須です。
36325 @c COMMON
36326
36327 @example
36328 (stream->list (stream-range 0 10))
36329 @result{} (0 1 2 3 4 5 6 7 8 9)
36330 @end example
36331 @end defun
36332
36333 @defun stream-from start :optional step
36334 [R7RS stream]
36335 @c MOD util.stream
36336 @c EN
36337 This is yet another number sequence generator. Generates an infinite
36338 sequence whose @var{i}-th element is @code{(+ @var{start} (* i @var{step}))}.
36339 If @var{step} is omitted, 1 is assumed. If both @var{start} and @var{step}
36340 are exact, exact numbers are generated. Otherwise, inexact numbers are
36341 generated.
36342 @c JP
36343 もうひとつの数値シーケンス生成手続きです。@var{i}番目の項が
36344 @code{(+ @var{start} (* i @var{step}))}であるような無限シーケンスを返します。
36345 @var{step}が省略されたら1が使われます。
36346 @var{start}と@var{step}が正確数なら、正確数のシーケンスが、
36347 そうでなければ非正確数のシーケンスが返されます。
36348 @c COMMON
36349 @end defun
36350
36351 @defun stream-iterate f seed
36352 [R7RS stream]
36353 @c MOD util.stream
36354 @c EN
36355 Returns a stream starting from @var{seed}, and each successive element
36356 is calculated by @code{(@var{f} @var{s})} where @var{s} is the previous
36357 element.
36358 @c JP
36359 @var{seed}を初期値とし、ひとつ前の要素@var{s}から次の要素を@code{(@var{f} @var{s})}で
36360 計算するような無限長のストリームを返します。
36361 @c COMMON
36362
36363 @example
36364 (stream->list 5 (stream-iterate (cut cons 'x <>) '()))
36365 @result{} (() (x) (x x) (x x x) (x x x x))
36366 @end example
36367
36368 @c EN
36369 See also @code{literate} in @code{gauche.lazy} (@pxref{Lazy sequence utilities}).
36370 @c JP
36371 @code{gauche.lazy}の@code{literate}も参照
36372 (@ref{Lazy sequence utilities}).
36373 @c COMMON
36374 @end defun
36375
36376 @defun stream-xcons a b
36377 @c MOD util.stream
36378 @c EN
36379 @code{(stream-cons b a)}. Just for convenience.
36380 @c JP
36381 @code{(stream-cons b a)}のこと。利便性のためだけにある。
36382 @c COMMON
36383 @end defun
36384
36385 @defun stream-cons* elt @dots{} stream
36386 @c MOD util.stream
36387 @c EN
36388 Creates a new stream which appends @var{elt} @dots{} before @var{stream}.
36389 @c JP
36390 @var{stream}の前に@var{elt} @dots{}を連結した新しいストリームを生成し
36391 ます。
36392 @c COMMON
36393 @end defun
36394
36395 @defun list->stream list
36396 [R7RS stream]
36397 @c MOD util.stream
36398 @c EN
36399 Returns a new stream whose elements are the elements in @var{list}.
36400 @c JP
36401 @var{list}の要素を要素とする新たなストリームを作って返します。
36402 @c COMMON
36403 @end defun
36404
36405 @defun string->stream string :optional tail-stream
36406 @c MOD util.stream
36407 @c EN
36408 Converts a string to a stream of characters. If an optional
36409 @var{tail-stream} is given, it becomes the tail of the resulting
36410 stream.
36411 @c JP
36412 文字列を文字のストリームに変換します。@var{tail-stream}が与えられた場合は、
36413 文字ストリームの後にそれが付け加えられます。
36414 @c COMMON
36415
36416 @example
36417 @end example
36418 (stream->list (string->stream "abc" (list->stream '(1 2 3))))
36419 @result{} (#\a #\b #\c 1 2 3)
36420 @end defun
36421
36422 @defun stream-format fmt arg @dots{}
36423 @c MOD util.stream
36424 @c EN
36425 Returns a stream which is a result of applying @code{string->stream}
36426 to @code{(format fmt arg @dots{})}.
36427 @c JP
36428 @code{string->stream}を@code{(format fmt arg @dots{})}に適用した結果の
36429 ストリームを返します。
36430 @c COMMON
36431 @end defun
36432
36433 @defun port->stream :optional iport reader closer
36434 [R7RS stream]
36435 @c MOD util.stream
36436 @c EN
36437 Creates a stream, whose elements consist of the items
36438 read from the input port @var{iport}.
36439 The default @var{iport} is the current input port.
36440 The default @var{reader} is @code{read-char}.
36441
36442 The result stream terminates at the point where @var{reader}
36443 returns EOF (EOF itself is not included in the stream).
36444 The port won't be closed by default when it reaches EOF.
36445
36446 If @var{closer} is given, it is called with @var{iport} as
36447 an argument just after @var{reader} reads EOF. You can close the port
36448 with it.
36449
36450 The @var{reader} and @var{closer} arguments are Gauche's extension.
36451 R7RS @code{scheme.stream} only takes one optional argument, @var{iport}.
36452 @c JP
36453 @var{iport}から@var{reader}を使って読み出されるデータを要素とする新たなストリームを
36454 作って返します。@var{iport}のデフォルトは現在の入力ポート、
36455 @var{reader}のデフォルトは@code{read-char}です。
36456
36457 @var{reader}がEOFを返したらストリームの終端となります (EOF自体は
36458 ストリームには含まれません)。
36459 EOFに達してもポートはクローズされません。
36460
36461 もし@var{closer}引数が与えられたら、それが@var{iport}を引数として
36462 EOFが読まれた直後に呼ばれます。そこでポートをクローズするこはできます。
36463
36464 @var{reader}と@var{closer}引数はR7RSの@code{scheme.stream}では
36465 定義されない、Gaucheの拡張です。
36466 @c COMMON
36467 @end defun
36468
36469 @defun generator->stream gen
36470 @c MOD util.stream
36471 @c EN
36472 Creates a lazy stream of values generated by a generator @var{gen}.
36473 A generator is a thunk that returns a value every time it is called,
36474 with returning EOF to indicate the end of the input.
36475 @xref{Generators}, for the details of generators.
36476 @c JP
36477 ジェネレータ@var{gen}が生成する値の列からなる遅延ストリームを作って返します。
36478 ジェネレータは引数を取らない手続きで、呼ばれる度に値を返し、EOFを返すことで
36479 終端を示すものです(EOFはストリームには含まれません)。
36480 詳しくは@ref{Generators}を参照してください。
36481 @c COMMON
36482
36483 @c EN
36484 See also @code{generator->lseq}, which is another way to get
36485 a lazy sequence from a generator (@pxref{Lazy sequences}, for the details).
36486 @c JP
36487 似た手続きに、ジェネレータから遅延シーケンスを得る@code{generator->lseq}も
36488 あります(@ref{Lazy sequences}参照)。
36489 @c COMMON
36490 @end defun
36491
36492
36493 @defun iterator->stream iter
36494 @c MOD util.stream
36495 @c EN
36496 A generic procedure to turn an internal iterator @var{iter}
36497 into a stream of iterated results.
36498 @c JP
36499 イテレータ@var{iter}から遅延シーケンスを作る手続きです。
36500 @c COMMON
36501
36502 @c EN
36503 The @var{iter} argument is a procedure that takes two arguments,
36504 @var{next} and @var{end}, where @var{next} is a procedure that takes
36505 one argument and @var{end} is a thunk.
36506 @var{Iter} is supposed to iterate over some set and call @var{next}
36507 for each argument, then call @var{end} to indicate the end of
36508 the iteration. Here's a contrived example:
36509 @c JP
36510 @var{iter}は二つの引数@var{next}と@var{end}を取る手続きです。
36511 @var{next}は一つの引数を取る手続き、@var{end}は引数を取らない手続きです。
36512 @var{iter}手続きは、その中で何らかの値の集合に対して順に@var{next}手続きを呼び、
36513 最後に@var{end}手続きを呼びます。次はわざとらしい例です:
36514 @c COMMON
36515
36516 @example
36517 (stream->list
36518 (iterator->stream
36519 (lambda (next end) (for-each next '(1 2 3 4 5)) (end))))
36520 @result{} (1 2 3 4 5)
36521 @end example
36522
36523 @c EN
36524 Internally @code{iterator->stream} uses the ``inversion of iterator''
36525 technique, so that @var{iter} only iterates to the element that
36526 are needed by the stream. Thus @var{iter} can iterate over
36527 an infinite set. In the following example, @var{iter} is
36528 an infinite loop calling @var{next} with increasing integers,
36529 but only the first 10 elements are calculated because of
36530 @code{stream-take}:
36531 @c JP
36532 内部的に、@code{iterator->stream}はいわゆる「イテレータの反転」テクニックを
36533 使っていて、@var{iter}は必要なだけしかイテレーションを行いません。なので
36534 @var{iter}は無限の要素を扱うこともできます。
36535 例えば次の例では、@var{iter}は増加する整数に対して@var{next}を無限に呼び出す
36536 ようになっていますが、@code{stream-take}によって最初の10要素しか計算されません。
36537 @c COMMON
36538
36539 @example
36540 (stream->list
36541 (stream-take
36542 (iterator->stream
36543 (lambda (next end)
36544 (let loop ((n 0)) (next n) (loop (+ n 1)))))
36545 10))
36546 @result{} (0 1 2 3 4 5 6 7 8 9)
36547 @end example
36548 @end defun
36549
36550 @defmac stream-of elt-expr clause @dots{}
36551 [R7RS stream]
36552 @c MOD util.stream
36553 @c EN
36554 Stream comprehension. Returns a stream in which each element
36555 is computed by @var{elt-expr}.
36556 The @var{clause} creates scope of @var{elt-expr}
36557 and controls iterations. Each @var{clause} can be one of the following
36558 forms:
36559 @c JP
36560 ストリーム内包表記。各要素が@var{elt-expr}で計算されるストリームを返します。
36561 @var{clause}は@var{elt-expr}のスコープを作り、繰り返しを制御します。
36562 各@var{clause}は以下の形のいずれかです:
36563 @c COMMON
36564 @table @code
36565 @item (@var{x} in @var{stream-expr})
36566 @c EN
36567 Iterate over @var{stream-expr}, binding @var{x} to each element in
36568 each iteration. The variable @var{x} is visible in successive @var{clause}s
36569 and @var{elt-expr}
36570 @c JP
36571 @var{stream-expr}が返すストリームの各要素を、@var{x}に束縛して繰り返します。
36572 変数@var{x}のスコープは後続の@var{clause}および@var{elt-expr}です。
36573 @c COMMON
36574 @item (@var{x} is @var{expr})
36575 @c EN
36576 Bind a variable @var{x} with the value of @var{expr}. The variable @var{x}
36577 is visible in successive @var{clause}s
36578 and @var{elt-expr}.
36579 @c JP
36580 変数@var{x}に値@var{expr}の結果を束縛します。@var{x}のスコープは
36581 後続の@var{clause}および@var{elt-expr}です。
36582 @c COMMON
36583 @item expr
36584 @c EN
36585 If @var{expr} evaluates to @code{#f}, this iteration is skipped without
36586 generating a new element.
36587 @c JP
36588 @var{expr}が@code{#f}に評価されたらこの回は値を生成せずに打ちきられ、
36589 次の繰り返しに進みます。
36590 @c COMMON
36591 @end table
36592
36593 @c EN
36594 The following comprehension generates infinite sequence of pythagorean
36595 triples:
36596 @c JP
36597 次の内包表記はピタゴラス数の無限シーケンスを生成します:
36598 @c COMMON
36599
36600 @example
36601 (define pythagorean-triples
36602 (stream-of (list a b c)
36603 (c in (stream-from 3))
36604 (b in (stream-range 2 c))
36605 (a in (stream-range 1 b))
36606 (= (square c) (+ (square b) (square a)))))
36607
36608 (stream->list 5 pythagorean-triples)
36609 @result{} ((3 4 5) (6 8 10) (5 12 13) (9 12 15) (8 15 17))
36610 @end example
36611 @end defmac
36612
36613 @node Stream binding, Stream consumers, Stream constructors, Stream library
36614 @subsection Stream binding
36615
36616 @defmac define-stream (name . formals) body body2 @dots{}
36617 [R7RS stream]
36618 @c MOD util.stream
36619 @c EN
36620 A convenient macro to define a procedure that yields a stream.
36621 Same as the following form:
36622 @c JP
36623 ストリームを作って返す関数を手軽に定義するマクロです。
36624 次のフォームと同じです:
36625 @c COMMON
36626
36627 @example
36628 (define (name . formals)
36629 (stream-delay
36630 (let () body body2 @dots{})))
36631 @end example
36632 @end defmac
36633
36634 @defmac stream-let loop-var ((var init) @dots{}) body body2 @dots{}
36635 [R7RS stream]
36636 @c MOD util.stream
36637 @c EN
36638 A handy macro to write a lazy named-let loop. It is the same as the
36639 following:
36640 @c JP
36641 lazyなnamed-letによるループを書くときに便利なマクロです。次のフォームと同じです:
36642 @c COMMON
36643 @example
36644 (let loop-var ((var init) @dots{})
36645 (stream-delay
36646 (let () body body2 @dots{})))
36647 @end example
36648 @end defmac
36649
36650 @defmac stream-match stream-expr clause @dots{}
36651 [R7RS stream]
36652 @c MOD util.stream
36653 @c EN
36654 This allows accessing streams via simple pattern matching.
36655 The @var{stream-expr} argument is evaluated and must yield a stream.
36656 Each @var{clause}
36657 must be either a form of @code{(@var{pattern} @var{expr})} or
36658 @code{(@var{pattern} @var{fender} @var{expr})}.
36659
36660 The content of the stream is matched to each @var{pattern},
36661 which must have one of the following forms:
36662 @c JP
36663 このマクロは簡単なパターンマッチングを使ってストリームの要素にアクセスします。
36664 @var{stream-expr}はストリームを返す式でなければなりません。
36665 各@var{clause}は@code{(@var{pattern} @var{expr})}か
36666 @code{(@var{pattern} @var{fender} @var{expr})}という形です。
36667
36668 入力ストリームは各@var{pattern}に順マッチするかどうかテストされます。
36669 @var{pattern}には以下の形のいずれかです:
36670 @c COMMON
36671
36672 @table @code
36673 @item ()
36674 @c EN
36675 Matches a null stream.
36676 @c JP
36677 空のストリームとマッチします。
36678 @c COMMON
36679 @item (@var{p0} @var{p1} @dots{})
36680 @c EN
36681 Matches a stream that has exactly the same number of elements as
36682 the number of pattern elements.
36683 @c JP
36684 パターン内の要素の数と入力ストリームの要素数が一致した時にマッチします。
36685 @c COMMON
36686 @item (@var{p0} @var{p1} @dots{} . @var{pRest})
36687 @c EN
36688 Matches a stream that has at least the same number of elements as
36689 the number of pattern elements except @var{pRest}. The rest of stream
36690 matches with @var{pRest}.
36691 @c JP
36692 入力ストリームの要素数が、@var{pRest}を除いたパターン内の要素の数以上であれば
36693 マッチします。@var{pRest}にはストリームの残りがマッチします。
36694 @c COMMON
36695 @item @var{pRest}
36696 @c EN
36697 Matches an entire stream.
36698 @c JP
36699 入力ストリーム全体とマッチします。
36700 @c COMMON
36701 @end table
36702
36703 @c EN
36704 Each pattern element can be an identifier or a literal underscore. If it is
36705 an identifier, it is bound to the matched element while evaluating
36706 the corresponding @var{fender} and @var{expr}.
36707 @c JP
36708 パターンの各要素は識別子かリテラルのアンダースコア@code{_}です。
36709 アンダースコア以外の識別子の場合は、それらが対応する入力ストリームの要素に
36710 束縛された環境で@var{fender}と@var{expr}が評価されます。
36711 @c COMMON
36712
36713 @c EN
36714 If @var{fender} is present in the @var{clause}, it is evaluated; if
36715 it yields @code{#f}, the match of the clause fails and next clauses will be
36716 tried.
36717 @c JP
36718 もし@var{fender}があれば、まずそれが評価され、@code{#f}であったらその@var{clause}の
36719 マッチは失敗となり、次の@var{clause}が試されます。
36720 @c COMMON
36721
36722 @c EN
36723 Otherwise, @var{expr} is evaluated and the result(s) becomes the result(s)
36724 of @code{stream-match}.
36725 @c JP
36726 そうでなければ@var{expr}が評価され、その結果が@code{stream-match}の結果となります。
36727 @c COMMON
36728
36729 @c EN
36730 Only the elements from the stream that is required to match are accessed.
36731 @c JP
36732 入力ストリームの要素はマッチに必要なだけ取り出されます。
36733 @c COMMON
36734
36735 @c EN
36736 The following example defines a procedure to count the number of true
36737 values in the stream:
36738 @c JP
36739 次の例は、ストリーム中の真の値の数を数えています:
36740 @c COMMON
36741
36742 @example
36743 (define (num-trues strm)
36744 (stream-match strm
36745 (() 0)
36746 ((head . tail) head (+ 1 (num-trues tail)))
36747 ((_ . tail) (num-trues tail))))
36748
36749 (num-trues (stream #f #f #t #f #t #f #t #t))
36750 @result{} 4
36751 @end example
36752 @end defmac
36753
36754 @node Stream consumers, Stream operations, Stream binding, Stream library
36755 @subsection Stream consumers
36756
36757 @c EN
36758 These procedures takes stream(s) and consumes its/their elements
36759 until one of the streams is exhausted.
36760 @c JP
36761 これらの手続きはストリームを取り、その要素を消費し尽します。
36762 @c COMMON
36763
36764 @defun stream-for-each func . streams
36765 [R7RS stream]
36766 @c MOD util.stream
36767 @c EN
36768 Applies @var{func} for each element of @var{streams}.
36769 Terminates if one of @var{streams} reaches the end.
36770 @c JP
36771 @var{func}を@var{streams}の各要素に適用します。
36772 @var{streams}が終端に達したところで停止します。
36773 @c COMMON
36774 @end defun
36775
36776 @defun stream-fold f seed stream
36777 [R7RS stream]
36778 @c MOD util.stream
36779 @c EN
36780 Apply @var{f} on the current seed value and an element from
36781 @var{stream} to obtain the next seed value, and repeat it until
36782 @var{stream} is exhausted, then returns the last seed value.
36783 The initial seed value is given by @var{seed}.
36784
36785 Note: The argument order of @var{f} differs from other @code{*-fold}
36786 procedures, e.g. @code{fold} (@pxref{Walking over lists}) takes
36787 the element first, then the seed value.
36788 @c JP
36789 @var{f}を現在のシード値と@var{stream}の要素に適用し、その結果を次のシード値として
36790 @var{stream}が終端に達するまで繰り返します。最初のシード値は@var{seed}引数で与えられます。
36791 最後のシード値が返されます。
36792
36793 註: @var{f}の引数順は、他の@code{*-fold}系関数のそれと異なることに注意してください。
36794 例えば@code{fold} (@ref{Walking over lists}参照) では最初に要素、次にシード値が
36795 渡されます。
36796 @c COMMON
36797
36798 @example
36799 (stream-fold - 0 (stream 1 2 3 4 5))
36800 @result{} -15
36801 @end example
36802 @end defun
36803
36804 @node Stream operations, , Stream consumers, Stream library
36805 @subsection Stream operations
36806
36807 @defun stream-append stream @dots{}
36808 [R7RS stream]
36809 @c MOD util.stream
36810 @c EN
36811 Returns a new stream which is concatenation of given @var{stream}s.
36812 @c JP
36813 与えられた@var{stream}を全部つないだ新たなストリームを返します。
36814 @c COMMON
36815 @end defun
36816
36817 @defun stream-concat streams
36818 @defunx stream-concatenate streams
36819 [R7RS stream]
36820 @c MOD util.stream
36821 @c EN
36822 R7RS @code{scheme.stream} defines @code{stream-concat}. Gauche had
36823 @code{stream-concatenate}, and keeps it for the backward compatibility.
36824 Both are the same.
36825
36826 The @var{streams} argument is a stream of streams. Returns a new stream
36827 that is concatenation of them. Unlike @code{stream-append}, @var{streams}
36828 can generate infinite streams.
36829 @c JP
36830 R7RS @code{scheme.stream}は@code{stream-concat}を定義しました。
36831 Gaucheには@code{stream-concatenate}があったので互換性のためにそちらも残しています。
36832 どちらも同じです。
36833
36834 @var{streams}はストリームのストリームです。各ストリームを連結したストリームを作って
36835 返します。@code{stream-append}と違い、@var{streams}は無限個のストリームを生成
36836 することができます。
36837 @c COMMON
36838 @end defun
36839
36840
36841 @defun stream-map func stream stream2 @dots{}
36842 [R7RS stream]
36843 @c MOD util.stream
36844 @c EN
36845 Returns a new stream, whose elements are calculated by
36846 applying @var{func} to each element of @var{stream} @dots{}.
36847 @c JP
36848 @var{streams}の各要素に@var{func}を適用した値を要素とする新しいストリー
36849 ムを返します。
36850 @c COMMON
36851 @end defun
36852
36853 @defun stream-scan func seed stream
36854 [R7RS stream]
36855 @c MOD util.stream
36856 @c EN
36857 Returns a stream of @code{@var{seed}}, @code{(@var{func} @var{seed} @var{e0})},
36858 @code{(@var{func} (@var{func} @var{seed} @var{e0}) @var{e1})}, @dots{}, where
36859 @var{e0}, @var{e1} @dots{} are the elements from the input @var{stream}.
36860 If @var{stream} is finite, the result stream has one more elements than
36861 the number of elements in the original stream.
36862 @c JP
36863 @code{@var{seed}}、
36864 @code{(@var{func} @var{seed} @var{e0})}、
36865 @code{(@var{func} (@var{func} @var{seed} @var{e0}) @var{e1})} @dots{}
36866 で構成されるストリームを返します。ここで
36867 @var{e0}、@var{e1} @dots{}は入力ストリーム@var{stream}の要素です。
36868 @var{stream}が有限なら、その要素よりひとつ多い要素が出力ストリームには含まれます。
36869 @c COMMON
36870
36871 @example
36872 (stream->list
36873 (stream-scan xcons '() (stream 1 2 3 4 5)))
36874 @result{} (() (1) (2 1) (3 2 1) (4 3 2 1) (5 4 3 2 1))
36875 @end example
36876 @end defun
36877
36878 @defun stream-zip stream @dots{}
36879 [R7RS stream]
36880 @c MOD util.stream
36881 @c EN
36882 Returns a new stream whose elements are lists of corresponding
36883 elements from input @var{stream}s. The output stream ends
36884 when one of input streams is exhausted.
36885 @c JP
36886 入力ストリームの対応する要素のリストを要素とするストリームを作って返します。
36887 入力ストリームのいずれかが終端に達した時に出力ストリームも終わります。
36888 @c COMMON
36889
36890 @example
36891 (stream->list
36892 (stream-zip (stream 1 2 3) (stream 'a 'b 'c 'd)))
36893 @result{} ((1 a) (2 b) (3 c))
36894 @end example
36895
36896 @end defun
36897
36898 @defun stream-filter pred stream
36899 [R7RS stream]
36900 @c MOD util.stream
36901 @c EN
36902 Returns a new stream including only elements passing @var{pred}.
36903 This procedure returns immediately; @var{stream} can be infinite.
36904 @c JP
36905 @var{pred}をパスする要素のみからなる新しいストリームを返します。
36906 この手続きは直ちに返ります。@var{stream}は無限ストリームであっても構いません。
36907 @c COMMON
36908 @end defun
36909
36910 @defun stream-remove pred stream
36911 @c MOD util.stream
36912 @c EN
36913 Returns a new stream including only elements that doesn't satisfy @var{pred}.
36914 It is the same as @code{(stream-filter (complement pred) stream)}.
36915 @c JP
36916 述語@var{pred}を満たさない要素のみからなる新しいストリームを返します。
36917 @code{(stream-filter (complement pred) stream)}と同じです。
36918 @c COMMON
36919 @end defun
36920
36921 @defun stream-partition pred stream
36922 @c MOD util.stream
36923 @c EN
36924 Returns two streams, one consists of the elements in @var{stream}
36925 that satisfy @var{pred}, the other consists of the ones that doesn't
36926 satisfy @var{pred}.
36927 @c JP
36928 二つのストリームを返します。最初のストリームは@var{stream}の要素のうち
36929 述語@var{pred}を満たすもの、次のストリームは@var{pred}を満たさないもので構成されます。
36930 @c COMMON
36931 @end defun
36932
36933 @defun stream->list stream
36934 @defunx stream->list n stream
36935 [R7RS stream]
36936 @c MOD util.stream
36937 @c EN
36938 Converts a stream to a list. In the first form, all elements from
36939 @var{stream} are taken (thus it never returns if @var{stream} is infinite).
36940 In the second form, at most @var{n} elements are taken, where
36941 @var{n} must be a nonnegative exact integer.
36942
36943 Note: In usual Scheme conventions, the optional @var{n} comes after
36944 the main argument (@var{stream}).
36945 @c JP
36946 ストリームをリストに変換します。最初の形式では、@var{stream}の全ての要素が
36947 取り出されます (従って@var{stream}が無限ストリームであればこの関数は永遠に戻りません)。
36948 二番めの形式では最大で@var{n}要素までがストリームから取り出されそのリストが返されます。
36949 @var{n}は非負の正確な整数でなければなりません。
36950
36951 註:通常のSchemeの慣例では、省略可能な@var{n}は@var{stream}の後に来ますが、
36952 この関数はそうでないことに注意。
36953 @c COMMON
36954 @end defun
36955
36956 @defun stream->string stream
36957 @c MOD util.stream
36958 @c EN
36959 Converts a stream to a string.
36960 All elements of @var{stream} must be characters, or an error is signaled.
36961 @c JP
36962 ストリームを文字列に変換します。
36963 @var{stream}の全ての要素は文字でなければなりません。
36964 そうでない場合はエラーが投げられます。
36965 @c COMMON
36966 @end defun
36967
36968
36969 @defun stream-lines stream
36970 @c MOD util.stream
36971 @c EN
36972 Splits @var{stream} where its element equals to @code{#\n}, and
36973 returns a stream of splitted streams. The character @code{#\n} won't
36974 be included in the results.
36975 @c JP
36976 @var{stream}を、文字@code{#\n}が要素である箇所で分割し、
36977 分割されたストリームのストリームを返します。@code{#\n}自体は結果に含まれません。
36978 @c COMMON
36979
36980 @example
36981 (stream->list
36982 (stream-map stream->string
36983 (stream-lines (string->stream "abc\ndef\nghi"))))
36984 @result{} ("abc" "def" "ghi")
36985 @end example
36986 @end defun
36987
36988 @defun stream= elt= stream @dots{}
36989 @c MOD util.stream
36990 @c EN
36991 Returns true iff each corresponding element of @var{stream} @dots{}
36992 are the same in terms of @var{elt=}, which takes two arguments.
36993 This procedure won't terminate
36994 if all of @var{stream}s is infinite.
36995 @c JP
36996 引数のストリームの全ての対応する要素がそれぞれ、2引数を取る@var{elt=}で比較して等しい場合に
36997 @code{#t}を、そうでなければ@code{#f}を返します。
36998 全ての@var{stream}が無限である場合、この手続きは終了しません。
36999 @c COMMON
37000 @end defun
37001
37002 @defun stream-prefix= stream prefix :optional elt=
37003 @c MOD util.stream
37004 @c EN
37005 Compares initial elements of @var{stream} against
37006 a list @var{prefix} by @var{elt=}. Returns true iff they match.
37007 Only as many elements of @var{stream}
37008 as @var{prefix} has are checked.
37009 @c JP
37010 @var{stream}の最初の方の要素をリスト@var{prefix}と比較します。各要素は
37011 @var{elt=}で比較されます。@var{prefix}と全てマッチしたら@code{#t}を、
37012 そうでなければ@code{#f}を返します。最大でも@var{prefix}の要素分だけ@var{stream}から
37013 要素が取り出されます。
37014 @c COMMON
37015 @end defun
37016
37017 @defun stream-caar s
37018 @defunx stream-cadr s
37019 @findex stream-cdar
37020 @findex stream-cddr
37021 @findex stream-caaar
37022 @findex stream-caadr
37023 @findex stream-cadar
37024 @findex stream-caddr
37025 @findex stream-cdaar
37026 @findex stream-cdadr
37027 @findex stream-cddar
37028 @findex stream-cdddr
37029 @findex stream-caaaar
37030 @findex stream-caaadr
37031 @findex stream-caadar
37032 @findex stream-caaddr
37033 @findex stream-cadaar
37034 @findex stream-cadadr
37035 @findex stream-caddar
37036 @findex stream-cadddr
37037 @findex stream-cdaaar
37038 @findex stream-cdaadr
37039 @findex stream-cdadar
37040 @findex stream-cdaddr
37041 @findex stream-cddaar
37042 @findex stream-cddadr
37043 @dots{}
37044 @end defun
37045 @defun stream-cdddar s
37046 @defunx stream-cddddr s
37047 @c MOD util.stream
37048 @code{(stream-caar s)} = @code{(stream-car (stream-car s))} etc.
37049 @end defun
37050
37051 @defun stream-ref stream pos
37052 [R7RS stream]
37053 @c MOD util.stream
37054 @c EN
37055 Returns the @var{pos}-th element in the stream. @var{Pos}
37056 must be a nonnegative exact integer.
37057 @c JP
37058 ストリームの@var{pos}番目の要素を返します。@var{pos}は非負の正確な整数でなければなりません。
37059 @c COMMON
37060 @end defun
37061
37062 @defun stream-first s
37063 @defunx stream-second s
37064 @defunx stream-third s
37065 @defunx stream-fourth s
37066 @defunx stream-fifth s
37067 @defunx stream-sixth s
37068 @defunx stream-seventh s
37069 @defunx stream-eighth s
37070 @defunx stream-ninth s
37071 @defunx stream-tenth s
37072 @c MOD util.stream
37073 @code{(stream-first s)} = @code{(stream-ref s 0)} etc.
37074 @end defun
37075
37076 @defun stream-take stream count
37077 @defunx stream-take-safe stream count
37078 @c MOD util.stream
37079 @c EN
37080 Returns a new stream that consists of the first @var{count} elements
37081 of the given stream. If the given stream has less than
37082 @var{count} elements, the stream returned by @code{stream-take}
37083 would raise an error when the elements beyond the original stream
37084 is accessed. On the other hand, the stream returned by
37085 @code{stream-take-safe} will return a shortened stream when
37086 the given stream has less than @var{count} elements.
37087 @c JP
37088 与えられたストリームのうち、最初の@var{count}要素だけを含むストリームを返します。
37089 与えられたストリームが@var{count}要素より少ない要素しか持っていなかった場合、
37090 @code{stream-take}が返すストリームは、元のストリームの終端を越えてアクセスしようとした時に
37091 エラーを投げます。一方、@code{stream-take-safe}が返すストリームは、
37092 元のストリームが@var{count}要素より少なかった場合に、その要素までを返すストリームを
37093 返します。
37094 @c COMMON
37095
37096 @example
37097 (stream->list (stream-take (stream-iota -1) 10))
37098 @result{} (0 1 2 3 4 5 6 7 8 9)
37099
37100 (stream-take (stream 1 2) 5)
37101 @result{} @r{stream}
37102
37103 (stream->list (stream-take (stream 1 2) 5))
37104 @result{} @r{error}
37105
37106 (stream->list (stream-take-safe (stream 1 2) 5))
37107 @result{} (1 2)
37108 @end example
37109
37110 @c EN
37111 Note: SRFI-41 (@code{scheme.stream}) also defines @code{stream-take}, but
37112 the argument order is reversed, and also it allows @var{stream} to have
37113 less than @code{count} elements.
37114 @c JP
37115 註: SRFI-41 (@code{scheme.stream}) も@code{stream-take}を提供していますが、
37116 引数の順序が逆になっています。また、SRFI-41の@code{stream-take}は
37117 元のストリームが@var{count}以下の要素しか持っていなかった場合でもエラーとしません。
37118 @c COMMON
37119 @end defun
37120
37121 @defun stream-drop stream count
37122 @defunx stream-drop-safe stream count
37123 @c MOD util.stream
37124 @c EN
37125 Returns a new stream that consists of the elements in the given
37126 stream except the first @var{count} elements.
37127 If the given stream has less than @var{count} elements,
37128 @code{stream-drop} returns a stream that raises an error
37129 if its element is accessed, and @code{stream-drop-safe}
37130 returns an empty stream.
37131 @c JP
37132 与えられたストリームのうち、最初の@var{count}要素を取り除いたストリームを返します。
37133 与えられたストリームが@var{count}要素より少ない要素しか持っていなかった場合、
37134 @code{stream-drop}は、アクセスされるとエラーを投げるストリームを返します。
37135 一方、@code{stream-drop-safe}は空のストリームを返します。
37136 @c COMMON
37137
37138 @c EN
37139 Note: SRFI-41 (@code{scheme.stream}) also defines @code{stream-drop}, but
37140 the argument order is reversed, and also it allows @var{stream} to have
37141 less than @code{count} elements.
37142 @c JP
37143 註: SRFI-41 (@code{scheme.stream}) も@code{stream-drop}を提供していますが、
37144 引数の順序が逆になっています。また、SRFI-41の@code{stream-drop}は
37145 元のストリームが@var{count}以下の要素しか持っていなかった場合にエラーとせず
37146 空のストリームを返します。
37147 @c COMMON
37148 @end defun
37149
37150 @defun stream-intersperse stream element
37151 @c MOD util.stream
37152 @c EN
37153 Returns a new stream in which @var{element} is
37154 inserted between each consecutive two elements of @var{stream}.
37155 @c JP
37156 @var{element}が@var{stream}の連続する2要素の間に挿入されているような新たなストリームを
37157 返します。
37158 @c COMMON
37159
37160 @example
37161 (stream->list (stream-intersperse (stream 1 2 3) 0))
37162 @result{} (1 0 2 0 3)
37163 @end example
37164 @end defun
37165
37166 @defun stream-split stream pred
37167 @c MOD util.stream
37168 @c EN
37169 Split @var{stream} on elements that satisfy @var{pred},
37170 and returns a stream of splitted streams. The delimiting element
37171 won't be included in the result.
37172 @c JP
37173 @var{stream}を、@var{pred}を満たす要素で分割し、
37174 分割されたストリームのストリームを返します。
37175 分割に使われた要素は結果に含まれません。
37176 @c COMMON
37177
37178 @example
37179 (stream->list
37180 (stream-map stream->list
37181 (stream-split (stream 1 3 2 5 7 9 6 8 1) even?))))
37182 @result{} ((1 3) (5 7 9) () (1))
37183 @end example
37184 @end defun
37185
37186 @defun stream-last stream
37187 @c MOD util.stream
37188 @c EN
37189 Returns the last element of @var{stream}.
37190 If @var{stream} is empty, an error is thrown.
37191 If @var{stream} is infinite, this procedure won't return.
37192 @c JP
37193 @var{stream}の最後の要素を返します。@var{stream}が空ならエラーが投げられます。
37194 @var{stream}が無限ストリームの場合、この手続きは戻ってきません。
37195 @c COMMON
37196 @end defun
37197
37198 @defun stream-last-n stream count
37199 @c MOD util.stream
37200 @c EN
37201 Returns a stream that contains the last @var{count} elements
37202 in @var{stream}. The @var{count} argument must be a nonnegative exact
37203 integer. If the length of @var{stream} is smaller than @var{count},
37204 the resulting stream is the same as @var{stream}.
37205 If @var{stream} is infinite,
37206 this procedure won't return.
37207 @c JP
37208 @var{stream}の最後の@var{count}要素を含むストリームを返します。
37209 @var{count}は非負の正確な整数でなければなりません。
37210 もし@var{stream}が@var{count}要素より短ければ、@var{stream}がそのまま返されます。
37211 @var{stream}が無限ストリームならこの手続きは戻ってきません。
37212 @c COMMON
37213 @end defun
37214
37215 @defun stream-butlast stream
37216 @c MOD util.stream
37217 @c EN
37218 Returns a stream which is the same as @var{stream} but without the
37219 last element. If @var{stream} is empty, an empty stream is returned.
37220 immediately. The argument can be an infinite stream.
37221 @c JP
37222 @var{stream}の最後の要素を除く内容を持つストリームを返します。
37223 @var{stream}が空の場合は空のストリームが返されます。
37224 @var{stream}は無限ストリームであっても構いません。
37225 @c COMMON
37226 @end defun
37227
37228 @defun stream-butlast-n stream count
37229 @c MOD util.stream
37230 @c EN
37231 Returns a stream which is the same as @var{stream} but without the
37232 last @var{count} elements. The @var{count} argument must be a nonnegative exact
37233 integer. If @var{stream} is shorter than @var{count}, a null stream
37234 is returned. @var{Stream} can be infinite.
37235 @c JP
37236 @var{stream}の最後の@var{count}要素を除いた内容を持つストリームを作って返します。
37237 @var{count}は非負の正確な整数でなければなりません。
37238 @var{stream}の要素数が@var{count}より少なければ、空のストリームが返されます。
37239 @var{stream}は無限ストリームであっても構いません。
37240 @c COMMON
37241 @end defun
37242
37243 @defun stream-length stream
37244 [R7RS stream]
37245 @c MOD util.stream
37246 @c EN
37247 Returns the number of elements in @var{stream}.
37248 It diverges if @var{stream} is infinite.
37249 @c JP
37250 @var{stream}の要素数を返します。
37251 @var{stream}が無限ストリームの時は戻ってきません。
37252 @c COMMON
37253 @end defun
37254
37255 @defun stream-length>= stream n
37256 @defunx stream-length= stream n
37257 @c MOD util.stream
37258 @c EN
37259 Returns true iff the length of @var{stream} is greater than or equal to,
37260 and exactly equal to, @var{n}, respectively.
37261 These procedures only realizes @var{stream} up to @var{n} elements.
37262 @c JP
37263 @var{stream}の要素数が、それぞれ@var{n}以上か、@var{n}と等しければ@code{#t}を、
37264 そうでなければ@code{#f}を返します。
37265 これらの手続きは@var{stream}の最初の@var{n}要素のみを現実化します。
37266 @c COMMON
37267 @end defun
37268
37269 @defun stream-reverse stream :optional tail-stream
37270 [R7RS stream]
37271 @c MOD util.stream
37272 @c EN
37273 Returns a stream that returns the elements of @var{stream} in reverse order.
37274 If @var{tail-stream} is given, it is added after the reversed stream.
37275
37276 The optional argument is Gauche's extension. The description of @code{reverse}
37277 (@pxref{Other list procedures}) for more details.
37278 @c JP
37279 @var{stream}の要素を逆順にしたストリームを返します。@var{tail-stream}が与えられた
37280 場合、逆順にしたストリームの後にそれ付け加えられます。
37281
37282 省略可能な@var{tail-stream}はGaucheの拡張です。詳しくは
37283 @code{reverse}の説明を参照してください (@ref{Other list procedures})。
37284 @c COMMON
37285 @end defun
37286
37287 @defun stream-count pred stream @dots{}
37288 @c MOD util.stream
37289 @c EN
37290 The predicate @var{pred} is called with each of the first element of
37291 @var{stream} @dots{}, then each of the second element, and so on, until
37292 any of the stream is exhausted. Then returns the number that
37293 @var{pred} returns a true value.
37294 At least one stream needs to be finite.
37295 @c JP
37296 @var{pred}は、まず@var{stream} @dots{}それぞれの最初の要素を引数として呼び出され、
37297 次にそれぞれの2番目の要素を引数として呼ばれ、以降いずれかの@var{stream}が尽きるまで
37298 呼ばれます。そして、そのうち@var{pred}が真の値を返した数が戻り値となります。
37299 少なくとも@var{stream}のうちのひとつは有限でなければなりません。
37300 @c COMMON
37301
37302 @example
37303 (stream-count < (stream 1 2 3 4 5) (stream 2 2 2 10 10))
37304 @result{} 3
37305 @end example
37306 @end defun
37307
37308 @defun stream-find pred stream
37309 @c MOD util.stream
37310 @c EN
37311 The predicate @var{pred} is applied to each element of @var{stream} in turn,
37312 and as soon as the @var{pred} returns true, returns the element that
37313 caused @var{pred} to return true. Remaining elements of @var{stream}
37314 won't be realized.
37315
37316 If no elements in @var{stream} satisfy @var{pred}, @code{#f} is returned.
37317 @c JP
37318 @var{pred}を@var{stream}の要素に順に適用し、@var{pred}が真の値を返したら
37319 直ちにその要因となった要素を返します。@var{stream}の残りは現実化されません。
37320
37321 @var{stream}の要素の中に@var{pred}を満たすものが無かった場合は@code{#f}が返ります。
37322 @c COMMON
37323 @end defun
37324
37325 @defun stream-find-tail pred stream
37326 @c MOD util.stream
37327 @c EN
37328 The predicate @var{pred} is applied to each element of @var{stream} in turn,
37329 and as soon as the @var{pred} returns true, returns a stream
37330 that contains the element and the rest of the input stream.
37331 Remaining elements of @var{stream} won't be realized.
37332
37333 If no elements in @var{stream} satisfy @var{pred}, the empty stream is returned.
37334 @c JP
37335 @var{pred}を@var{stream}の要素に順に適用し、@var{pred}が真の値を返したら
37336 その要素およびそれ以降の要素からなるストリームを返します。
37337 @var{stream}の残りは現実化されません。
37338
37339 @var{stream}の要素の中に@var{pred}を満たすものが無かった場合は空のストリームが返ります。
37340 @c COMMON
37341 @end defun
37342
37343 @defun stream-take-while pred stream
37344 @defunx stream-drop-while pred stream
37345 [R7RS stream]
37346 @c MOD util.stream
37347 @c EN
37348 Returns a stream that contains or excludes initial consecutive elements
37349 of @var{stream} that satisfy @var{pred}, respectively.
37350 @c JP
37351 それぞれ、@var{stream}の最初から連続する、@var{pred}を満たす要素だけからなる
37352 ストリームと、それらの要素を除いたストリームを返します。
37353 @c COMMON
37354
37355 @example
37356 (stream->list (stream-take-while even? (stream 2 4 6 1 4 2)))
37357 @result{} (2 4 6)
37358 (stream->list (stream-drop-while even? (stream 2 4 6 1 4 2)))
37359 @result{} (1 4 2)
37360 @end example
37361 @end defun
37362
37363 @defun stream-span pred stream
37364 @defunx stream-break pred stream
37365 @c MOD util.stream
37366 @c EN
37367 Return two streams; the first one consists of the initial consequent
37368 elements of @var{stream} that satisfy or dissatisfy @var{pred},
37369 and the second one is the rest of the stream.
37370 @c JP
37371 ふたつのストリームを返します。最初のストリームは、@var{stream}の最初から連続する、
37372 @var{pred}を満たす/満たさない要素からなるストリームで、
37373 二番目のストリームは残りのストリームです。
37374 @c COMMON
37375
37376 @example
37377 (map stream->list
37378 (values->list (stream-span even? (stream 2 4 6 1 4 2))))
37379 @result{} ((2 4 6) (1 4 2))
37380 (map stream->list
37381 (values->list (stream-break even? (stream 1 9 6 1 4 2))))
37382 @result{} ((1 9) (6 1 4 2))
37383 @end example
37384 @end defun
37385
37386
37387 @defun stream-any pred stream @dots{}
37388 @defunx stream-every pred stream @dots{}
37389 @c MOD util.stream
37390 @c EN
37391 The predicate @var{pred} is applied to each of the first elements of
37392 @var{stream} @dots{}, then second, and so on.
37393 When @var{pred} returns a true value, @code{stream-any} returns
37394 the value immediately without looking further.
37395 When @var{pred} returns @code{#f}, @code{stream-every} returns @code{#f}
37396 immediately without looking further.
37397
37398 If none of applications of @var{pred} returns a true value
37399 until one of the streams is exhausted, @code{stream-any} returns @code{#f}.
37400 If none of applications of @var{pred} returns @code{#f}
37401 until one of the streams is exhausted, @code{stream-every} returns
37402 the last result of @var{pred}.
37403 @c JP
37404 @var{pred}は、まず@var{stream} @dots{}それぞれの最初の要素を引数として、
37405 次にそれぞれの2番目の要素を引数として、と順次呼ばれます。
37406 @code{stream-any}は@var{pred}が真の値を返したらただちに評価を打ち切り、
37407 @var{pred}が返した値をそのまま返します。
37408 @code{stream-every}は@var{pred}が@code{#f}を返したらただちに
37409 評価を打ち切り、@code{#f}を返します。
37410
37411 streamのいずれかが終端に達するまでに@code{pred}が一度も真の値を返さなければ、
37412 @code{stream-any}は@code{#f}を返します。
37413 streamのいずれかが終端に達するまでに@code{pred}が一度も偽の値を返さなければ、
37414 @code{stream-every}は最後の@var{pred}の結果を返します。
37415 @c COMMON
37416
37417 @example
37418 (stream-any (^[x y] (and (> x y) (list x y)))
37419 (stream 1 2 3 4 5)
37420 (stream 3 3 3 3 3))
37421 @result{} (4 3)
37422
37423 (stream-every (^[x y] (and (> x y) (list x y)))
37424 (stream 6 6 6 6 6)
37425 (stream 1 2 3 4 5))
37426 @result{} (6 5)
37427 @end example
37428 @end defun
37429
37430 @defun stream-index pred stream @dots{}
37431 @c MOD util.stream
37432 @c EN
37433 The predicate @var{pred} is applied to each of the first elements of
37434 @var{stream} @dots{}, then second, and so on. If it returns a true
37435 value, @code{stream-index} returns immediately with the index.
37436 If @var{pred} never returns a true value until one of
37437 the streams is exhausted, @code{stream-index} returns #f.
37438 @c JP
37439 @var{pred}は、まず@var{stream} @dots{}それぞれの最初の要素を引数として、
37440 次にそれぞれの2番目の要素を引数として、と順次呼ばれます。
37441 @var{pred}が真の値を返したら@code{stream-index}は評価を打ち切り、
37442 そのインデックスを返します。
37443 streamのいずれかが終端に達するまでに@code{pred}が一度も真の値を返さなければ、
37444 @code{#f}が返されます。
37445 @c COMMON
37446
37447 @example
37448 (stream-index odd? (stream 2 4 6 7 8))
37449 @result{} 3
37450 @end example
37451 @end defun
37452
37453 @defun stream-member obj stream :optional elt=
37454 @defunx stream-memq obj stream
37455 @defunx stream-memv obj stream
37456 @c MOD util.stream
37457 @c EN
37458 Stream version of @code{member}, @code{memq}, and @code{memv}
37459 (@pxref{Other list procedures}). Search an element equivalent to
37460 @var{obj} from @var{stream}, and if it is found, returns a stream
37461 consists of the element and the rest of the stream.
37462 If no such element is found, @code{#f} is returned.
37463
37464 They differ regarding which equivalent procedure to be used;
37465 @code{stream-member} uses the given @var{elt=} procedure, or @code{equal?}
37466 if omitted, @code{stream-memq} uses @code{eq?}, and @code{stream-memv}
37467 uses @code{eqv?}.
37468 @c JP
37469 @code{member}, @code{memq}, @code{memv}のストリーム版です
37470 (@ref{Other list procedures}参照)。
37471 @var{obj}と等しい要素を@var{stream}から探し、見つかったその要素を含む
37472 残りのストリームを返します。要素がみつからなければ@code{#f}を返します。
37473
37474 これらの手続きの違いは等価判定述語です。@code{stream-member}は与えられた@var{elt=}か、
37475 省略された場合は@code{equal?}を使います。
37476 @code{stream-memq}は@code{eq?}を、@code{stream-memv}は@code{eqv?}を使います。
37477 @c COMMON
37478 @end defun
37479
37480 @defun stream-delete obj stream :optional elt=
37481 @c MOD util.stream
37482 @c EN
37483 Equivalent to @code{(stream-remove (cut elt= obj <>) stream)}, that is,
37484 returns a stream that is the same as input except @var{obj}s.
37485 If @var{elt=} is omitted, @code{equal?} is used.
37486 @c JP
37487 @code{(stream-remove (cut elt= obj <>) stream)}と等価です。
37488 すなわち、入力ストリームから@var{obj}と等しい要素を除いた要素を持つ
37489 ストリームを返します。
37490 @c COMMON
37491 @end defun
37492
37493 @defun stream-delete-duplicates stream :optional elt=
37494 @c MOD util.stream
37495 @c EN
37496 Returns a stream that is the same as input except the consecutive
37497 equivalent elements are removed but the first one.
37498 Elements are compared with @var{elt=}, defaulted to @code{equal?}.
37499 @c JP
37500 入力ストリームのうち、連続する等しい要素があればその最初以外のものを除いた
37501 ストリームを返します。
37502 要素は@var{elt=}で比較されます。省略時は@code{equal?}が使われます。
37503 @c COMMON
37504 @end defun
37505
37506 @defun stream-grep re stream
37507 @c MOD util.stream
37508 @c EN
37509 The @var{re} argument must be a regexp object, or a string representation
37510 of regexp (which is converted to regexp by @code{string->regexp}).
37511
37512 Returns a stream that contains input elements that matches @var{re}.
37513 @c JP
37514 @var{re}引数は正規表現オブジェクトか、その文字列表現でなければなりません
37515 (文字列の場合は@code{string->regexp}で正規表現に変換されます)。
37516
37517 入力ストリームの要素のうち、@var{re}にマッチするものだけを含むようなストリームを
37518 返します。
37519 @c COMMON
37520 @end defun
37521
37522 @defun write-stream stream :optional oport writer
37523 @c MOD util.stream
37524 @c EN
37525 Writes each element of @var{stream} to @var{oport}, using @var{writer}.
37526 When @var{oport} is omitted, the current output port is used.
37527 When @var{writer} is omitted, @code{write-char} is used.
37528
37529 No 'spacer' is written between elements.
37530 As the default suggests, this is most useful to write out a stream
37531 of characters.
37532 @c JP
37533 @var{stream}の各要素を@var{writer}を使って@var{oport}に書き出します。
37534 @var{oport}が省略された場合は現在の出力ポートが、
37535 @var{writer}が省略された場合は@code{write-char}が使われます。
37536
37537 要素の間には何も出力されません。既定値が示すように、
37538 この手続きは文字の遅延ストリームを表示するのに便利です。
37539 @c COMMON
37540 @end defun
37541
37542 @c ----------------------------------------------------------------------
37543 @node Temporal relation, Topological sort (legacy), Stream library, Library modules - Utilities
37544 @section @code{util.temporal-relation} - Temporal relation
37545 @c NODE 時間的関係, @code{util.temporal-relation} - 時間的関係
37546
37547 @deftp {Module} util.temporal-relation
37548 @mdindex util.temporal-relation
37549 @c EN
37550 Procedures to find relation between two temporal intervals,
37551 or a temporal interval and a point in time.
37552 @c JP
37553 二つの時間間隔、もしくは時間間隔と時刻の関係を調べる手続きを提供します。
37554 @c COMMON
37555
37556 @c EN
37557 A temporal interval is represented by two points in time,
37558 @var{lesser} bound and @var{greater} bound. This module does not define
37559 a concrete structure for temporal intervals. Instead, the user
37560 provides a @emph{interval protocol}, which specifies how to
37561 access start/end time and how to compare them.
37562 @c JP
37563 時間間隔は、開始時刻(@emph{lesser bound})と終了時刻(@emph{greater bound})
37564 で表されるオブジェクトです。
37565 このモジュールは、時間間隔についての具体的なデータ構造は定めません。
37566 代わりに、ユーザは自分の好みのデータ構造が時間間隔として
37567 扱えるような@emph{時間間隔プロトコル}を提供します。
37568 @emph{時間間隔プロトコル}は、時間間隔の開始時刻と終了時刻へのアクセサおよび
37569 時間の比較方法をまとめたものです。
37570 @c COMMON
37571
37572 @c EN
37573 Given two temporal intervals x and y, there are 13 possible relations
37574 (the terms are taken from Haskell Rampart library
37575 @url{https://hackage.haskell.org/package/rampart-2.0.0.0/docs/Rampart.html}):
37576 @c JP
37577 二つの時間間隔xとyがある時、その関係は13種類に分類できます
37578 (用語はHaskellのRampartライブラリから取りました
37579 @url{https://hackage.haskell.org/package/rampart-2.0.0.0/docs/Rampart.html}):
37580 @c COMMON
37581
37582 @example
37583 |<-- x -->|
37584 |<-- y -->| x before y
37585
37586 |<-- x -->|
37587 |<-- y -->| x meets y
37588
37589 |<--- x ---->|
37590 |<-- y -->| x overlaps y
37591
37592 |<------ x ------->|
37593 |<-- y -->| x finished-by y
37594
37595 |<------- x -------->|
37596 |<---- y ---->| x contains y
37597
37598 |<-- x -->|
37599 |<------ y ---->| x starts y
37600
37601 |<---- x ---->|
37602 |<---- y ---->| x equal y
37603
37604 |<----- x ----->|
37605 |<-- y -->| x started-by y
37606
37607 |<---- x ---->|
37608 |<--------y -------->| x during y
37609
37610 |<-- x -->|
37611 |<------ y ------->| x finishes y
37612
37613 |<-- x -->|
37614 |<----- y ---->| x overlapped-by y
37615
37616 |<-- x -->|
37617 |<-- y -->| x met-by y
37618
37619 |<-- x -->|
37620 |<-- y -->| x after y
37621 @end example
37622 @end deftp
37623
37624 @defun make-interval-protocol lesser greater :optional compare-points
37625 @c MOD util.temporal-relation
37626 @c EN
37627 Creates and returns an interval protocol. The @var{lesser} and
37628 @var{greater} arguments are procedures taking an user-defined interval
37629 object, and returns its lesser bound and greater bound, respectively.
37630 The @var{compare-points} argument is a procedure that takes two points of
37631 time, and must return either a negative real value (if the first point is before
37632 the second), zero (if two points are the same), or a positive real value
37633 (if the first point is after the second).
37634 @c JP
37635 時間間隔プロトコルを作って返します。
37636 @var{lesser}と@var{greater}は、ユーザが使いたい時間間隔オブジェクトを引数にとって
37637 それぞれ開始時刻と終了時刻を返す手続きです。
37638 @var{compare-points}は二つの時刻a, bを取り、aの方がbより時間的に前なら
37639 負の実数を、aとbが同時刻なら0を、aの方がbより時間的に後なら正の実数を返す
37640 手続きです。
37641 @c COMMON
37642
37643 @c EN
37644 The actual representation of time points are up to the caller.
37645 @c JP
37646 時刻をどう表現するかはユーザに任されます。
37647 @c COMMON
37648
37649 @c EN
37650 If the @var{compare-points} argument is omitted,
37651 the built-in @code{compare} procedure
37652 is used (@pxref{Comparison}). It is suffice for most scalar values;
37653 e.g. you may use real numbers, @code{<time>}, or @code{<date>} objects.
37654 @c JP
37655 @var{compare-points}が省略された場合は、
37656 組み込みの@code{compare}が使われます(@ref{Comparison}参照)。
37657 ほとんどのスカラー値はそれで充分です。
37658 例えば実数や、@code{<time>}オブジェクト、@code{<date>}オブジェクトなどはそのまま
37659 時刻を表す値として使えます。
37660 @c COMMON
37661 @end defun
37662
37663 @defvar pair-interval-protocol
37664 @c MOD util.temporal-relation
37665 @c EN
37666 Bound to @code{(make-interval-protocol car cdr)}; that is, an interval
37667 represented by cons of lesser bound and greater bound.
37668 @c JP
37669 @code{(make-interval-protocol car cdr)}の値に束縛されています。
37670 すなわち、開始時刻と終了時刻のペアで時間間隔を表すプロトコルです。
37671 @c COMMON
37672 @end defvar
37673
37674 @defun relation? obj
37675 @c MOD util.temporal-relation
37676 @c EN
37677 Returns @code{#t} iff @var{obj} is a symbol representing
37678 a temporal relation. Valid symbols are one of
37679 @code{before}, @code{meets}, @code{overlaps}, @code{finished-by},
37680 @code{contains}, @code{starts}, @code{equal}, @code{started-by},
37681 @code{during}, @code{finishes}, @code{overlapped-by}, @code{met-by}
37682 and @code{after}.
37683 @c JP
37684 @var{obj}が時間的関係を表すシンボルであれば@code{#t}を、そうでなければ
37685 @code{#f}を返します。有効なシンボルは以下のいずれかです:
37686 @code{before}, @code{meets}, @code{overlaps}, @code{finished-by},
37687 @code{contains}, @code{starts}, @code{equal}, @code{started-by},
37688 @code{during}, @code{finishes}, @code{overlapped-by}, @code{met-by},
37689 @code{after}。
37690 @c COMMON
37691 @end defun
37692
37693 @defun inverse rel
37694 @c MOD util.temporal-relation
37695 @c EN
37696 The argument must be a symbol representing a temporal relation
37697 (see @code{relation?} above for the valid symbols).
37698 This procedure returns its inverse relation; that is,
37699 @code{(relate _ x y)} @equiv{} @code{(inverse (relate _ y x))},
37700 where @code{_} is an interval protocol.
37701 @c JP
37702 引数@var{rel}は時間的関係を表すシンボルでなければなりません
37703 (有効なシンボルについては上の@code{relation?}の項を参照)。
37704 この手続きは、@var{rel}の逆になる関係を表すシンボルを返します。
37705 すなわち、@code{_}を時間間隔プロトコルとした時に、
37706 @code{(relate _ x y)} @equiv{} @code{(inverse (relate _ y x))}が常に成り立ちます。
37707 @c COMMON
37708
37709 @c EN
37710 An error is thrown if @var{rel} is not a valid relation.
37711 @c JP
37712 @var{rel}が有効な時間的関係でなければエラーが投げられます。
37713 @c COMMON
37714 @end defun
37715
37716 @defun relate proto x y
37717 @c MOD util.temporal-relation
37718 @c EN
37719 The @var{proto} argument is an interval protocol, and both @var{x} and @var{y}
37720 must be temporal intervals that is compatible to the protocol @var{proto}.
37721 @c JP
37722 @var{proto}は時間間隔プロトコル、@var{x}と@var{y}はそのプロトコルが有効な
37723 時間間隔でなければなりません。
37724 @c COMMON
37725
37726 @c EN
37727 The procedure returns a temporal relation, represented as one of
37728 the following symbols:
37729 @code{before}, @code{meets}, @code{overlaps}, @code{finished-by},
37730 @code{contains}, @code{starts}, @code{equal}, @code{started-by},
37731 @code{during}, @code{finishes}, @code{overlapped-by}, @code{met-by}
37732 and @code{after}.
37733 @c JP
37734 この手続きは二つの時間間隔の時間的関係を返します。返り値は次のシンボルのいずれかです:
37735 @code{before}, @code{meets}, @code{overlaps}, @code{finished-by},
37736 @code{contains}, @code{starts}, @code{equal}, @code{started-by},
37737 @code{during}, @code{finishes}, @code{overlapped-by}, @code{met-by},
37738 @code{after}。
37739 @c COMMON
37740 @end defun
37741
37742 @defun relate-point proto x point
37743 @c MOD util.temporal-relation
37744 @c EN
37745 The @var{proto} argument is an interval protocol, and @var{x} must
37746 be a temporal interval that implements the protocol. The @var{point}
37747 is a point of time, comparable by the compare-points procedure
37748 of the protocol.
37749 @c JP
37750 @var{proto}は時間間隔プロトコル、@var{x}はそのプロトコルが有効な時間間隔、
37751 @var{point}は@var{proto}の時刻比較手続きに渡せる時刻でなければなりません。
37752 @c COMMON
37753
37754 @c EN
37755 The possible relations are a subset of interval-interval relations:
37756 @c JP
37757 返される時間関係は、時間間隔と時間間隔の間の関係のサブセットになります。
37758 @c COMMON
37759
37760 @example
37761 |<-- x -->|
37762 p x before p
37763
37764 |<--- x --->|
37765 p x finished-by p
37766
37767 |<--- x --->|
37768 p x contains p
37769
37770 |<--- x --->|
37771 p x started-by p
37772
37773 |<-- x -->|
37774 p x after p
37775 @end example
37776 @end defun
37777
37778
37779 @c ----------------------------------------------------------------------
37780 @node Topological sort (legacy), Unification, Temporal relation, Library modules - Utilities
37781 @section @code{util.toposort} - Topological sort
37782 @c NODE トポロジカルソート(レガシー), @code{util.toposort} - トポロジカルソート
37783
37784 @deftp {Module} util.toposort
37785 @mdindex util.toposort
37786 @c EN
37787 Implements topological sort algorithm.
37788 @c JP
37789 トポロジカルソートのアルゴリズムを実装します。
37790 @c COMMON
37791
37792 @c EN
37793 SRFI-234 now defines a superset of the functionalities this module provides.
37794 New code should use it instead of this module (@pxref{Topological sorting}).
37795 @c JP
37796 今では、SRFI-234がこのモジュールの上位互換の機能を提供しています
37797 (@ref{Topological sorting}参照)。
37798 新しいコードはSRFI-234を使ってください。
37799 @c COMMON
37800 @end deftp
37801
37802 @defun topological-sort graph :optional eqproc
37803 @c MOD util.toposort
37804 @c EN
37805 Returns a topologically sorted list of nodes,
37806 when the node dependencies are specified by @var{graph}.
37807 @xref{Topological sorting}, for the details.
37808
37809 This procedure differs from SRFI-234's @code{topological-sort}
37810 in the following ways:
37811
37812 @itemize @bullet
37813 @item
37814 When @var{graph} contains cycles, this one raises an error,
37815 while SRFI-234's returns @code{#f}.
37816 @item
37817 The default of node comparison predicate @var{eqproc} is @code{eqv?},
37818 while in SRFI-234 it is @code{equal?}
37819 @item
37820 This one does not take the third argument.
37821 @end itemize
37822 @c JP
37823 @var{graph}によって指定される依存関係の元で、
37824 トポロジカルソートされたノードのリストを返します。
37825 @var{graph}の形式について詳しくは@ref{Topological sorting}を参照してください。
37826
37827 この手続きは、SRFI-234の@code{topological-sort}に比べて次の点で異なります。
37828
37829 @itemize @bullet
37830 @item
37831 @var{graph}が循環を含んでいた場合、SRFI-234は@code{#f}を返しますが、
37832 この手続きはエラーを投げます。
37833 @item
37834 ノード比較手続き@var{eqproc}のデフォルトは、SRFI-234では@code{equal?}ですが、
37835 この手続きでは@code{eqv?}です。
37836 @item
37837 この手続きは3番目の引数を取りません。
37838 @end itemize
37839 @c COMMON
37840 @end defun
37841
37842 @c ----------------------------------------------------------------------
37843 @node Unification, CGI utility, Topological sort (legacy), Library modules - Utilities
37844 @section @code{util.unification} - Unification
37845 @c NODE ユニフィケーション, @code{util.unification} - ユニフィケーション
37846
37847 @deftp {Module} util.unification
37848 @mdindex util.unification
37849 @c EN
37850 Implements unification algorithm.
37851 @c JP
37852 ユニフィケーションのアルゴリズムを実装します。
37853 @c COMMON
37854
37855 @c EN
37856 The base API operates on abstract trees, while it is
37857 agnostic to the actual representation of the tree.
37858 The caller passes comparators and operators along the trees
37859 to unify.
37860 @c JP
37861 基本APIは、抽象的な木に対して動作しますが、木が実際にどう実装されているかは
37862 関知しません。
37863 呼び出し側は、ユニファイする木といっしょに、比較器や操作手続きを渡します。
37864 @c COMMON
37865
37866 @c EN
37867 We assume the abstract tree has the following structure:
37868 @c JP
37869 抽象的な木は、次の構造を持っていると考えます。
37870 @c COMMON
37871
37872 @example
37873 Tree : Variable | Value | Tuple
37874 Tuple : @{ Tree ... @}
37875 @end example
37876
37877 @c EN
37878 Here, @code{@{...@}} just represents a sequence of trees.
37879 @c JP
37880 ここで、@code{@{...@}}は単に木の並びを表します。
37881 @c COMMON
37882
37883 @c EN
37884 A variable can be bound to a tree. A value can only match itself.
37885 @c JP
37886 変数(Variable)は木に束縛されます。値(Value)はそれ自身とのみマッチします。
37887 @c COMMON
37888
37889 @c EN
37890 To operate on this tree, we need the following comparators and procedures,
37891 which the API takes as arguments:
37892 @c JP
37893 この木を扱うために、APIは以下の比較器と手続きを引数として取ります。
37894 @c COMMON
37895
37896 @table @asis
37897 @item Variable comparator: @code{var-cmpr}
37898 @c EN
37899 A comparator to see if an item is a variable, and also
37900 check equality of two variables. It must be hashable.
37901 @xref{Basic comparators}, for the details of comparators.
37902 @c JP
37903 要素が変数であるかどうかを調べ、また二つの変数が同じかどうかを判定
37904 するための比較器です。ハッシュ可能でなければなりません。
37905 比較器については@ref{Basic comparators}を参照してください。
37906 @c COMMON
37907 @item Value comparator: @code{val-cmpr}
37908 @c EN
37909 A comparator to see if an item is a value, and also
37910 check equality of two values.
37911 Note that if a tree satisfies neither @var{var-cmpr} nor @var{val-compr},
37912 it is regarded as a tuple.
37913 @c JP
37914 要素が値であるかどうかを調べ、また二つの値が等しいかどうかを
37915 判定するための比較器です。@var{var-cmpr}も@var{val-cmpr}も
37916 満たさない要素はタプルであるとみなされます。
37917 @c COMMON
37918 @item Tuple folder: @code{tuple-fold}
37919 @c EN
37920 A procedure @code{(tuple-folde proc seed tuple1 [tuple2])}.
37921 This procedure should work like @code{fold} (@pxref{Walking over lists})
37922 over the elements in the tuple(s). It is only called with
37923 either one or two tuples.
37924 @c JP
37925 @code{(tuple-folde proc seed tuple1 [tuple2])}の形で呼び出される手続きです。
37926 この手続きは、タプル中の要素について@code{fold}のように動作します
37927 (@ref{Walking over lists}参照)。常にひとつかふたつのタプルを引数とします。
37928 @c COMMON
37929 @item Tuple constructor: @code{make-tuple}
37930 @c EN
37931 A procedure @code{(make-tuple proto elements)}, where
37932 @var{proto} is a tuple and @var{elements} are a list of trees.
37933 It must return a new tuple with the given elements,
37934 while all other properties are the same as @var{proto}.
37935 This procedure isn't needed by @code{unify}.
37936 @c JP
37937 @code{(make-tuple proto elements)}の形式で呼び出される手続きです。
37938 @var{proto}はタプルで、@var{elements}は木のリストです。
37939 @var{proto}と同じ型のタプルで、要素だけを@var{elements}と置き換えた
37940 新たなタプルを作成して返します。
37941 @code{unify}はこの手続きを必要としません。
37942 @c COMMON
37943 @end table
37944 @end deftp
37945
37946 @defun unify a b var-cmpr val-cmpr tuple-fold
37947 @c MOD util.unification
37948 @c EN
37949 Unify two trees @var{a} and @var{b} and returns a substitution
37950 dictionary, which is a dictionary that maps variables
37951 to its bounded trees.
37952 @c JP
37953 二つの木、@var{a}と@var{b}を単一化し、置換辞書を返します。
37954 置換辞書は、変数をその値にマップするものです。
37955 @c COMMON
37956
37957 @c EN
37958 See the entry of @code{util.unification} above for the description
37959 of @var{var-cmpr}, @var{val-cmpr} and @var{tuple-fold}.
37960 @c JP
37961 引数@var{var-cmpr}、@var{val-cmpr}、@var{tuple-fold}に関しては
37962 上の@code{util.unification}の説明を参照してください。
37963 @c COMMON
37964
37965 @example
37966 (dict->alist (unify '(a 3 (c b)) '(c b (2 e))
37967 symbol-comparator
37968 number-comparator
37969 fold))
37970 @result{} ((e . 3) (a . c) (b . 3) (c . 2))
37971 @end example
37972
37973 @c EN
37974 As you can see in the example above,
37975 a variable may be mapped to another variable, or even to
37976 a tree that contains variables. If you apply the substitution
37977 to the original tree, you must do it recursively until all the
37978 variables in the dictionary is eliminated.
37979 @c JP
37980 この例にも見られるように、一つの変数の値が別の変数であったり、
37981 別の変数を含む木であったりする場合があります。
37982 元の木に置換を適用する場合は、辞書にある変数がすべて消去されるまで
37983 再帰的に置換を行う必要があります。
37984 @c COMMON
37985
37986 @c EN
37987 If two trees cannot be unified, @code{#f} is returned.
37988 @c JP
37989 二つの木が単一化できない場合は@code{#f}が返されます。
37990 @c COMMON
37991
37992 @example
37993 (unify '(a (a)) '(x x) symbol-comparator number-comparator fold)
37994 @result{} #f
37995 @end example
37996
37997 @end defun
37998
37999 @defun unify-merge a b var-cmpr val-cmpr tuple-fold make-tuple
38000 @c MOD util.unification
38001 @c EN
38002 Unify two trees @var{a} and @var{b}, and apply the result substitutions
38003 to create a new tree eliminating variables.
38004 @c JP
38005 二つの木、@var{a}と@var{b}を単一化し、結果の置換を適用して変数を消去した
38006 新たな木を返します。
38007 @c COMMON
38008
38009 @c EN
38010 See the entry of @code{util.unification} above for the description
38011 of @var{var-cmpr}, @var{val-cmpr}, @var{tuple-fold} and
38012 @var{make-tuple}.
38013 @c JP
38014 引数@var{var-cmpr}、@var{val-cmpr}、@var{tuple-fold}、@var{make-tuple}に関しては
38015 上の@code{util.unification}の説明を参照してください。
38016 @c COMMON
38017
38018 @example
38019 (unify-merge '(a 3 (c b)) '(c b (2 e))
38020 symbol-comparator
38021 number-comparator
38022 fold
38023 (^[_ elts] elts))
38024 @result{} (2 3 (2 3))
38025 @end example
38026
38027 @c EN
38028 If two trees can't be unified, @code{#f} is returned.
38029 @c JP
38030 二つの木が単一化できなければ、@code{#f}が返されます。
38031 @c COMMON
38032 @end defun
38033
38034
38035 @c ----------------------------------------------------------------------
38036 @node CGI utility, CGI testing, Unification, Library modules - Utilities
38037 @section @code{www.cgi} - CGI utility
38038 @c NODE CGIユーティリティ, @code{www.cgi} - CGIユーティリティ
38039
38040 @deftp {Module} www.cgi
38041 @mdindex www.cgi
38042 @c EN
38043 Provides a few basic functions useful to write a CGI script.
38044
38045 In order to write CGI script easily, you may want to use
38046 other modules, such as @code{rfc.uri} (@pxref{URI parsing and construction}),
38047 @code{text.html-lite} (@pxref{Simple HTML document construction}) and
38048 @code{text.tree} (@pxref{Lazy text construction}).
38049
38050 Note: it seems that there is no active formal specification for CGI.
38051 See @uref{http://w3c.org/CGI/} for more information.
38052 @c JP
38053 CGIスクリプトを書くのに便利ないくつかの基本的な手続きを提供します。
38054
38055 CGIスクリプトを手軽に書くにはこのモジュールの他に、
38056 @code{rfc.uri} (@ref{URI parsing and construction})、
38057 @code{text.html-lite} (@ref{Simple HTML document construction})、
38058 @code{text.tree} (@ref{Lazy text construction}) 等のモジュールを併せて
38059 使うとよいでしょう。
38060
38061 注:現在有効な、CGIに関する「正式な」仕様というのはどうも無いようです。
38062 @uref{http://w3c.org/CGI/}あたりを参照して下さい。
38063 @c COMMON
38064 @end deftp
38065
38066 @c EN
38067 @subheading Metavariables
38068 @c JP
38069 @subheading メタ変数
38070 @c COMMON
38071
38072 @deffn {Parameter} cgi-metavariables :optional metavariables
38073 @c MOD www.cgi
38074 @c EN
38075 Normally, httpd passes a cgi program various information
38076 via environment variables.
38077 Most procedures in @code{www.cgi} refer to them (meta-variables).
38078 However, it is sometimes inconvenient to require environment variable access
38079 while you're developing cgi-related programs.
38080 With this parameter, you can overrides the information of meta-variables.
38081
38082 @var{Metavariables} should be a list of two-element lists.
38083 Car of each inner list names the variable, and its cadr gives the
38084 value of the variable by string.
38085
38086 For example, the following code overrides @code{REQUEST_METHOD}
38087 and @code{QUERY_STRING} meta-variables during execution of
38088 @code{my-cgi-procedure}. (@xref{Parameters},
38089 for the details of @code{parameterize}).
38090 @c JP
38091 通常、httpdはcgiプログラムに様々な情報を環境変数経由で渡します。
38092 @code{www.cgi}中の多くの手続きはその情報(メタ変数)を参照します。
38093 しかし、cgiに関連するプログラムを開発中に環境変数にアクセスするのは
38094 不便な場合もあります。
38095 このパラメータを使うと、メタ変数をオーバライドすることができます。
38096
38097 @var{Metavariables}は2要素のリストのリストです。
38098 内側のリストは、最初の要素が変数名を、2つめの要素がその値を、それぞれ
38099 文字列で与えます。
38100
38101 例えば次のコードは@code{REQUEST_METHOD}と
38102 @code{QUERY_STRING}のメタ変数を@code{my-cgi-procedure}の実行期間中に
38103 上書きします。(@code{parameterize}の詳細については
38104 @ref{Parameters}を参照して下さい)。
38105 @c COMMON
38106
38107 @example
38108 (parameterize ((cgi-metavariables '(("REQUEST_METHOD" "GET")
38109 ("QUERY_STRING" "x=foo"))))
38110 (my-cgi-procedure))
38111 @end example
38112 @end deffn
38113
38114 @defun cgi-get-metavariable name
38115 @c MOD www.cgi
38116 @c EN
38117 Returns a value of cgi metavariable @var{name}.
38118 This function first searches the parameter @code{cgi-metavariables},
38119 and if the named variable is not found, calls @code{sys-getenv}.
38120
38121 CGI scripts may want to use @code{cgi-get-metavariable} instead
38122 of directly calling @code{sys-getenv}; doing so makes reuse of
38123 the script easier.
38124 @c JP
38125 @var{name}で指定されるCGIメタ変数の値を返します。
38126 この関数はまずパラメータ@code{cgi-metavariables}を探し、
38127 指定されたメタ変数が見つからなければ@code{sys-getenv}を呼びます。
38128
38129 CGIスクリプトは、なるべく@code{sys-getenv}を直接呼ぶのではなく
38130 @code{cgi-get-metavariable}を使うのが良いでしょう。
38131 スクリプトの再利用もしやすくなります。
38132 @c COMMON
38133 @end defun
38134
38135 @c EN
38136 @subheading Parameter extraction
38137 @c JP
38138 @subheading パラメータの取得
38139 @c COMMON
38140
38141 @defun cgi-parse-parameters :key :query-string :merge-cookies :part-handlers
38142 @c MOD www.cgi
38143 @c EN
38144 Parses query string and returns associative list of parameters.
38145 When a keyword argument @var{query-string} is given, it is used
38146 as a source query string. Otherwise, the function checks the
38147 metavariable @code{REQUEST_METHOD} and obtain the query string
38148 depending on the value (either from stdin or from the
38149 metavariable @code{QUERY_STRING}).
38150 If such a metavariable is not defined and
38151 the current input port is a terminal, the function prompts the user
38152 to type parameters; it is useful for interactive debugging.
38153 @c JP
38154 CGIプログラムに渡されたquery stringをパーズして、パラメータの連想リストにして
38155 返します。文字列がキーワード引数@var{query-string}に与えられればそれがパーズすべき
38156 query stringとなります。その引数が渡されなければこの手続きは
38157 メタ変数@code{REQUEST_METHOD}を参照し、その値によって標準入力もしくは
38158 メタ変数@code{QUERY_STRING}からquery stringが取られます。
38159 そのようなメタ変数が定義されておらず、かつ現在の入力ポートが端末である場合、
38160 インタラクティブにデバッグをしているものと考えて、
38161 この手続きはプロンプトを出してユーザにパラメータの入力を促します。
38162 @c COMMON
38163
38164 @c EN
38165 (If you need just to decompose URL query string, you can use
38166 @code{uri-decompose-query} in @code{rfc.uri} (@pxref{URI parsing and construction}).
38167 This procedure has more features useful for CGI scripting.)
38168 @c JP
38169 (単にURLクエリ文字列を分解したいだけなら、@code{rfc.uri}モジュールの
38170 @code{uri-decompose-query}を使うと良いでしょう
38171 (@ref{URI parsing and construction}参照)。
38172 この手続きはCGIスクリプトに便利な機能をたくさん追加しています。)
38173 @c COMMON
38174
38175 @c EN
38176 If @code{REQUEST_METHOD} is @code{POST}, this procedure can handle
38177 both @code{application/x-www-form-urlencoded} and
38178 @code{multipart/form-data} as the enctype. The latter is usually
38179 used if the form has file-uploading capability.
38180
38181 When the post data is sent by @code{multipart/form-data},
38182 each content of the part is treated as a value of the parameter.
38183 That is, the content of uploaded file will be seen as one big
38184 chunk of a string. The other information, such as the original file
38185 name, is discarded. If it is not desirable to read entire file
38186 into a string, you can customize the behavior by the @var{part-handler}
38187 argument. The details are explained in the "Handling file uploads"
38188 section below.
38189 @c JP
38190 @code{REQUEST_METHOD}が@code{POST}の場合、この手続きはenctypeとして
38191 @code{application/x-www-form-urlencoded}と@code{multipart/form-data}の
38192 両方を処理できます。後者は通常、ファイルアップロード機能を持つフォームに使われます。
38193
38194 POSTデータが@code{multipart/form-data}で送られて来た場合、
38195 各パートの内容がパラメータの値となります。すなわち、アップロードされた
38196 ファイルはその内容がひとつの文字列として得られることになります。
38197 元のファイル名のようなその他の情報は捨てられます。これが望ましい動作で
38198 ない場合は、@var{part-handlers}引数によって動作をカスタマイズすることができます。
38199 詳しくは下の「ファイルアップロードの処理」で説明します。
38200 @c COMMON
38201
38202 @c EN
38203 When a true value is given to @var{merge-cookies}, the cookie
38204 values obtained from the metavariable @code{HTTP_COOKIE}
38205 are appended to the result.
38206 @c JP
38207 キーワード引数@var{merge-cookies}に真の値が与えられた場合は、
38208 メタ変数@code{HTTP_COOKIE}からクッキーの値が読まれ、解析されて
38209 結果に追加されます。
38210 @c COMMON
38211
38212 @c EN
38213 Note that the query parameter may have multiple values,
38214 so @code{cdr} of each element in the result is a list, not an atom.
38215 If no value is given to the parameter, @code{#t} is placed as its value.
38216 See the following example:
38217 @c JP
38218 パラメータは複数の値を取り得るため、結果のパラメータに対応する値は常にリストになります。
38219 パラメータに値が与えられていなければ、結果のパラメータに対する値には@code{#t}が置かれます。
38220 次の例を参照して下さい。
38221 @c COMMON
38222 @example
38223 (cgi-parse-parameters
38224 :query-string "foo=123&bar=%22%3f%3f%22&bar=zz&buzz")
38225 @result{} (("foo" "123") ("bar "\"??\"" "zz") ("buzz" #t))
38226 @end example
38227 @end defun
38228
38229
38230 @defun cgi-get-parameter name params :key :default :list :convert
38231 @c MOD www.cgi
38232 @c EN
38233 A convenient function to obtain a value of the parameter @var{name} from
38234 parsed query string @var{params}, which is the value
38235 @code{cgi-parse-parameters} returns. @var{Name} should be a string.
38236 @c JP
38237 @code{cgi-parse-parameters}が返す、パーズされたQuery文字列@var{params}から、
38238 名前@var{name}を持つパラメータの値を簡単に取り出すための手続きです。
38239 @var{name}は文字列です。
38240 @c COMMON
38241
38242 @c EN
38243 Unless true value is given to @var{list}, the returned value is
38244 a scalar value. If more than one value is associated to @var{name},
38245 only the first value is returned. If @var{list} is true, the
38246 returned value is always a list, even @var{name} has only one value.
38247 @c JP
38248 キーワード引数@var{list}に真の値が与えられていなければ、
38249 返される値はスカラー値です。パラメータ@var{name}に複数の値が与えられた場合でも、
38250 最初の値のみが返されます。@var{list}に真の値が与えられれば、返されるのは
38251 常に値のリストとなります。
38252 @c COMMON
38253
38254 @c EN
38255 After the value is retrieved, you can apply a procedure to
38256 convert the string value to the appropriate type by giving
38257 a procedure to the @var{convert} argument. The procedure must
38258 take one string argument. If @var{list} is true, the convert
38259 procedure is applied to each values.
38260 @c JP
38261 キーワード引数@var{convert}に手続きを与えると、対応する値が取り出された後でその
38262 手続きが値を引数として呼ばれます。これによって値を文字列から必要な型へと変換することが
38263 できます。@var{list}に真の値が与えられている場合、変換手続きは各値に対して呼ばれ、
38264 その結果のリストが@var{cgi-get-parameter}から返されます。
38265 @c COMMON
38266
38267 @c EN
38268 If the parameter @var{name} doesn't appear in the query,
38269 a value given to the keyword argument @var{default} is returned;
38270 the default value of @var{default}
38271 is @code{#f} if @var{list} is false, or @code{()} otherwise.
38272 @c JP
38273 パラメータ@var{name}がQuery中に現れなかった場合は、
38274 @var{default}に与えられた値がそのまま
38275 返されます。@var{default}が省略された場合、@var{list}が偽であれば@code{#f}が、
38276 真であれば@code{()}が返されます。
38277 @c COMMON
38278 @end defun
38279
38280 @c EN
38281 @subheading Output generation
38282 @c JP
38283 @subheading 出力の生成
38284 @c COMMON
38285
38286
38287 @defun cgi-header :key status content-type location cookies
38288 @c MOD www.cgi
38289 @c EN
38290 Creates a text tree (@pxref{Lazy text construction}) for the
38291 HTTP header of the reply message. The most simple form is
38292 like this:
38293 @c JP
38294 HTTPリプライメッセージのヘッダを、テキストツリー形式(@ref{Lazy text construction}参照)
38295 で作成して返します。最も簡単な呼び出しでは次のようになります。
38296 @c COMMON
38297 @example
38298 (tree->string (cgi-header))
38299 @result{} "Content-type: text/html\r\n\r\n"
38300 @end example
38301
38302 @c EN
38303 You can specify alternative content-type by the keyword argument
38304 @var{content-type}. If you want to set cookies to the client,
38305 specify a list of cookie strings to the keyword argument @var{cookies}.
38306 You can use @code{construct-cookie-string} (@pxref{HTTP cookie handling})
38307 to build such a list of cookie strings.
38308 @c JP
38309 キーワード引数@var{content-type}によってContent typeを指定できます。
38310 また、@var{cookies}にクッキー文字列のリストを渡すことにより、
38311 クライアントにクッキーを設定できます。クッキー文字列を構築するには手続き
38312 @code{construct-cookie-string} (@ref{HTTP cookie handling}参照)
38313 が使えます。
38314 @c COMMON
38315
38316 @c EN
38317 The keyword argument @var{location} may be used to generate
38318 a @code{Location:} header to redirect the client to the specified URI.
38319 You can also specify the @code{Status:} header by the keyword argument
38320 @var{status}. A typical way to redirect the client is as follows:
38321 @c JP
38322 キーワード引数@var{location}は、@code{Location}ヘッダを作成して
38323 クライアントを別のURIに誘導するのに使えます。また、@code{Status}ヘッダを
38324 指定するために@var{status}キーワード引数が使えます。クライアントを
38325 別URIに転送するよくある方法は次のようなものです。
38326 @c COMMON
38327
38328 @example
38329 (cgi-header :status "302 Moved Temporarily"
38330 :location target-uri)
38331 @end example
38332
38333 @end defun
38334
38335 @deffn {Parameter} cgi-output-character-encoding :optional encoding
38336 @c MOD www.cgi
38337 @c EN
38338 The value of this parameter specifies the character encoding scheme (CES)
38339 used for CGI output by @code{cgi-main} defined below.
38340 The default value is Gauche's native encoding.
38341 If the parameter is set other than the native encoding, @code{cgi-main}
38342 converts the output
38343 encoding by @code{gauche.charconv} module
38344 (@pxref{Character code conversion}).
38345 @c JP
38346 このパラメータの値は次に説明する@code{cgi-main}が出力するデータの
38347 文字符合化法(CES)を指定します。デフォルトの値はGaucheのネイティブエンコーディング
38348 です。それ以外の値がセットされている場合、@code{cgi-main}は
38349 @code{gauche.charconv}モジュールを用いて出力のエンコーディングの変換を
38350 行います。
38351 (@ref{Character code conversion}参照)。
38352 @c COMMON
38353 @end deffn
38354
38355
38356 @c EN
38357 @subheading Convenience procedures
38358 @c JP
38359 @subheading 便利な手続き
38360 @c COMMON
38361
38362 @defun cgi-main proc :key on-error merge-cookies output-proc part-handlers
38363 @c MOD www.cgi
38364 @c EN
38365 A convenient wrapper function for CGI script.
38366 This function calls @code{cgi-parse-parameters}, then calls
38367 @var{proc} with the result of @code{cgi-parse-parameters}.
38368 The keyword argument @var{merge-cookies} is passed to
38369 @code{cgi-parse-parameters}.
38370 @c JP
38371 CGIスクリプトのための便利なラッパー手続きです。
38372 この手続きは、まず@code{cgi-parse-parameters}を呼び出してCGIスクリプトに
38373 渡されたパラメータを解析し、続いてその結果を引数として@var{proc}を呼び出します。
38374 キーワード引数@var{merge-cookies}は、与えられればそのまま
38375 @code{cgi-parse-parameters}に渡されます。
38376 @c COMMON
38377
38378 @c EN
38379 @var{proc} has to return a tree of strings
38380 (@pxref{Lazy text construction}), including the HTTP header.
38381 @code{cgi-main} outputs the returned tree to the current output port
38382 by @code{write-tree}, then returns zero.
38383 @c JP
38384 手続き@var{proc}はHTTPヘッダを含むドキュメントを
38385 テキストツリー構造(@ref{Lazy text construction}参照)で
38386 返さなければなりません。@code{cgi-main}はそれを@code{write-tree}を使って
38387 現在の出力ポートに書き出し、0を返します。
38388 @c COMMON
38389
38390 @c EN
38391 If an error is signaled in @var{proc}, it is caught and an HTML
38392 page reporting the error is generated. You can customize the
38393 error page by providing a procedure to the @var{on-error} keyword argument.
38394 The procedure takes an @code{<condition>} object (@pxref{Conditions}),
38395 and has to return a tree of string for the error reporting HTML
38396 page, including an HTTP header.
38397 @c JP
38398 もし@var{proc}内でエラーが起こった場合、そのエラーは捕捉されて、エラーを報告する
38399 HTMLページが作成されて出力されます。このエラーページは、@var{on-error}キーワード引数に
38400 手続きを渡すことでカスタマイズできます。@var{on-error}に渡された手続きは
38401 エラー発生時に@code{<condition>}オブジェクト(@ref{Conditions}参照)
38402 を引数として呼ばれ、HTTPヘッダを含むドキュメントをテキストツリー構造で返さねばなりません。
38403 @c COMMON
38404
38405 @c EN
38406 When output the result, @code{cgi-main} refers to
38407 the value of the parameter @code{cgi-output-character-encoding},
38408 and converts the character encoding if necessary.
38409 @c JP
38410 @code{cgi-main}は最終的な結果を出力を書き出す時に
38411 パラメータ@code{cgi-output-character-encoding}を参照し、
38412 必要ならば出力の文字エンコーディングを変換します。
38413 @c COMMON
38414
38415 @c EN
38416 The output behavior of @code{cgi-main} can be customized
38417 by a keyword argument @var{output-proc}; if it is given,
38418 the text tree (either the normal return value of @var{proc},
38419 or an error page constructed by the error handler) is passed
38420 to the procedure given to @var{output-proc}. The procedure
38421 is responsible to format and output a text to the current
38422 output port, including character conversions, if necessary.
38423 @c JP
38424 @code{cgi-main}の出力のふるまいはキーワード引数@var{output-proc}で
38425 カスタマイズできます。@var{output-proc}が渡された場合、それは
38426 @var{proc}の戻り値、あるいはエラーハンドラが作成したテキストツリー構造を
38427 受け取る手続きでなければなりません。その手続きはテキストツリーを
38428 フォーマットして現在の出力ポートに出力しなければなりません。
38429 必要ならば文字エンコーディングの変換もその手続き内で行います。
38430 @c COMMON
38431
38432 @c EN
38433 The keyword argument @var{part-handlers} are simply passed to
38434 @code{cgi-parse-parameters}, by which you can customize
38435 how the file uploads should be handled. See the "Handling file
38436 uploads" section below for the details.
38437
38438 If you specify to use temporary file(s) by it, @code{cgi-main}
38439 makes sure to clean up them whenever @var{proc} exits,
38440 even by error. See @code{cgi-add-temporary-file} below
38441 to utilize this feature for other purpose.
38442 @c JP
38443 キーワード引数@var{part-handlers}は、そのまま@code{cgi-parse-parameters}
38444 に渡されます。この引数によって、ファイルアップロードの際の動作をカスタマイズ
38445 できます。詳しくは下の「ファイルアップロードの処理」の項を参照して下さい。
38446
38447 この引数で、一時ファイルを使うように指定した場合、@code{cgi-main}は
38448 @var{proc}から抜ける際に(エラーでも正常終了でも)一時ファイルを
38449 消去します。この機能を他でも利用するには@code{cgi-add-temporary-file}の項を
38450 参考にして下さい。
38451 @c COMMON
38452
38453 @c EN
38454 Before calling @var{proc}, @code{cgi-main} changes the buffering mode
38455 of the current error port to @code{:line} (See @code{port-buffering}
38456 in @ref{Common port operations} for the details about the buffering mode).
38457 This makes the error output easier for web servers to capture.
38458 @c JP
38459 @var{proc}を呼ぶ前に、@code{cgi-main}はカレントエラーポートの
38460 バッファリングモードを@code{:line}に変更します。
38461 (バッファリングモードの詳細については@ref{Common port operations}の
38462 @code{port-buffering}の項を参照してください)。
38463 これはwebサーバがcgiスクリプトのエラー出力を捕捉しやすくするためです。
38464 @c COMMON
38465
38466 @c EN
38467 The following example shows the parameters given to the CGI program.
38468 @c JP
38469 以下の例はCGIに渡されたパラメータ全てをテーブルにして表示します。
38470 @c COMMON
38471
38472 @example
38473 #!/usr/local/bin/gosh
38474
38475 (use text.html-lite)
38476 (use www.cgi)
38477
38478 (define (main args)
38479 (cgi-main
38480 (lambda (params)
38481 `(,(cgi-header)
38482 ,(html-doctype)
38483 ,(html:html
38484 (html:head (html:title "Example"))
38485 (html:body
38486 (html:table
38487 :border 1
38488 (html:tr (html:th "Name") (html:th "Value"))
38489 (map (lambda (p)
38490 (html:tr
38491 (html:td (html-escape-string (car p)))
38492 (html:td (html-escape-string (x->string (cdr p))))))
38493 params))))
38494 ))))
38495 @end example
38496 @end defun
38497
38498
38499 @defun cgi-add-temporary-file filename
38500 @c MOD www.cgi
38501 @c EN
38502 This is supposed to be called inside @var{proc} of @code{cgi-main}.
38503 It registers @var{filename} as a temporary file, which should be
38504 unlinked when @var{proc} exits. It is a convenient way to ensure
38505 that your cgi script won't leave garbages even if it throws an error.
38506 It is OK in @var{proc} to unlink or rename @var{filename} after
38507 calling this procedure.
38508 @c JP
38509 この手続きは@code{cgi-main}に渡される@var{proc}中で呼ばれることを
38510 想定しています。
38511 この手続きは、@var{filename}を一時ファイルとして登録し、@var{proc}が
38512 終了する際に消去されるようにします。cgiスクリプトがエラー終了した場合
38513 などでもごみを残さないようにする便利な方法です。
38514 この手続きを呼んだ後で、@var{proc}が@var{filename}を消去したり
38515 名前を変えたりしても構いません。
38516 @c COMMON
38517 @end defun
38518
38519 @deffn {Parameter} cgi-temporary-files
38520 @c MOD www.cgi
38521 @c EN
38522 Keeps a list of filenames registered by @code{cgi-add-temporary-file}.
38523 @c JP
38524 @code{cgi-add-temporary-file}で登録された一時ファイルを保持するパラメータです。
38525 @c COMMON
38526 @end deffn
38527
38528 @c EN
38529 @subheading Handling file uploads
38530 @c JP
38531 @subheading ファイルアップロードの処理
38532 @c COMMON
38533
38534 @c EN
38535 As explained in @code{cgi-parse-parameters} above, file uploads
38536 are handled transparently by default, taking the file content
38537 as the value of the parameter. Sometimes you might want to change this
38538 behavior, for the file might be quite big and you don't want
38539 to keep around a huge chunk of a string in memory. It is possible to
38540 customize handling of file uploads of @code{cgi-parse-parameters}
38541 and @code{cgi-main} by @var{part-handlers} argument.
38542 (The argument is only effective for the form data submitted by
38543 @code{multipart/form-data} enctype)
38544 @c JP
38545 @code{cgi-parse-parameters}の項で説明したように、ファイルアップロードは
38546 デフォルトでは透過的に扱われます。すなわち、アップロードされた
38547 ファイルの内容がパラメータの値となります。
38548 これは望みの動作ではないかもしれません。例えばアップロードされるファイルが
38549 巨大であることが予想されるなら、それを全てメモリに読み込んで持ち回りたくは
38550 ないかもしれません。@code{cgi-parse-parameters}や@code{cgi-main}の
38551 @var{part-handlers}引数によって、ファイルアップロードの
38552 処理をカスタマイズすることが可能です。
38553 (この引数は、フォームデータが@code{multipart/form-data} enctypeで
38554 送られた場合にのみ意味を持ちます)。
38555 @c COMMON
38556
38557 @c EN
38558 The @var{part-handlers} argument is, if given, a list of lists;
38559 each inner list is a form of
38560 @code{(@var{name-pattern} @var{action} @var{kv-list} @dots{})}.
38561 Each uploaded file with a matching parameter name with @var{name-pattern} is
38562 handled according to @var{action}. (Here, a parameter name
38563 is the 'name' attribute given to the @code{input} element in the
38564 submitted form, not the name of the uploaded file).
38565 @c JP
38566 @var{part-handlers}引数が与えられている場合、それはリストのリストで、
38567 内部のリストは@code{(@var{name-pattern} @var{action} @var{kv-list} @dots{})} の形式で
38568 なければなりません。
38569 アップロードされたファイルは、そのパラメータ名が@var{name-pattern}に
38570 マッチした場合に@var{action}で指示されるように処理されます。
38571 (ここで、パラメータ名とはsubmitされたフォームの@code{input}要素に与えられた
38572 'name'属性のことです。アップロードされたファイルの名前ではありません)。
38573 @c COMMON
38574
38575 @c EN
38576 @var{Name-pattern} must be either a list of string (matches one of them),
38577 a regexp, or @code{#t} (matches anything).
38578 @c JP
38579 @var{name-pattern}は文字列のリストか、正規表現か、@code{#t}です。
38580 文字列のリストの場合はそれのいずれかとパラメータ名が等しければマッチと
38581 みなされます。@code{#t}は全てのものにマッチします。
38582 @c COMMON
38583
38584 @c EN
38585 @var{Action} must be either one of the followings:
38586 @table @code
38587 @item #f
38588 Default action, i.e. the content of the uploaded file is turned into
38589 a string and becomes the value of the parameter.
38590 @item ignore
38591 The uploaded content is discarded.
38592 @item file
38593 The uploaded content is saved in a temporary file. The value of
38594 the parameter is the pathname of the temporary file.
38595
38596 For this action, you can write an entry like
38597 @code{(@var{name-pattern} file @var{prefix})}, to specify the
38598 prefix of the pathname of the temporary file. For example, if you
38599 specify @code{("image" file "/var/mycgi/incoming/img")},
38600 the file uploaded as @code{"image"} parameter will be stored as
38601 something like @file{/var/mycgi/incoming/img49g2Ua}.
38602
38603 The application should move the temporary file to appropriate
38604 location; if you're using @code{cgi-main}, the temporary files
38605 created by this action will be unlinked when @code{cgi-main} exits.
38606
38607 @item file+name
38608 Like @code{file}, but the value of the parameter is a list of
38609 temporary filename and the filename passed by the client.
38610 It is useful if you want to use client's filename (but do not
38611 blindly assume the client sends a valid pathname; for example,
38612 you shouldn't use it to rename the uploaded file without
38613 validating it).
38614
38615 @item @var{procedure}
38616 In this case, @var{procedure} is called to handle the uploaded
38617 contents. It is called with four arguments:
38618 @code{(procedure @var{name} @var{filename} @var{part-info} @var{iport})}.
38619
38620 @var{Name} is the name of the parameter. @var{Filename} is
38621 the name of the original file (pathname in the client).
38622 @var{Part-info} is a @code{<mime-part>} object that keeps information
38623 about this mime part, and @var{iport} is where the body can be
38624 read from.
38625 For the details about these arguments,
38626 see @ref{MIME message handling}; you might be able to
38627 use procedures provided by @code{rfc.mime}, such as @code{mime-retrieve-body},
38628 to construct your own procedure.
38629
38630 If you create a temporary file in @var{procedure}, you can call
38631 @code{cgi-add-temporary-file} to make sure it is removed even if
38632 an error occurs during cgi processing.
38633 @end table
38634 @c JP
38635 @code{action}は次のいずれかの値でなければなりません。
38636 @table @code
38637 @item #f
38638 デフォルトのアクションです。すなわち、アップロードされたファイルの内容が
38639 文字列として読み込まれ、パラメータの値となります。
38640 @item ignore
38641 アップロードされたファイルの内容を無視します。
38642 @item file
38643 アップロードされたファイルの内容は一時ファイルへと格納されます。
38644 パラメータの値は、一時ファイルの名前となります。
38645
38646 このアクションを使う場合は、エントリを
38647 @code{(@var{name-pattern} file @var{prefix})} のように書くことも
38648 でき、その場合は@var{prefix}が一時ファイルのパス名のプリフィクスとして
38649 使われます。例えば@code{("image" file "/var/mycgi/incoming/img")}
38650 のようにしておくと、@code{"image"}パラメータとしてアップロードされた
38651 ファイルが@file{/var/mycgi/incoming/img49g2Ua}のような一時ファイルに
38652 格納されることになります。
38653
38654 アプリケーションは、この一時ファイルを(必要ならば)適切な場所に
38655 移動しなければなりません。@code{cgi-main}を用いている場合は、
38656 一時ファイルは@code{cgi-main}を抜ける際に(まだあれば)unlinkされます。
38657
38658 @item file+name
38659 @code{file}と同様ですが、パラメータの値が一時ファイル名と
38660 クライアントが送ってきたファイル名からなるリストになります。
38661 クライアントが送信したファイル名を利用したい場合に便利です
38662 (ただ、クライアントが常に正しいファイル名を送って来ると仮定しては
38663 いけません。例えば、アップロードされたファイルを
38664 チェック無しにクライアントが送ってきた名前にrenameするというような
38665 ことは避けてください)。
38666
38667
38668 @item @var{procedure}
38669 この場合、アップロードされた内容を処理するために、手続き@var{procedure}が
38670 呼ばれます。手続きは4つの引数を伴って呼ばれます:
38671 @code{(procedure @var{name} @var{filename} @var{part-info} @var{iport})}.
38672
38673 @var{name}はパラメータの名前、@var{filename}はオリジナルファイルの名前
38674 (クライアント側でのパス名)です。@var{part-info}は@code{<mime-part>}オブジェクトで、
38675 このMIMEパートの情報を保持しており、そして@var{iport}は内容を読むための入力ポートです。
38676 これらの引数の詳しい意味については@ref{MIME message handling}を
38677 参照して下さい。独自の@var{procedure}を書く際に、@code{rfc.mime}の
38678 @code{mime-retrieve-body}のような手続きが使えるかもしれません。
38679
38680 @var{procedure}内で一時ファイルを作る場合は、それを
38681 @code{cgi-add-temporary-file}で登録しておけば、cgi処理中に
38682 エラーが起きた場合でも一時ファイルが消去されるようにすることができます。
38683 @end table
38684 @c COMMON
38685
38686 @c EN
38687 If @var{kv-list} is given after @var{action}, it must be a
38688 keyword-value list and further modifies action. The following
38689 keywords are supported.
38690 @c JP
38691 @var{action}の後ろに@var{kv-list}が与えられた場合、それは
38692 キーワード-値リストでなければなりません。次のキーワードがサポートされています。
38693 @c COMMON
38694
38695 @table @code
38696 @item :prefix
38697 @c EN
38698 Valid only if @var{action} is either @code{file} or @code{file+name}.
38699 Specifies the prefix of the temporary file. If you give
38700 @code{:prefix "/tmp/foo"}, for example, the file is saved
38701 as something like @file{/tmp/fooxAgjeQ}.
38702 @c JP
38703 @var{action}が@code{file}か@code{file+name}の時のみ有効です。
38704 一時ファイルのプリフィクスを指定します。例えば@code{:prefix "/tmp/foo"}を
38705 与えると、ファイルは@file{/tmp/fooxAgjeQ}のような名前でセーブされます。
38706 @c COMMON
38707 @item :mode
38708 @c EN
38709 Valid only if @var{action} is either @code{file} or @code{file+name}.
38710 Specifies the mode of the temporary file in unix-style integer. By default
38711 it is @code{#o600}.
38712 @c JP
38713 @var{action}が@code{file}か@code{file+name}の時のみ有効です。
38714 一時ファイルのモードをunix式の整数で指定します。デフォルトは@code{#o600}です。
38715 @c COMMON
38716 @end table
38717
38718
38719 @c EN
38720 Note that the parameters that are not file uploads are not the subject
38721 of @var{part-handlers}; such parameter values are always turned into a string.
38722 @c JP
38723 ファイルアップロード以外のパラメータは@var{part-handlers}の対象外である
38724 ことに注意して下さい。それらのパラメータの値は常に文字列へと変換されます。
38725 @c COMMON
38726
38727
38728 @c EN
38729 Here's a short example. Suppose you have a form like this:
38730 @c JP
38731 簡単な例を示します。例えば次のようなフォームがあったとします。
38732 @c COMMON
38733
38734 @example
38735 <form enctype="multipart/form-data" method="POST" action="mycgi.cgi">
38736 <input type="file" name="imagefile" />
38737 <input type="text" name="description" />
38738 <input type="hidden" name="mode" value="normal" />
38739 </form>
38740 @end example
38741
38742 @c EN
38743 If you use @code{cgi-parse-parameters} in @file{mycgi.cgi}
38744 without @var{part-handlers} argument,
38745 you'll get something like the following as the result.
38746 (The actual values depend on how the web client filled the form).
38747 @c JP
38748 @file{mycgi.cgi}内で、@code{cgi-parse-parameters}を
38749 @var{part-handlers}引数なしで使った場合は、
38750 例えば次のようなリストがパラメータパージングの結果として得られるでしょう。
38751 (実際の値は、webクライアントがどのようにフォームを埋めたかに依存します)。
38752 @c COMMON
38753
38754 @example
38755 (("imagefile" #**".....(image file content as a string)....")
38756 ("description" "my image")
38757 ("mode" "normal"))
38758 @end example
38759
38760 @c EN
38761 If you pass @code{'(("imagefile" file :prefix "/tmp/mycgi"))}
38762 to @var{part-handlers}
38763 instead,
38764 you might get something like the following, with the
38765 content of uploaded file saved in @file{/tmp/mycgi7gq0B}
38766 @c JP
38767 ここでもし、@code{'(("imagefile" file :prefix "/tmp/mycgi"))}を
38768 @var{part-handlers}に
38769 渡したなら、替わりに次のような結果が得られるでしょう。
38770 ここで、アップロードされたファイルは@file{/tmp/mycgi7gq0B}にセーブ
38771 されていることになります。
38772 @c COMMON
38773
38774 @example
38775 (("imagefile" "/tmp/mycgi7gq0B")
38776 ("description" "my image")
38777 ("mode" "normal"))
38778 @end example
38779
38780 @c EN
38781 If you use a symbol @code{file+name} instead of @code{file} above,
38782 you'll get something like @code{("/tmp/mycgi7gq0B" "logo.jpg")} as
38783 the value of @code{"imagefile"}, where @code{"logo.jpg"} is the
38784 client-side filename. (Note: the client can send any string
38785 as the name of the file, so @emph{never} assume it is a valid
38786 pathname).
38787 @c JP
38788 上の例でシンボル@code{file}のかわりに@code{file+name}を使えば、
38789 例えば@code{"imagefile"}の値として@code{("/tmp/mycgi7gq0B" "logo.jpg")}
38790 のようなものが得られるでしょう。ここで@code{"logo.jpg"}は
38791 アップロードされたファイルのクライアント側でのパス名です。
38792 (注意:クライアントは任意の文字列をファイル名として送信することが
38793 できるため、その文字列が有効なパス名であることを仮定してはなりません。)
38794
38795 @c COMMON
38796
38797 @c @c EN
38798 @c Now, you pass the following structure to @var{part-handlers}:
38799 @c @c JP
38800 @c 次のような構造を@var{part-handlers}に渡した場合:
38801 @c @c COMMON
38802
38803 @c @example
38804 @c `(("imagefile"
38805 @c ,(lambda (name fname info iport)
38806 @c (receive (outp tmpfile) (sys-mkstemp "/var/log/mycgi/tmp")
38807 @c (mime-retrieve-body info iport outp)
38808 @c (close-output-port outp)
38809 @c (cgi-add-temporary-file tmpfile)
38810 @c (string-append fname ":" tmpfile))))
38811 @c )
38812 @c @end example
38813
38814 @c @c EN
38815 @c You'll get something like the following; i.e. the cgi application
38816 @c can see the client-side file name as well as the temporary file name.
38817 @c @c JP
38818 @c 例えば次のようなパーズ結果が得られるでしょう。つまり、
38819 @c cgiアプリケーションは一時ファイル名と同時に
38820 @c クライアント側でのファイル名も参照することができます。
38821 @c @c COMMON
38822
38823 @c @example
38824 @c (("imagefile" "logo.jpg:/var/log/mycgi/tmp820iQj")
38825 @c ("description" "my image")
38826 @c ("mode" "normal"))
38827 @c @end example
38828
38829
38830 @c ----------------------------------------------------------------------
38831 @node CGI testing, CSS parsing and construction, CGI utility, Library modules - Utilities
38832 @section @code{www.cgi.test} - CGI testing
38833 @c NODE CGIのテスト, @code{www.cgi.test} - CGIのテスト
38834
38835 @deftp {Module} www.cgi.test
38836 @mdindex www.cgi.test
38837 @c EN
38838 This module defines a useful procedures to test CGI script.
38839 The test actually runs the named script, with specified environment
38840 variable settings, and retrieve the output. Your test procedure
38841 then examine whether the output is as expected or not.
38842 @c JP
38843 CGIスクリプトをテストするための便利な手続きを定義しています。
38844 このテストは、指定された環境変数をセットし、実際にスクリプトを
38845 実行し、出力を取得します。ユーザのテスト手続きは、その出力が
38846 期待したものであるかどうかを検査します。
38847 @c COMMON
38848 @end deftp
38849
38850 @defun cgi-test-environment-ref envvar-name
38851 @defunx {(setter cgi-test-environment-ref)} envvar-name value
38852 @c MOD www.cgi.test
38853 @c EN
38854 The module keeps a table of default values of environment variables
38855 with which the cgi script will be run. These procedures allow
38856 the programmer to get/set those default values.
38857
38858 Note that you can override these default values and/or pass additional
38859 environment variables for each call of cgi script.
38860 @c JP
38861 モジュールにより、CGIスクリプトが実行される際の環境変数の
38862 デフォルト値のテーブルが保持されます。プログラマは、これらの
38863 手続きを使ってそのデフォルト値を取得したり設定したりできます。
38864
38865 CGIスクリプトの呼び出し毎に、これらのデフォルト値を上書きしたり、
38866 追加の環境変数を渡したりできます。
38867
38868 @c EN
38869 The following environment variables are set by default.
38870 @c JP
38871 デフォルトでは、下記の環境変数が設定されています。
38872 @c COMMON
38873 @multitable @columnfractions .5 .5
38874 @item Name @tab Value
38875 @item @code{SERVER_SOFTWARE}
38876 @tab @code{cgitest/1.0}
38877 @item @code{SERVER_NAME}
38878 @tab @code{localhost}
38879 @item @code{GATEWAY_INTERFACE}
38880 @tab @code{CGI/1.1}
38881 @item @code{SERVER_PROTOCOL}
38882 @tab @code{HTTP/1.1}
38883 @item @code{SERVER_PORT}
38884 @tab @code{80}
38885 @item @code{REQUEST_METHOD}
38886 @tab @code{GET}
38887 @item @code{REMOTE_HOST}
38888 @tab @code{remote}
38889 @item @code{REMOTE_ADDR}
38890 @tab @code{127.0.0.1}
38891 @end multitable
38892 @end defun
38893
38894 @defun call-with-cgi-script script proc :key (environment ()) (parameters #f)
38895 @c MOD www.cgi.test
38896 @c EN
38897 Runs a script with given environment, and calls @var{proc} with
38898 one argument, an input port which is connected to the pipe of script's
38899 standard output.
38900 @c JP
38901 与えられた環境でスクリプトを実行し、そのスクリプトの標準出力のパイプに
38902 接続された入力ポートを1つ引数に取る @var{proc} を呼び出します。
38903
38904 @c EN
38905 The argument @var{script} should be a list of
38906 program name and its arguments. Each element are
38907 passed to @code{x->string} first to stringify.
38908 @c JP
38909 引数 @var{script} は、プログラムの名前とその引数のリストでなければ
38910 なりません。リストの要素はそれぞれ、文字列化されるためにまず
38911 @code{x->string}に渡されます。
38912
38913 @c EN
38914 The script is run under the environment given by @var{environment}
38915 variable and the default test environment described above.
38916 The @var{environment} argument must be an associative list, in which each
38917 key (@code{car}) is the name of the environment variable and
38918 its @code{cdr} is the value. Both are passed to @code{x->string} first.
38919 If the same environment variable appears in @var{environment} and
38920 the default test environment, the one in @var{environment} is used.
38921 @c JP
38922 スクリプトは、変数 @var{environment} で与えられる環境と、上述した
38923 デフォルトのテスト環境の下で実行されます。
38924 @var{environment}は、キー(@code{car})がその環境変数の名前、
38925 @code{cdr}が対応する値であるような連想リストでなければなりません。
38926 両方ともまず @code{x->string} に渡されます。
38927 @var{environment} とデフォルトのテスト環境に同じ環境変数がある場合は、
38928 @var{environment} にあるものが使われます。
38929
38930 @c EN
38931 Additionally, if an associative list is given to the @var{parameters}
38932 argument, a query string is built from it and passed the script.
38933 The actual method to pass the query string depends on the value
38934 of @code{REQUEST_METHOD} environment variable in the setting.
38935 If @code{REQUEST_METHOD} is either @code{GET} or @code{HEAD},
38936 the query string is put in an environment variable @code{QUERY_STRING}.
38937 If it is @code{POST}, the query string is fed to the standard
38938 input of the script. In the latter case, @code{CONTENT_TYPE}
38939 is set to @code{application/x-www-form-urlencoded} and
38940 @code{CONTENT_LENGTH} are set to the length of @code{QUERY_STRING}
38941 automatically. If @code{REQUEST_METHOD} is other values,
38942 @var{parameters} is ignored.
38943 You can bypass this mechanism and set up environment variable
38944 @code{QUERY_STRING} directly, if you wish.
38945 @c JP
38946 さらに、引数 @var{parameters} に連想リストが渡された場合、そこから
38947 クエリストリングが作られスクリプトに渡されます。
38948 クエリストリングを渡す実際のメソッドは、環境変数 @code{REQUEST_METHOD}の
38949 値に依存します。@code{REQUEST_METHOD} が @code{GET} か @code{HEAD} で
38950 ある場合は、クエリストリングは環境変数 @code{QUERY_STRING} に置かれます。
38951 @code{REQUEST_METHOD} が @code{POST} の場合は、クエリストリングは
38952 スクリプトの標準入力から取得されます。後者の場合、@code{CONTENT_TYPE} には
38953 @code{application/x-www-form-urlencoded}が、
38954 @code{CONTENT_LENGTH} には @code{QUERY_STRING}の長さが、それぞれ自動的に
38955 セットされます。@code{REQUEST_METHOD} がその他の値の場合は、
38956 @var{parameters} は無視されます。
38957 必要であれば、このメカニズムをバイパスして、環境変数 @code{QUERY_STRING} を
38958 直接セットアップすることも可能です。
38959 @c COMMON
38960 @end defun
38961
38962 @defun run-cgi-script->header&body script reader :key environment parameters
38963 @c MOD www.cgi.test
38964 @c EN
38965 A convenient wrapper of @code{call-with-cgi-script}.
38966 The @var{script}, @var{environment} and @var{parameters} are passed
38967 to @code{call-with-cgi-script} as they are.
38968 The output of the script is parsed by
38969 @code{run-cgi-script->header&body}.
38970 First, the RFC2822 header fields are parsed by
38971 @code{rfc822-read-headers} (@pxref{RFC822 message parsing}).
38972 Then, the @var{reader} is called with an input port which
38973 is piped to the script's output.
38974 @c JP
38975 @code{call-with-cgi-script} の便利なラッパー手続きです。
38976 @var{script}、@var{environment}、@var{parameters}は、
38977 そのまま @code{call-with-cgi-script}に渡されます。
38978 スクリプトの出力は、@code{run-cgi-script->header&body}により
38979 パーズされます。
38980 最初に、RFC2822ヘッダフィールドが @code{rfc822-read-headers}
38981 (@ref{RFC822 message parsing}参照)によりパーズされます。
38982 次に、@var{reader}が、スクリプトの出力にパイプされた入力ポートと
38983 ともに呼ばれます。
38984
38985 @c EN
38986 @code{Run-cgi-script->header&body} returns two values,
38987 the list of headers (as parsed by @code{rfc822-read-headers}),
38988 and the return value of @var{reader}.
38989 @c JP
38990 @code{run-cgi-script->header&body}は、ヘッダのリスト
38991 (@code{rfc822-read-headers}によりパーズされたもの)と
38992 @var{reader}の戻り値の2つの値を返します。
38993 @c COMMON
38994 @end defun
38995
38996 @defun run-cgi-script->sxml script :key environment parameters
38997 @c MOD www.cgi.test
38998 @c EN
38999 This is a procedure that uses @code{ssax:xml->sxml}
39000 (@pxref{Functional XML parser}) as the @var{reader}
39001 in @code{run-cgi-script->header&body}.
39002 Useful when you're testing a cgi script that produces
39003 well-formed HTML and/or XML document.
39004 @c JP
39005 この手続きでは、@code{run-cgi-script->header&body}の
39006 @var{reader}として、@code{ssax:xml->sxml}
39007 (@ref{Functional XML parser}参照)を使います。
39008 整形式(Well-formed)のHTMLやXMLドキュメントを生成する
39009 CGIスクリプトをテストする場合に便利です。
39010 @c COMMON
39011 @end defun
39012
39013 @defun run-cgi-script->string script :key environment parameters
39014 @defunx run-cgi-script->string-list script :key environment parameters
39015 @c MOD www.cgi.test
39016 @c EN
39017 These procedures use @code{port->string}
39018 and @code{port->string-list}
39019 (@pxref{Input utility functions}) as the @var{reader}
39020 in @code{run-cgi-script->header&body}, respectively.
39021 @c JP
39022 これらの手続きは、@code{run-cgi-script->header&body}の
39023 @var{reader}として、それぞれ @code{port->string}、
39024 @code{port->string-list}を使います。
39025 @c COMMON
39026 @end defun
39027
39028 @c EN
39029 An example:
39030 @c JP
39031 例:
39032 @c COMMON
39033 @example
39034 (run-cgi-script->string-list "bbs.cgi"
39035 :environment '((REMOTE_ADDR . "12.34.56.78"))
39036 :parameters '((command . "view")
39037 (page . 1234)))
39038 @end example
39039
39040
39041 @c ----------------------------------------------------------------------
39042 @node CSS parsing and construction, , CGI testing, Library modules - Utilities
39043 @section @code{www.css} - CSS parsing and construction
39044 @c NODE CSSのパーズと構築, @code{www.css} - CSSのパーズと構築
39045
39046 @deftp {Module} www.css
39047 @c EN
39048 This module provides tools to convert between S-expression and CSS.
39049
39050 The S-expression CSS (SxCSS) is a convenient way to manipulate
39051 CSS in Scheme.
39052 @c JP
39053 このモジュールはS式とCSSを相互変換するツールを提供します。
39054
39055 S式CSS(SxCSS)はCSSをSchemeから操作するのに便利な方法です。
39056 @c COMMON
39057 @end deftp
39058
39059 @c EN
39060 For example, the following CSS and SxCSS are equivalent, and
39061 can be converted back and forth:
39062 @c JP
39063 例えば、次のCSSとSxCSSは等価で、相互に変換可能です。
39064 @c COMMON
39065
39066 CSS:
39067 @example
39068 body @{ padding-left: 11em;
39069 font-family: Georgia, "Times New Roman", Times, serif;
39070 color: purple;
39071 background-color: #d8da3d @}
39072 ul.navbar li @{ background: white;
39073 margin: 0.5em 0;
39074 padding: 0.3em;
39075 border-right: 1em solid black @}
39076 ul#spec > a @{ text-decoration: none @}
39077 a:visited @{ color: purple !important @}
39078 @end example
39079
39080 SxCSS:
39081 @example
39082 ((style-rule body
39083 (padding-left (11 em))
39084 (font-family (:or Georgia "Times New Roman" Times serif))
39085 (color purple)
39086 (background-color (color "d8da3d")))
39087 (style-rule ((ul (class navbar)) li)
39088 (background white)
39089 (margin #((0.5 em) 0))
39090 (padding (0.3 em))
39091 (border-right #((1 em) solid black)))
39092 (style-rule ((ul (id spec)) > a) (text-decoration none))
39093 (style-rule (a (: visited)) (color purple !important)))
39094 @end example
39095
39096 @c EN
39097 See the ``CSS in S-expression'' section below for the complete
39098 specification.
39099 @c JP
39100 完全な仕様については下の ``S式CSS'' を参照してください。
39101 @c COMMON
39102
39103 @c EN
39104 @subheading Constructing CSS
39105 @c JP
39106 @subheading CSSの構築
39107 @c COMMON
39108
39109 @defun construct-css sxcss :optional oport
39110 @c MOD www.css
39111 @c EN
39112 Take SxCSS and writes out CSS to the given port, defaulted to
39113 the current output port.
39114 @c JP
39115 SxCSSを取り、与えられたポートにCSSを書き出します。@var{oport}のデフォルトは
39116 現在の出力ポートです。
39117 @c COMMON
39118 @end defun
39119
39120 @c EN
39121 @subheading Parsing CSS
39122 @c JP
39123 @subheading CSSのパーズ
39124 @c COMMON
39125
39126 @defun parse-css :optional iport
39127 @c MOD www.css
39128 @c EN
39129 Read CSS from the given port, defaulted to the current input port,
39130 and returns SxCSS.
39131
39132 When it encounters unparsable CSS (either a malformed CSS, or
39133 unsupported syntax), it emits a warning message, ignore the
39134 unparsable part and tries to continue reading the rest.
39135
39136 NB: Currently we don't handle @code{@@charset} directive; we assume
39137 the text is already in the port's encoding. We may support
39138 it in future versions.
39139 @c JP
39140 CSSを与えられたポートから読み、SxCSSを返します。@var{iport}のデフォルトは
39141 現在の入力ポートです。
39142
39143 パーズできないCSS (不正なCSSか、サポートされていない構文) に出会った場合、
39144 warningメッセージを出力してその箇所を飛ばし、次にパーズできるところから処理を続けます。
39145
39146 註:今のところ、@code{@@charset}ディレクティブは無視され、
39147 入力テキストはポートのエンコーディングであると仮定されます。将来は対応するかもしれません。
39148 @c COMMON
39149 @end defun
39150
39151 @defun parse-css-file file :key encoding
39152 @c MOD www.css
39153 @c EN
39154 Read the CSS text from the given file and parse it using
39155 @code{parse-css}. Again, we don't handle @code{@@charset} directive
39156 yet, and you have to pass @code{encoding} argument if
39157 the CSS text isn't in the Gauche's native character encoding.
39158 @c JP
39159 与えられたファイルからCSSを読み、@code{parse-css}を使ってパーズして結果をSxCSSで
39160 返します。@code{@@charset}ディレクティブはまだ認識されないので、
39161 CSSファイルがGaucheのネイティブエンコーディングと異なるエンコーディングで書かれている
39162 場合は、@var{encoding}にエンコーディング名を渡してください。
39163 @c COMMON
39164 @end defun
39165
39166 @defun parse-css-selector-string str
39167 @c MOD www.css
39168 @c EN
39169 This parses the selector part of the CSS.
39170 @c JP
39171 CSSのセレクター部分をパーズするユーティリティです。
39172 @c COMMON
39173
39174 @example
39175 (parse-css-selector-string "ul li.item span#foo")
39176 @result{} (ul (li (class item)) (span (id foo)))
39177
39178 (parse-css-selector-string "h1,h2")
39179 @result{} (:or h1 h2)
39180 @end example
39181 @end defun
39182
39183 @c EN
39184 @subheading CSS in S-expression
39185 @c JP
39186 @subheading S式CSS
39187 @c COMMON
39188
39189 @c EN
39190 The following is the complete rules of SxCSS syntax.
39191 @c JP
39192 完全なSxCSSの構文規則を以下に示します。
39193 @c COMMON
39194
39195 @smallexample
39196 <sxcss> : (@{<style-rule> | <at-rule>@} ...)
39197
39198 <style-rule> : (style-rule <pattern> <declaration> ...)
39199 | (style-decls <declaration> ...)
39200
39201 <pattern> : <selector> | (:or <selector> ...)
39202 <selector> : <simple-selector>
39203 | <chained-selector>
39204 <chained-selector> : (<simple-selector> . (<op>? . <chained-selector>))
39205 <op> : > | + | ~
39206 <simple-selector> : <element-name>
39207 | (<element-name> <option> ...)
39208 <option> : (id <name>) ; E#id
39209 | (class <ident>) ; E.class
39210 | (has <ident>) ; E[attrib]
39211 | (= <ident> <attrib-value>) ; E[attrib=val]
39212 | (~= <ident> <attrib-value>) ; E[attrib~=val]
39213 | (:= <ident> <attrib-value>) ; E[attrib|=val]
39214 | (*= <ident> <attrib-value>) ; E[attrib*=val]
39215 | (^= <ident> <attrib-value>) ; E[attrib^=val]
39216 | ($= <ident> <attrib-value>) ; E[attrib$=val]
39217 | (:not <negation-arg>) ; E:not(s)
39218 | (: <ident>) ; E:pseudo-class
39219 | (: (<fn> <ident> ...)) ; E:pseudo-class(arg)
39220 | (:: <ident>) ; E::pseudo-element
39221 <element-name> : <ident> | *
39222 <attrib-value> : <ident> | <string>
39223 <negation-arg> | <element-name> | * | <option> ; except <negation-arg>
39224
39225 <declaration> : (<ident> <expr> <expr2> ... <important>?)
39226 <important> : !important
39227 <expr> : <term>
39228 | (/ <term> <term> ...)
39229 | (:or <term> <term> ...)
39230 | #(<term> <term> ...) ; juxtaposition
39231 <term> : <quantity> | (- <quantity>) | (+ <quantity>)
39232 | <string> | <ident> | <url> | <hexcolor> | <function>
39233 <quantity> : <number>
39234 | (<number> %)
39235 | (<number> <ident>)
39236 <url> | (url <string>)
39237 <hexcolor> | (color <string>) ; <string> must be hexdigits
39238 <function> | (<fn> <arg> ...)
39239 <arg> | <term> | #(<term> ...) | (/ <term> <term> ...)
39240
39241 <at-rule> : <at-media-rule> | <at-import-rule>
39242 ; NB: Other at-rules are not supported yet
39243 <at-media-rule> : (@@media (<symbol> ...) <style-rule> ...)
39244 <at-import-rule> : (@@import <string> (<symbol> ...))
39245 @end smallexample
39246
39247 @c EN
39248 NB: Negation op is @code{:not} instead of @code{not},
39249 since @code{(not <negation-arg>)}
39250 would be ambiguous from the simple node named "not" with one option.
39251 @c JP
39252 註: 否定オペレータは@code{not}ではなく@code{:not}です。
39253 というのは、@code{(not <negation-arg>)}だと ``not'' と言う名前を持ち
39254 一つのオプションを持つノードと区別できないからです。
39255 @c COMMON
39256
39257 @c EN
39258 NB: @code{style-decls} selector rule is currently won't appear in
39259 the @code{parse-css} output; it can be used in SxCSS to make
39260 @code{construct-css} render declarations only, which can be
39261 used in the @code{style} attribute of the document, for example.
39262 @c JP
39263 註: @code{style-decls}セレクタルールは@code{parse-css}の出力には
39264 現れません。
39265 ドキュメントの@code{style}属性に渡すCSS断片を生成したい場合に、
39266 @code{(style-decls <declaration> ...)}を@code{construct-css}に渡します。
39267 @c COMMON
39268 @example
39269 (with-output-to-string
39270 (cut construct-css
39271 '((style-decls (width (50 %))
39272 (padding #(0 (10 pt) 0 (10 pt)))))))
39273 @result{} "width:50%;padding:0 10pt 0 10pt"
39274 @end example
39275
39276 @c Local variables:
39277 @c mode: texinfo
39278 @c coding: utf-8
39279 @c end: