Debian Codegraph @

doc/modgauche.texi

raw
1 @node Library modules - Gauche extensions, Library modules - R7RS standard libraries, Library modules - Overview, Top
2 @chapter Library modules - Gauche extensions
3 @c NODE ライブラリモジュール - Gauche拡張モジュール
4
5 @c ----------------------------------------------------------------------
6 @menu
7 * Arrays:: gauche.array
8 * Importing gauche built-ins:: gauche.base
9 * Bitvector utilities:: gauche.bitvector
10 * Generating C code:: gauche.cgen
11 * Character code conversion:: gauche.charconv
12 * Collection framework:: gauche.collection
13 * Configuration parameters:: gauche.config
14 * Generating build files:: gauche.configure
15 * Connection framework:: gauche.connection
16 * Dictionary framework:: gauche.dictionary
17 * Low-level file operations:: gauche.fcntl
18 * Generators:: gauche.generator
19 * Hooks:: gauche.hook
20 * Interactive session:: gauche.interactive
21 * Lazy sequence utilities:: gauche.lazy
22 * Listener:: gauche.listener
23 * User-level logging:: gauche.logger
24 * Instance pools:: gauche.mop.instance-pool
25 * Propagating slot access:: gauche.mop.propagate
26 * Singleton:: gauche.mop.singleton
27 * Slot with validator:: gauche.mop.validator
28 * Networking:: gauche.net
29 * Package metainformation:: gauche.package
30 * Parameters (legacy):: gauche.parameter
31 * Parsing command-line options:: gauche.parseopt
32 * Partial continuations:: gauche.partcont
33 * High-level process interface:: gauche.process
34 * Record types:: gauche.record
35 * Reloading modules:: gauche.reload
36 * Simple dispatcher:: gauche.selector
37 * Sequence framework:: gauche.sequence
38 * Syslog:: gauche.syslog
39 * Terminal control:: gauche.termios
40 * Unit testing:: gauche.test
41 * Threads:: gauche.threads
42 * Measure timings:: gauche.time
43 * Unicode utilities:: gauche.unicode
44 * Uniform vector library:: gauche.uvector
45 * Comparing version numbers:: gauche.version
46 * Virtual ports:: gauche.vport
47 @end menu
48
49 @node Arrays, Importing gauche built-ins, Library modules - Gauche extensions, Library modules - Gauche extensions
50 @section @code{gauche.array} - Arrays
51 @c NODE 配列, @code{gauche.array} - 配列
52
53 @deftp {Module} gauche.array
54 @mdindex gauche.array
55 @c EN
56 This module provides multi-dimensional array data type and operations.
57 The primitive API follows SRFI-25.
58 Besides a generic SRFI-25 array that can store any Scheme objects,
59 this module also provides array classes that stores numeric objects
60 efficiently, backed up by
61 homogeneous numeric vectors (@pxref{Uniform vectors}).
62 An external representation of arrays, using SRFI-10 mechanism,
63 is also provided.
64 @c JP
65 このモジュールは多次元配列のデータタイプとそれに関する操作を提供します。
66 プリミティブなAPIはSRFI-25で定義されているものに従います。
67 任意のSchemeオブジェクトを保持できるSRFI-25の汎用配列の他に、
68 均一な数値ベクタ(@ref{Uniform vectors}参照)を使って
69 数値要素を効率良く保持する配列型も提供されます。
70 また、SRFI-10を使った配列の外部表現も実装されます。
71 @c COMMON
72
73 @c EN
74 Each element of an @var{N}-dimensional array can be accessed
75 by @var{N} integer indices,
76 @code{[ @var{i_0} @var{i_1} @dots{} @var{i_N-1} ]}.
77 An array has associated @var{shape} that knows lower-bound @var{s_k} and
78 upper-bound @var{e_k} of index of each dimension, where
79 @var{s_k} <= @var{e_k}, and the index @var{i_k} must satisfy
80 @var{s_k} <= @var{i_k} < @var{e_k}.
81 (Note: it is allowed to have @var{s_k} == @var{e_k}, but such array can't
82 store any data. It is also allowed to have zero-dimensional array,
83 that can store a single data.).
84 The shape itself is a [ @var{D} x 2 ] array, where @var{D} is the
85 dimension of the array which the shape represents.
86 @c JP
87 @var{N}次元の配列の各エレメントは@code{N}個の整数のインデックス
88 @code{[ @var{i_0} @var{i_1} @dots{} @var{i_N-1} ]}でアクセスされます。
89 配列は、各次元のインデックスの下限@var{s_k}および上限@var{e_k}を決める
90 @var{shape}を持っています。ここで、@var{s_k} <= @var{e_k}であり、
91 @var{k}次元目のインデックス@var{i_k}は
92 @var{s_k} <= @var{i_k} < @var{e_k} を満たすものとします。
93 (@var{s_k} == @var{e_k} であるような配列も作れますが、
94 その配列にはデータをストアすることはできません。
95 また、0次元の配列は作れます。それは一つだけデータを保持できます)。
96 Shapeはそれ自体が [ @var{D} x 2 ] の配列です。
97 ここで@var{D}はそのshapeが表現する配列の次元数です。
98 @c COMMON
99
100 @c EN
101 You can pass index(es) to array access primitives in a few ways;
102 each index can be passed as individual argument,
103 or can be 'packed' in a vector or one-dimensional array.
104 In the latter case, such a vector or an array is called an "index object".
105 Using a vector is efficient in Gauche when you iterate over the elements
106 by changing the vector elements, for it won't involve memory allocation.
107 @c JP
108 配列のプリミティブに対しインデックスを渡すにはいくつか方法があります。
109 各インデックスをばらばらの引数として渡すこともできますし、
110 ベクタや1次元の配列にパックして渡すこともできます。
111 後者においてインデックスがパックされたベクタや配列を「インデックスオブジェクト」
112 と呼ぶことがあります。Gaucheでは、配列の要素に次々とアクセスするような処理では
113 ベクタをインデックスオブジェクトとして使うと若干効率が良いでしょう。
114 @c COMMON
115
116 @c EN
117 Arrays can be compared by the @code{equal?} procedure.
118 @code{Equal?} returns @code{#t} if two arrays have the same
119 shape and their corresponding elements are the same
120 in the sense of @code{equal?}.
121 @c JP
122 配列は@code{equal?}手続きで比較することが出来ます。
123 二つの配列のshapeが等しく、また対応する各要素が@code{equal?}の意味で
124 等しい場合に二つの配列は@code{equal?}であると見なされます。
125 @c COMMON
126
127 @c EN
128 Internally, an array consists of a backing storage and a mapping procedure.
129 A backing storage is an object of aggregate type that can be accessed
130 by an integer index. A mapping procedure takes
131 multi-dimensional indices (or index object) and
132 returns a scalar index into the backing storage.
133 @c JP
134 内部的には、配列は1次元のインデックスでアクセスされるバッキングストレージと、
135 多次元のインデックスをバッキングストレージへのインデックスにマップする手続きとから
136 構成されています。
137 @c COMMON
138 @end deftp
139
140 @deftp {Class} <array-base>
141 @clindex array-base
142 @c MOD gauche.array
143 @c EN
144 An abstract base class of array types, that implements generic operations
145 on the array. To create an array instance,
146 you should use one of the following concrete array classes.
147 @c JP
148 配列に関する汎用操作を実装している、抽象ベースクラスです。
149 実際に配列のインスタンスを作るには、以下のいずれかの具体クラスを使って下さい。
150 @c COMMON
151 @end deftp
152
153 @deftp {Class} <array>
154 @deftpx {Class} <u8array>
155 @deftpx {Class} <s8array>
156 @deftpx {Class} <u16array>
157 @deftpx {Class} <s16array>
158 @deftpx {Class} <u32array>
159 @deftpx {Class} <s32array>
160 @deftpx {Class} <u64array>
161 @deftpx {Class} <s64array>
162 @deftpx {Class} <f16array>
163 @deftpx {Class} <f32array>
164 @deftpx {Class} <f64array>
165 @clindex array
166 @clindex u8array
167 @clindex s8array
168 @clindex u16array
169 @clindex s16array
170 @clindex u32array
171 @clindex s32array
172 @clindex u64array
173 @clindex s64array
174 @clindex f16array
175 @clindex f32array
176 @clindex f64array
177 @c MOD gauche.array
178 @c EN
179 Concrete array classes. The @code{<array>} class implements SRFI-25
180 compatible array, i.e. an array that can store any Scheme objects.
181 The @code{<u8array>} class through @code{<f64array>} classes uses
182 a @code{<u8vector>} through @code{<f64vector>} as a backing storage,
183 and can only store a limited range of integers or inexact real numbers,
184 but they are space efficient.
185 @c JP
186 具体配列クラスです。@code{<array>}クラスはSRFI-25互換の配列、
187 すなわち、任意のSchemeオブジェクトを格納できる配列を実装します。
188 @code{<u8array>}から@code{<f64array>}までは、
189 それぞれ@code{<u8vector>}から@code{<f64vector>}をバッキングストレージとして
190 用いる配列を実装し、制限された範囲の整数もしくは非正確な実数のみを
191 効率良く格納することができます。
192 @c COMMON
193 @end deftp
194
195
196 @deftp {Reader Syntax} @code{#,(<array> @var{shape} @var{obj} @dots{})}
197 @c EN
198 An array is written out in this format. (Substitute @code{<array>} for
199 @code{<u8array>} if the array is @code{<u8array>}, etc.)
200 @var{shape} is a list
201 of even number of integers, and each 2@var{n}-th integer
202 and 2@var{n}+1-th integer specifies the
203 inclusive lower-bound and exclusive upper-bound of @var{n}-th dimension,
204 respectively. The following @var{obj} @dots{} are the values in the array
205 listed in row-major order.
206 @c JP
207 配列はこの形式で書き出されます。
208 (配列が例えば@code{<u8array>}であるなら、@code{<array>}の部分は@code{<u8array>}
209 となります。)
210 @var{shape}は偶数個の整数のリストで、
211 2@var{n}番目の整数が@var{n}次元目のインデックスの下限を、2@var{n}+1番目の
212 整数が@var{n}次元目のインデックスの上限(+1)を表します。
213 その後に、配列の要素がrow-majorの順で書き出されます。
214 @c COMMON
215
216 @c EN
217 When read back, this syntax is read as an array with the same shape
218 and content, so it is @code{equal?} to the original array.
219 @c JP
220 この構文が読み込まれると、もとの配列と@code{equal?}である配列が作成されます。
221 @c COMMON
222
223 @example
224 @c EN
225 ; an array such that:
226 @c JP
227 ; 次のような配列:
228 @c COMMON
229 ; 8 3 4
230 ; 1 5 9
231 ; 6 7 2
232 #,(<array> (0 3 0 3) 8 3 4 1 5 9 6 7 2)
233
234 @c EN
235 ; a 4x4 identity matrix
236 @c JP
237 ; 4x4の単位行列
238 @c COMMON
239 #,(<array> (0 4 0 4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1)
240 @end example
241 @end deftp
242
243 @defun array? obj
244 [SRFI-25]
245 @c MOD gauche.array
246 @c EN
247 Returns @code{#t} if @var{obj} is an array, @code{#f} otherwise.
248 It is equivalent to @code{(is-a? obj <array-base>)}.
249 @c JP
250 @var{obj}が配列であれば@code{#t}が、そうでなければ@code{#f}が返されます。
251 @code{(is-a? obj <array-base>)}と等価です。
252 @c COMMON
253 @end defun
254
255 @defun make-array shape :optional init
256 [SRFI-25]
257 @c MOD gauche.array
258 @c EN
259 Creates an array of shape @var{shape}.
260 @var{Shape} must be a [ @var{D} x 2 ] array, and for each @var{k}
261 (0 <= @var{k} < @var{D}), the [ @var{k} 0 ] element must be less than or
262 equal to the [ @var{k} 1] element.
263 If @var{init} is given, all the elements are initialized by it.
264 Otherwise, the initial value of the elements are undefined.
265 @c JP
266 Shapeが@var{shape}である配列を作成します。
267 @var{Shape}は [ @var{D} x 2 ] の配列で、
268 0 <= @var{k} < @var{D} なる各@var{k}に対して要素 [ @var{k} 0 ] は
269 要素[ @var{k} 1 ]以下でなければなりません。
270 @var{init}が与えられた場合は、配列の各要素が@var{init}で初期化されます。
271 @var{init}が与えられなかった場合の配列の要素の初期値は不定です。
272 @c COMMON
273
274 @example
275 (make-array (shape 0 2 0 2 0 2) 5)
276 @result{} #,(<array> (0 2 0 2 0 2) 5 5 5 5 5 5 5 5)
277 @end example
278 @end defun
279
280 @defun make-u8array shape :optional init
281 @defunx make-s8array shape :optional init
282 @findex make-u16array
283 @findex make-s16array
284 @findex make-u32array
285 @findex make-s32array
286 @findex make-u64array
287 @findex make-s64array
288 @findex make-f16array
289 @dots{}
290 @end defun
291 @defun make-f32array shape :optional init
292 @defunx make-f64array shape :optional init
293 @c MOD gauche.array
294 @c EN
295 Like @code{make-array}, but creates and returns an uniform numeric array.
296 @c JP
297 @code{make-array}と似ていますが、均一な数値配列を返します。
298 @c COMMON
299 @end defun
300
301 @defun array-copy array
302 @c MOD gauche.array
303 @c EN
304 Returns a copy of @var{array}, with the same class, shape and
305 content.
306 @c JP
307 @var{array}と同じクラス、shape、内容を持つコピーを返します。
308 @c COMMON
309 @end defun
310
311 @defun shape bound @dots{}
312 [SRFI-25]
313 @c MOD gauche.array
314 @c EN
315 Takes even number of exact integer arguments, and returns
316 a two-dimensional array that is suitable for representing the shape
317 of an array.
318 @c JP
319 偶数個の正確な整数を引数に取り、配列のshapeとして使える2次元の配列を返します。
320 @c COMMON
321
322 @example
323 (shape 0 2 1 3 3 5)
324 @result{} #,(<array> (0 3 0 2) 0 2 1 3 3 5)
325
326 (shape)
327 @result{} #,(<array> (0 0 0 2))
328 @end example
329 @end defun
330
331 @defun array shape init @dots{}
332 [SRFI-25]
333 @c MOD gauche.array
334 @c EN
335 Creates an array of shape @var{shape}, initializing its elements by
336 @var{init} @dots{}.
337 @c JP
338 Shapeが@var{shape}であるような配列を作成し、
339 その要素を@var{init} @dots{}で初期化します。
340 @c COMMON
341
342 @example
343 (array (shape 0 2 1 3) 'a 'b 'c 'd)
344 @result{} #,(<array> (0 2 1 3) a b c d)
345 @end example
346 @end defun
347
348 @defun u8array shape init @dots{}
349 @defunx s8array shape init @dots{}
350 @findex u16array
351 @findex s16array
352 @findex u32array
353 @findex s32array
354 @findex u64array
355 @findex s64array
356 @findex f16array
357 @dots{}
358 @end defun
359 @defun f32array shape init @dots{}
360 @defunx f64array shape init @dots{}
361 @c MOD gauche.array
362 @c EN
363 Like @code{array}, but creates and returns an uniform numeric array
364 initialized by @var{init} @dots{}.
365 @c JP
366 @code{array}と同様ですが、@var{init} @dots{}で初期化された
367 均一な数値配列を返します。
368 @c COMMON
369
370 @example
371 (u8array (shape 0 2 0 2) 1 2 3 4)
372 @result{} #,(<u8array> (0 2 0 2) 1 2 3 4)
373 @end example
374 @end defun
375
376 @defun array-rank array
377 [SRFI-25]
378 @c MOD gauche.array
379 @c EN
380 Returns the number of dimensions of an array @var{array}.
381 @c JP
382 配列@var{array}の次元数を返します。
383 @c COMMON
384
385 @example
386 (array-rank (make-array (shape 0 2 0 2 0 2))) @result{} 3
387 (array-rank (make-array (shape))) @result{} 0
388 @end example
389 @end defun
390
391 @defun array-shape array
392 @c MOD gauche.array
393 @c EN
394 Returns a shape array of @var{array}.
395 @c JP
396 配列@var{array}のshapeを表す配列を返します。
397 @c COMMON
398 @end defun
399
400 @defun array-start array dim
401 @defunx array-end array dim
402 @defunx array-length array dim
403 [SRFI-25+]
404 @c MOD gauche.array
405 @c EN
406 @code{Array-start} returns the inclusive lower bound of index of
407 @var{dim}-th dimension of an array @var{array}.
408 @code{Array-end} returns the exclusive upper bound.
409 And @code{array-length} returns the difference between two.
410 @code{Array-start} and @code{array-end} are defined in SRFI-25.
411 @c JP
412 @code{array-start}は配列@var{array}の@var{dim}番目の次元の
413 インデックスの下限を返します。
414 @code{array-end}は上限+1を、そして@code{array-length}は両者の差を返します。
415 @code{array-start}と@code{array-end}はSRFI-25で定義されています。
416 @c COMMON
417
418 @example
419 (define a (make-array (shape 1 5 0 2)))
420
421 (array-start a 0) @result{} 1
422 (array-end a 0) @result{} 5
423 (array-length a 0) @result{} 4
424 (array-start a 1) @result{} 0
425 (array-end a 1) @result{} 2
426 (array-length a 1) @result{} 2
427 @end example
428 @end defun
429
430 @defun array-size array
431 @c MOD gauche.array
432 @c EN
433 Returns the total number of elements in the array @var{array}.
434 @c JP
435 配列@var{array}の全要素数を返します。
436 @c COMMON
437
438 @example
439 (array-size (make-array (shape 5 9 1 3))) @result{} 8
440 (array-size (make-array (shape))) @result{} 1
441 (array-size (make-array (shape 0 0 0 2))) @result{} 0
442 @end example
443 @end defun
444
445 @defun array-ref array k @dots{}
446 @defunx array-ref array index
447 [SRFI-25]
448 @c MOD gauche.array
449 @c EN
450 Gets the element of array @code{array}. In the first form,
451 the element is specified by indices @var{k} @dots{}.
452 In the second form, the element is specified by an index object
453 @var{index}, which must be a vector or an one-dimensional array.
454 @c JP
455 配列@var{array}の要素を取り出します。最初の形式では、
456 要素は整数のインデックス@var{k} @dots{}で指定されます。
457 2番目の形式では、要素はベクタまたは1次元配列のインデックスオブジェクト@var{index}
458 で指定されます。
459 @c COMMON
460 @end defun
461
462 @defun array-set! array k @dots{} value
463 @defunx array-set! array index value
464 [SRFI-25]
465 @c MOD gauche.array
466 @c EN
467 Sets the element of array @var{array} to @var{value}. In the first form,
468 the element is specified by indices @var{k} @dots{}.
469 In the second form, the element is specified by an index object
470 @var{index}, which must be a vector or an one-dimensional array.
471 @c JP
472 配列@var{array}の要素に@var{value}をセットします。
473 最初の形式では、
474 要素は整数のインデックス@var{k} @dots{}で指定されます。
475 2番目の形式では、要素はベクタまたは1次元配列のインデックスオブジェクト@var{index}
476 で指定されます。
477 @c COMMON
478 @end defun
479
480 @defun share-array array shape proc
481 [SRFI-25]
482 @c MOD gauche.array
483 @c EN
484 Creates and returns a new array of shape @var{shape}, that shares
485 the backing storage with the given array @var{array}.
486 The procedure @var{proc} maps the indices of the new array to
487 the indices to the original array, i.e. @var{proc} must be a @var{n}-ary
488 procedure that returns @var{m} values, where @var{n} is the dimension
489 of the new array and @var{m} is the one of the original array.
490 Furthermore, @var{proc} must be an affine function; each mapping
491 has to be a linear combination of input arguments plus optional constant.
492 (@code{Share-array} optimizes the mapping function based on the affinity
493 assumption, so @var{proc} won't be called every time the new array
494 is accessed).
495 @c JP
496 Shapeが@var{shape}であり、与えられた配列@var{array}とバッキングストレージを
497 共有する新しい配列を作成して返します。
498 @var{proc}は、新しい配列へのインデックスを古い配列へのインデックスへ
499 マップする手続きです。新しい配列の次元数を@var{n}、古い配列の次元数を@var{m}と
500 した時、@var{proc}は@var{n}個の引数を取り@var{m}個の値を返す手続きでなければ
501 なりません。さらに、各マッピングはaffineマッピング、すなわち、
502 出力は入力の線形合成(プラス定数)でなければなりません。
503 (@code{share-array}は@var{proc}がaffineマッピングであるという事実に基づいた
504 最適化を行います。新しい配列にアクセスする度に@var{proc}が呼ばれるというわけでは
505 ありません)。
506 @c COMMON
507 @end defun
508
509 @defun array-for-each-index array proc :optional index
510 @c MOD gauche.array
511 @c EN
512 Calls @var{proc} with every index of @var{array}.
513 If no @var{index} argument is provided, @var{proc} is called
514 as @code{(@var{proc} @var{i} @var{j} @var{k} @dots{})}, in which
515 (@var{i},@var{j},@var{k},@dots{}) walks over the index.
516 It begins from the least index value of each dimension, and
517 latter dimension is incremented faster.
518 @c JP
519 @var{array}の各インデックスに対して@var{proc}を呼びます。
520 @var{index}引数が省略された場合は、
521 @var{proc}はインデックス (@var{i}, @var{j},@var{k},@dots{}) に対して
522 @code{(@var{proc} @var{i} @var{j} @var{k} @dots{})} のように呼ばれます。
523 最初は各次元のインデックスの最小値から始まり、後の方の次元が優先的にインクリメントされます。
524 @c COMMON
525
526 @example
527 gosh> (define a (array (shape 0 2 0 2) 1 2 3 4))
528 a
529 gosh> a
530 #,(<array> (0 2 0 2) 1 2 3 4)
531 gosh> (array-for-each-index a (^(i j) (print i","j)))
532 0,0
533 0,1
534 1,0
535 1,1
536 @end example
537
538 @c EN
539 This form of passing indexes is simple but not very efficient, though.
540 For better performance,
541 you can pass an index object to an optional
542 argument @var{index},
543 which is modified for each index and passed to @var{proc}.
544 The index object must be mutable, and
545 either a vector, an one-dimensional array, an s8vector, an s16vector
546 or an s32vector. The length of the index object must match the
547 rank of the array. Using index object is efficient since the loop
548 won't allocate. Don't forget that the index object is destructively
549 modified within the loop.
550 @c JP
551 この形式の呼び出しは簡単なのですが、あまり効率が良くありません。
552 インデックスオブジェクトを省略可能引数@var{index}に渡すことで、
553 より良い性能を引き出すことができます。
554 インデックスオブジェクトはループの度に、各インデックスを表す値に書き換えられます。
555 インデックスオブジェクトに使えるのは、変更可能な、ベクタ・1次元の配列・
556 s8vector・s16vectorあるいはs32vectorで、その長さは配列@var{array}の
557 ランクと一致していなければなりません。インデックスオブジェクトを使うと、
558 ループ中に一切アロケーションが行われないため速度的に有利です。
559 ただし、ループの度にインデックスオブジェクトの内容が書き換えられることに
560 注意する必要があります。
561 @c COMMON
562
563 @example
564 gosh> (array-for-each-index a (cut format #t "~s\n" <>) (vector 0 0))
565 #(0 0)
566 #(0 1)
567 #(1 0)
568 #(1 1)
569
570 gosh> (array-for-each-index a (cut format #t "~s\n" <>) (s8vector 0 0))
571 #s8(0 0)
572 #s8(0 1)
573 #s8(1 0)
574 #s8(1 1)
575 @end example
576
577 @c EN
578 The procedure returns an unspecified value.
579 @c JP
580 戻り値は未定義です。
581 @c COMMON
582 @end defun
583
584 @defun shape-for-each shape proc :optional index
585 @c MOD gauche.array
586 @c EN
587 Calls @var{proc} with all possible indexes represented by the shape
588 @var{shape}.
589 The optional @var{index} argument works the same
590 way as @code{array-for-each-index}. Returns an unspecified value.
591 @c JP
592 シェイプ@var{shape}が表現する全ての可能なインデックスに対して@var{proc}を呼びます。
593 省略可能な@var{index}引数の動作は@code{array-for-each-index}と同様です。
594 戻り値は未定義です。
595 @c COMMON
596
597 @example
598 gosh> (shape-for-each (shape 0 2 0 2) (^(i j) (print i","j)))
599 0,0
600 0,1
601 1,0
602 1,1
603 @end example
604 @end defun
605
606 @defun tabulate-array shape proc :optional index
607 @c MOD gauche.array
608 @c EN
609 Calls @var{proc} over each index represented by the shape @var{shape},
610 and creates an array from the result of @var{proc}. The optional
611 index object can be used in the same way as @code{array-for-each-index}.
612 The following example creates an identity matrix of the given shape:
613 @c JP
614 @var{shape}が表現する各インデックスについて@var{proc}を呼び出し、
615 その戻り値から配列を構築して返します。省略可能なインデックスオブジェクトの用途は
616 @code{array-for-each-index}と同じです。
617 次の例は与えられたシェイプに対する単位行列を生成します:
618 @c COMMON
619
620 @example
621 (tabulate-array (shape 0 3 0 3) (^(i j) (if (= i j) 1 0)))
622 @result{} #,(<array> (0 3 0 3) 1 0 0 0 1 0 0 0 1)
623 @end example
624 @end defun
625
626 @defun array-retabulate! array proc :optional index
627 @defunx array-retabulate! array shape proc :optional index
628 @c MOD gauche.array
629 @c EN
630 Calls @var{proc} over each index of the given @var{array}, and
631 modifies the array's element by the returned value of @var{proc}.
632 The optional index object can be used in
633 the same way as @code{array-for-each-index}.
634 The second form takes a shape; it must match
635 the @var{array}'s shape. It is redundant, but may allow some
636 optimization in future in case @var{shape} is a literal.
637 Returns an unspecified value.
638 @c JP
639 配列@var{array}の各インデックスに対して@var{proc}を呼び、その戻り値で
640 @var{array}の要素を置き換えます。
641 省略可能なインデックスオブジェクトの用途は
642 @code{array-for-each-index}と同じです。
643 二番目の呼び出し形式は第二引数にシェイプを取ります。
644 それは@var{array}のシェイプと一致しなければなりません。
645 意味的には冗長ですが、@var{shape}がリテラルである場合、
646 何らかの最適化がなされる可能性があります。
647 戻り値は未定義です。
648 @c COMMON
649 @end defun
650
651 @defun array-map proc array0 array1 @dots{}
652 @defunx array-map shape proc array0 array1 @dots{}
653 @c MOD gauche.array
654 @c EN
655 The arguments @var{array0}, @var{array1}, @dots{} must be arrays
656 with the same shape. For each set of corresponding elements of
657 the input arrays, @var{proc} is called, and a new array of the
658 same shape is created by the returned values.
659 The second form takes a shape argument, which must match the
660 shape of input array(s). It is redundant, but may allow some
661 optimization in future in case @var{shape} is a literal.
662 @c JP
663 引数@var{array0}, @var{array1}, @dots{}は同じシェイプを持つ
664 配列でなければなりません。各入力配列の対応する要素について、
665 それらを引数として@var{proc}が呼ばれ、その戻り値から
666 新たな配列が作られて返されます。
667 二番目の呼び出し形式は第二引数にシェイプを取ります。
668 それは入力配列のシェイプと一致しなければなりません。
669 意味的には冗長ですが、@var{shape}がリテラルである場合、
670 何らかの最適化がなされる可能性があります。
671 @c COMMON
672
673 @example
674 (array-map - (array (shape 0 2 0 2) 1 2 3 4))
675 @result{} #,(<array> (0 2 0 2) -1 -2 -3 -4)
676 @end example
677 @end defun
678
679 @defun array-map! array proc array0 array1 @dots{}
680 @defunx array-map! array shape proc array0 array1 @dots{}
681 @c MOD gauche.array
682 @c EN
683 Like @code{array-map}, but the results of @var{proc} are stored by the
684 given @var{array}, whose shape must match the shape of input array(s).
685 Returns unspecified value.
686 @c JP
687 @code{array-map}と似ていますが、@var{proc}の結果は
688 与えられた@var{array}に格納されます。@var{array}のシェイプは
689 入力配列のシェイプと同じでなければなりません。
690 戻り値は未定義です。
691 @c COMMON
692 @end defun
693
694 @defun array->vector array
695 @defunx array->list array
696 @c MOD gauche.array
697 @c EN
698 Returns a fresh vector or a fresh list of all elements in @var{array}.
699 @c JP
700 @var{array}の全要素を並べたベクタもしくはリストを作って返します。
701 @c COMMON
702
703 @example
704 (array->vector
705 (tabulate-array (shape 1 3 1 4)
706 (^(i j) (+ (* 10 i) j))))
707 @result{} #(11 12 13 21 22 23)
708 @end example
709 @end defun
710
711 @defun array-concatenate a b :optional dimension
712 @c MOD gauche.array
713 @c EN
714 Concatenates arrays at the specified dimension. The sizes of the
715 specified dimension of two arrays must match, although the shapes
716 can be different. Arrays can be of any ranks, but two ranks must
717 match.
718 @c JP
719 指定の次元で配列を結合します。指定の次元の大きさは一致していなければなりません。
720 それ以外のシェイプは異なっていても構いません。配列のランクはいくつであっても
721 構いませんが、両配列のランクは同じでなければなりません。
722 @c COMMON
723
724 @example
725 ;; [a b] [a b]
726 ;; [c d] (+) => [c d]
727 ;; [e f] [e f]
728 (array-concatenate
729 (array (shape 0 2 0 2) 'a 'b 'c 'd)
730 (array (shape 0 1 0 2) 'e 'f))
731 @result{} #,(<array> (0 3 0 2) a b c d e f)
732
733 ;; [a b] [e] [a b e]
734 ;; [c d] (+) [f] => [c d f]
735 (array-concatenate
736 (array (shape 0 2 0 2) 'a 'b 'c 'd)
737 (array (shape 0 2 0 1) 'e 'f)
738 1)
739 @result{} #,(<array> (0 2 0 3) a b e c d f)
740
741 @c EN
742 ;; The index range can differ, as far as the sizes match
743 @c JP
744 ;; 結合次元の大きさが同じであればインデックスの範囲は異なっていてもよい
745 @c COMMON
746 (array-concatenate
747 (array (shape 0 2 0 2) 'a 'b 'c 'd)
748 (array (shape 1 3 0 1) 'e 'f) 1)
749 @result{} #,(<array> (0 2 0 3) a b e c d f)
750 @end example
751 @end defun
752
753 @defun array-transpose array :optional dim1 dim2
754 @c MOD gauche.array
755 @c EN
756 The given array must have a rank greater than or equal to 2.
757 Transpose the array's @var{dim1}-th dimension and
758 @var{dim2}-th dimension. The default is 0 and 1.
759 @c JP
760 @var{array}はランク2以上の配列でなければなりません。
761 配列の@var{dim1}番目の次元と@var{dim2}番目の次元を転置します。
762 デフォルトは0番目と1番目です。
763 @c COMMON
764 @end defun
765
766 @defun array-rotate-90 array :optional dim1 dim2
767 @c MOD gauche.array
768 @c EN
769 The given array must have a rank greater than or equal to 2.
770 We regard the array as a matrix with @var{dim1}-th dimension
771 as rows and @var{dim2}-th dimension as columns, and returns
772 a fresh array whose content is filled by @emph{rotating}
773 @var{array} 90 degree clockwise. The defaults of
774 @var{dim1} and @var{dim2} are 0 and 1, respectively.
775 @c JP
776 @var{array}はランク2以上の配列でなければなりません。
777 配列の@var{dim1}番目の次元と@var{dim2}番目の次元をそれぞれ行と列とみなした行列を
778 考え、その行列を時計まわりに90度回転した新たな配列を作って返します。
779 @c COMMON
780
781 @example
782 ;; [1 2 3] [4 1]
783 ;; [4 5 6] => [5 2]
784 ;; [6 3]
785 (array-rotate-90 (array (shape 0 2 0 3) 1 2 3 4 5 6))
786 @result{} #,(<array> (0 3 0 2) 4 1 5 2 6 3)
787 @end example
788
789 @c EN
790 If @var{array} has a rank greater than 2, the array is
791 treated as a matrix of subarrays.
792 @c JP
793 @var{array}のランクが2より大きい場合は、@var{array}は「部分配列の行列」
794 と考えられます。
795 @c COMMON
796 @end defun
797
798 @defun array-flip array :optional dimension
799 @defunx array-flip! array :optional dimension
800 @c MOD gauche.array
801 @c EN
802 Flips the content of the array across the @var{dimension}-th dimension.
803 (default is 0). @code{array-flip!} modifies the content of @var{array}
804 and return it. @code{array-flip} doesn't modify @var{array} but creates
805 a fresh array with the flipped content and returns it.
806 @c JP
807 配列の内容を、指定番目の次元 (デフォルトは0) で裏返しにします。
808 @code{array-flip!}は@var{array}を直接変更してそれを返します。
809 @code{array-flip}は@var{array}には触らず、裏返した内容で新たな配列を作って返します。
810 @c COMMON
811
812 @example
813 ;; [1 2 3] => [4 5 6]
814 ;; [4 5 6] [1 2 3]
815 (array-flip (array (shape 0 2 0 3) 1 2 3 4 5 6))
816 @result{} #,(<array> (0 2 0 3) 4 5 6 1 2 3)
817
818 ;; [1 2 3] => [3 2 1]
819 ;; [4 5 6] [6 5 4]
820 (array-flip (array (shape 0 2 0 3) 1 2 3 4 5 6) 1)
821 @result{} #,(<array> (0 2 0 3) 3 2 1 6 5 4)
822 @end example
823 @end defun
824
825 @defun identity-array dimension :optional class
826 @c MOD gauche.array
827 @c EN
828 Returns a fresh identity array of rank 2, with the given dimension.
829 You can pass one of array classes to @var{class} to make the result
830 the instance of the class; the default class is @code{<array>}.
831 @c JP
832 ランク2で行列ともに@var{dimension}である単位行列を作って返します。
833 配列のクラスを@var{class}に渡せば、結果はそのインスタンスになります。
834 デフォルトは@code{<array>}クラスです。
835 @c COMMON
836
837 @example
838 (identity-array 3)
839 @result{} #,(<array> (0 3 0 3) 1 0 0 0 1 0 0 0 1)
840
841 (identity-array 3 <f32array>)
842 @result{} #,(<f32array> (0 3 0 3) 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0)
843 @end example
844 @end defun
845
846 @defun array-inverse array
847 @c MOD gauche.array
848 @c EN
849 Regards the @var{array} as a matrix, and returns its inverse matrix;
850 @var{array} must be 2-dimensional, and must have square shape. If
851 @var{array} doesn't satisfy these conditions, an error is thrown.
852
853 If @var{array} isn't a regular matrix, @code{#f} is returned.
854 @c JP
855 @var{array}を行列とみなし、その逆行列を返します。
856 @var{array}は2次元で、正方行列となるシェイプを持っていなければなりません。
857 そうでない場合はエラーが投げられます。
858
859 @var{array}が正則行列でない場合は@code{#f}が返されます。
860 @c COMMON
861 @end defun
862
863 @defun determinant array
864 @defunx determinant! array
865 @c MOD gauche.array
866 @c EN
867 Regards the @var{array} as a matrix, and calculates its determinant;
868 @var{array} must be 2-dimensional, and must have square shape. If
869 @var{array} doesn't satisfy these conditions, an error is thrown.
870
871 @code{determinant!} destructively modifies the given array during
872 calculation. It is faster than @code{determinant}, which copies
873 @var{array} before calculation to preserve it.
874 @c JP
875 @var{array}を行列とみなし、その行列式を計算します。
876 @var{array}は2次元で、正方行列となるシェイプを持っていなければなりません。
877 そうでない場合はエラーが投げられます。
878
879 また、@code{determinant!}は計算過程で@var{array}の内容を破壊します。
880 @code{determinant}は計算の前に@var{array}をコピーするオーバヘッドが
881 ありますが、@var{array}は変更されません。
882 @c COMMON
883 @end defun
884
885 @defun array-mul a b
886 @c MOD gauche.array
887 @c EN
888 Arrays @var{a} and @var{b} must be rank 2. Regarding them
889 as matrices, multiply them together. The number of rows of @var{a}
890 and the number of columns of @var{b} must match.
891 @c JP
892 配列@var{a}と@var{b}はともに2次元でなければなりません。
893 それらを行列とみなして乗算を行います。@var{a}の行数と@var{b}の列数は
894 一致していなければなりません。
895 @c COMMON
896
897 @example
898 ;; [6 5]
899 ;; [1 2 3] x [4 3] => [20 14]
900 ;; [4 5 6] [2 1] [56 41]
901
902 (array-mul (array (shape 0 2 0 3) 1 2 3 4 5 6)
903 (array (shape 0 3 0 2) 6 5 4 3 2 1))
904 @result{} #,(<array> (0 2 0 2) 20 14 56 41)
905 @end example
906 @end defun
907
908 @defun array-expt array pow
909 @c MOD gauche.array
910 @c EN
911 Raises @var{array} to the power of @var{pow}; @var{array} must be
912 a square matrix, and @var{pow} must be a nonnegative exact integer.
913 @c JP
914 @var{array}の@var{pow}乗を返します。@var{array}は正方行列、
915 @var{pow}は非負の正確な整数でなければなりません。
916 @c COMMON
917 @end defun
918
919 @defun array-div-left a b
920 @defunx array-div-right a b
921 @c MOD gauche.array
922 @c EN
923 Inverse of @code{array-mul}; @code{array-div-left}
924 returns a matrix @code{M} such that @code{(array-mul B M)}
925 equals to @code{A}, and @code{array-div-right} returns
926 a matrix @code{M} such that @code{(array-mul M B)} equals to @code{A}.
927 @var{A} and @var{B} must be a 2-dimensional square matrix.
928 If @code{B} isn't regular, an error is thrown.
929 @c JP
930 @code{array-mul}の逆を行います。
931 @code{array-div-left}は@code{(array-mul B M)}が@code{A}と
932 等しくなるような行列@code{M}を、
933 @code{array-div-right}は@code{(array-mul M B)}が@code{A}と
934 等しくなるような行列@code{M}を返します。
935 @var{A}と@var{B}は2次元の正方行列でなければなりません。
936 @var{B}が正則行列でない場合はエラーが通知されます。
937 @c COMMON
938 @end defun
939
940 @defun array-add-elements array array-or-scalar @dots{}
941 @defunx array-add-elements! array array-or-scalar @dots{}
942 @defunx array-sub-elements array array-or-scalar @dots{}
943 @defunx array-sub-elements! array array-or-scalar @dots{}
944 @defunx array-mul-elements array array-or-scalar @dots{}
945 @defunx array-mul-elements! array array-or-scalar @dots{}
946 @defunx array-div-elements array array-or-scalar @dots{}
947 @defunx array-div-elements! array array-or-scalar @dots{}
948 @c MOD gauche.array
949 @c EN
950 Element-wise arithmetics. The second argument and after must
951 be an array of the same shape of the first argument, or a number;
952 if it is a number, it is interpreted as an array of the same shape
953 of the first argument, and each element of which is the given number.
954
955 Returns an array of the same shape of the first argument,
956 where each element is the result of addition, subtraction, multiplication
957 or division of the corresponding elements of the arguments.
958
959 The linear-update version (procedures whose name ends with @code{!})
960 may reuse the storage of the first array to calculate the result.
961 The first array must be mutable. The caller must still use the returned
962 value instead of counting on the side effects.
963 @c JP
964 要素ごとの計算をする手続きです。2つ目以降の引数は、
965 最初の引数の配列と同じ形の配列か、数値でなければなりません。
966 数値の場合は、要素が全てその数値である、最初の引数の配列と同じ形の配列だと解釈されます。
967
968 要素ごとに加算、減算、乗算、除算を行い、結果を最初の引数の配列と同じ形の配列で返します。
969
970 @code{!}で終わっている手続きは、最初の配列を結果を作るために再利用するかもしれません。
971 したがって最初の配列は変更可能である必要があります。ただし、必ず再利用されるとは
972 限らないので、呼び出し側は常に戻り値を使う必要があります。
973 @c COMMON
974
975 @example
976 (array-add-elements (array (shape 0 2 0 2) 1 2 3 4)
977 (array (shape 0 2 0 2) 5 6 7 8)
978 10)
979 @result{} #,(<array> (0 2 0 2) 16 18 20 22)
980
981 (array-div-elements (array (shape 0 2 0 2) 1 3 5 7)
982 100
983 (array (shape 0 2 0 2) 2 4 6 8))
984 @result{} #,(<array> (0 2 0 2) 1/200 3/400 1/120 7/800)
985 @end example
986
987 @c EN
988 If only one argument is passed, these procedures
989 returns the argument itself.
990 @c JP
991 ひとつだけ引数が渡された場合は、これらの手続きはその引数をそのまま返します。
992 @c COMMON
993
994 @c EN
995 You can mix different types of arrays as long as their shapes are
996 the same. The result is the same type as the first argument.
997 @c JP
998 形が同じであれば、異なる型の配列同士での演算もできます。
999 結果は最初の引数の配列の型になります。
1000 @c COMMON
1001
1002 @example
1003 (array-mul-elements (make-u8array (shape 0 2 0 2) 3)
1004 (array (shape 0 2 0 2) 1 3 5 7))
1005 @result{} #,(<u8array> (0 2 0 2) 3 9 15 21)
1006 @end example
1007 @end defun
1008
1009
1010 @defun array-negate-elements array
1011 @defunx array-negate-elements! array
1012 @c EN
1013 Returns an array with the same type of the shape of @var{array},
1014 but each element is a negation of the corresponding
1015 elements in the original array.
1016 @c JP
1017 @var{array}と同じ型、shapeだけれども各要素の符号が元の配列から反転されているような
1018 配列を返します。
1019 @c COMMON
1020
1021 @example
1022 (array-negate-elements (array (shape 0 2 0 2) 1 2 3 4))
1023 @result{} #,(<array> (0 2 0 2) -1 -2 -3 -4)
1024 @end example
1025 @end defun
1026
1027 @defun array-reciprocate-elements array
1028 @defunx array-reciprocate-elements! array
1029 @c EN
1030 Returns an array with the same type of the shape of @var{array},
1031 but each element is a reciprocal of the corresponding
1032 elements in the original array.
1033 @c JP
1034 @var{array}と同じ型、shapeだけれども各要素が元の配列の要素の逆数になっているような
1035 配列を返します。
1036 @c COMMON
1037
1038 @example
1039 (array-reciprocate-elements (array (shape 0 2 0 2) 1 2 3 4))
1040 @result{} #,(<array> (0 2 0 2) 1 1/2 1/3 1/4)
1041 @end example
1042 @end defun
1043
1044 @c ----------------------------------------------------------------------
1045 @node Importing gauche built-ins, Bitvector utilities, Arrays, Library modules - Gauche extensions
1046 @section @code{gauche.base} - Importing gauche built-ins
1047 @c NODE Gauche組み込み関数のインポート, @code{gauche.base} - Gauche組み込み関数のインポート
1048
1049 @deftp {Module} gauche.base
1050 @mdindex gauche.base
1051 @c EN
1052 This module exports Gauche built-in procedures and syntaxes, so that
1053 they can be imported to other modules that don't inherit @code{gauche} module.
1054
1055 All the bindings available in the @code{gauche} module are exported,
1056 except @code{import}, which is renamed to @code{gauche:import} to
1057 avoid conflict with R7RS @code{import}.
1058
1059 The module extends @code{gauche.keyword}, so
1060 also exports all the keywords---the bindings from @code{gauche.keyword}---
1061 so that the code imports @code{gauche.base} can access to self-bound keywords
1062 without inheriting the keyword module.
1063 @c JP
1064 このモジュールはGaucheの組み込み手続きと構文をexportし、
1065 @code{gauche}モジュールを継承しない他のモジュールからもimportして
1066 Gaucheの組み込み機能を使えるようにします。
1067
1068 @code{gauche}モジュールで見えるすべての束縛のうち、@code{import}を除いたものは
1069 そのままexportされます。@code{import}はR7RSの@code{import}との
1070 衝突を避けるため@code{gauche:import}としてexportされます。
1071
1072 このモジュールはまた、
1073 全てのキーワード(@code{gauche.keyword}モジュールにある
1074 束縛)もexportします。これで、Gauche関連のモジュールを継承しなくても
1075 @code{gauche.base}をimportすれば自己束縛したキーワードを使えます。
1076 @c COMMON
1077 @end deftp
1078
1079 @c EN
1080 Typical Gauche code doesn't need this module, for built-ins are available
1081 by default through inheritance.
1082 A newly created module @emph{inherits} the @code{gauche} module by default.
1083 (@xref{Module inheritance}, for the details.)
1084 @c JP
1085 通常のGaucheコードはこのモジュールを必要としません。組み込み関数はモジュール継承によって、
1086 何もしなくても使えるようになっています。
1087 新たに作られるモジュールは、何も指定しなければ@code{gauche}モジュールを
1088 継承するからです (詳しくは@ref{Module inheritance}参照)。
1089 @c COMMON
1090
1091 @c EN
1092 Sometimes you need a module that doesn't inherit the @code{gauche} module,
1093 yet you want to use Gauche built-in features. Particularly, R7RS libraries
1094 and programs require any bindings to be explicitly imported,
1095 so R7RS's @code{import} and @code{define-library} sets up the module not
1096 to inherit the @code{gauche} module. In R7RS code, you need
1097 @code{(import (gauche base))} to use Gauche's built-in features.
1098 @c JP
1099 しばしば、@code{gauche}モジュールを継承しないけれどGaucheの組み込み関数を使いたい
1100 という場合があります。特にR7RSライブラリとプログラムは、そこで使う束縛をすべて
1101 陽にimportする必要があります。従ってGaucheでも、R7RSの@code{import}と
1102 @code{define-library}は@code{gauche}モジュールを継承しないモジュールを設定します。
1103 R7RSコードでGaucheの組み込み機能を使うには、
1104 @code{(import (gauche base))}とする必要があります。
1105 @c COMMON
1106
1107 @c EN
1108 Another use case is to eliminate some built-in bindings, yet
1109 keep the rest of bindings accessible, in your module.
1110 For example, the following setup creates @code{almost-gauche} module
1111 that has almost all default bindings except @code{string-scan}
1112 and @code{string-split}:
1113 @c JP
1114 別の用途としては、自分のモジュールで、Gaucheの組み込み機能のうちいくつかを隠したい、
1115 といった場合があります。例えば次のコードは、Gaucheの組み込み機能のうち
1116 @code{string-scan}と@code{string-split}だけが見えない
1117 @code{almost-gauche}というモジュールを作ります。
1118 @c COMMON
1119
1120 @example
1121 (define-module almost-gauche
1122 (use scheme.r5rs)
1123 (use gauche.base :except (string-scan string-split)
1124 :rename ((gauche:import import)))
1125 (extend)
1126 )
1127 (select-module almost-gauche)
1128
1129 ;; your code here
1130 @end example
1131
1132 @c EN
1133 Note the empty @code{extend}; it empties the module's inheritance.
1134 (The @code{:rename} option of @code{gauche.base} is just to get
1135 the original name of @code{import} back in @code{almost-gauche} module;
1136 if you don't use @code{import} directly, you won't need it.)
1137 @c JP
1138 空の@code{extend}フォームに注目してください。このフォームで、
1139 モジュールの継承リストを空にします。
1140 (@code{gauche.base}の@code{:rename}オプションは、@code{almost-gauche}内で
1141 元の@code{import}の名前を使えるようにするためのものです。@code{import}を直接
1142 使わないのならこの@code{:rename}オプションは不要です。)
1143 @c COMMON
1144
1145 @c ----------------------------------------------------------------------
1146 @node Bitvector utilities, Generating C code, Importing gauche built-ins, Library modules - Gauche extensions
1147 @section @code{gauche.bitvector} - Bitvector utilities
1148 @c NODE ビットベクタユーティリティ, @code{gauche.bitvector} - ビットベクタユーティリティ
1149
1150 @c EN
1151 This module adds more operations on bitvectors.
1152 This module and built-in bitvector procedures covers SRFI-178
1153 Bitvector library interface (@pxref{Bitvector library})
1154 @c JP
1155 このモジュールは、ビットベクタを扱う多くの操作を提供します。
1156 このモジュールの手続きと組み込みのビットベクタ手続きは、SRFI-178のスーパーセットに
1157 なっています (@ref{Bitvector library}参照)。
1158 @c COMMON
1159
1160 @deftp {Module} gauche.bitvector
1161 @mdindex gauche.bitvector
1162 @c EN
1163 Gauche supports bitvectors as a native type, but the core library only
1164 offers a handful of primitives (@pxref{Bitvectors}).
1165 This module provides the comprehensive
1166 operations on bitvectors.
1167 @c JP
1168 Gaucheはビットベクタを組み込みでサポートしていますが、コアで提供されるのは
1169 ごく基本的な手続きのみです(@ref{Bitvectors}参照)。
1170 このモジュールではビットベクタに対する包括的な操作を提供します。
1171 @c COMMON
1172 @end deftp
1173
1174 @c EN
1175 @subheading Constructors
1176 @c JP
1177 @subheading コンストラクタ
1178 @c COMMON
1179
1180 @defun bitvector-unfold f length seed @dots{}
1181 @defunx bitvector-unfold-right f length seed @dots{}
1182 [SRFI-178]
1183 @c MOD gauche.bitvector
1184 @c EN
1185 Creates a bitvector of length @var{length}, and fill its contents by
1186 repeatedly applying @var{f}. The procedure @var{f} must take one more
1187 than the number of seeds, and must return the same number
1188 of values. First, @var{f} is applied to the index and @var{seed} @dots{},
1189 then its first return value (which must be a bit, i.e. 0, 1 or a boolean
1190 value) is used to initialize the index-th element of the bitvector,
1191 and the rest of the return value is used as the next argument to @var{f}.
1192 It is repeated @var{length} times.
1193 @c JP
1194 長さ@var{length}のビットベクタを作り、その内容を@var{f}を繰り返し呼ぶことで
1195 埋めて行きます。@var{f}は@var{seed} @dots{}に与えられた引数の数よりひとつ多い
1196 引数を取り、同じ数の戻り値を返します。まず、@var{f}はインデックスおよび@var{seed} @dots{}
1197 を引数として呼び出され、戻り値の最初の値(それはビット、すなわち0, 1, 真偽値のいずれかでなければなりません)がビットベクタのインデックス位置の値にセットされます。
1198 次の@var{f}は、新たなインデックスおよび残りの戻り値を引数として呼び出されます。
1199 これが@var{length}回繰り返されます。
1200 @c COMMON
1201
1202 @c EN
1203 While @code{bitvector-unfold} fills the bits from left to right,
1204 @code{bitvector-unfold-right} does from right to left.
1205 @c JP
1206 @code{bitvector-unfold}はビットを左から右に、
1207 @code{bitvector-unfold-right}は右から左に埋めて行きます。
1208 @c COMMON
1209
1210 @example
1211 (use math.prime)
1212 (bitvector-unfold (^[index n]
1213 (values (small-prime? n) (+ n 1)))
1214 20 0)
1215 @result{} #*00110101000101000101
1216 (bitvector-unfold-right (^[index n]
1217 (values (small-prime? n) (+ n 1)))
1218 20 0)
1219 @result{} #*10100010100010101100
1220 @end example
1221
1222 @c EN
1223 Note: This procedure follows the protocol of @code{vector-unfold}
1224 (@pxref{R7RS vectors}), and has a different protocol from other
1225 @code{unfold} procedures (@pxref{R7RS lists}).
1226 @c JP
1227 註: この手続きは@code{vector-unfold}のプロトコルに準じています (@ref{R7RS vectors}参照)。
1228 他の@code{unfold}のプロトコルとは異なることに注意してください (@ref{R7RS lists}参照)。
1229 @c COMMON
1230 @end defun
1231
1232 @defun bitvector-reverse-copy bv :optional start end
1233 [SRFI-178]
1234 @c MOD gauche.bitvector
1235 @c EN
1236 Copies a bitvector @var{bv} in reverse order. Optional @var{start}
1237 and @var{end} arguments limits the range of the input.
1238 @c JP
1239 ビットベクタ@var{bv}の、順序を逆にしたものを新に作って返します。
1240 省略可能な@var{start}と@var{end}引数は入力の範囲を制限します。
1241 @c COMMON
1242
1243 @example
1244 (bitvector-reverse-copy #*10110011100011110000 4 16)
1245 @result{} #*111100011100
1246 @end example
1247 @end defun
1248
1249 @defun bitvector-append bv @dots{}
1250 [SRFI-178]
1251 @c MOD gauche.bitvector
1252 @c EN
1253 All arguments must be bytevectors. Returns a fresh bytevector
1254 which is concatenation of all arguments.
1255 @c JP
1256 全ての引数はビットベクタでなければなりません。全てのビットベクタをつなげたビットベクタを
1257 新たに作って返します。
1258 @c COMMON
1259 @end defun
1260
1261 @defun bitvector-concatenate bvs
1262 [SRFI-178]
1263 @c MOD gauche.bitvector
1264 @c EN
1265 The argument must be a list of bitvectors. Returns a fresh bytevector
1266 which is concatenation of all bitvectors.
1267 @c JP
1268 引数はビットベクタのリストでなければなりません。
1269 その全てのビットベクタをつなげたビットベクタを新にたに作って返します。
1270 @c COMMON
1271 @end defun
1272
1273 @defun bitvector-append-subbitvectors bv start end @dots{}
1274 [SRFI-178]
1275 @c MOD gauche.bitvector
1276 @c EN
1277 The number of arguments must be a multiple of 3. Each triplet of
1278 the arguments is a bytevector followed by start and end index,
1279 specifying the input bytevector range. Returns a fresh bytevector
1280 which is concatenation of all the subvectors.
1281 @c JP
1282 引数の総数は3の倍数でなければなりません。それぞれの三つ組は、
1283 ビットベクタと、そのビットベクタに対する開始インデックス、終了インデックスです。
1284 それぞれのビットベクタの、インデックスで指定される範囲を抜き出したものを
1285 つなげたビットベクタを新たに作って返します。
1286 @c COMMON
1287
1288 @example
1289 (bitvector-append-subbitvectors
1290 #*11100011 2 6
1291 #*01010101 3 8)
1292 @result{} #*100010101
1293 @end example
1294 @end defun
1295
1296 @c EN
1297 @subheading Predicates
1298 @c JP
1299 @subheading 述語
1300 @c COMMON
1301
1302 @defun bitvector-emtpy? bv
1303 [SRFI-178]
1304 @c MOD gauche.bitvector
1305 @c EN
1306 Returns @code{#t} if @var{bv} is an empty bytevector,
1307 @code{#f} if it is a non-empty bitvector.
1308 An error is thrown if @var{bv} is not a bitvector.
1309 @c JP
1310 @var{bv}が空のビットベクタなら@code{#t}を、空でないビットベクタなら@code{#f}を返します。
1311 @var{bv}がビットベクタでなければエラーが投げられます。
1312 @c COMMON
1313 @end defun
1314
1315 @defun bitvector=? bv @dots{}
1316 [SRFI-178]
1317 @c MOD gauche.bitvector
1318 @c EN
1319 All arguments must be bitvectors.
1320 Returns @code{#t} iff all the bitvectors have the same length and content.
1321 If there's zero or one argument, it returns @code{#t}.
1322 @c JP
1323 全ての引数はビットベクタでなければなりません。
1324 全てのビットベクタが同じ長さ、同じ内容なら@code{#t}を、そうでなければ@code{#f}を返します。
1325 引数が0個もしくは1個の場合は@code{#t}を返します。
1326 @c COMMON
1327 @end defun
1328
1329 @c EN
1330 @subheading Iteration
1331 @c JP
1332 @subheading 繰り返し
1333 @c COMMON
1334
1335 @defun bitvector-take bv n
1336 @defunx bitvector-take-right bv n
1337 [SRFI-178]
1338 @c MOD gauche.bitvector
1339 @c EN
1340 Returns a new bitvector with the first/last @var{n} bits of a bitvector @var{bv}.
1341 An error is thrown if length of @var{bv} is less than @var{n}.
1342 @c JP
1343 ビットベクタ@var{bv}の最初から/終わりの@var{n}ビットを切り出した新たなビットベクタを
1344 返します。@var{bv}の長さが@var{n}より小さければエラーが投げられます。
1345 @c COMMON
1346
1347 @c EN
1348 In Gauche, you can also use generic @code{(subseq bv 0 n)} to take the
1349 first @var{n} bits. @xref{Sequence framework}.
1350 @c JP
1351 Gaucheではジェネリックな@code{(subseq bv 0 n)}で最初の@var{n}ビットを
1352 切り出すこともできます (@ref{Sequence framework}参照)。
1353 @c COMMON
1354 @end defun
1355
1356 @defun bitvector-drop bv n
1357 @defunx bitvector-drop-right bv n
1358 [SRFI-178]
1359 @c MOD gauche.bitvector
1360 @c EN
1361 Returns a new bitvector with bits except first/last @var{n} bits of
1362 a bitvector @var{bv}.
1363 An error is thrown if length of @var{bv} is less than @var{n}.
1364 @c JP
1365 ビットベクタ@var{bv}の最初から/終わりの@var{n}ビットを取り除いた新たなビットベクタを
1366 返します。@var{bv}の長さが@var{n}より小さければエラーが投げられます。
1367 @c COMMON
1368
1369 @c EN
1370 In Gauche, you can also use generic @code{(subseq bv n)}
1371 to drop the first @var{n} bits. @xref{Sequence framework}.
1372 @c JP
1373 Gaucheではジェネリックな@code{(subseq bv n)}で最初の@var{n}ビットを
1374 取り除いたビットベクタを得ることもできます (@ref{Sequence framework}参照)。
1375 @c COMMON
1376 @end defun
1377
1378 @defun bitvector-segment bv n
1379 [SRFI-178]
1380 @c MOD gauche.bitvector
1381 @c EN
1382 Slices a bitvector @var{bv} with @var{n}-bits each, and returns
1383 a list of bitvectors. If the length of @var{bv} isn't a multiple
1384 of @var{n}, the last bitvector may be shorter.
1385 @c JP
1386 ビットベクタ@var{bv}を@var{n}ビットごとの切片に切り分け、
1387 それぞれを新たなビットベクタにしたもののリストを返します。
1388 @var{bv}が@var{n}の倍数でなければ、最後のビットベクタは@var{n}ビット未満になります。
1389 @c COMMON
1390 @end defun
1391
1392 @defun bitvector-fold/int kons knil bv1 bv2 @dots{}
1393 @defunx bitvector-fold/bool kons knil bv1 bv2 @dots{}
1394 @defunx bitvector-fold-right/int kons knil bv1 bv2 @dots{}
1395 @defunx bitvector-fold-right/bool kons knil bv1 bv2 @dots{}
1396 [SRFI-178]
1397 @c MOD gauche.bitvector
1398 @c EN
1399 Fold @var{kons} over the elements of bitvectors with @var{knil} as
1400 the initial state value.
1401 @c JP
1402 状態値を受け渡しながら、@var{kons}をビットベクタの各要素に適用してゆきます。
1403 @var{knil}は最初の状態値です。
1404 @c COMMON
1405
1406 @c EN
1407 The @var{kons} procedure is always called as
1408 @code{(kons state e1 e2 @dots{})}, where @var{e1} @var{e2} @dots{}
1409 are elements from each bitvectors, as integer 0/1 (for @code{/int} procdures)
1410 or boolean @code{#f}/@code{#t} (for @code{/bool} procedures).
1411 This is the same order as @code{vector-fold} in
1412 @code{scheme.vector} module (@pxref{R7RS vectors}).
1413 (Note that list @code{fold} procedure calls the @var{kons} procedure
1414 with different order; @pxref{Walking over lists}).
1415 @c JP
1416 @var{kons}は@code{(kons state e1 e2 @dots{})}のように
1417 呼び出されます。ここで@var{e1} @var{e2} @dots{} は引数の各ビットベクタの対応する
1418 要素を取り出したものです (@code{/int}の手続きでは0/1、@code{/bool}の手続きでは
1419 @code{#f}/@code{#t})。
1420 これは@code{scheme.vector}モジュールの@code{vector-fold}と同じ引数順です
1421 (@ref{R7RS vectors})。
1422 (リストについての@code{fold}手続きでは@var{kons}手続きの最後の引数として
1423 状態値が渡されることに注意してください。@ref{Walking over lists}参照)。
1424 @c COMMON
1425
1426 @c EN
1427 All bitvectors must have the same length; otherwise, an error is thrown.
1428 @c JP
1429 引数の全てのビットベクタは同じ長さでなければなりません。
1430 そうでなければエラーが投げられます。
1431 @c COMMON
1432 @end defun
1433
1434 @defun bitvector-map/int f bv1 bv2 @dots{}
1435 @defunx bitvector-map/bool f bv1 bv2 @dots{}
1436 [SRFI-178]
1437 @c MOD gauche.bitvector
1438 @c EN
1439 Apply a procedure @var{f} over each element taken from given bitvectors.
1440 The result of the procedure is gathered as a fresh bitvector and returned.
1441 @c JP
1442 手続き@var{f}を与えられたビットベクタから取り出したビットに対して適用し、
1443 その結果を新たなビットベクタにまとめて返します。
1444 @c COMMON
1445
1446 @example
1447 (bitvector-map/int logand #*10101 #*00111)
1448 @result{} #*00101
1449 @end example
1450
1451 @c EN
1452 All bitvectors must have the same length; otherwise, an error is thrown.
1453 @c JP
1454 引数の全てのビットベクタは同じ長さでなければなりません。
1455 そうでなければエラーが投げられます。
1456 @c COMMON
1457 @end defun
1458
1459 @defun bitvector-map!/int f bv1 bv2 @dots{}
1460 @defunx bitvector-map!/bool f bv1 bv2 @dots{}
1461 [SRFI-178]
1462 @c MOD gauche.bitvector
1463 @c EN
1464 Apply a procedure @var{f} over each element taken from given bitvectors.
1465 The result of the procedure is set into @var{bv1}.
1466 @c JP
1467 手続き@var{f}を与えられたビットベクタから取り出したビットに対して適用し、
1468 その結果を@var{bv1}に破壊的代入します。
1469 @c COMMON
1470
1471 @c EN
1472 These procedure returns undefined value; you should count on the
1473 side effect onto @var{bv1}. In other words, they are not
1474 linear-updating procedures.
1475 @c JP
1476 これらの手続きは未定義値を返します。呼び出し側は@var{bv1}への副作用を使わなければ
1477 なりません。言い換えれば、これらの手続きは線形更新手続きではありません。
1478 @c COMMON
1479
1480 @c EN
1481 All bitvectors must have the same length; otherwise, an error is thrown.
1482 @c JP
1483 引数の全てのビットベクタは同じ長さでなければなりません。
1484 そうでなければエラーが投げられます。
1485 @c COMMON
1486 @end defun
1487
1488 @defun bitvector-map->list/int f bv1 bv2 @dots{}
1489 @defunx bitvector-map->list/bool f bv1 bv2 @dots{}
1490 [SRFI-178]
1491 @c MOD gauche.bitvector
1492 @c EN
1493 Apply a procedure @var{f} over each element taken from given bitvectors.
1494 The result of the procedure is gathered as a list and returned.
1495 @c JP
1496 手続き@var{f}を与えられたビットベクタから取り出したビットに対して適用し、
1497 その結果をリストに集めて返します。
1498 @c COMMON
1499
1500 @c EN
1501 All bitvectors must have the same length; otherwise, an error is thrown.
1502 @c JP
1503 引数の全てのビットベクタは同じ長さでなければなりません。
1504 そうでなければエラーが投げられます。
1505 @c COMMON
1506 @end defun
1507
1508 @defun bitvector-value-map-index->list f bv val
1509 @c MOD gauche.bitvector
1510 @c EN
1511 Apply a procedure @var{f} over each index such that the index-th element
1512 of @var{bv} is @var{val}, which must be either a boolean value or @code{0}
1513 or @code{1}. The result of applications are gathered into a list,
1514 from smaller index.
1515 @c JP
1516 ビットベクタ@var{bv}の要素のうち、それが@var{val}とビットとして
1517 一致するもの (@code{#t}か@code{1}なら真と一致、@code{#f}か@code{0}なら偽と一致)
1518 について、それぞれそのインデックスを引数に手続き@var{f}を呼びます。結果は
1519 インデックスの小さい順にリストに集められて返されます。
1520 @c COMMON
1521
1522 @c EN
1523 For example, the following returns a list of indices where the
1524 bit is true.
1525 @c JP
1526 下の例はビットベクタのビットが真であるインデックスのリストを返します。
1527 @c COMMON
1528
1529 @example
1530 (bitvector-value-map-index->list identity #*10011 #t)
1531 @result{} (0 3 4)
1532 @end example
1533 @end defun
1534
1535 @defun bitvector-for-each/int f bv1 bv2 @dots{}
1536 @defunx bitvector-for-each/bool f bv1 bv2 @dots{}
1537 [SRFI-178]
1538 @c MOD gauche.bitvector
1539 @c EN
1540 Apply a procedure @var{f} over each element taken from given bitvectors.
1541 The result of the procedure is discarded.
1542 @c JP
1543 与えられたビットベクタの各ビットに対して@var{f}を適用します。@var{f}の結果は捨てられます。
1544 @c COMMON
1545
1546 @c EN
1547 All bitvectors must have the same length; otherwise, an error is thrown.
1548 @c JP
1549 引数の全てのビットベクタは同じ長さでなければなりません。
1550 そうでなければエラーが投げられます。
1551 @c COMMON
1552
1553 @example
1554 (bitvector-for-each/int print #*11100 #*01110 #00111)
1555 @result{} @r{prints}
1556 100
1557 110
1558 111
1559 011
1560 001
1561 @end example
1562 @end defun
1563
1564 @defun bitvector-value-for-each-index f bv val
1565 @c MOD gauche.bitvector
1566 @c EN
1567 Apply a procedure @var{f} over each index such that the index-th element
1568 of @var{bv} is @var{val}, which must be either a boolean value or @code{0}
1569 or @code{1}. The result of @var{f} is discarded.
1570 @c JP
1571 @var{bv}の各ビットを最初から走査し、そのビットが@var{val}とビットとして一致したものについて、
1572 そのインデックスを引数に@var{f}を呼び出します。@var{f}の結果は捨てられます。
1573 @c COMMON
1574
1575 @example
1576 (bitvector-value-for-each-index print #*1101111010 #f)
1577 @result{} @r{prints}
1578 2
1579 7
1580 9
1581 @end example
1582
1583 @c EN
1584 See also @code{bitvector-value-map-index->list} above.
1585 @c JP
1586 上の@code{bitvector-value-map-index->list}も参照。
1587 @c COMMON
1588 @end defun
1589
1590 @c EN
1591 @subheading Prefixes, suffixes, trimming and padding
1592 @c JP
1593 @subheading プレフィクス、サフィックス、トリム、パディング
1594 @c COMMON
1595
1596 @defun bitvector-prefix-length bv1 bv2
1597 @defunx bitvector-suffix-length bv1 bv2
1598 [SRFI-178]
1599 @c MOD gauche.bitvector
1600 @c EN
1601 Returns the length of common prefix/suffix of two bitvectors
1602 @var{bv1} and @var{bv2}.
1603 @c JP
1604 二つのビットベクタ@var{bv1}、@var{bv2}に共通するプレフィクスまたはサフィックスの
1605 長さを返します。
1606 @c COMMON
1607
1608 @example
1609 (bitvector-prefix-length #*1100101001 #*110001101) @result{} 4
1610 (bitvector-suffix-length #*1100101001 #*110001101) @result{} 2
1611 @end example
1612 @end defun
1613
1614 @defun bitvector-prefix? needle haystack
1615 @defunx bitvector-suffix? needle haystack
1616 [SRFI-178]
1617 @c MOD gauche.bitvector
1618 @c EN
1619 Both arguments must be bitvectors. Returns @code{#t}
1620 iff @var{needle} is a prefix/suffix of @var{haystack}.
1621 @c JP
1622 引数はどちらもビットベクタでなければなりません。
1623 @var{needle}が@var{haystack}のプレフィックスまたはサフィックスになっている時に
1624 @code{#t}を、そうでなければ@code{#f}を返します。
1625 @c COMMON
1626
1627 @example
1628 (bitvector-prefix? #*101 #*1010100) @result{} #t
1629 (bitvector-prefix? #*101 #*1000110) @result{} #f
1630 (bitvector-suffix? #*110 #*1000110) @result{} #t
1631 (bitvector-suffix? #*110 #*1010100) @result{} #f
1632 @end example
1633 @end defun
1634
1635 @defun bitvector-pad bit bv len
1636 @defunx bitvector-pad-right bit bv len
1637 [SRFI-178]
1638 @c MOD gauche.bitvector
1639 @c EN
1640 If the length of a bitvector @var{bv} is smaller than @var{len},
1641 returns a bitvector of length @var{len} by adding @var{bit} before/after
1642 @var{bv}. If the length of @var{bv} is greater than @var{len},
1643 returns a bitvector of length @var{len} such that
1644 @var{bv} left/right bits of @var{bv} are trimmed.
1645 If the length of @var{bv} is equal to @var{len},
1646 a copy of @var{bv} is returned as is.
1647 @c JP
1648 ビットベクタ@var{bv}の長さが@var{len}未満であれば、
1649 長さが@var{len}になるまで@var{bv}の先頭もしくは末尾に@var{bit}を付加した
1650 ビットベクタを作って返します。@var{bv}の長さが@var{len}より大きな場合は
1651 長さ@var{len}になるまで@var{bv}の先頭もしくは末尾のビットを削ったビットベクタを
1652 作って返します。@var{len}が@var{bv}の長さと同じなら、@var{bv}のコピーが
1653 返されます。
1654 @c COMMON
1655
1656 @example
1657 (bitvector-pad 1 #*00010 10) @result{} #*1111100010
1658 (bitvector-pad-right 1 #*00010 10) @result{} #*0001011111
1659
1660 (bitvector-pad 1 #*0100011 3) @result{} #*011
1661 (bitvector-pad-right 1 #*0100011 3) @result{} #*010
1662 @end example
1663 @end defun
1664
1665 @defun bitvector-trim bit bv
1666 @defunx bitvector-trim-right bit bv
1667 @defunx bitvector-trim-both bit bv
1668 [SRFI-178]
1669 @c MOD gauche.bitvector
1670 @c EN
1671 Returns a fresh bitvector without preceding and/or trailing consecutive
1672 @var{bit} from @var{bv}.
1673 @c JP
1674 ビットベクタ@var{bv}の先頭、末尾、あるいは両方から、連続する@var{bit}をできる限り
1675 除いたビットベクタを新たに作って返します。
1676 @c COMMON
1677
1678 @example
1679 (bitvector-trim 0 #*000101000) @result{} #*101000
1680 (bitvector-trim-right 0 #*000101000) @result{} #*000101
1681 (bitvector-trim-both 0 #*000101000) @result{} #*101
1682 @end example
1683 @end defun
1684
1685 @c EN
1686 @subheading Mutators
1687 @c JP
1688 @subheading 破壊的変更
1689 @c COMMON
1690
1691 @defun bitvector-swap! bv i j
1692 [SRFI-178]
1693 @c MOD gauche.bitvector
1694 @c EN
1695 Swap the @var{i}-th value and @var{j}-th value of a bitvector @var{bv}.
1696 Returns an undefined value.
1697 If the index is out of range, an error is thrown.
1698 @c JP
1699 ビットベクタ@var{bv}の@var{i}番目と@var{j}番目のビットを入れ替えます。
1700 戻り値は未定義です。
1701 インデックスが範囲外であればエラーが投げられます。
1702 @c COMMON
1703 @end defun
1704
1705 @defun bitvector-reverse! bv :optional start end
1706 [SRFI-178]
1707 @c MOD gauche.bitvector
1708 @c EN
1709 Reverse the order of the content of a bitvector @var{bv} destructively.
1710 The optional @var{start}/@var{end} indexes limit the range of the operation;
1711 elements outside of the range won't be affected.
1712 Returns an undefined value.
1713 @c JP
1714 ビットベクタ@var{bv}のビット順を破壊的に反転します。
1715 省略可能な@var{start}/@var{end}が与えられた場合は、
1716 それらのインデックスで指定される範囲内だけが変更対象となります。
1717 戻り値は未定義です。
1718 @c COMMON
1719 @end defun
1720
1721 @defun bitvector-reverse-copy! to tstart from :optional start end
1722 [SRFI-178]
1723 @c MOD gauche.bitvector
1724 @c EN
1725 Same as @code{(bitvector-copy! to start (bitvector-reverse-copy from start end))},
1726 but potentially more efficient.
1727 Returns an undefined value.
1728 @c JP
1729 @code{(bitvector-copy! to start (bitvector-reverse-copy from start end))}
1730 と意味的に同じですが、より効率が良いかもしれません。
1731 戻り値は未定義です。
1732 @c COMMON
1733 @end defun
1734
1735 @c EN
1736 @subheading Conversion
1737 @c JP
1738 @subheading 変換
1739 @c COMMON
1740
1741 @defun bitvector->list/int bv :optional start end
1742 @defunx bitvector->list/bool bv :optional start end
1743 @defunx reverse-bitvector->list/int bv :optional start end
1744 @defunx reverse-bitvector->list/bool bv :optional start end
1745 [SRFI-178]
1746 @c MOD gauche.bitvector
1747 @c EN
1748 Returns a list of integers (0 or 1) or boolean values of bitvector
1749 @var{bv}. The first two procedures returns the leftmost bit first,
1750 while the @code{reverse-} variations returns the rightmost bit first.
1751 The optional @var{start}/@var{end} arguments limit the range of @var{bv}
1752 to be extracted.
1753 @c JP
1754 ビットベクタ@var{bv}の内容を整数0または1のリスト、あるいは真偽値のリストとして
1755 返します。最初の2つの手続きは左から、@code{reverse-}のつく2つの手続きは
1756 右からビットを取ります。省略可能な@var{start}/@var{end}引数は
1757 取り出すビットの範囲を指定します。
1758 @c COMMON
1759
1760 @example
1761 (bitvector->list/int #*010011000111 2 10)
1762 @result{} (0 0 1 1 0 0 0 1)
1763 (reverse-bitvector->list/int #*010011000111 2 10)
1764 @result{} (1 0 0 0 1 1 0 0)
1765 @end example
1766 @end defun
1767
1768 @defun reverse-list->bitvector lis
1769 [SRFI-178]
1770 @c MOD gauche.bitvector
1771 @c EN
1772 Like @code{list->bitvector} (@pxref{Bitvectors}), but pack bits
1773 from right to left.
1774 @c JP
1775 @code{list->bitvector}(@ref{Bitvectors}参照)と似ていますが、
1776 ビットを右から左に詰めてゆきます。
1777 @c COMMON
1778
1779 @example
1780 (reverse-list->bitvector '(1 0 #f #f #t #t))
1781 @result{} #*110001
1782 @end example
1783 @end defun
1784
1785 @defun bitvector->vector/int bv :optional start end
1786 @defunx bitvector->vector/bool bv :optional start end
1787 @defunx revrese-bitvector->vector/int bv :optional start end
1788 @defunx reverse-bitvector->vector/bool bv :optional start end
1789 [SRFI-178]
1790 @c MOD gauche.bitvector
1791 @c EN
1792 Returns a vector of integers (0 or 1) or boolean values of
1793 bitvector @var{bv}. The first two procedures returns the leftmost bit first,
1794 while the @code{reverse-} variations returns the rightmost bit first.
1795 The optional @var{start}/@var{end} arguments limit the range of @var{bv}
1796 to be extracted.
1797 @c JP
1798 ビットベクタ@var{bv}の内容を整数0または1のベクタ、あるいは真偽値のベクタとして
1799 返します。最初の2つの手続きは左から、@code{reverse-}のつく2つの手続きは
1800 右からビットを取ります。省略可能な@var{start}/@var{end}引数は
1801 取り出すビットの範囲を指定します。
1802 @c COMMON
1803 @end defun
1804
1805 @defun vector->bitvetor vec :optional start end
1806 @defunx reverse-vector->bitvector vec :optional start end
1807 [SRFI-178]
1808 @c MOD gauche.bitvector
1809 @c EN
1810 Converts @var{vec} to a fresh bitvector;
1811 @var{vec} must be a vector of 0/1 or boolean values.
1812 The first procedure packs bits in the same left to right order,
1813 while the @code{reverse-} version reverses the order.
1814 The optional @var{start}/@var{end} arguments limit the range of @var{vec}
1815 to be extracted.
1816 @c JP
1817 ベクタ@var{vec}を新たなビットベクタに変換します。@var{vec}の要素は
1818 0、1、あるいは真偽値でなければなりません。
1819 最初の手続きはビットを左から右に同じ順で、@code{reverse-}のつく手続きは
1820 逆順で詰めてゆきます。
1821 省略可能な@var{start}/@var{end}引数は@var{vec}から取り出すビットの範囲を指定します。
1822 @c COMMON
1823
1824 @example
1825 (vector->bitvector #(0 0 1 1 #t #f #t #t) 2 7)
1826 @result{} #*11101
1827 (reverse-vector->bitvector #(0 0 1 1 #t #f #t #t) 2 7)
1828 @result{} #*10111
1829 @end example
1830 @end defun
1831
1832 @defun bitvector->integer bv
1833 @defunx integer->bitvector n :optional len
1834 [SRFI-178]
1835 @c MOD gauche.bitvector
1836 @c EN
1837 Convert between bitvectors and exact nonnegative integers.
1838 Note that the leftmost bit of
1839 @var{bv} corresponds to the least significant bit.
1840 @c JP
1841 ビットベクタと正確な非負整数とを相互変換します。
1842 @var{bv}の最初(最左)のビットは、整数の最下位のビットに対応することに注意してください。
1843 @c COMMON
1844
1845 @example
1846 (bitvector->integer #*1000) @result{} 1
1847 (bitvector->integer #*0001) @result{} 8
1848 @end example
1849
1850 @c EN
1851 This is consistent with @code{bits->list} etc. of SRFI-151
1852 (@pxref{R7RS bitwise operations}), where least significant bit
1853 corresponts to the first element of the list.
1854 @c JP
1855 SRFI-151の@code{bits->list}等は最下位ビットから順にビットをリストにするので、
1856 それと一貫性があります(@ref{R7RS bitwise operations}参照)。
1857 @c COMMON
1858
1859 @c EN
1860 @code{integer->bitvector} takes an optional argument @var{len} to
1861 specify the number of bits in @var{n} (count from the least siginificant
1862 bit) to be taken. When omitted, @code{(integer-length n)} is used
1863 (@pxref{Basic bitwise operations}).
1864 @c JP
1865 @code{integer->bitvector}はさらに省略可能な@var{len}引数で、
1866 引数の整数@var{n}の最下位から何ビット目までを取るかを指定できます。
1867 省略時は@code{(integer-length n)}の値が使われます
1868 (@ref{Basic bitwise operations}参照)。
1869 @c COMMON
1870
1871 @example
1872 (integer->bitvector 11) @result{} #*1101
1873 (integer->bitvector 11 8) @result{} #*11010000
1874 @end example
1875 @end defun
1876
1877 @c EN
1878 @subheading Generators
1879 @c JP
1880 @subheading ジェネレータ
1881 @c COMMON
1882
1883 @defun bitvector->int-generator bv :optional start end
1884 @defunx bitvector->bool-generator bv :optional start end
1885 @c MOD gauche.bitvector
1886 @c EN
1887 Returns a generator of integers (0 or 1) and boolean values, respectively.
1888 The value is taken from a bitvector @var{bv} from left to right.
1889 The optional @var{start}/@var{end} arguments limits the range of
1890 the bitvector to be used.
1891 @c JP
1892 それぞれ、整数0か1を生成するジェネレータと真偽値を生成するジェネレータを返します。
1893 値はビットベクタ@var{bv}の左から右へと取られます。
1894 省略可能な@var{start}/@var{end}引数は@var{vec}から取り出すビットの範囲を指定します。
1895 @c COMMON
1896
1897 @example
1898 (generator->list (bitvector->int-generator #*10111000))
1899 @result{} (1 0 1 1 1 0 0 0)
1900 @end example
1901
1902 @c EN
1903 The names are consistent with Gauche convention.
1904 SRFI-178 defines these procedures with the name
1905 @code{make-bitvector/int-generator} and @code{make-bitvector/bool-generator}.
1906 @c JP
1907 これらの名前はGaucheの名前付けと一貫性があります。
1908 SRFI-178ではこれらを
1909 @code{make-bitvector/int-generator}および@code{make-bitvector/bool-generator}
1910 と呼んでいます。
1911 @c COMMON
1912
1913 @c EN
1914 @xref{Generators}, for the details of generators.
1915 @c JP
1916 ジェネレータについて詳しくは@ref{Generators}を参照してください。
1917 @c COMMON
1918 @end defun
1919
1920
1921 @defun make-bitvector/int-generator bv
1922 @defunx make-bitvector/bool-generator bv
1923 [SRFI-178]
1924 @c MOD gauche.bitvector
1925 @c EN
1926 These are same as @code{bitvector->int-generator} and
1927 @code{bitvector->bool-generator} except the optional arguments,
1928 and defined in SRFI-178.
1929 @c JP
1930 これらは省略可能引数を取らないことを除いて、
1931 それぞれ@code{bitvector->int-generator}および@code{bitvector->bool-generator}
1932 と同じです。SRFI-178で定義されました。
1933 @c COMMON
1934 @end defun
1935
1936 @defun bitvector->index-generator bv val :optional start end
1937 @c MOD gauche.bitvector
1938 @c EN
1939 Returns a generator that generates indexes of @var{bv} such that
1940 the index-th value of @var{bv} matches @var{val}, which must
1941 be either 0, 1 or a boolean value. The bitvector is scanned from
1942 left to right.
1943 The optional @var{start}/@var{end} arguments limits the range of
1944 the bitvector to be used.
1945 @c JP
1946 ビットベクタ@var{bv}のうち、値が@var{val}と一致するビットのインデックスを
1947 左から右への順番で生成するジェネレータを返します。
1948 @var{val}は0, 1, @code{#f}, @code{#t}のいずれかでなければなりません。
1949 省略可能な@var{start}/@var{end}引数は@var{vec}から取り出すビットの範囲を指定します。
1950 @c COMMON
1951
1952 @c EN
1953 This is handy when you have a bitvector as a bitmap, and want to
1954 process something where bit is set (or reset).
1955 @c JP
1956 これは、ビットベクタをビットマップとして使い、
1957 ビットがセットされている/されていない要素について何かする、といった場合に便利です。
1958 @c COMMON
1959
1960 @example
1961 (generator->list (bitvector->index-generator #*101110001 1))
1962 @result{} (0 2 3 4 8)
1963 @end example
1964 @end defun
1965
1966 @defun make-bitvector-accumulator
1967 [SRFI-178]
1968 @c MOD gauche.bitvector
1969 @c EN
1970 Returns an accumulator that collects given bits, and returns
1971 a bitvector at the end of accumulation.
1972 @c JP
1973 与えられたビットを蓄積し、最後にビットベクタを作って返すアキュムレータを返します。
1974 @c COMMON
1975
1976 @example
1977 (let ((a (make-bitvector-accumulator)))
1978 (a 1)
1979 (a 0)
1980 (a 0)
1981 (a 1)
1982 (a 1)
1983 (a (eof-object)))
1984 @result{} #*10011
1985 @end example
1986
1987 @c EN
1988 @xref{R7RS generators}, for the details of accumulators.
1989 @c JP
1990 アキュムレータについて詳しくは@ref{R7RS generators}を参照してください。
1991 @c COMMON
1992 @end defun
1993
1994 @c EN
1995 @subheading Bitwise operations
1996 @c JP
1997 @subheading ビット演算
1998 @c COMMON
1999
2000 @defun bitvector-not bv
2001 @defunx bitvector-not! bv
2002 [SRFI-178]
2003 @c MOD gauche.bitvector
2004 @c EN
2005 Returns a bitvector whose bits are logical negation of @var{bv}.
2006 The linear updating version @code{bitvector-not!} may reuse @var{bv} to
2007 produce the result.
2008 @c JP
2009 ビットベクタ@var{bv}の各ビットを反転したビットベクタを返します。
2010 線形更新版の@code{bitvector-not!}は、結果を作るために
2011 @var{bv}を破壊的に変更するかもしれません。
2012 @c COMMON
2013
2014 @example
2015 (bitvector-not #*10100) @result{} #*01011
2016 @end example
2017 @end defun
2018
2019 @defun bitvector-and bv1 bv2 bv @dots{}
2020 @defunx bitvector-and! bv1 bv2 bv @dots{}
2021 @defunx bitvector-ior bv1 bv2 bv @dots{}
2022 @defunx bitvector-ior! bv1 bv2 bv @dots{}
2023 @defunx bitvector-xor bv1 bv2 bv @dots{}
2024 @defunx bitvector-xor! bv1 bv2 bv @dots{}
2025 @defunx bitvector-eqv bv1 bv2 bv @dots{}
2026 @defunx bitvector-eqv! bv1 bv2 bv @dots{}
2027 [SRFI-178]
2028 @c MOD gauche.bitvector
2029 @c EN
2030 Returns a bitvector whose bits are the result of logical operaion of
2031 corresponding bits of the given bitvectors. All bitvectors must be
2032 the same length.
2033 The linear updating version (procedures with @code{!}) may reuse @var{bv1} to
2034 produce the result.
2035 @c JP
2036 与えられたビットベクタの各ビット間に指定の演算を施した結果を要素とするビットベクタを
2037 返します。引数のビットベクタは全て同じ長さでなければなりません。
2038 線形更新版(名前に@code{!}がついているもの)は、
2039 結果を作るために@var{bv1}を破壊的に変更するかもしれません。
2040 @c COMMON
2041
2042 @c EN
2043 When more than two bitvectors are given to xor and eqv operation,
2044 it works left-associatively, that is,
2045 @c JP
2046 3つ以上のビットベクタが与えられた場合、xorとeqv操作は左結合的に行われます。すなわち:
2047 @c COMMON
2048
2049 @example
2050 (bitvector-xor a b c)
2051 @equiv{} (bitvector-xor (bitvector-xor a b) c)
2052 (bitvector-eqv a b c)
2053 @equiv{} (bitvector-eqv (bitvector-eqv a b) c)
2054 @end example
2055 @end defun
2056
2057 @defun bitvector-nand bv1 bv2
2058 @defunx bitvector-nand! bv1 bv2
2059 @defunx bitvector-nor bv1 bv2
2060 @defunx bitvector-nor! bv1 bv2
2061 @defunx bitvector-andc1 bv1 bv2
2062 @defunx bitvector-andc1! bv1 bv2
2063 @defunx bitvector-andc2 bv1 bv2
2064 @defunx bitvector-andc2! bv1 bv2
2065 @defunx bitvector-orc1 bv1 bv2
2066 @defunx bitvector-orc1! bv1 bv2
2067 @defunx bitvector-orc2 bv1 bv2
2068 @defunx bitvector-orc2! bv1 bv2
2069 [SRFI-178]
2070 @c MOD gauche.bitvector
2071 @c EN
2072 Returns a bitvector, where each bit is the result of
2073 logical operation of corresponding bits of @var{bv1} and @var{bv2}.
2074 Two bitvectors must be the same length.
2075 @c JP
2076 @var{bv1}と@var{bv2}の対応する各ビットに演算を施した結果をビットベクタにして返します。
2077 @var{bv1}と@var{bv2}は同じ長さでなければなりません。
2078 @c COMMON
2079
2080 @example
2081 nand : (not (and bv1 bv2))
2082 nor : (not (or bv1 bv2)
2083 andc1 : (and (not bv1) bv2)
2084 andc2 : (and bv1 (not bv2))
2085 orc1 : (or (not bv1) bv2)
2086 orc2 : (or bv1 (not bv2))
2087 @end example
2088
2089 @c EN
2090 The linear updating version (procedures with @code{!}) may reuse @var{bv1} to
2091 produce the result.
2092 @c JP
2093 線形更新版(名前に@code{!}がついているもの)は、
2094 結果を作るために@var{bv1}を破壊的に変更するかもしれません。
2095 @c COMMON
2096 @end defun
2097
2098 @c EN
2099 @subheading Quasi-integer operations
2100 @c JP
2101 @subheading 整数に準ずる演算
2102 @c COMMON
2103
2104 @defun bitvector-logical-shift bv count bit
2105 [SRFI-178]
2106 @c MOD gauche.bitvector
2107 @c EN
2108 Returns a bitvector with the same length of @var{bv}, but the
2109 content is shifted @var{count} bits to the left (when @var{count} >= 0)
2110 or @var{-count} bits to the right (when @var{count} < 0).
2111 The spilled bits are discarded.
2112 The vacated bits are filled with @var{bit}.
2113 @c JP
2114 @var{bv}を左に@var{count}ビットシフトした、@var{bv}と同じ長さのビットベクタを
2115 返します。@var{count}が負の場合は@var{-count}ビット右にシフトします。
2116 あふれたビットは捨てられます。空き部分のビットは@var{bit}で埋められます。
2117 @c COMMON
2118
2119 @example
2120 (bitvector-logical-shift #*101100111000 4 1)
2121 @result{} #*001110001111
2122 (bitvector-logical-shift #*101100111000 -4 0)
2123 @result{} #*000010110011
2124 @end example
2125 @end defun
2126
2127 @defun bitvector-count bit bv
2128 [SRFI-178]
2129 @c MOD gauche.bitvector
2130 @c EN
2131 Returns the number of @var{bit} values in @var{bv}.
2132 @c JP
2133 @var{bv}中のビットで、@var{bit}と一致するものの数を返します。
2134 @c COMMON
2135 @end defun
2136
2137 @defun bitvector-count-run bit bv start
2138 [SRFI-178]
2139 @c MOD gauche.bitvector
2140 @c EN
2141 Returns the number of consecutive @var{bit} values in @var{bv}, starting
2142 from index @var{i}.
2143 @c JP
2144 @var{bv}中の、@var{i}ビット目から@var{bit}がいくつ連続しているか、その数を返します。
2145 @c COMMON
2146
2147 @example
2148 (bitvector-count-run 1 #*11111111100 0)
2149 @result{} 9
2150 @end example
2151 @end defun
2152
2153 @defun bitvector-if bv-if bv-then bv-else
2154 [SRFI-178]
2155 @c MOD gauche.bitvector
2156 @c EN
2157 All bitvectors must be the same length.
2158 Returns a new bitvector with the same length, composed as follows.
2159
2160 The @var{k}-th bit of resulting vector is the same as @var{k}-th bit
2161 of @var{bv-then} if @var{k}-th bit of @var{bv-if} is @code{#t} (1),
2162 otherwise the same as @var{k}-th bit of @var{bv-else}
2163 @c JP
2164 各ビットベクタは同じ長さでなければなりません。
2165 同じ長さのビットベクタを次のように構成して返します。
2166
2167 結果の@var{k}ビット目は、@var{bv-if}の@var{k}ビット目が@code{#t}(1)であれば
2168 @var{bv-then}の@var{k}ビット目、そうでなければ@var{bv-else}の@var{k}ビット目と
2169 同じになります。
2170 @c COMMON
2171 @end defun
2172
2173 @defun bitvector-first-bit bit bv
2174 [SRFI-178]
2175 @c MOD gauche.bitvector
2176 @c EN
2177 Returns the index of the leftmost @var{bit} in @var{bv}.
2178 If @var{bv} doesn't have @var{bit}, returns @code{-1}.
2179 @c JP
2180 @var{bv}中で一番左にある@var{bit}のインデックスを返します。
2181 @var{bv}中に@var{bit}が無ければ@code{-1}を返します。
2182 @c COMMON
2183
2184 @example
2185 (bitvector-first-bit 1 #*0010011) @result{} 2
2186 (bitvector-first-bit 0 #*1111111) @result{} -1
2187 @end example
2188 @end defun
2189
2190 @c EN
2191 @subheading Bit field operations
2192 @c JP
2193 @subheading ビットフィールド操作
2194 @c COMMON
2195
2196 @c EN
2197 Those procedures operates on a partial field of a bitvector,
2198 between @var{start}-th bit (inclusive) and @var{end}-th bit (exclusive).
2199 @c JP
2200 以下の手続きは、ビットベクタの
2201 @var{start}ビット目(含む)から@var{end}ビット目(含まない)までの部分について
2202 操作するものです。
2203 @c COMMON
2204
2205 @defun bitvector-field-any? bv start end
2206 [SRFI-178]
2207 @c MOD gauche.bitvector
2208 @c EN
2209 Returns @code{#t} iff at least one bit between @var{start} and @var{end}
2210 in @var{bv} is 1.
2211 @c JP
2212 ビットベクタ@var{bv}の@var{start}ビット目から@var{end}ビット目までのいずれかに
2213 1のビットがあれば@code{#t}を、そうでなければ@code{#f}を返します。
2214 @c COMMON
2215
2216 @c EN
2217 This is equivalent to @code{(bitvector-any-value? bv 1 start end)},
2218 using Gauche's built-in procedure (@pxref{Bitvectors}).
2219 @c JP
2220 Gaucheの組み込み手続きを使って
2221 @code{(bitvector-any-value? bv 1 start end)}とした場合と同じです
2222 (@ref{Bitvectors}参照)。
2223 @c COMMON
2224 @end defun
2225
2226 @defun bitvector-field-every? bv start end
2227 [SRFI-178]
2228 @c MOD gauche.bitvector
2229 @c EN
2230 Returns @code{#t} iff every bit between @var{start} and @var{end}
2231 in @var{bv} is 1.
2232 @c JP
2233 ビットベクタ@var{bv}の@var{start}ビット目から@var{end}ビット目までのすべてが
2234 1であれば@code{#t}を、そうでなければ@code{#f}を返します。
2235 @c COMMON
2236
2237 @c EN
2238 This is equivalent to @code{(bitvector-every-value? bv 1 start end)},
2239 using Gauche's built-in procedure (@pxref{Bitvectors}).
2240 @c JP
2241 Gaucheの組み込み手続きを使って
2242 @code{(bitvector-every-value? bv 1 start end)}とした場合と同じです
2243 (@ref{Bitvectors}参照)。
2244 @c COMMON
2245 @end defun
2246
2247 @defun bitvector-field-clear bv start end
2248 @defunx bitvector-field-clear! bv start end
2249 @defunx bitvector-field-set bv start end
2250 @defunx bitvector-field-set! bv start end
2251 [SRFI-178]
2252 @c MOD gauche.bitvector
2253 @c EN
2254 Returns a bitvector with the same content as @var{bv}, except
2255 the bits between @var{start} (inclusive) and @var{end} (exclusive)
2256 are cleared or set, respectively.
2257 @c JP
2258 ビットベクタ@var{bv}の内容のうち、
2259 @var{start}ビット目から@var{end}ビット目までのすべてがクリアされた、
2260 あるいはセットされたビットベクタをそれぞれ返します。
2261 @c COMMON
2262
2263 @c EN
2264 The liner-updating version may mutate @var{bv} to produce the result.
2265 @c JP
2266 線形更新版は結果を作るために@var{bv}を破壊的に変更するかもしれません。
2267 @c COMMON
2268
2269 @example
2270 (bitvector-field-clear #*10010010101001 2 7)
2271 @result{} #*10000000101001
2272 (bitvector-field-set #*10010010101001 2 7)
2273 @result{} #*10111110101001
2274 @end example
2275 @end defun
2276
2277 @defun bitvector-field-replace to from start end
2278 @defunx bitvector-field-replace! to from start end
2279 [SRFI-178]
2280 @c MOD gauche.bitvector
2281 @c EN
2282 Returns a bitvector with the same content as @var{to-bv}, except
2283 its bits between @var{start} (inclusive) and @var{end} (exclusive)
2284 are replaced with the content of @var{from-bv}.
2285 @c JP
2286 ビットベクタ@var{bv}の内容のうち、
2287 @var{start}ビット目から@var{end}ビット目までを、
2288 @var{from-bv}の内容で置き換えたビットベクタを返します。
2289 @c COMMON
2290
2291 @c EN
2292 The length of @var{from-bv} must be at least @var{end}-@var{start}.
2293 If it is longer, the exceeding bits are ignored.
2294 @c JP
2295 @var{from-bv}の長さは少なくとも@var{end}-@var{start}だけなければなりません。
2296 @var{from-bv}がそれより長い場合、余分なビットは無視されます。
2297 @c COMMON
2298
2299 @c EN
2300 The liner-updating version may mutate @var{to-bv} to produce the result.
2301 @c JP
2302 線形更新版は結果を作るために@var{bv}を破壊的に変更するかもしれません。
2303 @c COMMON
2304
2305 @example
2306 (bitvector-field-replace #*10010010101001 #*110011 2 8)
2307 @result{} #*10110011101001
2308 @end example
2309
2310 @c EN
2311 See also @code{bitvector-field-replace-same} below.
2312 @c JP
2313 下の@code{bitvector-field-replace-same}も参照のこと。
2314 @c COMMON
2315 @end defun
2316
2317 @defun bitvector-field-replace-same to-bv from-bv start end
2318 @defunx bitvector-field-replace-same! to-bv from-bv start end
2319 [SRFI-178]
2320 @c MOD gauche.bitvector
2321 @c EN
2322 Returns a bitvector with the same content as @var{to-bv}, except
2323 its bits between @var{start} (inclusive) and @var{end} (exclusive)
2324 are replaced with the content of @var{from-bv} between @var{start} and
2325 @var{end}.
2326 @c JP
2327 ビットベクタ@var{bv}の内容のうち、@var{start}ビット目から@var{end}ビット目までを、
2328 @var{from-bv}の@var{start}ビット目から@var{end}ビット目までで置き換えたものを返します。
2329 @c COMMON
2330
2331 @c EN
2332 The length of @var{from-bv} must be greater than or equal to @var{end}.
2333 @c JP
2334 @var{from-bv}の長さは@var{end}より大きくなければなりません。
2335 @c COMMON
2336
2337 @c EN
2338 The liner-updating version may mutate @var{to-bv} to produce the result.
2339 @c JP
2340 線形更新版は結果を作るために@var{bv}を破壊的に変更するかもしれません。
2341 @c COMMON
2342
2343 @example
2344 (bitvector-field-replace-same #*10010010101001 #*11001100 2 8)
2345 @result{} #*10001100101001
2346 @end example
2347
2348 @c EN
2349 See also @code{bitvector-field-replace} above.
2350 @c JP
2351 上の@code{bitvector-field-replace}も参照のこと。
2352 @c COMMON
2353 @end defun
2354
2355
2356 @defun bitvector-field-rotate bv count start end
2357 [SRFI-178]
2358 @c MOD gauche.bitvector
2359 @c EN
2360 Returns a bitvector whose content is the same as @var{bv} except
2361 the range between @var{start}-th bit (inclusive) and
2362 @var{end}-th bit (exclusive) being rotated by @var{count} bits toward
2363 right. You can give a negative @var{count} to rotate towards left.
2364 @c JP
2365 ビットベクタ@var{bv}の内容のうち、@var{start}ビット目から@var{end}ビット目までが
2366 @var{count}ビットだけ右にローテートされた内容に置き換えられているものを返します。
2367 @var{count}が負なら、その絶対値分だけ左にローテートします。
2368 @c COMMON
2369
2370 @example
2371 (bitvector-field-rotate #*001100110011 1 4 8)
2372 @result{} #*001101100011
2373 (bitvector-field-rotate #*001100110011 -1 4 8)
2374 @result{} #*001110010011
2375 @end example
2376 @end defun
2377
2378 @defun bitvector-field-flip bv start end
2379 @defunx bitvector-field-flip! bv start end
2380 [SRFI-178]
2381 @c MOD gauche.bitvector
2382 @c EN
2383 Returns a bitvector whose content is the same as @var{bv}
2384 except the bits in the range
2385 between @var{start}-th bit (inclusive) and
2386 @var{end}-th bit (exclusive) are inverted.
2387 @c JP
2388 ビットベクタ@var{bv}の内容のうち、@var{start}ビット目から@var{end}ビット目までの
2389 ビットが論理否定されているものを返します。
2390 @c COMMON
2391
2392 @c EN
2393 The liner-updating version may mutate @var{to-bv} to produce the result.
2394 @c JP
2395 線形更新版は結果を作るために@var{bv}を破壊的に変更するかもしれません。
2396 @c COMMON
2397
2398 @example
2399 (bitvector-field-flip #*001100110011 4 8)
2400 @result{} #*001111000011
2401 @end example
2402 @end defun
2403
2404
2405
2406 @c ----------------------------------------------------------------------
2407 @node Generating C code, Character code conversion, Bitvector utilities, Library modules - Gauche extensions
2408 @section @code{gauche.cgen} - Generating C code
2409 @c NODE Cコードの生成, @code{gauche.cgen} - Cコードの生成
2410
2411 @c EN
2412 Significant part of Gauche is written in Gauche or S-expression
2413 based DSL. During the building process, they are converted
2414 into C sources and then compiled by C compiler.
2415 The @code{gauche.cgen} module and its submodules expose
2416 the functionality Gauche build process is using to the general use.
2417 @c JP
2418 Gauche本体の多くの部分は、Gauche自身、もしくはS式ベースのDSLで書かれています。
2419 これらのコードはビルド中にCソースに変換され、Cコンパイラで
2420 コンパイルされます。
2421 @code{gauche.cgen}モジュールおよびそのサブモジュールは、
2422 Gaucheビルドプロセスが使っているこの機能を一般にも使えるように公開するものです。
2423 @c COMMON
2424
2425 @c EN
2426 Required features for a C code generator differ greatly among
2427 applications, and too much scaffolding could be a constraint
2428 for the module users. So, instead of providing a single
2429 solid framework, we provide a set of loosely coupled modules
2430 so that you can combine necessary features freely. In fact,
2431 some of Gauche build process only use @code{gauche.cgen.unit}
2432 and @code{gauche.cgen.literal} (see @file{src/builtin-syms.scm},
2433 for example).
2434 @c JP
2435 Cコードジェネレータに要求される機能はアプリケーションによって多種多様であり、
2436 あまりがちがちに枠組みを固定してしまうと却って使い辛くなるでしょう。
2437 そこで、ひとつの固定したフレームワークではなく、
2438 ゆるく連携するいくつかのモジュールを提供し、ユーザが必要な機能を自由に
2439 組み合わせて使えるようにしてあります。実際、Gaucheのビルド時に走る
2440 プロセスの中には、@code{gauche.cgen.unit}や@code{gauche.cgen.literal}だけしか
2441 使わないものもあります(例えば@file{src/builtin-syms.scm}を見てください)。
2442 @c COMMON
2443
2444 @deftp {Module} gauche.cgen
2445 @mdindex gauche.cgen
2446 @c EN
2447 This is a convenience module that extends
2448 @code{gauche.cgen.unit}, @code{gauche.cgen.literal},
2449 @code{gauche.cgen.type} and @code{gauche.cgen.cise} together.
2450 @c JP
2451 このモジュールは、簡便のために
2452 @code{gauche.cgen.unit}、@code{gauche.cgen.literal}、
2453 @code{gauche.cgen.type}、@code{gauche.cgen.cise}を
2454 extendしたものです。
2455 @c COMMON
2456 @end deftp
2457
2458 @c EN
2459 Usually you can just use @code{gauche.cgen} and don't need
2460 to think about individual submodules.
2461 The following subsections are organized by submodules
2462 only for the convenience of explanation.
2463 @c JP
2464 大抵の場合、@code{gauche.cgen}をuseしておけば、個々のサブモジュールについて
2465 考える必要はありません。
2466 以降のセクションは主に説明のしやすさのために、サブモジュールごとに
2467 分けて記述してあります。
2468 @c COMMON
2469
2470 @menu
2471 * Generating C source files:: gauche.cgen.unit
2472 * Generating Scheme literals:: gauche.cgen.literals
2473 * Conversions between Scheme and C:: gauche.cgen.type
2474 * C in S expression:: gauche.cgen.cise
2475 * Stub generation:: gauche.cgen.stub
2476 @end menu
2477
2478 @node Generating C source files, Generating Scheme literals, Generating C code, Generating C code
2479 @subsection Generating C source files
2480 @c NODE Cソースファイルを生成する
2481
2482 @c EN
2483 One of the tricky issues about generating C source is that
2484 you have to put several fragments of code in different
2485 parts of the source file, even you want to say just one thing---that is,
2486 sometimes you have to put declaration before the actual definition,
2487 plus some setup code that needs to be run at initialization time.
2488 The @code{<cgen-unit>} class takes care of such code placement.
2489 @c JP
2490 Cソースを生成する際に面倒なのは、ひとつの機能を実装するのにも、
2491 ソースの断片を離れた場所に配置しなければならないことです。
2492 それが参照されているコードより前に宣言が置かれなければならないですし、
2493 必要な初期化コードは初期化ルーチン内に書かれなければなりません。
2494 @code{<cgen-unit>}クラスはそういったコード配置の面倒をみてくれます。
2495 @c COMMON
2496
2497 @c EN
2498 @subsubheading Creating a frame
2499 @c JP
2500 @subsubheading 枠組みを作る
2501 @c COMMON
2502
2503 @deftp {Class} <cgen-unit>
2504 @clindex cgen-unit
2505 @c MOD gauche.cgen
2506 @c EN
2507 A @emph{cgen-unit} is a unit of C source generation.
2508 It corresponds to one .c file, and optionally one .h file.
2509 During the processing, a "current unit" is kept in a parameter
2510 @code{cgen-current-unit}, and most cgen APIs implicitly work to it.
2511 @c JP
2512 @emph{cgen-uint}はCソースコード生成の単位です。
2513 ひとつのインスタンスがひとつの@code{.c}ファイルと、
2514 必要に応じてひとつの@code{.h}ファイルに対応します。
2515 処理中には「現在のunit」がパラメータ@code{cgen-current-unit}に束縛されていて、
2516 多くのcgen APIはそれを暗黙に参照します。
2517 @c COMMON
2518
2519 @c EN
2520 The following slot are for public use. They are used to tailor
2521 the output. Usually you set those slots at initialization time.
2522 The effect is undefined if you change them in the middle of
2523 the code generation process.
2524 @c JP
2525 以下のスロットが公開されていて、出力をカスタマイズするのに使えます。
2526 通常、これらのスロットは初期化時に設定します。
2527 コード生成の途中でこれらのスロットの値を変えた場合の動作は未定義です。
2528 @c COMMON
2529
2530 @defivar {<cgen-unit>} name
2531 @c EN
2532 A string to name this unit. This is used for the default name
2533 of the generated files (@file{@var{name}.c} and @file{@var{name}.h})
2534 and the suffix of the default name of initialization function.
2535 Other cgen modules may use this to generate names. Avoid using
2536 characters that are not valid for C identifiers.
2537
2538 You can override those default names by setting the other slots.
2539 @c JP
2540 このunitの名前を示す文字列。これは、
2541 生成されるファイルのデフォルトの名前
2542 (@file{@var{name}.c} と @file{@var{name}.h})、
2543 および初期化関数名に使われます。
2544 他のcgenモジュールでも、この値をもとに名前を作り出すものがあります。
2545 従って、Cの識別子として有効な文字だけを使うようにしてください。
2546
2547 生成されるデフォルトの名前は個別に他のスロットで上書きすることができます。
2548 @c COMMON
2549 @end defivar
2550
2551 @defivar {<cgen-unit>} c-file
2552 @defivarx {<cgen-unit>} h-file
2553 @c EN
2554 The name of the C source file and header file, in strings.
2555 If they are @code{#f} (by default), the value of @code{name} slot
2556 is used as the file name, with extension @code{.c} or @code{.h}
2557 is attached, respectively.
2558
2559 To get the file names to be generated, use @code{cgen-unit-c-file}
2560 and @code{cgen-unit-h-file} generic functions, instead of reading
2561 these slots.
2562 @c JP
2563 Cソースファイルとヘッダファイルの名前を指定する文字列。
2564 デフォルトは@code{#f}で、その場合は@code{name}スロットの値に
2565 拡張子@code{.c}および@var{.h}をつけたものが使われます。
2566
2567 生成されるファイル名を使いたい場合は、これらのスロットの値ではなく、
2568 @code{cgen-unit-c-file}および@code{cgen-unit-h-file}を呼んでください。
2569 @c COMMON
2570 @end defivar
2571
2572 @defivar {<cgen-unit>} preamble
2573 @c EN
2574 A list of strings to be inserted at the top of the generated sources.
2575 The default value is @code{("/* Generated by gauche.cgen */")}.
2576 Each string appears in its own line.
2577 @c JP
2578 生成されるソースの先頭に挿入される文字列のリスト。
2579 デフォルトは@code{("/* Generated by gauche.cgen */")}です。
2580 各文字列が独立した行になります。
2581 @c COMMON
2582 @end defivar
2583
2584 @defivar {<cgen-unit>} init-prologue
2585 @defivarx {<cgen-init>} init-epilogue
2586 @c EN
2587 A string to start or to end the initialization function, respectively.
2588 The default value of @code{init-prologue} is
2589 @code{"void Scm_Init_NAME(void) @{"} where @code{NAME} is the
2590 value of the @code{name} slot. The default value of @code{init-epilogue}
2591 is just @code{"@}"}. Each string appears in its own line.
2592
2593 To get the default initialization function name, use @code{cgen-unit-init-name}
2594 generic function.
2595
2596 To customize initialization function name, arguments and/or return type,
2597 set @code{init-prologue}.
2598
2599 The content of initialization function is filled by the code
2600 fragments registered by @code{cgen-init}.
2601 @c JP
2602 初期化関数の先頭と末尾に置かれる文字列。
2603 @code{init-prologue}のデフォルトは
2604 @code{"void Scm_Init_NAME(void) @{"}、
2605 @code{init-epilogue}のデフォルトは
2606 @code{"@}"}です。ただし@code{NAME}は@code{name}スロットの値です。
2607 各文字列は独立した行におかれます。
2608
2609 デフォルトの初期化関数名を知りたい場合は、@code{gen-unit-init-name}を呼んでください。
2610
2611 初期化関数名やその引数をカスタマイズしたい場合は、
2612 @code{init-prologue}を変更してください。
2613
2614 初期化関数の中身は、@code{cgen-init}で登録されたコード片から生成されます。
2615 @c COMMON
2616 @end defivar
2617 @end deftp
2618
2619 @deffn {Parameter} cgen-current-unit
2620 @c EN
2621 A parameter to keep the current cgen-unit.
2622 @c JP
2623 現在のcgen unitを保持するパラメータです。
2624 @c COMMON
2625 @end deffn
2626
2627 @c EN
2628 A typical flow of generating C code is as follows:
2629 @c JP
2630 Cコードを生成する典型的な流れは次のとおりです。
2631 @c COMMON
2632
2633 @enumerate
2634 @item
2635 @c EN
2636 Create a @code{<cgen-unit>} instance and make it the current unit.
2637 @c JP
2638 @code{<cgen-unit>}のインスタンスを作り、現在のunitとする。
2639 @c COMMON
2640 @item
2641 @c EN
2642 Call code insertion APIs with code fragments. Fragments are accumulated
2643 in the current unit.
2644 @c JP
2645 コード片を挿入するAPIを呼ぶ。コード片は現在のunitに蓄積される。
2646 @c COMMON
2647 @item
2648 @c EN
2649 Call @emph{emit} method (@code{cgen-emit-c}, @code{cgen-emit-h})
2650 on the unit, which generates a C file
2651 and optionally a header file.
2652 @c JP
2653 unitに対して@emph{emit}メソッド(@code{cgen-emit-c}、@code{cgen-emit-h})
2654 を呼ぶ。これでCファイルと、必要に応じてヘッダファイルが生成される。
2655 @c COMMON
2656 @end enumerate
2657
2658 @deffn {Generic Function} cgen-emit-c cgen-unit
2659 @deffnx {Generic Function} cgen-emit-h cgen-unit
2660 @c MOD gauche.cgen
2661 @c EN
2662 Write the accumulated code fragments in @var{cgen-unit} to a
2663 C source file and C header file. The name of the files are
2664 determined by calling @code{cgen-unit-c-file} and @code{cgen-unit-h-file},
2665 respectively. If the files already exist, its content is overwritten;
2666 you can't gradually write to the files.
2667 So, usually these procedures are called at the last step of the code
2668 generation.
2669 @c JP
2670 @var{cgen-unit}に蓄積されたコード片を、それぞれCソースファイルとCヘッダファイルに
2671 書き出します。ファイルの名前はそれぞれ@code{cgen-unit-c-file}と
2672 @code{cgen-unit-h-file}が返す値になります。
2673 ファイルが既に存在する場合、それは上書きされます
2674 (コードを追加してゆくようなことはできません)。
2675 したがって、これらはコード生成の最後のステップで呼ばれるのが普通です。
2676 @c COMMON
2677
2678 @c EN
2679 We'll explain the details of how each file is organized under
2680 ``Filling the content'' section below.
2681 @c JP
2682 各ファイルがどう構成されるかは、下の「内容を埋めてゆく」の項を参照してください。
2683 @c COMMON
2684 @end deffn
2685
2686 @deffn {Generic Function} cgen-unit-c-file cgen-unit
2687 @deffnx {Generic Function} cgen-unit-h-file cgen-unit
2688 @c MOD gauche.cgen
2689 @c EN
2690 Returns a string that names C source and header file for
2691 @var{cgen-unit}, respectively. The default method first
2692 looks at @code{c-file} or @code{h-file} slot of the
2693 @var{cgen-unit}, and if it is @code{#f}, use the value of @code{name}
2694 slot and appends an extension @code{.c} or @code{.h}.
2695 @c JP
2696 @var{cgen-unit}が扱うCソースファイルおよびヘッダファイルの名前を返します。
2697 デフォルトメソッドは、まず@var{cgen-unit}の@code{c-file}または@code{h-file}スロット
2698 の値を見て、@code{#f}でなければそれを返し、
2699 @code{#f}であれば@code{name}スロットの値に
2700 @code{.c}または@code{.h}の拡張子をつけたものを返します。
2701 @c COMMON
2702 @end deffn
2703
2704 @deffn {Generic Function} cgen-unit-init-name cgen-unit
2705 @c MOD gauche.cgen
2706 @c EN
2707 Returns a string that names the initialization function
2708 generated to C. It is used to create the default
2709 @code{init-prologue} value.
2710 @c JP
2711 Cで生成される初期化関数の名前を返します。この名前は@code{init-prologue}の
2712 デフォルト値の中で使われます。
2713 @c COMMON
2714 @end deffn
2715
2716 @c EN
2717 @subsubheading Filling the content
2718 @c JP
2719 @subsubheading 中身を埋めてゆく
2720 @c COMMON
2721
2722 @c EN
2723 There are four parts to which you can add C code
2724 fragment. Within each part, code fragments are rendered in the
2725 same order as added.
2726 @c JP
2727 Cコード片を追加できるパートは4つあります。それぞれのパートの中で、
2728 コード片は追加された順に出力されます。
2729 @c COMMON
2730
2731 @table @asis
2732 @item extern
2733 @c EN
2734 This part is put into the header file, if exists.
2735 @c JP
2736 このパートは、ヘッダファイルに出力されます。
2737 @c COMMON
2738 @item decl
2739 @c EN
2740 Placed at the beginning of the C source, after the standard
2741 prologue.
2742 @c JP
2743 Cソースファイル中の先頭部分、標準の先頭要素が出力されたあとに出力されます。
2744 @c COMMON
2745 @item body
2746 @c EN
2747 Placed in the C source, following the 'decl' part.
2748 @c JP
2749 Cソースファイル中の、declパートの後に出力されます。
2750 @c COMMON
2751 @item init
2752 @c EN
2753 Placed inside the initialization function, which appears at
2754 the end of the C source.
2755 @c JP
2756 Cソースファイルの末尾に出力される、初期化関数の中に出力されます。
2757 @c COMMON
2758 @end table
2759
2760 @c EN
2761 The following procedures are the simple way to put a source
2762 code fragments in an appropriate part:
2763 @c JP
2764 それぞれのパートにコードを追加するための手続きは次のとおりです。
2765 @c COMMON
2766
2767 @defun cgen-extern code @dots{}
2768 @defunx cgen-decl code @dots{}
2769 @defunx cgen-body code @dots{}
2770 @defunx cgen-init code @dots{}
2771 @c MOD gauche.cgen
2772 @c EN
2773 Put code fragments @var{code} @dots{} to the appropriate parts.
2774 Each fragment must be a string.
2775 @c JP
2776 コード片@var{code} @dots{}を各パートに追加します。
2777 各コード片は文字列でなければなりません。
2778 @c COMMON
2779 @end defun
2780
2781 @c EN
2782 This is a minimal example to show the typical usage.
2783 After running this code you'll get @code{my-cfile.c} and
2784 @code{my-cfile.h} in the current directory.
2785 @c JP
2786 下に、典型的な使い方の単純な例を示します。このコードを走らせると、
2787 カレントディレクトリに@code{my-cfile.c}と@code{my-cfile.h}ができます。
2788 @c COMMON
2789
2790 @example
2791 (use gauche.cgen)
2792
2793 (define *unit* (make <cgen-unit> :name "my-cfile"))
2794
2795 (parameterize ([cgen-current-unit *unit*])
2796 (cgen-decl "#include <stdio.h>")
2797 (cgen-init "printf(stderr, \"initialization function\\n\");")
2798 (cgen-body "void foo(int n) @{ printf(stderr, \"got %d\\n\", n); @}")
2799 (cgen-extern "void foo(int n);")
2800 )
2801
2802 (cgen-emit-c *unit*)
2803 (cgen-emit-h *unit*)
2804 @end example
2805
2806 @c EN
2807 These are handy escaping procedures; they are useful even
2808 if you don't use other parts of the @code{cgen} modules.
2809 @c JP
2810 次に示す手続きは、Cコードとして安全になるように文字列をエスケープします。
2811 他の@code{cgen}モジュールを使わずにCコードを生成する際に便利です。
2812 @c COMMON
2813
2814 @defun cgen-safe-name string
2815 @defunx cgen-safe-name-friendly string
2816 @defunx cgen-safe-string string
2817 @defunx cgen-safe-comment string
2818 @c MOD gauche.cgen
2819 @c EN
2820 Escapes characters invalid in C identifiers, C string literals or C comments.
2821 @c JP
2822 Cの識別子、文字列リテラル、あるいはコメントとして使えない文字の並びをエスケープします。
2823 @c COMMON
2824
2825 @c EN
2826 With @code{cgen-safe-name}, characters other than ASCII alphabets
2827 and digits are converted to a form @code{_XX}, where @code{XX} is
2828 hexadecimal notation of the character code. (Note that the character
2829 @code{_} is also converted.) So the returned string can be used
2830 safely as a C identifier. The mapping is injective, that is,
2831 if the source strings differ, the result string always differ.
2832 @c JP
2833 @code{cgen-safe-name}は、文字列中にASCIIアルファベットや数字以外の文字が
2834 現れたら、@code{_XX}に変換します。ここで@code{XX}はその文字の文字コードの
2835 16進数表現です(@code{_}自身も変換されます)。
2836 返される文字列はそのままCの識別子として使えます。
2837 この変換は単射であり、元の文字列が異なれば結果の文字列も異なったものになります。
2838 @c COMMON
2839
2840 @c EN
2841 On the other hand, @code{cgen-safe-name-friendly} converts
2842 the input string into more readable C identifier. @code{->} becomes
2843 @code{_TO} (e.g. @code{char->integer} becomes @code{char_TOinteger}),
2844 other @code{-} and @code{_} become @code{_},
2845 @code{?} becomes @code{P} (e.g. @code{char?} becomes @code{charP}),
2846 @code{!} becomes @code{X} (e.g. @code{set!} becomes @code{setX}),
2847 @code{<} and @code{>} become @code{_LT} and @code{_GT} respectively.
2848 Other special characters except @code{_} are converted to @code{_XX}
2849 as in @code{cgen-safe-name}. The mapping is not injective; e.g.
2850 both @code{read-line} and @code{read_line} map to @code{read_line}.
2851 Use this only when you think some human needs to read the generated
2852 C code (which is not recommended, by the way.)
2853 @c JP
2854 一方、@code{cgen-safe-name-friendly}はちょっと異なり、
2855 文字列をより読みやすいCの識別子の名前にします。
2856 @code{->}は@code{_TO}に (例: @code{char->integer}は@code{char_TOinteger}に)、
2857 他の@code{-}および@code{_}は@code{_}へとマップされます。
2858 @code{?}は@code{P} (例: @code{char?}は@code{charP}に)、
2859 @code{!}は@code{X} (例: @code{set!}は@code{setX}に),
2860 @code{<}と@code{>}はそれぞれ@code{_LT}と@code{_GT}になります。
2861 以上の文字を除く特殊な文字は@code{cgen-safe-name}と同様に@code{_XX}になります。
2862 この変換は単射ではありません。@code{read-line}と@code{read_line}は
2863 ともに@code{read_line}になってしまいます。
2864 生成されたCコードを人間に読みやすくしたい場合に限り使ってください
2865 (ただ、生成したCコードを人間が読むことは推奨されません)。
2866 @c COMMON
2867
2868 @c EN
2869 If you want to write out a Scheme string as a C string literal,
2870 you can use @code{cgen-safe-string}. It escapes control
2871 characters and non-ascii characters. If the Scheme string contains
2872 a character beyond ASCII, it is encoded in Gauche's native encoding.
2873 (NB: It also escapes @code{?}, to avoid accidenal formation of
2874 C trigraphs).
2875 @c JP
2876 Scheme文字列をCの文字列リテラルにしたい場合は@code{cgen-safe-string}が使えます。
2877 これは制御文字と非ASCII文字をエスケープします。
2878 ASCII範囲外の文字については、Gaucheの内部エンコーディングが使われます
2879 (この変換はまた、@code{?}も変換します。うっかりCのトライグラフを出力してしまわないためです)。
2880 @c COMMON
2881
2882 @c EN
2883 Much simpler is @code{cgen-safe-comment}, which just converts
2884 @code{/*} and @code{*/} into @code{/ *} and @code{* /} (a space
2885 between those two characters), so that it won't terminate the
2886 comment inadvertently. (Technically, escaping only @code{*/} suffice,
2887 but some simple-minded C parser might be confused by @code{/*} in the
2888 comments). The conversion isn't injective as well.
2889 @c JP
2890 @code{cgen-safe-comment}はずっとシンプルで、
2891 @code{/*}と@code{*/}をそれぞれ@code{/ *}と@code{* /}にするだけです
2892 (二文字の間に空白を入れます)。これは、Scheme文字列をCコメントの内部に出力する際に
2893 うっかりコメントを終わらせてしまわないようにするためです。
2894 (厳密には、エスケープするのは@code{*/}だけで良いはずですが、
2895 簡易的なCパーザには余分な@code{/*}で混乱してしまうものがあるかもしれないので
2896 @code{/*}もエスケープしています)。
2897 この変換も単射ではありません。
2898 @c COMMON
2899
2900 @example
2901 (cgen-safe-name "char-alphabetic?")
2902 @result{} "char_2dalphabetic_3f"
2903 (cgen-safe-name-friendly "char-alphabetic?")
2904 @result{} "char_alphabeticP"
2905 (cgen-safe-string "char-alphabetic?")
2906 @result{} "\"char-alphabetic\\077\""
2907
2908 (cgen-safe-comment "*/*"
2909 @result{} "* / *"
2910 @end example
2911 @end defun
2912
2913 @c EN
2914 If you want to conditionalize a fragment by C preprocessor
2915 @code{#ifdef}s, use the following macro:
2916 @c JP
2917 コードの断片をCプリプロセッサの@code{#ifdef}で条件的に含めたい場合は、
2918 次のマクロが使えます。
2919 @c COMMON
2920
2921 @defmac cgen-with-cpp-condition cpp-expr body @dots{}
2922 @c MOD gauche.cgen
2923 @c EN
2924 Code fragments submitted in @var{body} @dots{} are protected
2925 by @code{#if @var{cpp-expr}} and @code{#endif}.
2926 @c JP
2927 @var{body} @dots{}中で提出されたコード片が
2928 @code{#if @var{cpp-expr}}と@code{#endif}に囲まれて出力されます。
2929 @c COMMON
2930
2931 @c EN
2932 If @var{cpp-expr} is a string, it is emitted literally:
2933 @c JP
2934 @var{cpp-expr}が文字列の場合は、それが条件式としてそのまま出力されます。
2935 @c COMMON
2936
2937 @example
2938 (cgen-with-cpp-condition "defined(FOO)"
2939 (cgen-init "foo();"))
2940
2941 ;; will generate:
2942 #if defined(FOO)
2943 foo();
2944 #endif /* defined(FOO) */
2945 @end example
2946
2947 @c EN
2948 You can also construct @var{cpp-expr} by S-expr.
2949 @c JP
2950 @var{cpp-expr}にS式を使うこともできます。
2951 @c COMMON
2952
2953 @example
2954 <cpp-expr> : <string>
2955 | (defined <cpp-expr>)
2956 | (not <cpp-expr>)
2957 | (<n-ary-op> <cpp-expr> <cpp-expr> ...)
2958 | (<binary-op> <cpp-expr> <cpp-expr>)
2959
2960 <n-ary-op> : and | or | + | * | - | /
2961
2962 <binary-op> : > | >= | == | < | <= | !=
2963 | logand | logior | lognot | >> | <<
2964 @end example
2965
2966 @c EN
2967 Example:
2968 @c JP
2969 例:
2970 @c COMMON
2971
2972 @example
2973 (cgen-with-cpp-condition '(and (defined FOO)
2974 (defined BAR))
2975 (cgen-init "foo();"))
2976
2977 ;; will generate:
2978 #if ((defined FOO)&&(defined BAR))
2979 foo();
2980 #endif /* ((defined FOO)&&(defined BAR)) */
2981 @end example
2982
2983 @c EN
2984 You can nest @code{cgen-with-cpp-condition}.
2985 @c JP
2986 @code{cgen-with-cpp-condition}はネストすることもできます。
2987 @c COMMON
2988 @end defmac
2989
2990 @c EN
2991 @subsubheading Submitting code fragments for more than one parts
2992 @c JP
2993 @subsubheading 二つ以上のパートにコード片を出力する
2994 @c COMMON
2995
2996 @c EN
2997 When you try to abstract code generation process,
2998 calling individual procedures for each parts (e.g. @code{cgen-body}
2999 or @code{cgen-init}) becomes tedious, since such higher-level
3000 constructs are likely to require generating code fragments
3001 to various parts. Instead, you can create a customized class
3002 that handles submission of fragments to appropriate parts.
3003 @c JP
3004 コードの生成を抽象化してゆくと、ひとつの高レベルの構造が
3005 複数のパートにコードを出力しなければならないことがよくあります。
3006 その度に@code{cgen-body}や@code{cgen-init}を個別に呼ぶのは不便です。
3007 そのかわりに、カスタマイズされたクラスを定義して、適切なパートへの
3008 コード出力を処理させることができます。
3009 @c COMMON
3010
3011 @deftp {Class} <cgen-node>
3012 @clindex cgen-node
3013 @c MOD gauche.cgen
3014 @c EN
3015 A base class to represent a set of code fragments.
3016
3017 The state of C preprocessor condition (set by @code{with-cgen-cpp-condition})
3018 is captured when an instance of the subclass of this class is
3019 created, so generating appropriate @code{#if}s and @code{#endif}s are
3020 automatically handled.
3021 @c JP
3022 関連するコード断片の集まりを表すベースクラスです。
3023
3024 このクラスのサブクラスのインスタンスが作られた時点で、
3025 @code{with-cgen-cpp-condition}で指定されているCプリプロセッサの条件が補足され、
3026 コード生成時に必要な@code{#if}や@code{#endif}が出力されます。
3027 @c COMMON
3028 @end deftp
3029
3030 @c EN
3031 You subclass @code{<cgen-node>}, then define method(s) to
3032 one or more of the following generic functions:
3033 @c JP
3034 @code{<cgen-node>}のサブクラスを定義して、それに対して以下のメソッドのうち一つ以上を
3035 定義してください。
3036 @c COMMON
3037
3038 @deffn {Generic Function} cgen-emit-xtrn cgen-node
3039 @deffnx {Generic Function} cgen-emit-decl cgen-node
3040 @deffnx {Generic Function} cgen-emit-body cgen-node
3041 @deffnx {Generic Function} cgen-emit-init cgen-node
3042 @c MOD gauche.cgen
3043 @c EN
3044 These generic functions are called during writing out
3045 the C source within @code{cgen-emit-c} and @code{cgen-emit-h}.
3046 Inside these methods, anything written out to the
3047 current output port goes into the output file.
3048 @c JP
3049 @code{cgen-emit-c}や@code{cgen-emit-h}がCコードを書き出す際に、
3050 これらのジェネリックファンクションが呼ばれます。
3051 これらのメソッド内でcurrent output portに書き出されたものが、
3052 出力ファイルへと書き込まれます。
3053 @c COMMON
3054
3055 @c EN
3056 While generating @code{.h} file by @code{cgen-emit-h},
3057 @code{cgen-emit-xtrn} method for all submitted nodes are
3058 called in order of submission.
3059 @c JP
3060 @code{cgen-emit-h}によって@code{.h}ファイルが生成されている最中に、
3061 登録されたノードの@code{cgen-emit-xtrn}メソッドが、登録された順に呼ばれます。
3062 @c COMMON
3063
3064 @c EN
3065 While generating @code{.c} file by @code{cgen-emit-c},
3066 @code{cgen-emit-decl} method for all submitted nodes are
3067 called first, then @code{cgen-emit-body} method, then
3068 @code{cgen-emit-init} method.
3069 @c JP
3070 @code{cgen-emit-c}によって@code{.c}ファイルが生成されている最中に、
3071 登録されたノードに対し、
3072 まず@code{cgen-emit-decl}メソッドがまず登録された順に呼ばれ、
3073 次に@code{cgen-emit-body}メソッドが同じ順で呼ばれ、
3074 最後に@code{cgen-emit-init}メソッドが同じ順で呼ばれます。
3075 @c COMMON
3076
3077 @c EN
3078 If you don't specialize any one of these method, it doesn't
3079 generate code in that part.
3080 @c JP
3081 どれかのメソッドを特殊化していなければ、該当するパートのコードは生成されません。
3082 @c COMMON
3083 @end deffn
3084
3085 @c EN
3086 Once you define your subclass and create an instance,
3087 you can submit it to the current cgen unit by this procedure:
3088 @c JP
3089 サブクラスを定義しインスタンスを作った後で、次の手続きにより
3090 現在のcgen unitに対してノードを登録できます。
3091 @c COMMON
3092
3093 @defun cgen-add! cgen-node
3094 @c MOD gauche.cgen
3095 @c EN
3096 Submit @var{cgen-node} to the current cgen unit.
3097 If the current unit is not set, @var{cgen-node} is simply ignored.
3098 @c JP
3099 @var{cgen-node}を現在のcgen unitに登録します。
3100 現在のunitがセットされていなければ、@var{cgen-node}は単に無視されます。
3101 @c COMMON
3102 @end defun
3103
3104 @c EN
3105 In fact, the procedures @code{cgen-extern}, @code{cgen-decl},
3106 @code{cgen-body} and @code{cgen-init} are just a convenience
3107 wrapper to create an internal subclass specialized to generate
3108 code fragment only to the designated part.
3109 @c JP
3110 実のところ、手続き@code{cgen-extern}、@code{cgen-decl}、
3111 @code{cgen-body}、@code{cgen-init}はいずれも、
3112 該当するパートに出力されるメソッドだけを定義した@code{<cgen-node>}のサブクラスを
3113 内部的に使っています。
3114 @c COMMON
3115
3116
3117 @node Generating Scheme literals, Conversions between Scheme and C, Generating C source files, Generating C code
3118 @subsection Generating Scheme literals
3119 @c NODE Schemeリテラルを生成する
3120
3121 @c EN
3122 Sometimes you want to refer to a Scheme constant value in C code.
3123 It is trivial if the value is a simple thing like Scheme boolean
3124 (@code{SCM_TRUE}, @code{SCM_FALSE}), characters (@code{SCM_MAKE_CHAR(code)}),
3125 small integers (@code{SCM_MAKE_INT(value)}), etc. You can directly
3126 write it in C code. However, once you step outside of these simple
3127 values, it gets tedious quickly, involving static data declarations
3128 and/or runtime initialization code.
3129 @c JP
3130 Schemeの値を定数としてCコードに埋め込みたい場合がしばしばあります。
3131 それが単純な値、例えばSchemeの真偽値(@code{SCM_TRUE}/@code{SCM_FALSE})、
3132 文字(@code{SCM_MAKE_CHAR(code)})、小さい整数(@code{SCM_MAKE_INT(value)})、
3133 等であれば、直接Cコードに書き込めます。
3134 しかし、ひとたび単純な値の範囲を離れると、
3135 こっちでstaticデータ宣言をしてこっちでランタイムに初期化して…といった具合に
3136 急速に面倒になります。
3137 @c COMMON
3138
3139 @c EN
3140 For example, to get a Scheme value of a list of symbols @code{(a b c)},
3141 you have to (1) create @code{ScmString}s for the names of the symbols,
3142 (2) pass them to @code{Scm_Intern} to get Scheme symbols, then
3143 (3) call @code{Scm_Cons}es (or a convenience macro @code{SCM_LIST3}) to
3144 build a list.
3145 @c JP
3146 例えば、シンボルのリスト@code{(a b c)}をCに埋め込みたいとしたら、次の手順を
3147 踏む必要があります。
3148 (1) それぞれのシンボルの名前を@code{ScmString}として作る、
3149 (2) それを@code{ScmIntern}に渡してSchemeシンボルを作る、
3150 (3) @code{ScmCons} (あるいは便利なマクロ@code{SCM_LIST3}) でリストを作る。
3151 @c COMMON
3152
3153 @c EN
3154 With @code{gauche.cgen}, those code can be generated automatically.
3155 @c JP
3156 @code{gauche.cgen}を使うと、これらのコードを自動的に生成できます。
3157 @c COMMON
3158
3159 @c EN
3160 NOTE: If you use @code{cgen-literal}, make sure you call
3161 @code{(cgen-decl "#include <gauche.h>")} to include @file{gauche.h}
3162 before the first call of @code{cgen-literal}, which may insert
3163 declarations that needs @file{gauche.h}.
3164 @c JP
3165 註: @code{cgen-literal}を使う場合、最初にそれを呼ぶ前に
3166 @code{(cgen-decl "#include <gauche.h>")}
3167 を呼ぶようにしてください。@code{cgen-literal}が生成するコードは
3168 @file{gauche.h}内にある宣言を必要とします。
3169 @c COMMON
3170
3171 @defun cgen-literal obj
3172 @c MOD gauche.cgen
3173 @c EN
3174 Returns an @code{<cgen-literal>} object for a Scheme object @var{obj},
3175 and submit necessary declarations and initialization code to the
3176 current cgen unit.
3177 @c JP
3178 Schemeオブジェクト@var{obj}を表す@code{<cgen-literal>}オブジェクトを返します。
3179 また、必要な宣言や初期化コードが現在のcgenユニットに登録されます。
3180 @c COMMON
3181
3182 @c EN
3183 The detail of the @code{<cgen-literal>} object isn't for public use,
3184 but one thing you can do is to pass it to @code{cgen-cexpr}
3185 to obtain a C code fragment that refers to the Scheme value at runtime.
3186 See the example in @code{cgen-expr} entry below.
3187 @c JP
3188 @code{<cgen-literal>}オブジェクトの詳細は公開していませんが、
3189 @code{cgen-cexpr}にそれを渡すことで、Scheme値を実行時にCから参照するための
3190 Cコード断片を得ることができます。下の@code{cgen-cexpr}のエントリにある
3191 例を参照してください。
3192 @c COMMON
3193 @end defun
3194
3195 @deffn {Generic Function} cgen-cexpr cgen-literal
3196 @c MOD gauche.cgen
3197 @c EN
3198 Returns a C code expression fragment of type @code{ScmObj},
3199 which represents the Scheme literal value.
3200 @c JP
3201 @var{cgen-literal}が表すSchemeリテラル値を得るCコード片を返します。
3202 Cでの型は@code{ScmObj}になります。
3203 @c COMMON
3204
3205 @c EN
3206 If the Scheme object is a immediate one such as boolean or fixnum,
3207 the C code is a immediate code to return the value, e.g.
3208 @code{SCM_FALSE} or @code{SCM_MAKE_INT(1234)}. If the Scheme object
3209 requires allocation, @code{cgen-literal} allocates memory and
3210 initializes it, and @code{cgen-cexpr} returns a pointer to that object.
3211 @c JP
3212 Schemeオブジェクトが真偽値やfixnumのような単純な即値オブジェクトの場合は、
3213 @code{SCM_FALSE}や@code{SCM_MAKE_INT(1234)}といったその値を生成する式が
3214 返されます。Schemeオブジェクトがメモリ上に置かれなければならない場合は、
3215 @code{cgen-literal}は必要なメモリアロケーションと初期化のコードを生成し、
3216 @code{cgen-cexpr}はそのオブジェクトへのポインタを返す式を返します。
3217 @c COMMON
3218
3219 @c EN
3220 The following example creates a C function @code{printabc} that prints
3221 the literal value @code{(a b c)}, created by @code{cgen-literal}.
3222 @c JP
3223 次の例では、@code{cgen-literal}で作られたリテラル値@code{(a b c)}を
3224 表示するC関数@code{printabc}を生成しています。
3225 @c COMMON
3226
3227 @example
3228 (define *unit* (make <cgen-unit> :name "foo"))
3229 (parameterize ((cgen-current-unit *unit*))
3230 (let1 lit (cgen-literal '(a b c))
3231 (cgen-body
3232 (format "void printabc() @{ Scm_Printf(SCM_CUROUT, \"%S\", ~a); @}"
3233 (cgen-c-name lit)))))
3234 (cgen-emit-c *unit*)
3235 @end example
3236
3237 @c EN
3238 If you examine the generated file @file{foo.c}, you'll get a
3239 general idea of how it is handled.
3240 @c JP
3241 作られた@file{foo.c}を見ると、どのようにリテラル値が扱われているかわかるでしょう。
3242 @c COMMON
3243 @end deffn
3244
3245 @c EN
3246 One advantage of @code{cgen-literal} is that it tries to share
3247 the same literal whenever possible. If you call
3248 @code{(cgen-literal '(a b c))} twice in the same cgen unit,
3249 you'll get one instance of cgen-literal. If you call
3250 @code{(cgen-literal '(b c))} then, it will share the tail
3251 of the original list @code{(a b c)}. So you can just use
3252 @code{cgen-literal} whenever you need to have Scheme literal
3253 values, without worrying about generating excessive amount of
3254 duplicated code.
3255 @c JP
3256 @code{cgen-literal}を使うひとつのメリットは、共通のリテラルが共有されることです。
3257 ひとつのunitの中で@code{(cgen-literal '(a b c))}を2度呼ぶと、
3258 同じ実体が参照されます。さらに@code{(cgen-literal '(b c))}を呼ぶと、
3259 そのリテラルは@code{(a b c)}のリテラルの末尾部分を共有します。
3260 従って、リテラルが重複することを心配せずに、必要になった時に@code{cgen-literal}を
3261 呼ぶことができます。
3262 @c COMMON
3263
3264 @c EN
3265 (Note that the literals registered with @code{cgen-literal} must
3266 be treated as immutable, just as in the Scheme world.)
3267 @c JP
3268 (@code{cgen-literal}で登録されたリテラルは変更不可なものとして扱ってください。
3269 Scheme界でリテラルが変更不可なのと同じです)
3270 @c COMMON
3271
3272 @c EN
3273 Certain Scheme objects cannot be generated as a literal; for example,
3274 an opened port can't, since it carries lots of runtime information.
3275 @c JP
3276 Schemeオブジェクトの中にはリテラルにできないものもあります。
3277 例えばオープンされているポートは、実行時特有の情報を含むためリテラルにできません。
3278 @c COMMON
3279
3280 @c EN
3281 (There's a machinery to allow programmers to extend the @code{cgen-literal}
3282 behavior for new types. The API isn't fixed yet, though.)
3283 @c JP
3284 (プログラマが独自の型のために@code{cgen-literal}を拡張できる仕組みもありますが、
3285 APIがまだ固まっていません。)
3286 @c COMMON
3287
3288 @node Conversions between Scheme and C, C in S expression, Generating Scheme literals, Generating C code
3289 @subsection Conversions between Scheme and C
3290 @c NODE SchemeとCの間の変換
3291
3292 @c EN
3293 In the C world, Scheme objects are uniformly represented
3294 as an opaque tagged pointer @code{ScmObj}. In order to access
3295 the actual objects, you need to check its runtime type information
3296 and to retrive the actual C type out of it.
3297 @c JP
3298 Cの世界では、Schemeオブジェクトは不透明なタグつきポインタ@code{ScmObj}として
3299 統一的に扱われます。オブジェクトの実体にアクセスするには、
3300 実行時型情報を調べて、適切なCの型を取り出す必要があります。
3301 @c COMMON
3302
3303 @c EN
3304 @emph{Stub types} are the objects that bridge Scheme runtime types
3305 and C types. Since mappings between Scheme types and C types are
3306 not one-to-one, there are more stub types than either types;
3307 for example, Scheme @code{<integer>} type may be bridged to C @code{int}
3308 type by the stub type @code{<int>}, but it may also be bridged to
3309 C @code{short} type by the stub type @code{<short>}.
3310 @c JP
3311 @emph{スタブタイプ}はSchemeの型とCの型の橋渡しをするオブジェクトです。
3312 Schemeの型とCの型の対応は1対1ではないので、どちらの型よりも多いスタブタイプがあります。
3313 例えばSchemeの@code{<integer>}型は、スタブタイプ@code{<int>}によってCの@code{int}型
3314 にマップされるかもしれませんし、スタブタイプ@code{<short>}によってCの@code{short}型に
3315 マップされるかもしれません。
3316 @c COMMON
3317
3318 @c EN
3319 Do not confuse stub types and Gauche's runtime types---stub types
3320 are meta information associated to runtime types. You can look up
3321 a stub type by its name by @code{cgen-type-from-name}.
3322 The session below shows the difference of the runtime types and
3323 stub types:
3324 @c JP
3325 スタブタイプとGaucheの実行時型を混同しないようにしてください。
3326 スタブタイプは、実行時の型に結びつけられたメタ情報と言えます。
3327 スタブタイプの名前がわかると、@code{cgen-type-from-name}によって
3328 スタブタイプの実体を得ることができます。
3329 次のセッションは実行時型とスタブタイプの違いを見せるものです。
3330 @c COMMON
3331
3332 @example
3333 gosh> <int>
3334 #<native-type <int>>
3335 gosh> ,d
3336 #<native-type <int>> is an instance of class <native-type>
3337 slots:
3338 name : <int>
3339 super : #<class <integer>>
3340 c-type-name: "int"
3341 size : 4
3342 alignment : 4
3343
3344 gosh> (cgen-type-from-name '<int>)
3345 #<cgen-type <int>>
3346 gosh> ,d
3347 #<cgen-type <int>> is an instance of class <cgen-type>
3348 slots:
3349 name : <int>
3350 scheme-type: #<native-type <int>>
3351 c-type : "int"
3352 description: "int"
3353 cclass : #f
3354
3355 gosh> <integer>
3356 #<class <integer>>
3357 gosh> ,d
3358 #<class <integer>> is an instance of class <integer-meta>
3359 slots:
3360 name : <integer>
3361 cpl : (#<class <integer>> #<class <rational>> #<class <real>> #<cl
3362 direct-supers: (#<class <rational>>)
3363 accessors : ()
3364 slots : ()
3365 direct-slots: ()
3366 num-instance-slots: 0
3367 direct-subclasses: ()
3368 direct-methods: ()
3369 initargs : ()
3370 defined-modules: (#<module gauche>)
3371 redefined : #f
3372 category : builtin
3373 core-size : 0
3374
3375 gosh> (cgen-type-from-name '<integer>)
3376 #<cgen-type <integer>>
3377 gosh> ,d
3378 #<cgen-type <integer>> is an instance of class <cgen-type>
3379 slots:
3380 name : <integer>
3381 scheme-type: #<class <integer>>
3382 c-type : "ScmObj"
3383 description: "exact integer"
3384 cclass : #f
3385 @end example
3386
3387 Each stub type ``knows'' how to generate C expressions of
3388 @emph{C-predicate}, a @emph{boxer} and an @emph{unboxer}.
3389 A C-predicate takes @code{ScmObj} object and returns C boolean
3390 value that if the given object has a valid type and range for the
3391 stub type.
3392 A boxer takes C object and converts it to a Scheme object; it
3393 usually involves wrapping or @emph{boxing} the C value in a
3394 tagged pointer or object, hence the name.
3395 An unboxer does the opposite: takes a Scheme object and convert
3396 it to a C value. The Scheme object must be checked by the C-predicate
3397 before being passed to the unboxer.
3398
3399 We have a few categories of stub types.
3400
3401 @itemize @bullet
3402 @item
3403 Stub types corresponds to native types (@pxref{Native types}).
3404 @item
3405 Stub types corresponds to C-class types. These are Scheme object whose structure is defined in C.
3406 They can be treated as ScmObj or can be casted to the specific C type;
3407 e.g. @code{<symbol>} can be casted to @code{ScmSymbol*}.
3408 Its unboxer is @code{ScmObj -> C-TYPE*},
3409 and boxer is @code{C-TYPE* -> ScmObj}.
3410 @item
3411 Pass-through types. These are Scheme object that are also handled
3412 as ScmObj in C-level. Stub types only typecheck, and its boxer and
3413 unboxer are just identity. It can be either purely-Scheme-defined
3414 objects, or an object that can take multiple representations
3415 (e.g. @code{<integer>} can be a fixnum or @code{ScmBignum*},
3416 so the stub generator passes through it,
3417 and the C routine handles the internals.)
3418 @item
3419 Maybe stub types. It is noted by a question mark suffix.
3420 In stub context, we only concern maybe type
3421 that can be unboxed into a C pointer type. In addition to the objects
3422 of the origial type, it maps Scheme's @code{#f} to C's @code{NULL}
3423 and vice versa. For example, @code{<port>?} maps Scheme's @code{<port>}
3424 instance to C's @code{ScmPort*},
3425 @emph{and} Scheme's @code{#f} to C's @code{NULL}.
3426 @end itemize
3427
3428 @deftp {Class} <cgen-type>
3429 @clindex cgen-type
3430 @c MOD gauche.cgen
3431 An instance of this class represents a stub type.
3432 It can be looked up by name such as @code{<const-cstring>} by
3433 @code{cgen-type-from-name}.
3434 @end deftp
3435
3436 @defun cgen-type-from-name name
3437 @c MOD gauche.cgen
3438 Returns an instance of @code{<cgen-type>} that has @var{name}.
3439 If the name is unknown, @code{#f} is returned.
3440 @end defun
3441
3442 @defun cgen-box-expr cgen-type c-expr
3443 @defunx cgen-unbox-expr cgen-type c-expr
3444 @defunx cgen-pred-expr cgen-type c-expr
3445 @c MOD gauche.cgen
3446 @var{c-expr} is a string denotes a C expression.
3447 Returns a string of C expression that boxes, unboxes, or
3448 typechecks the @var{c-expr} according to the @var{cgen-type}.
3449
3450 @example
3451 ;; suppose foo() returns char*
3452 (cgen-box-expr
3453 (cgen-type-from-name '<const-cstring>)
3454 "foo()")
3455 @result{} "SCM_MAKE_STR_COPYING(foo())"
3456 @end example
3457 @end defun
3458
3459
3460 @node C in S expression, Stub generation, Conversions between Scheme and C, Generating C code
3461 @subsection CiSE - C in S expression
3462 @c NODE S式で書くC, CiSE - S式で書くC
3463
3464 Some low-level routines in Gauche are implemented in C, but they're
3465 written in S-expression. We call it ``C in S expression'', or @emph{CiSE}.
3466
3467 The advantage of using S-expression is its readability, obviously.
3468 Another advantage is that it allows us to write macros as
3469 S-expr to S-expr translation, just like the legacy Scheme macros.
3470 That's a powerful feature---effectively you can extend C language
3471 to suit your needs.
3472
3473 The @code{gauche.cgen.cise} module provides a set of tools to convert
3474 CiSE code into C code to be passed to the C compiler. It also has
3475 some support to overcome C quirks, such as preparing forward
3476 declarations.
3477
3478 Currently, we don't do rigorous check for CiSE; you can pass a
3479 CiSE expression to the translator that yields invalid C code, which will
3480 cause the C compiler
3481 to emit errors. The translator inserts line directives by default so the
3482 C compiler error message points to the location of original (CiSE) source
3483 instead of generated code; however, sometimes you need to look at
3484 the generated code to figure out what went wrong. We hope this
3485 will be improved in future.
3486
3487 In Gauche source code, CiSE is extensively used in precompiled Scheme
3488 files and recognized by the precompiler. However,
3489 @code{gauche.cgen.cise} is an independent module only relies
3490 on @code{gauche.cgen} basic features, so you can plug it
3491 to your own C code generating programs.
3492
3493 @menu
3494 * CiSE overview::
3495 * CiSE syntax::
3496 * CiSE procedures::
3497 @end menu
3498
3499 @node CiSE overview, CiSE syntax, C in S expression, C in S expression
3500 @subsubsection CiSE overview
3501
3502 Before diving into the details, it's easier to grasp
3503 some basic concepts.
3504
3505 A @emph{CiSE fragment} is an S-expression that follows
3506 CiSE syntax (@pxref{CiSE syntax}). A CiSE fragment can be
3507 translated to a C code fragment by @code{cise-render}.
3508 Note that some translation may not be local, e.g. it may
3509 want to emit forward declarations before other C code fragments.
3510 So, the full translation requires buffering---you process all
3511 the CiSE fragments and save output, emit forward declarations,
3512 then emit the saved C code fragments. We have a wrapper procedure,
3513 @code{cise-translate}, to take care of it, but for your purpose
3514 you may want to roll your own wrapper.
3515
3516 A @emph{CiSE macro} is a Scheme code that translates a CiSE
3517 fragment to another CiSE fragment. There are number of
3518 predefined CiSE macros. You can add your own CiSE macros by
3519 utilities such as
3520 @code{define-cise-stmt} and @code{define-cise-expr}.
3521
3522 A @emph{CiSE ambient} is a bundle of information that affects
3523 fragment translation. It contains CiSE macro definitions,
3524 and also it keeps track of forward declarations.
3525
3526 If you're not sure how a cise fragment corresponds to C code,
3527 you can interactively try it:
3528
3529 @example
3530 gosh> (cise-render-to-string
3531 '(.struct foo (i::int c::(const char*)))))
3532 "struct foo @{ int i; const char* c; @} "
3533 gosh> (cise-render-to-string
3534 '(define-cfn foo (x::int) (return (+ x 3)))
3535 'toplevel))
3536 " ScmObj foo(int x)@{@{return ((x)+(3));@}@}"
3537 @end example
3538
3539 (The second argument of @code{cise-render-to-string} specifies the
3540 context; @pxref{CiSE procedures}, for the details.)
3541
3542 @node CiSE syntax, CiSE procedures, CiSE overview, C in S expression
3543 @subsubsection CiSE syntax
3544
3545 In this section, we lists basic CiSE syntax. They are just data from
3546 the viewpoint of Gauche---so you can build and manipulate them like
3547 any S-expression (quasiquote comes pretty handy).
3548
3549 @subsubheading CiSE types
3550
3551 C types can be written either as a symbol (e.g. @code{int}) or
3552 a list (e.g. @code{(const char *)}. When used in definition, it is
3553 preceded by @code{::}. The following example shows types
3554 are used in local variable definitions:
3555
3556 @example
3557 (let* ([a :: int 0]
3558 [b :: (const char *) "abc"])
3559 ...)
3560 @end example
3561
3562 For the convenience and readability, you can write the variable name,
3563 separating double-colon and type name concatenated. You can also concatenate
3564 point suffixes (@code{char*} instead of @code{char *} in the following example):
3565
3566 @example
3567 (let* ([a::int 0]
3568 [b::(const char*) "abc"])
3569 ...)
3570 @end example
3571
3572 CiSE translater first breaks up these concatenated forms, then
3573 deal with types.
3574
3575 At this moment, CiSE does @emph{not} check if type is valid C type.
3576 It just pass along whatever given.
3577
3578 There are a few special type notations for more complex types.
3579 These can appear in middle of the type; for example, you can write
3580 @code{(const .struct x (a::int b::double) *)} to produce
3581 @code{const struct x @{int a; double b;@} *}.
3582
3583 @deffn {CiSE Type} .array elt-type (dim @dots{})
3584 Expands to C array type, whose element type is of @var{elt-type}
3585 and dimensions are @var{dim @dots{}}.
3586
3587 @example
3588 (cise-render-to-string '(.array char (3)))
3589 @result{} "char [3]"
3590
3591 (cise-render-to-string '(.array int (2 5)))
3592 @result{} "int [2][5]"
3593 @end example
3594
3595 The last element of @var{dim} can be @code{*}, corresponds to
3596 the C type without specifying the array size:
3597
3598 @example
3599 (cise-render-to-string '(.array char (*)))
3600 @result{} "char [3]"
3601
3602 (cise-render-to-string '(.array int (10 *)))
3603 @result{} "int [10][]"
3604 @end example
3605
3606 Here's an example of global C variable definition of array type:
3607
3608 @example
3609 (cise-render-to-string '(define-cvar params ::(.array int (PARAM_SIZE)))
3610 'toplevel)
3611 @result{} " int params[PARAM_SIZE];"
3612 @end example
3613 @end deffn
3614
3615 @deffn {CiSE Type} .struct [tag] [(field-spec @dots{})]
3616 @deffnx {CiSE Type} .union [tag] [(field-spec @dots{})]
3617 @end deffn
3618
3619 @deffn {CiSE Type} .function (arg-spec @dots{}) ret-type
3620 @end deffn
3621
3622
3623 @subsubheading CiSE statements
3624
3625 @deffn {CiSE Statement} begin stmt @dots{}
3626 Code grouping with @code{@{} and @code{@}}
3627 @end deffn
3628
3629 @deffn {CiSE Statement} let* (binding @dots{}) stmt @dots{}
3630 Define and optionally assign initial values to local variables.
3631 The @var{binding} is a form of either one of the following type:
3632
3633 @table @code
3634 @item (@var{name} [:: @var{type}] [@var{init-expr}])
3635 Define a C variable @var{name} of type @var{type}.
3636 @var{type} should be a CiSE type.
3637 If @var{type} is omitted, the default type is @code{ScmObj}.
3638 Optional @var{init-expr} is a CiSE expression to compute the initial
3639 value of @var{name}.
3640 Note that array initialization is not supported yet.
3641 @item (_ @var{cise-form})
3642 This is to allow arbitrary CiSE statement or expression @var{cise-form}
3643 between local variable definitions. See the example below.
3644 @end table
3645
3646 The @code{(_ cise-form)} binding is useful when you want to
3647 do some check between other bindings, without having nested
3648 @code{let*}:
3649
3650 @example
3651 (let* ([len::ScmSmallInt (Scm_Length lis)]
3652 [_ (when (< len 1) (Scm_Error "Lis is too short: %S" lis))]
3653 [first (SCM_CAR lis)])
3654 ...)
3655 @end example
3656 @end deffn
3657
3658 @deffn {CiSE Statement} if test-expr then-stmt [else-stmt]
3659 @deffnx {CiSE Statement} when test-expr stmt @dots{}
3660 @deffnx {CiSE Statement} unless test-expr stmt @dots{}
3661 @deffnx {CiSE Statement} cond (cond1 stmt1 @dots{}) @dots{} [ (@code{else} else-stmt @dots{}) ]
3662 Conditional statements.
3663 @end deffn
3664
3665 @deffn {CiSE Statement} case expr ((val1 @dots{}) stmt1 @dots{}) @dots{} [ (@code{else} else-stmt @dots{}) ]
3666 @deffnx {CiSE Statement} case/fallthrough expr ((val1 @dots{}) stmt1 @dots{}) @dots{} [ (@code{else} else-stmt @dots{}) ]
3667 Switch-case statement. @code{case} does not fall through between 'case'
3668 blocks while @code{case/fallthrough} does.
3669 @end deffn
3670
3671 @deffn {CiSE Statement} for (start-expr test-expr update-expr) stmt @dots{}
3672 @deffnx {CiSE Statement} for () stmt @dots{}
3673 @deffnx {CiSE Statement} loop stmt @dots{}
3674 @deffnx {CiSE Statement} while test-expr body @dots{}
3675 Loop statements.
3676 @end deffn
3677
3678 @deffn {CiSE Statement} for-each (@code{lambda} (var) stmt @dots{}) expr
3679 @deffnx {CiSE Statement} dolist [var expr] stmt @dots{}
3680 @var{expr} must yield a list. Traverse the list, binding each element to @var{var}
3681 and executing @var{stmt} @dots{}. The lambda form is a fake; you don't
3682 really create a closure.
3683 @end deffn
3684
3685 @deffn {CiSE Statement} pair-for-each (@code{lambda} (var) stmt @dots{}) expr
3686 Like @code{for-each}, but @var{var} is bound to each 'spine' cell instead of each
3687 element of the list.
3688 @end deffn
3689
3690 @deffn {CiSE Statement} dopairs [var expr] stmt @dots{}
3691 @end deffn
3692
3693 @deffn {CiSE Statement} dotimes (var expr) stmt @dots{}
3694 @var{expr} must yield an integer, @var{n}. Repeat @var{stmt} @dots{} by binding @var{var} from 0
3695 to (@var{n}-1).
3696 @end deffn
3697
3698 @deffn {CiSE Statement} return [expr]
3699 @deffnx {CiSE Statement} break
3700 @deffnx {CiSE Statement} continue
3701 Return, break and continue statements.
3702 @end deffn
3703
3704 @deffn {CiSE Statement} label name
3705 @deffnx {CiSE Statement} goto name
3706 Label and goto statements. We always add a null statement after the
3707 label so that we can place @code{(label @var{name})} at the end of a compound
3708 statement.
3709 @end deffn
3710
3711 @deffn {CiSE Statement} .if @var{expr} @var{stmt} [@var{stmt}]
3712 @deffnx {CiSE Statement} .when @var{expr} @var{stmt} @dots{}
3713 @deffnx {CiSE Statement} .unless @var{expr} @var{stmt} @dots{}
3714 @deffnx {CiSE Statement} .cond @var{clause} @dots{}
3715 @deffnx {CiSE Statement} .define @var{name}[(@var{arg} @dots{})] [@var{expr}]
3716 @deffnx {CiSE Statement} .undef @var{name}
3717 @deffnx {CiSE Statement} .include @var{path}
3718 Preprocessor directives.
3719
3720 @var{expr} could be
3721 a string, a symbol, a number or one of the following forms:
3722 @itemize
3723 @item
3724 @code{(defined @var{c})}
3725 @item
3726 @code{(not @var{c})}
3727 @item
3728 @code{(and @var{c})}
3729 @item
3730 @code{(or @var{c})}
3731 @item
3732 @code{(@var{op} @var{c} @dots{})} where @var{op} is either @code{+} or
3733 @code{*}.
3734 @item
3735 @code{(@var{op} @var{c} @var{c} @dots{})} where @var{op} is either
3736 @code{-} or @code{/}.
3737 @item
3738 @code{(@var{op} @var{c} @var{c})} where @var{op} is either @code{>},
3739 @code{>=}, @code{==}, @code{<}, @code{<=}, @code{!=}, @code{logand},
3740 @code{logior}, @code{lognot}, @code{<<} or @code{>>}.
3741 @end itemize
3742
3743 Note that defining a macro function without value
3744 @example
3745 #define foo(abc)
3746 @end example
3747 is not supported because it's ambiguous with
3748 @example
3749 #define foo abc()
3750 @end example
3751 when written in CiSE syntax. @code{(.define foo (abc))} always
3752 generates the latter.
3753
3754 @code{.include} could take a symbol. This is used for including system
3755 header files, e.g. @code{(.include <stdint.h>)}.
3756 @end deffn
3757
3758 @deffn {CiSE Statement} define-cfn name (arg [@code{::} type] @dots{}) [ret-type [qualifier @dots{}]] stmt @dots{}
3759 Defines a C function.
3760
3761 If @var{type} or @var{ret-type} is omitted, the default type is
3762 @code{ScmObj}.
3763
3764 Supported qualifiers are @code{:static} and @code{:inline}, corresponding
3765 to C's @code{static} and @code{inline} keywords. If @code{:static} is
3766 specified, forward declaration is automatically generated.
3767 @end deffn
3768
3769 @deffn {CiSE Statement} define-cvar name [@code{::} type] [qualifier @dots{}] [<init-expr>]
3770 Defines a global C variable. Supported qualifier is
3771 @code{:static}. Note that array initialization is not supported yet.
3772 @end deffn
3773
3774 @deffn {CiSE Statement} define-ctype name [@code{::} type]
3775 Defines a new type using @code{typedef}
3776 @end deffn
3777
3778 @deffn {CiSE Statement} declare-cfn name (arg [@code{::} type] @dots{}) [ret-type]
3779 @deffnx {CiSE Statement} declare-cvar name [@code{::} type]
3780 Declares an external C function or variable.
3781 @end deffn
3782
3783
3784 @deffn {CiSE Statement} .static-decls
3785
3786 Produce declarations of static functions before function bodies.
3787
3788 @end deffn
3789
3790 @deffn {CiSE Statement} .raw-c-code body @dots{}
3791
3792 @end deffn
3793
3794 @subsubheading CiSE expressions
3795
3796 @deffn {CiSE Expression} + expr @dots{}
3797 @deffnx {CiSE Expression} - expr @dots{}
3798 @deffnx {CiSE Expression} * expr @dots{}
3799 @deffnx {CiSE Expression} / expr @dots{}
3800 @deffnx {CiSE Expression} % expr1 expr2
3801 Arithmetic operations.
3802 @end deffn
3803
3804 @deffn {CiSE Expression} and expr @dots{}
3805 @deffnx {CiSE Expression} or expr @dots{}
3806 @deffnx {CiSE Expression} not expr
3807 Boolean operations.
3808 @end deffn
3809
3810 @deffn {CiSE Expression} logand expr1 expr2 @dots{}
3811 @deffnx {CiSE Expression} logior expr1 expr2 @dots{}
3812 @deffnx {CiSE Expression} logxor expr1 expr2 @dots{}
3813 @deffnx {CiSE Expression} lognot expr
3814 @deffnx {CiSE Expression} << expr1 expr2
3815 @deffnx {CiSE Expression} >> expr1 expr2
3816 Bitwise operations.
3817 @end deffn
3818
3819 @deffn {CiSE Expression} * expr
3820 @deffnx {CiSE Expression} -> expr1 expr2 @dots{}
3821 @deffnx {CiSE Expression} ref expr1 expr2 @dots{}
3822 @deffnx {CiSE Expression} aref expr1 expr2 @dots{}
3823 @deffnx {CiSE Expression} & expr
3824 Dereference, reference and address operations. @code{ref} is C's
3825 @code{.}. @code{aref} is array reference.
3826 @end deffn
3827
3828 @deffn {CiSE Expression} pre++ expr
3829 @deffnx {CiSE Expression} post++ expr
3830 @deffnx {CiSE Expression} pre-- expr
3831 @deffnx {CiSE Expression} post-- expr
3832 Pre/Post increment or decrement.
3833 @end deffn
3834
3835 @deffn {CiSE Expression} < expr1 expr2
3836 @deffnx {CiSE Expression} <= expr1 expr2
3837 @deffnx {CiSE Expression} > expr1 expr2
3838 @deffnx {CiSE Expression} >= expr1 expr2
3839 @deffnx {CiSE Expression} == expr1 expr2
3840 @deffnx {CiSE Expression} != expr1 expr2
3841 Comparison.
3842 @end deffn
3843
3844 @deffn {CiSE Expression} set! lvalue1 expr1 lvalue2 expr2 @dots{}
3845 @deffnx {CiSE Expression} = lvalue1 expr1 lvalue2 expr2 @dots{}
3846 @deffnx {CiSE Expression} += lvalue expr
3847 @deffnx {CiSE Expression} -= lvalue expr
3848 @deffnx {CiSE Expression} *= lvalue expr
3849 @deffnx {CiSE Expression} /= lvalue expr
3850 @deffnx {CiSE Expression} %= lvalue expr
3851 @deffnx {CiSE Expression} <<= lvalue expr
3852 @deffnx {CiSE Expression} >>= lvalue expr
3853 @deffnx {CiSE Expression} logand= lvalue expr
3854 @deffnx {CiSE Expression} logior= lvalue expr
3855 @deffnx {CiSE Expression} logxor= lvalue expr
3856 Assignment expressions.
3857 @end deffn
3858
3859 @deffn {CiSE Expression} cast type expr
3860 Type casting.
3861 @end deffn
3862
3863 @deffn {CiSE Expression} ?: test-expr then-expr else-expr
3864 Conditional expression.
3865 @end deffn
3866
3867 @deffn {CiSE Expression} .type type
3868 Useful to place a type name, e.g. an argument of sizeof operator.
3869 @end deffn
3870
3871 @deffn {CiSE Expression} new type
3872 @deffnx {CiSE Expression} new (type expr ...)
3873 @deffnx {CiSE Expression} new type (dim ...)
3874 @deffnx {CiSE Expression} new (type expr ...) (dim ...)
3875 C++ new operator. The second argument can be just a type name,
3876 or a constructor call. The optional second argument specifies
3877 array dimensions.
3878
3879 @example
3880 (new MyClass) @result{} new MyClass;
3881 (new (MyClass a b) (1 2)) @result{} new MyClass(a, b)[1,2];
3882 @end example
3883 @end deffn
3884
3885 @deffn {CiSE Expression} delete expr
3886 @deffnx {CiSE Expression} delete () expr
3887 C++ delete operator. The second form is to delete an array.
3888
3889 @example
3890 (delete (* foo)) @result{} delete *foo;
3891 (delete () foo) @result{} delete[] foo;
3892 @end example
3893 @end deffn
3894
3895
3896 @node CiSE procedures, , CiSE syntax, C in S expression
3897 @subsubsection CiSE procedures
3898
3899
3900 @deffn {Parameter} cise-ambient
3901 @c MOD gauche.cgen
3902 @end deffn
3903
3904 @defun cise-default-ambient
3905 @c MOD gauche.cgen
3906 @end defun
3907
3908 @defun cise-ambient-copy ambient
3909 @c MOD gauche.cgen
3910 @end defun
3911
3912 @defun cise-ambient-decl-strings ambient
3913 @c MOD gauche.cgen
3914 @end defun
3915
3916 @deffn {Parameter} cise-emit-source-line
3917 @c MOD gauche.cgen
3918 @end deffn
3919
3920 @defun cise-render cise-fragment :optional port context
3921 @c MOD gauche.cgen
3922 @end defun
3923
3924 @defun cise-render-to-string cise-fragment :optional context
3925 @c MOD gauche.cgen
3926 @end defun
3927
3928 @defun cise-render-rec cise-fragment stmt/expr env
3929 @c MOD gauche.cgen
3930 @end defun
3931
3932 @defun cise-translate inp outp :key environment
3933 @c MOD gauche.cgen
3934 @end defun
3935
3936
3937 @defun cise-register-macro! name expander :optional ambient
3938 @c MOD gauche.cgen
3939 @end defun
3940
3941 @defun cise-lookup-macro name :optional ambient
3942 @c MOD gauche.cgen
3943 @end defun
3944
3945 @defmac define-cise-stmt name [env] clause @dots{} [:where definition @dots{}]
3946 @defmacx define-cise-expr name [env] clause @dots{} [:where definition @dots{}]
3947 @defmacx define-cise-toplevel name [env] clause @dots{} [:where definition @dots{}]
3948 @c MOD gauche.cgen
3949 @end defmac
3950
3951 @defmac define-cise-macro (name form env) body @dots{}
3952 @defmacx define-cise-macro name name2
3953 @c MOD gauche.cgen
3954 @end defmac
3955
3956 @node Stub generation, , C in S expression, Generating C code
3957 @subsection Stub generation
3958 @c NODE スタブの生成
3959
3960 @deffn {Stub Form} define-stub-type NAME C-TYPE [DESC C-PREDICATE UNBOXER BOXER]
3961 Register a new type to be recognized. This is rather a declaration
3962 than definition; no C code will be generated directly by this form.
3963 @end deffn
3964
3965 @deffn {Stub Form} define-cproc name (args @dots{}) [ret-type] [flag @dots{}] [qualifier @dots{}] stmt @dots{}
3966 Create Scheme procedure.
3967
3968 @var{args} specifies arguments:
3969 @itemize
3970 @item
3971 @code{@var{arg} @dots{} [:rest @var{var}]} :
3972 Each @var{arg} is variable name or @var{var::type}, specifies required
3973 argument. If @code{:rest} is given, list of excessive arguments are
3974 passed to @var{var}.
3975
3976 @item
3977 @code{@var{arg} @dots{} :optional @var{spec} @dots{} [:rest @var{rest-var}]} :
3978 Optional arguments. @var{spec} is @var{var} or (@var{var}
3979 @var{default}). If no @var{default} is given, @var{var} receives
3980 @code{SCM_UNBOUND}---if @var{var} isn't a type of @code{ScmObj} it will
3981 raise an error.
3982
3983 @item
3984 @code{ARG @dots{} :key @var{spec} @dots{} [:allow-other-keys [:rest @var{rest-var}]]} :
3985 Keyword arguments. @var{spec} is @var{var} or (@var{var}
3986 @var{default}). If no @var{default} is given, @var{var} receives
3987 @code{SCM_UNBOUND}---if @var{var} isn't a type of @code{ScmObj} it will raise
3988 an error.
3989
3990 @item
3991 @code{arg @dots{} :optarray (@var{var} @var{cnt} @var{max}) [:rest @var{rest-var}]} :
3992 A special syntax to receive optional arguments as a C array.
3993 @var{var} is a C variable of type @code{ScmObj*}. @var{cnt} is a C
3994 variable of type @code{int}, which receives the number of optional
3995 argument in the ScmObj array. @var{max} specifies the maximum number
3996 of optional arguments that can be passed in the array form. If more
3997 than @var{max} args are given, a list of excessive arguments are
3998 passed to the @var{rest-var} if it is specified
3999 @end itemize
4000
4001 @var{ret-type} specifies the return type of function. It could be
4002 either @code{:: @var{typespec}} or @code{::@var{typespec}} where
4003 @var{typespec} is a valid stub type, or @code{(@var{type} @dots{})} when
4004 multiple values are returned. When omitted, the procedure is assumed
4005 to return @code{<top>}.
4006
4007 @var{flag} is a keyword to modify some aspects of the procedure.
4008 Supported flags are as follows:
4009
4010 @itemize
4011 @item
4012 @code{:fast-flonum} - indicates that the procedure accepts flonum
4013 arguments and it won't retain the reference to them. The VM can pass
4014 flonums on VM registers to the procedure with this flag. (This
4015 improves floating-point number handling, but it's behavior is highly
4016 VM-specific; ordinary stub writers shouldn't need to care about this
4017 flag at all.)
4018
4019 @item
4020 @code{:constant} - indicates that this procedure returns a constant
4021 value if all args are compile-time constants. The compiler may replace
4022 the call to this proc with the value, if it determines all arguments
4023 are known at the compile time. The resulting value should be
4024 serializable to the precompiled file.
4025
4026 NB: Since this procedure may be called at compile time, a subr that
4027 may return a different value for batch/cross compilation shouldn't
4028 have this flag.
4029 @end itemize
4030
4031 @var{qualifier} is a list to adds auxiliary information to the
4032 procedure. Currently the following qualifiers are officially
4033 supported.
4034
4035 @itemize
4036 @item
4037 @code{(setter @var{setter-name})} : specify setter. @var{setter-name} should
4038 be a cproc name defined in the same stub file
4039
4040 @item
4041 @code{(setter (@var{args} @dots{}) @var{body} @dots{})} : specify setter
4042 anonymously.
4043
4044 @item
4045 @code{(catch (@var{decl} @var{c-stmt} @dots{}) @dots{})} : when writing a stub
4046 for C++ function that may throw an exception, use this spec to ensure
4047 the exception will be caught and converted to Gauche error condition.
4048
4049 @item
4050 @code{(inliner @var{insn-name})} : only used in Gauche core procedures that
4051 can be inlined into an VM instruction.
4052 @end itemize
4053
4054 @var{stmt} is a cise expression. Inside the expression, a cise macro
4055 @code{(result expr @dots{})} can be used to assign the value(s) to
4056 return from the cproc. As a special case, if @var{stmt} is a single
4057 symbol, it names a C function to be called with the same argument (mod
4058 unboxing) as the cproc.
4059 @end deffn
4060
4061 @deffn {Stub Form} define-cgeneric @var{name} @var{c-name} @var{property-clause} @dots{}
4062 Defines generic function. @var{c-name} specifies a C variable name
4063 that keeps the generic function structure. One or more of the
4064 following clauses can appear in @var{property-clause} @dots{}:
4065
4066 @itemize
4067 @item
4068 @code{(extern)} : makes @var{c-name} visible from other file (i.e. do
4069 not define the structure as @code{static}).
4070
4071 @item
4072 @code{(fallback "fallback")} : specifies the fallback function.
4073
4074 @item
4075 @code{(setter . @var{setter-spec})} : specifies the setter.
4076 @end itemize
4077 @end deffn
4078
4079 @deffn {Stub Form} define-cmethod @var{name} (@var{arg} @dots{}) @var{body} @dots{}
4080 @end deffn
4081
4082 @deffn {Stub Form} define-cclass @var{scheme-name} [@var{qualifier} @dots{}] @var{c-type-name} @var{c-class-name} @var{cpa} (@var{slot-spec} @dots{}) @var{property} @dots{}
4083 Generates C stub for static class definition, slot accessors and
4084 initialization. Corresponding C struct has to be defined elsewhere.
4085
4086 The following qualifiers are supported:
4087 @itemize
4088 @item
4089 @code{:base} generates a base class definition (inheritable from
4090 Scheme code).
4091 @item
4092 @code{:built-in} generates a built-in class definition (not
4093 inheritable from Scheme code). This is the default if neither
4094 @code{:base} nor @code{:built-in} are specified.
4095 @item
4096 @code{:private} - the class declaration and standard macro definitions
4097 are also generated (which needs to be in the separate header file if
4098 you want the C-level structure to be used from other C code. If the
4099 extension is small enough to be contained in one C file, this option
4100 is convenient.)
4101 @end itemize
4102
4103 @var{cpa} lists ancestor classes in precedence order. They need to be
4104 C identifiers of Scheme class @code{Scm_*Class}, for the time being.
4105 @code{Scm_TopClass} is added at the end automatically.
4106
4107 @var{slot-spec} is defined as @code{(@var{slot-name} [@var{qualifier}
4108 @dots{}])} or @code{@var{slot-name}}. The following qualifiers are
4109 supported:
4110
4111 @itemize
4112 @item
4113 @code{:type @var{cgen-type}}
4114 @item
4115 @code{:c-name @var{c-name}} specifies the C field name if the
4116 autogenerated name from @var{slot-name} is not accurate.
4117 @item
4118 @code{:c-spec @var{c-spec}}
4119 @item
4120 @code{:getter @var{proc-spec}}
4121 specifies how to create the slot getter. @var{proc-spec} could be
4122 @itemize
4123 @item
4124 @code{#f} to omit the getter
4125 @item
4126 @code{#t} to generate a default one with type conversion according to
4127 @var{type}
4128 @item
4129 A string is interpreted as the C code to implement the getter
4130 @item
4131 @code{(c @var{c-name})} specifies the C function name that implements
4132 the getter, which is implemented elsewhere.
4133 @end itemize
4134 @item
4135 @code{:setter @var{proc-spec}}
4136 specifies how to create the slot setter. The syntax is the same as
4137 @code{:getter}.
4138 @end itemize
4139
4140 The following @var{property} are supported:
4141
4142 @itemize
4143 @item
4144 @code{(allocator @var{proc-spec})}
4145 @item
4146 @code{(printer @var{proc-spec})}
4147 @item
4148 @code{(comparer @var{proc-spec})}
4149 @item
4150 @code{(direct-supers @var{string} @dots{})}
4151 @end itemize
4152
4153 @end deffn
4154
4155 @deffn {Stub Form} define-cptr @var{scheme-name} [@var{qualifier} @dots{}] @var{c-type} @var{c-name} @var{c-pred} @var{c-boxer} @var{c-unboxer} [(flags @var{flag} @dots{})] [(print @var{print-proc})] [(cleanup @var{cleanup-proc})]
4156 Defines a new foreign pointer class based on
4157 @code{<foreign-pointer>}. It is suitable when the C structure is
4158 mostly passed around using pointers; most typically, when the foreign
4159 library allocates the structure and returns the pointer to the Scheme
4160 world.
4161
4162 @var{scheme-name} is a Scheme variable name. This will be bound to a
4163 newly-created subclass of @code{<foreign-pointer>} to represent this
4164 C-ptr type.
4165
4166 @var{c-type} is the type of the C pointer we wrap.
4167
4168 @var{c-name} is the C variable name (of type @code{ScmClass *}). In
4169 initialization code, an instance of a class (the same one bound to
4170 @var{scm-name} in the Scheme world) will be stored in this C variable.
4171
4172 @var{c-pred} is a macro name to determine if a @code{ScmObj} is of
4173 this type.
4174 @var{c-boxer} is a macro name to wrap C pointer and return a
4175 @code{ScmObj}
4176 @var{c-unboxer} is a macro name to extract C pointer from a
4177 @code{ScmObj}
4178
4179 The only supported qualifier is @code{:private}, which will generate
4180 @var{c-pred}, @var{c-boxer} and @var{c-unboxer} definitions
4181 automatically. Otherwise those definitions must be provided elsewhere.
4182
4183 The two supported flags are
4184 @itemize
4185 @item
4186 @code{:keep-identity} (which is
4187 @code{SCM_FOREIGN_POINTER_KEEP_IDENTITY} in the C world) keeps a weak
4188 hash table that maps the wrapped C pointer to the wrapping
4189 @code{ScmObj}, so @code{Scm_MakeForeignPointer} (i.e. @var{c-boxer}
4190 when @code{:private} is used) returns eq? object if the same C pointer
4191 is given.
4192
4193 This incurs some overhead, but cleanup procedure can safely free the
4194 foreign object without worrying if there's other ScmObj that's
4195 pointing to the same C pointer.
4196
4197 Do not use this flag if the C pointer is also allocated by
4198 @code{GC_malloc}. The used hash table is only weak for its value, so
4199 the C pointer wouldn't be GCed.
4200 @item
4201 @code{:map-null} (which is @code{SCM_FOREIGN_POINTER_MAP_NULL} in the
4202 C world) makes @code{Scm_MakeForeignPointer} (i.e. @var{c-boxer} when
4203 @code{:private} is used) return @code{SCM_FALSE} when the C pointer is
4204 @code{NULL}.
4205 @end itemize
4206 @end deffn
4207
4208 @deffn {Stub Form} define-symbol @var{scheme-name} [@var{c-name}]
4209 Defines a Scheme symbol. No Scheme binding is created.
4210 When @var{c-name} is given, the named C variable points to the created
4211 @code{ScmSymbol}.
4212 @end deffn
4213
4214 @deffn {Stub Form} define-variable @var{scheme-name} @var{initializer}
4215 Defines a Scheme variable.
4216 @end deffn
4217
4218 @deffn {Stub Form} define-constant @var{scheme-name} @var{initializer}
4219 Defines a Scheme constant.
4220 @end deffn
4221
4222 @deffn {Stub Form} define-enum @var{name}
4223 A @code{define-constant} specialized for enum values. This is useful for
4224 exporting C enums to Scheme.
4225 @end deffn
4226
4227 @deffn {Stub Form} define-enum-conditionally @var{name}
4228 Abbreviation of @code{(if "defined(name)" (define-enum name))}
4229 @end deffn
4230
4231 @deffn {Stub Form} define-cise-stmt @var{name} @var{clause} @dots{}
4232 @deffnx {Stub Form} define-cise-expr @var{name} @var{clause} @dots{}
4233 @deffnx {Stub Form} define-cfn @dots{}
4234 @deffnx {Stub Form} declare-cfn @dots{}
4235 @deffnx {Stub Form} define-cvar @dots{}
4236 @deffnx {Stub Form} declare-cvar @dots{}
4237 @deffnx {Stub Form} define-ctype @dots{}
4238 @deffnx {Stub Form} .define @dots{}
4239 @deffnx {Stub Form} .if @dots{}
4240 @deffnx {Stub Form} .include @dots{}
4241 @deffnx {Stub Form} .undef @dots{}
4242 @deffnx {Stub Form} .unless @dots{}
4243 @deffnx {Stub Form} .when @dots{}
4244 Cise macro definitions (see @ref{C in S expression}).
4245 @end deffn
4246
4247 @deffn {Stub Form} initcode @var{c-code}
4248 Insert @var{c-code} literally in the initialization function
4249 @end deffn
4250
4251 @deffn {Stub Form} declcode @var{stmt} @dots{}
4252 Inserts declaration code. @var{stmt} is usually @code{.include} or
4253 other preprocessor statements but it could also be a string which is
4254 treated as C fragments.
4255 @end deffn
4256
4257 @deffn {Stub Form} begin @var{form} @dots{}
4258 Treat each @var{form} as if they are toplevel stub forms.
4259 @end deffn
4260
4261 @deffn {Stub Form} if @var{test} @var{then-stmt} [@var{else-stmt}]
4262 @deffnx {Stub Form} when @var{test} @var{stmt}
4263 @c DEPRECATED
4264 Please use @code{.if} and @code{.when} instead.
4265 @end deffn
4266
4267 @deffn {Stub Form} include @var{file}
4268 Include and evaluate another stub file.
4269 @end deffn
4270
4271
4272 @c ----------------------------------------------------------------------
4273 @node Character code conversion, Collection framework, Generating C code, Library modules - Gauche extensions
4274 @section @code{gauche.charconv} - Character Code Conversion
4275 @c NODE 文字コード変換, @code{gauche.charconv} - 文字コード変換
4276
4277 @deftp {Module} gauche.charconv
4278 @mdindex gauche.charconv
4279 @c EN
4280 This module defines a set of functions that converts character encoding
4281 schemes (CES) of the given data stream.
4282
4283 This module is implicitly loaded when @code{:encoding} keyword argument
4284 is given to the file stream creating functions
4285 (such as @code{open-input-file} and @code{call-with-output-file}).
4286 @c JP
4287 与えられたデータストリームの文字エンコーディングを変換するための手続き群を提供する
4288 モジュールです。
4289
4290 このモジュールはまた、@code{open-input-file}や
4291 @code{call-with-output-file}等のファイルストリームを作成する手続きに
4292 @code{:encoding}キーワード引数が与えられた場合に暗黙にロードされます。
4293 @c COMMON
4294
4295 @c EN
4296 For the portable programs, you can use @emph{transcoded ports}
4297 defined in SRFI-181 (@pxref{Transcoded ports}).
4298 @c JP
4299 ポータブルなコードには、SRFI-181で定義される@emph{符号変換ポート}を使うこともできます
4300 (@ref{Transcoded ports}参照)。
4301 @c COMMON
4302 @end deftp
4303
4304 @menu
4305 * Supported character encoding schemes::
4306 * Autodetecting the encoding scheme::
4307 * Conversion ports::
4308 @end menu
4309
4310 @node Supported character encoding schemes, Autodetecting the encoding scheme, Character code conversion, Character code conversion
4311 @subsection Supported character encoding schemes
4312 @c NODE サポートされる文字エンコーディング
4313
4314 @c EN
4315 A CES is represented by its name as a string or a symbol.
4316 Case is ignored. There may be several aliases defined for a single encoding.
4317 @c JP
4318 CESの名前は文字列またはシンボルで指定します。大文字小文字の違いは無視されます。
4319 同じCESにいくつかの別名がついていることがあります。
4320 @c COMMON
4321
4322 @c EN
4323 A CES name "none" is special; it means the string is an octet sequence
4324 and it's up to the application
4325 to interpret the sequence in an appropriate encoding. So, conversion
4326 to and from CES "none" does nothing.
4327 @c JP
4328 CES名 "none" は特殊で、文字列を単なるバイト列として扱い、そのエンコーディングの解釈は
4329 アプリケーションに任されます。したがって、CES "none" への変換、および "none"
4330 からの変換は「何もしない」変換として扱われます。
4331 @c COMMON
4332
4333 @c EN
4334 Gauche natively supports conversions between
4335 Unicode transfer encodings (UTF-8, UTF-16, UTF-16BE, UTF-16LE,
4336 UTF-32, UTF-32BE, UTF-32LE), Latin-N encodings
4337 (ISO8859-1 to 16), and
4338 typical Japanese character encodings: ISO2022JP, ISO2022JP-3,
4339 EUC-JP (EUC-JISX0213), Shift_JISX0213.
4340 @c JP
4341 Gaucheは自前で、Unicode Transfer Encoding (UTF-8, UTF-16, UTF-16BE, UTF-16LE,
4342 UTF-32, UTF-32BE, UTF-32LE)、Latin-N (ISO8859-1から16)、
4343 そして主要な日本語エンコーディング
4344 (ISO2022JP, ISO2022JP-3, EUC-JP (EUC-JISX0213), Shift_JIS (Shift_JISX0213))、
4345 の間の変換を行います。
4346 @c COMMON
4347
4348 @c EN
4349 Conversions between other encodings are handled by @code{iconv(3)}
4350 by default. However, @code{iconv(3)} API lacks a feature to customize
4351 the behavior when an input character can't be encoded in the output CES.
4352 If you need to be sensitive about it, you can disable delegation to
4353 @code{iconv(3)} by the following parameter.
4354 @c JP
4355 上記以外のコードとの変換はデフォルトで@code{iconv(3)}を利用します。
4356 ただ、@code{iconv(3)}のAPIには、出力CESでエンコードできない文字が入力に
4357 含まれていた場合の振る舞いをカスタマイズするインタフェースがありません。
4358 そこまでの制御が必要なら、次のパラメータで@code{iconv(3)}の使用を止めることができます。
4359 @c COMMON
4360
4361 @deffn {Parameter} external-conversion-library
4362 @c EN
4363 The value of this parameter can be a symbol @code{iconv} or @code{#f}.
4364 The default value is @code{iconv}.
4365
4366 Conversion ports opened during this parameter being @code{iconv}
4367 will use @code{iconv(3)} library if the requested conversion isn't
4368 supported by Gauche's native converters.
4369 This only affect when the conversion port
4370 is opened---once it is opened, this parameter value is irrelevant.
4371 @c JP
4372 このパラメータの値はシンボル@code{iconv}か@code{#f}でなければなりません。
4373 デフォルトの値は@code{iconv}です。
4374
4375 このパラメータの値が@code{iconv}である間にオープンされた変換ポートは、
4376 要求された変換がGauche内部でサポートされていなかった場合に@code{iconv(3)}ライブラリを
4377 使います。変換ポートがopenされる時点でのパラメータの値が重要です--一旦オープンされたら、
4378 パラメータの値はそのポートの動作に影響を与えません。
4379 @c COMMON
4380 @end deffn
4381
4382 @c EN
4383 You can check whether the specific conversion is supported on
4384 your system or not, by the following function.
4385 @c JP
4386 特定の変換がシステムでサポートされているかどうかは次の手続きで調べることができます。
4387 @c COMMON
4388
4389 @defun ces-conversion-supported? from-ces to-ces
4390 @c MOD gauche.charconv
4391 @c EN
4392 Returns @code{#t} if conversion from the character encoding scheme
4393 (CES) @var{from-ces} to @var{to-ces} is supported in this system.
4394
4395 Note that this procedure may return true even if system only supports
4396 partial conversion between @var{from-ces} and @var{to-ces}.
4397 In such case, actual conversion might lose information by coercing
4398 characters in @var{from-ces} which are not supported in @var{to-ces}.
4399 (For example, conversion from Unicode to EUC-JP is "supported",
4400 although Unicode has characters that are not in EUC-JP).
4401
4402 Also note that this procedure always returns @code{#t}
4403 if @var{from-ces} and/or @var{to-ces} is "none",
4404 for conversion to/from CES "none" always succeeds (in fact, it does nothing).
4405
4406 This procedure may be affected by the value of the parameter
4407 @code{external-conversion-library}.
4408 @c JP
4409 CES @var{from-ces}から@var{to-ces}への変換がサポートされていれば@code{#t}を、
4410 そうでなければ@code{#f}を返します。
4411
4412 システムが@var{from-ces}から@var{to-ces}への変換を部分的にしか
4413 サポートしていない場合でもこの手続きは@code{#t}を返すことに注意して下さい。
4414 そのような場合、実際の変換作業は@var{from-ces}にあって@var{to-ces}にない
4415 コードを置換文字に置き換える等で情報を失うかもしれません
4416 (例えば、UnicodeからEUC-JPへの変換はサポートされていますが、
4417 UnicodeにはEUC-JPにない文字も含まれています)。
4418
4419 @var{from-ces}か@var{to-ces}が "none" ならばこの手続きは常に@code{#t}を
4420 返します。なぜならそのような変換は常に成功するからです(何も変換しないわけですが)。
4421
4422 この手続きは、パラメータ@code{external-conversion-library}に影響を受けます。
4423 @c COMMON
4424 @end defun
4425
4426 @c EN
4427 Also there are two useful procedures to deal with CES names.
4428 @c JP
4429 また、CESを扱う二つの便利な手続きが用意されています。
4430 @c COMMON
4431
4432 @defun ces-equivalent? ces-a ces-b :optional unknown-value
4433 @c MOD gauche.charconv
4434 @c EN
4435 Returns true if two CESes @var{ces-a} and @var{ces-b} are equivalent
4436 to the knowledge of the system. Returns false if they are not.
4437 If the system doesn't know about equivalency, @var{unknown-value}
4438 is returned, whose default is @code{#f}.
4439
4440 CES "none" works like a wild card; it is "equivalent" to any CES.
4441 (Thus, @code{ces-equivalent?} is not transitive.
4442 The intended use of @code{ces-equivalent?}
4443 is to compare two given CES names and see if conversion is required or not).
4444 @c JP
4445 CES @var{ces-a}と@var{ces-b}がシステムの知る限りで等価だった場合に
4446 @code{#t}を、等価でない場合に@code{#f}を返します。
4447 システムがその等価性を判断出来ない場合は@var{unknown-value}に与えられた
4448 値を返します。そのデフォルトは@code{#f}です。
4449
4450 CES名 "none" はワイルドカードのように動作します。それはどんなCESとも
4451 等価と見倣されます。(従って、@code{ces-equivalent?} は遷移的ではありません。
4452 この手続きは、二つのCESを知った時に相互の変換が
4453 必要かどうかを判断するためのものです)。
4454 @c COMMON
4455
4456 @example
4457 (ces-equivalent? 'eucjp "EUC-JP") @result{} #t
4458 (ces-equivalent? 'shift_jis "EUC-JP") @result{} #f
4459 (ces-equivalent? "NoSuchEncoding" 'utf-8 '?) @result{} ?
4460 @end example
4461 @end defun
4462
4463 @defun ces-upper-compatible? ces-a ces-b :optional unknown-value
4464 @c MOD gauche.charconv
4465 @c EN
4466 Returns true if a string encoded in CES @var{ces-b} can also
4467 be regarded as a string encoded in @var{ces-a} without conversion,
4468 to the knowledge of the system.
4469 Returns false if not. Returns @var{unknown-value}
4470 if the system can't determine which is the case.
4471
4472 Like @code{ces-equivalent?}, CES "none" works like a wildcard.
4473 It is upper-compatible to any CES, and any CES is upper-compatible to
4474 "none".
4475 @c JP
4476 CES @var{ces-b}でエンコードされた文字列が、システムの知る限りで
4477 変換無しに@var{ces-a}でエンコードされたものと見倣せる場合に@code{#t}を
4478 返します。見倣せない場合は@code{#f}を返します。
4479 システムが判断できない場合は@var{unknown-value}に与えられた
4480 値を返します。そのデフォルトは@code{#f}です。
4481
4482 @code{ces-equivalent?}と同様に、CES名 "none" はワイルドカードとして
4483 働きます。@var{ces-a} か @var{ces-b} が "none" であれば、
4484 常に@code{#t}が返されます。
4485 @c COMMON
4486
4487 @example
4488 (ces-upper-compatible? "eucjp" "ASCII") @result{} #t
4489 (ces-upper-compatible? "eucjp" "utf-8") @result{} #f
4490 (ces-upper-compatible? "utf-8" "NoSuchEncoding" '?) @result{} ?
4491 @end example
4492 @end defun
4493
4494 @c EN
4495 When Gauche's internal conversion routine encounters a character that can't
4496 be mapped, the behaivor depends on the @emph{illegal output handling mode}
4497 of the conversion port, specified by @var{illegal-output} keyword
4498 arguments.
4499 If the mode is @code{raise}, an @code{<io-encoding-error>}
4500 is thrown. If the mode is @code{replace},
4501 the character is replaced with a replacement character.
4502
4503 A replacement character is U+FFFD (REPLACEMENT CHARACTER) if it is
4504 available. For Japanese encodings, U+FFFD isn't available, and
4505 we use U+3013 (geta mark), for it is traditionally used as the
4506 replacement character. If neither one is available,
4507 @code{?} is used.
4508
4509 If that happens in iconv, handling of such character depends
4510 on iconv implementation (glibc implementation returns an error).
4511 @c JP
4512 出力CESへマップ不可能な入力文字に出会った場合のGaucheの内部変換ルーチンの動作は、
4513 @var{illegal-output}キーワード引数で指定される
4514 変換ポートの不正出力ハンドリングモードで決まります。
4515 モードが@code{raise}なら@code{<io-encoding-error>}が投げられます。
4516 モードが@code{replace}なら、その文字は置換文字に置き換えられます。
4517
4518 変換先の文字エンコーディングで UniocdeのU+FFFD (REPLACEMENT CHARACTER)
4519 が使えればそれが置換文字となります。日本語エンコーディングではその文字は
4520 使えませんが、伝統的にgeta mark '〓' (U+3013) が使われてきたので
4521 それに準じてU+3013を使います。どちらの文字も使えなければ@code{?}に置換します。
4522
4523 入力CESでシングルバイトである場合は '?' に置換します。
4524 iconvによる変換でマップ不可能な文字に出会った場合の処理はiconvの実装に
4525 依存します(例えばglibcではエラーとなります)。
4526 @c COMMON
4527
4528 @c EN
4529 If the conversion routine encounters an input sequence that
4530 is illegal in the input CES, an @code{<io-decoding-error>} is signaled.
4531 @c JP
4532 変換ルーチンが、入力CESとして不正な入力文字列に出会った場合は
4533 @code{<io-decoding-error>}が報告されます。
4534 @c COMMON
4535
4536 @c EN
4537 @subsubheading UTF encoding and BOM
4538 @c JP
4539 @subsubheading UTFエンコーディングとBOM
4540 @c COMMON
4541
4542 @c EN
4543 Unicode character U+FEFF (Zero-Width No-Break Space) can have a
4544 special meaning if it appears at the very beginning of UTF stream.
4545 It serves as a BOM (Byte-order mark) to signify the byte order
4546 of the following UTF data. For UTF-16 and UTF-32, it is critical
4547 to know the byte order. UTF-8 does not need one, for the byte order
4548 doesn't matter. Nevertheless, some software adds BOM to a UTF-8 data
4549 just to indicate it is in UTF-8.
4550 @c JP
4551 Unicode文字U+FEFF (Zero-Width No-Break Space) はUTFストリームの最初に
4552 現れると特別な意味を持ちます。後続のUTFデータのバイトオーダーを記述する
4553 BOM (Byte-order mark)になるのです。
4554 UTF-16とUTF-32ではバイトオーダーを知ることは決定的に重要です。
4555 一方、UTF-8ではバイトオーダーは関係ないのでBOMは必要ではありませんが、
4556 いくつかのソフトウェアはデータがUTF-8であることを判別するためだけに
4557 BOMを付加することがあります。
4558 @c COMMON
4559
4560 @c EN
4561 Technically, BOM is not a part of the text content, but rather a
4562 piece of meta-information about the format. That poses an issue;
4563 when you deal with a data stream,
4564 sometimes you just want to deal with the content, while the other times
4565 you want to deal with the entire data, including the meta-information.
4566 Traditionally those two are not strictly distinguished and
4567 dealt in ad-hoc way.
4568 We take the following approach, depending on the specified encoding.
4569 @c JP
4570 技術的な観点からは、BOMはテキストの内容の一部ではなく、フォーマットに関するメタ情報です。
4571 これはちょっと困った事態を引き起こします。データストリームを扱う時に、
4572 テキストの内容を読みたい場合と、メタ情報を含めた全体を扱いたい場合があるからです。
4573 伝統的に、この二つは厳密には区別されず、アドホックな方法で処理されてきました。
4574 Gaucheでは指定されたエンコーディングに応じて以下のとおりにしています。
4575 @c COMMON
4576
4577 @table @code
4578 @item UTF-8
4579 @c EN
4580 We don't treat BOM specially; if the first codepoint is U+FEFF,
4581 it is read as the character @code{#\ufeff}.
4582 For output, no BOM will be produced.
4583 This is the default behaivor of I/O.
4584 @c JP
4585 BOMは特別扱いされません。入力の最初にU+FEFFがあれば、それは文字@code{#\ufeff}
4586 として読まれます。出力の場合、BOMは付加されません。
4587 これがI/Oでのデフォルトの挙動です。
4588 @c COMMON
4589 @item UTF-8-BOM
4590 @c EN
4591 This is a 'pseudo' encoding---it is UTF-8, but if the input data begins
4592 with BOM, it is simply ignored. This is for the convenience
4593 of the programs that just don't want to be bothered by optional BOM
4594 at the beginning of UTF-8 stream. This encoding can't be used
4595 for output. If you absolutely need to produce UTF-8 with BOM,
4596 just write @code{#\ufeff} at the beginning of the UTF-8 stream.
4597 @c JP
4598 これは、UTF-8だけれども入力データにBOMがあればそれをただ無視するという
4599 「擬似」エンコーディングです。UTF-8ストリームの先頭のBOMの有無を気にしたくない
4600 プログラムのために用意されています。
4601 このエンコーディングは出力には使えません。UTF-8の出力にどうしてもBOMをつける必要があるなら、
4602 最初に@code{#\ufeff}を書き出してください。
4603 @c COMMON
4604 @item UTF-16, UTF-32
4605 @c EN
4606 The input recognizes BOM and decides the byte order; BOM itself won't
4607 appear in the read data. If BOM is missing, big-endian
4608 (UTF-16BE, UTF-32BE) is assumed.
4609 The output emits BOM at the beginning of the data.
4610 @c JP
4611 入力はBOMを認識してバイトオーダーを決定します。BOM自身は読まれるデータには含まれません。
4612 BOMが無かった場合はビッグエンディアン(UTF-16BE, UTF-32BE)が使われます。
4613 出力の場合はBOMが先頭に付加されます。
4614 @c COMMON
4615 @item UTF-16LE, UTF-32LE, UTF-16BE, UTF-32BE
4616 @c EN
4617 We assume the byte-order meta-information is given via separate channel,
4618 so that the caller already know the byte-order of the input.
4619 These do not treat BOM specially; if the first codepoint is U+FEFF,
4620 it is read as the character @code{#\ufeff}.
4621 For output, no BOM will be produced.
4622 @c JP
4623 これらのエンコーディングでは、メタ情報は既に別の方法で与えられていて
4624 呼び出し元は入力データのバイトオーダーを既に知っているものとみなします。
4625 従ってBOMは特別扱いされません。入力の最初にU+FEFFがあれば、それは文字@code{#\ufeff}
4626 として読まれます。出力の場合、BOMは付加されません。
4627 @c COMMON
4628 @end table
4629
4630 @c EN
4631 @subsubheading Details of Gauche's native conversion algorithm
4632 @c JP
4633 @subsubheading Gaucheの内部変換アルゴリズムの詳細
4634 @c COMMON
4635
4636 @c EN
4637 Between EUC_JP, Shift JIS and ISO2022JP, Gauche uses arithmetic
4638 conversion whenever possible. This even maps the undefined codepoint
4639 properly. Between Unicode (UTF-8) and EUC_JP, Gauche uses lookup tables.
4640 Between Unicode and Shift JIS or ISO2022JP, Gauche converts the
4641 input CES to EUC_JP, then convert it to the output CES.
4642 ISO8859-N are converted to Unicode using tables, then converted to
4643 the output CES if necessary.
4644 If the same CES is specified for input and output, Gauche's conversion
4645 routine just copies input characters to output characters, without
4646 checking the validity of the encodings.
4647 @c JP
4648 EUC_JP、Shift JIS、及びISO2022JP間の変換は可能な限り計算で行います。
4649 文字が未定義のコードポイントも計算式に従って変換されます。
4650 Unicode(UTF-8)とEUC_JP間の変換はテーブルルックアップによって行われます。
4651 UnicodeとShift JISまたはISO2022JP間の変換は、入力CESを一度EUC_JPに
4652 変換し、それを出力CESに変換することによって行います。
4653 ISO8859-NはUnicodeにへテーブルで変換され、必要ならばそこから出力CESに変換されます。
4654 入力と出力のCESがGaucheの内部アルゴリズムがサポートする範囲で等しかった場合、
4655 Gaucheの変換ルーチンはエンコーディングの正当性はチェックせず、
4656 単に入力を出力にコピーします。
4657 @c COMMON
4658
4659 @table @code
4660 @item EUC_JP, EUCJP, EUCJ, EUC_JISX0213
4661 @c EN
4662 Covers ASCII, JIS X 0201 kana, JIS X 0212 and JIS X 0213 character sets.
4663 JIS X 0212 character set is supported merely because it uses
4664 the code region JIS X 0213 doesn't use, and JIS X 0212 characters
4665 are not converted properly to Shift JIS and UTF-8.
4666 Use JIS X 0213.
4667 @c JP
4668 ASCII, JIS X 0201カナ、JIS X 0212、及びJIS X 0213文字集合をカバーします。
4669 JIS X 0212は、単にJIS X 0213と重ならないコードを使っているためにサポート
4670 されていますが、他のCESへの変換は行われないので注意して下さい。
4671 なるべくJIS X 0213の使用をおすすめします。
4672 @c COMMON
4673
4674 @item SHIFT_JIS, SHIFTJIS, SJIS
4675 @c EN
4676 Covers Shift_JISX0213, except that 0x5c and 0x7e is mapped to ASCII
4677 character set (REVERSE SOLIDUS and TILDE),
4678 instead of JIS X 0201 Roman (YEN SIGN and OVERLINE).
4679 @c JP
4680 Shift_JISX0213をカバーします。但し、0x5cと0x7eに関しては
4681 JIS X 0201 Roman (YEN SIGNとOVERLINE) ではなく
4682 ASCII (REVERSE SOLIDUSとTILDE) にマップされます。
4683 @c COMMON
4684
4685 @item UTF-8, UTF8
4686 @c EN
4687 Unicode. Note that some JIS X 0213 characters are mapped to Extension B
4688 (U+20000 and up).
4689 Some JIS X 0213 characters are mapped to two
4690 unicode characters (one base character plus a combining character).
4691 @c JP
4692 Unicodeです。JIS X 0213中の文字のいくつかはExtension B (U+20000〜)
4693 にマップされます。JIS X 0213中の他の文字のいくつかは2つのUnicode文字
4694 (base character + combining character)にマップされます。
4695 @c COMMON
4696
4697 @item ISO2022JP, CSISO2022JP, ISO2022JP-1, ISO2022JP-2, ISO2022JP-3
4698 @c EN
4699 These encodings differ a bit
4700 (except ISO2022JP and CSISO2022JP, which are synonyms), but
4701 Gauche handles them same. If one of these CES is specified as input,
4702 Gauche recognizes escape sequences of any of CES.
4703 ISO2022JP-2 defines several non-Japanese escape sequences, and
4704 they are recognized by Gauche, but mapped to substitution character
4705 ('?' or geta mark).
4706 @c JP
4707 これらのエンコーディングは、CSISO2022JPがISO2022JPのエイリアスであることを除き
4708 異なるエスケープシーケンスを使いますが、Gaucheの中では同じルーチンで処理されます。
4709 これらのエンコーディングのいずれかが入力CESに指定された場合、
4710 Gaucheは全てのバリエーションのエスケープシーケンスを認識します。
4711 但し、ISO2022JP-2に定義された日本語以外の言語のエスケープシーケンスに関しては、
4712 Gaucheはエスケープシーケンスの認識だけを行い、
4713 文字は'?'あるいは'〓' に置換します。
4714 @c COMMON
4715
4716 @c EN
4717 For output, Gauche assumes ISO2022JP first, and uses ISO2022JP-1
4718 escape sequence to put JIS X 0212 character, or uses ISO2022JP-3
4719 escape sequence to put JIS X 0213 plane 2 character.
4720 Thus, if the string contains only JIS X 0208 characters,
4721 the output is compatible to ISO2022JP.
4722 Precisely speaking, JIS X 0213 specifies some characters in JIS X 0208
4723 codepoint that shouldn't be mixed with JIS X 0208 characters;
4724 Gauche output those characters as JIS X 0208 for compatibility.
4725 (This is the same policy as Emacs-Mule's iso2022jp-3-compatible mode).
4726 @c JP
4727 出力に関してはGaucheは出来る限りISO2022JPでエンコードし、
4728 JIS X 0212文字に出会ったらISO2022JP-1のエスケープシーケンスを、
4729 JIS X 0213の第2面の文字に出会ったらISO2022JP-3のエスケープシーケンスを
4730 用います。したがって、文字列がJIS X 0208の範囲だけで構成されていた場合は
4731 出力はISO2022JP互換となります。
4732 厳密には、JIS X 0213では包摂基準の変更により、
4733 「JIS X 0208と同じコードポイントを用いるがJIS X 0208のエスケープシーケンスを
4734 使ってはいけない文字」というのが定義されています。
4735 Gaucheでは互換性のため、これらの文字もJIS X 0208のエスケープシーケンスを
4736 用いてエンコードします (これは、Emacs-Muleにおけるiso2022jp-3-compatible
4737 モードと同じ方針です)。
4738 @c COMMON
4739 @end table
4740
4741 @node Autodetecting the encoding scheme, Conversion ports, Supported character encoding schemes, Character code conversion
4742 @subsection Autodetecting the encoding scheme
4743 @c NODE 文字エンコーディングの自動判定
4744
4745 @c EN
4746 There are cases that you don't know the CES of the input, but
4747 you know it is one of several possible encodings.
4748 The charconv module has a mechanism
4749 to guess the input encoding. There can be multiple algorithms,
4750 and each algorithm has the name (wildcard CES). Right now, there's only one
4751 algorithm implemented:
4752 @c JP
4753 しばしば、入力のCESが未知であり、可能性のあるいくつかの候補から入力のCESを
4754 推測しなければならない場合があります。推測するアルゴリズムはいくつも考えられるので、
4755 それぞれに名前がついています(ワイルドカードCES)。
4756 今のところ、一つのアルゴリズムしか実装されていません。
4757 @c COMMON
4758 @table @code
4759 @item "*JP"
4760 @c EN
4761 To guess the character encoding from japanese text, among either
4762 ISO2022-JP(-1,2,3), EUCJP, SHIFT_JIS or UTF-8.
4763
4764 (Even when the input is UTF-8 with BOM, it is still recognized as UTF-8,
4765 not UTF-8-BOM).
4766 @c JP
4767 日本語のテキストのCESを、ISO2022-JP(-1,2,3), EUCJP, SHIFT_JIS または UTF-8の
4768 いずれかであるとして推測する。
4769
4770 (入力がBOMつきUTF-8であった場合も、UTF-8-BOMではなくUTF-8が認識結果となります)。
4771 @c COMMON
4772 @end table
4773
4774 @c EN
4775 The wildcard CES can be used in place of CES name for some conversion functions.
4776 @c JP
4777 ワイルドカードCESは、いくつかの変換関数においてCES名の代わりに使うことができます。
4778 @c COMMON
4779
4780
4781 @defun ces-guess-from-string string scheme
4782 @c MOD gauche.charconv
4783 @c EN
4784 Guesses the CES of @var{string} by the character guessing scheme
4785 @var{scheme} (e.g. "*JP"). Returns CES name that can be used
4786 by other charconv functions. It may return @code{#f} if the
4787 guessing scheme finds no possible encoding in @var{string}.
4788 Note that if there may be more than one possible encoding in
4789 @var{string}, the guessing scheme returns one of them,
4790 usually in favor of the native CES.
4791 @c JP
4792 文字列@var{string}のCESを、CES推測アルゴリズム@var{scheme} ("*JP"など)
4793 を使って推測し、結果のCES名を返します。もしどのCESにも該当しないデータが
4794 含まれていれば@code{#f}が返されます。複数のCESが可能である場合、
4795 ネイティブエンコーディングが含まれていればそれを、
4796 そうでなければ可能なCESからどれかひとつが選んで返されます。
4797 @c COMMON
4798 @end defun
4799
4800
4801 @node Conversion ports, , Autodetecting the encoding scheme, Character code conversion
4802 @subsection Conversion ports
4803 @c NODE 変換ポート
4804
4805 @defun open-input-conversion-port source from-code :key to-code buffer-size owner? illegal-output
4806 @c MOD gauche.charconv
4807 @c EN
4808 Takes an input port @var{source}, which feeds characters
4809 encoded in @var{from-code}, and returns another input port,
4810 from which you can read characters encoded in @var{to-code}.
4811 @c JP
4812 文字が符号化方法@var{from-code}で符号化されているデータを読み出せる
4813 入力ポート@var{source}を取り、符号化方法@var{to-code}で符号化されたデータを
4814 読み出せるポートを作成して返します。
4815 @c COMMON
4816
4817 @c EN
4818 If @var{to-code} is omitted, the native CES is assumed.
4819 @c JP
4820 @var{to-code}が省略された場合はネイティブのCESと見なされます。
4821 @c COMMON
4822
4823 @c EN
4824 @var{buffer-size} is used to allocate internal buffer size for
4825 conversion. The default size is about 1 kilobytes and it's suitable
4826 for typical cases.
4827 @c JP
4828 @var{buffer-size}は変換のための内部バッファのサイズを指定します。
4829 省略時のサイズは1Kバイト程で、通常の使用には問題ないサイズです。
4830 @c COMMON
4831
4832 @c EN
4833 @var{hanlding} argument specifies the behavior when the output CES
4834 doesn't have the corresponding character of input. It can be a symbol
4835 @code{raise} to raise an @code{<io-encoding-error>} in such cases,
4836 or a symbol @code{replace} to replace the character with a replacement
4837 character appropriate in the output CES. If omitted, @code{raise}
4838 is assumed.
4839 @c JP
4840 @var{illegal-output}引数は、出力CESに入力に対応する文字がない場合の動作を指定します。
4841 引数はシンボル@code{raise}か@code{replace}でなければなりません。
4842 @code{raise}の場合は、@code{<io-encoding-error>}が投げられます。
4843 @var{replace}の場合は、出力CESに応じた適切な置換文字が代わりに出力されます。
4844 省略された場合は@code{raise}の動作となります。
4845 @c COMMON
4846
4847 @c EN
4848 Note that @code{iconv(3)} library API doesn't offer an option to
4849 choose the illegal-output handling mode. So when the conversion is delegated to
4850 @code{iconv(3)}, @var{illegal-output} is ignored and the behavior follows
4851 the underlying @code{iconv(3)} implementation. If you need to make
4852 sure @var{illegal-output} is honored, you can bind the parameter
4853 @code{external-conversion-library} to @code{#f} when calling
4854 this procedure; then the conversion port won't
4855 use @code{iconv(3)} and raises unsupported encodings error if the
4856 conversion can't be handled entirely within Gauche.
4857 @c JP
4858 @code{iconv(3)}ライブラリは、ハンドリングモードを指定するAPIを持っていないことに
4859 注意してください。変換が@code{iconv(3)}に任されると、@var{illegal-output}の指定は
4860 無視され、動作は@code{iconv(3)}の実装に依存します。
4861 @var{illegal-output}の指定通りに動いて欲しい場合は、パラメータ
4862 @code{external-conversion-library}を@code{#f}に束縛している環境で
4863 この手続きを呼んでください。そうすると、変換ポートは@code{iconv(3)}を使わず、
4864 Gauche内部で変換できない場合はエラーを投げます。
4865 @c COMMON
4866
4867 @c EN
4868 By default, @code{open-input-conversion-port} leaves @var{source} open.
4869 If you specify true value to @var{owner?}, the function closes
4870 @var{source} after it reads EOF from the port.
4871 @c JP
4872 通常、@code{open-input-conversion-port}は変換が全て終了した後でも@var{source}
4873 はオープンしたままにします。キーワード引数@var{owner?}に真の値を指定すると、
4874 EOFが読まれた後で@var{source}はクローズされます。
4875 @c COMMON
4876
4877 @c EN
4878 If you don't know the @var{source}'s CES, you can specify
4879 CES guessing scheme, such as @code{"*JP"}, in place of @var{from-code}.
4880 The conversion port tries to guess the encoding, by prefetching
4881 the data from @var{source} up to the buffer size. It signals an error
4882 if the code guessing routine finds no appropriate CES.
4883 If the guessing routine finds ambiguous input, however, it silently
4884 assume one of possible CES's, in favor of the native CES.
4885 Hence it is possible that the guessing is wrong if the buffer
4886 size is too small. The default size is usually enough for most
4887 text documents, but it may fail if the large text contains mostly ASCII
4888 characters and multibyte characters appear only at the very end of
4889 the document.
4890 To be sure for the worst case,
4891 you have to specify the buffer size large enough to
4892 hold entire text.
4893 @c JP
4894 入力のCESが不明な場合、@code{"*JP"}などのCES推測アルゴリズム名を@var{from-code}
4895 として指定することができます。変換ポートは最高でバッファサイズまでのデータを先読みし、
4896 CESを推測しようとします。そのアルゴリズムで推測されるどのCESにも該当しないデータが
4897 検出された場合はエラーが報告されます。もし複数のCESが可能であるようなデータであった
4898 場合は、Gaucheのネイティブエンコーディングが可能なCESに含まれていればそれが選ばれ、
4899 そうでなければいずれかのCESが適当に選ばれます。従って、バッファサイズが小さすぎると
4900 誤った判定をする可能性が高くなります。大抵のテキストドキュメントに対して、
4901 既定のバッファサイズは十分ですが、大きなテキストのほとんどがASCII文字で最後だけ
4902 マルチバイト文字が現われるようなテキストでは誤判定の可能性があります。
4903 最悪の場合でも結果を保証するには、テキスト全体が格納できるバッファサイズを指定すると
4904 良いでしょう。
4905 @c COMMON
4906
4907
4908 @c EN
4909 For example, the following code copies a file @file{unknown.txt} to a file
4910 @file{eucjp.txt}, converting unknown japanese CES to EUC-JP.
4911 @c JP
4912 例を示しましょう。以下のコードは未知のCES(但しEUC-JP, SJIS, ISO2022-JP, UTF8の
4913 いずれかであることは分かっている)で書かれたテキストファイル@file{unknown.txt}を
4914 読みだし、文字エンコーディングをEUC-JPに変換して@file{eucjp.txt}に書き出します。
4915 @c COMMON
4916 @example
4917 (call-with-output-file "eucjp.txt"
4918 (lambda (out)
4919 (copy-port (open-input-conversion-port
4920 (open-input-file "unknown.txt")
4921 "*jp" ;@r{guess code}
4922 :to-code "eucjp"
4923 :owner? #t) ;@r{close unknown.txt afterwards}
4924 out)))
4925 @end example
4926
4927 @c EN
4928 For the portable code, you can also use SRFI-181 @code{transcoded-port}
4929 (@pxref{Transcoded ports}).
4930 @c JP
4931 ポータブルなコードでは、SRFI-181の@code{transcoded-port}を使うこともできます
4932 (@ref{Transcoded ports}参照)。
4933 @c COMMON
4934 @end defun
4935
4936
4937 @defun open-output-conversion-port sink to-code :key from-code buffer-size owner? illegal-output
4938 @c MOD gauche.charconv
4939 @c EN
4940 Creates and returns an output port that converts
4941 given characters from @var{from-code} to @var{to-code}
4942 and feed to an output port @var{sink}.
4943 If @var{from-code} is omitted, the native CES is assumed.
4944 You can't specify a character guessing scheme (such as "*JP") to
4945 neither @var{from-code} nor @var{to-code}.
4946 @c JP
4947 文字のエンコーディングを@var{from-code}から@var{to-code}に変換して
4948 出力ポート@var{sink}に書き出すような出力変換ポートを作成して返します。
4949 @var{from-code}が省略された場合はネイティブのCESと見なされます。
4950 @var{from-code}にも@var{to-code}にも、CES推測アルゴリズム名を
4951 使用することはできません。
4952 @c COMMON
4953
4954 @c EN
4955 @var{buffer-size} specifies the size of internal conversion buffer.
4956 The characters put to the returned port may stay in the buffer,
4957 until the port is explicitly flushed (by @code{flush}) or
4958 the port is closed.
4959 @c JP
4960 @var{buffer-size}は内部で変換に使われるバッファサイズを指定します。
4961 出力変換ポートに書き出された文字は、@code{flush}を使って明示的に
4962 フラッシュするか出力変換ポートが閉じられるまで、バッファ内に残っている可能性があります。
4963 @c COMMON
4964
4965 @c EN
4966 By default, the returned port doesn't closes @var{sink} when
4967 itself is closed. If a keyword argument @var{owner?} is provided
4968 and true, however, it closes @var{sink} when it is closed.
4969 @c JP
4970 通常、出力変換ポートがクローズされても@var{sink}はクローズされません。
4971 @var{owner?}に真の値を与えれば、出力変換ポートのクローズ時に@var{sink}を
4972 クローズするようにできます。
4973 @c COMMON
4974
4975 @c EN
4976 The @var{illegal-output} keyword argument is the same
4977 as @code{open-input-conversion-port}.
4978 @c JP
4979 @var{illegal-output}キーワード引数は、
4980 @code{open-input-conversion-port}と同じです。
4981 @c COMMON
4982
4983 @c EN
4984 For the portable code, you can also use SRFI-181 @code{transcoded-port}
4985 (@pxref{Transcoded ports}).
4986 @c JP
4987 ポータブルなコードでは、SRFI-181の@code{transcoded-port}を使うこともできます
4988 (@ref{Transcoded ports}参照)。
4989 @c COMMON
4990 @end defun
4991
4992 @defun ces-convert-to return-type source from-code :optional to-code :key illegal-output
4993 @defunx ces-convert source from-code :optional to-code :key illegal-output
4994 @c MOD gauche.charconv
4995 @c EN
4996 Convert @var{source}, which is a string or an u8vector
4997 of multibyte encoding in @var{from-code}, to a
4998 string or u8vector encoded in @var{to-code}. If @var{to-code} is
4999 omitted, the native CES is assumed.
5000 @c JP
5001 文字エンコーディング@var{from-code}でエンコードされた
5002 文字列もしくはu8vectorの@var{source}を変換し、
5003 文字エンコーディング@var{to-code}でエンコードされた文字列またはu8vectorを返します。
5004 @var{to-code}が省略された場合はネイティブエンコーディングへと変換されます。
5005 @c COMMON
5006
5007 @c EN
5008 In @code{ces-convert-to}, you can specify the return type by
5009 @var{return-type} argument; it must be either a class object @code{<string>}
5010 or @code{<u8vector>}. On the other hand, @code{ces-convert} always returns
5011 a string, regardless of the type of @var{source}.
5012 @c JP
5013 @code{ces-convert-to}では、戻り値の型を@var{return-type}で指定します。
5014 @var{return-type}はクラスオブジェクト@code{<string>}か@code{<u8vector>}
5015 でなければなりません。一方、@code{ces-convert}は、@var{source}の型にかかわらず
5016 常に文字列を返します。
5017 @c COMMON
5018
5019 @c EN
5020 If @var{to-code} is different from the native CES and a string
5021 is returned, it can be an incomplete string. It's for the backward
5022 compatibility---in general, we recommend to use u8vector to represent
5023 multibyte sequence in CES other than the native encoding.
5024 @c JP
5025 ネイティブエンコーディング以外のエンコーディングを@var{to-code}に指定して
5026 文字列が返された場合、それは不完全な文字列であるかもしれません。
5027 これは後方互換性のためです。一般的には、ネイティブエンコーディング以外の
5028 マルチバイトシーケンスを扱う場合はu8vectorを使うことをおすすめします。
5029 @c COMMON
5030
5031 @c EN
5032 @var{from-code} can be a name of character guessing scheme
5033 (e.g. "*JP").
5034 @c JP
5035 @var{from-code}にはCES推測アルゴリズム名("*JP"など)を与えることができます。
5036 @c COMMON
5037
5038 @c EN
5039 The keyword argument @var{illegal-output} controls
5040 the behavior when input contains a character that can't be encoded
5041 in the output. See @code{open-input-conversion-port} above for the
5042 description. By default, an @code{<io-encoding-error>} is raised,
5043 except when the conversion is delegated to @code{iconv(3)}, in which case
5044 the behavior depends on the external library.
5045 @c JP
5046 キーワード引数@var{illegal-output}は出力側でエンコードできない文字が
5047 入力された場合の振る舞いを指定します。上の@code{open-input-conversion-port}の
5048 説明を参照してください。デフォルトでは@code{<io-encoding-error>}が投げられます
5049 (ただし、変換が@code{iconv(3)}に任された場合、
5050 その振る舞いは外部ライブラリの実装に依存します)。
5051 @c COMMON
5052
5053 @c EN
5054 For the portable code, you can also use SRFI-181 @code{bytevector->string}
5055 and @code{string->bytevector}
5056 (@pxref{Transcoded ports}).
5057 @c JP
5058 ポータブルなコードでは、SRFI-181の@code{bytevector->string}
5059 および@code{string->bytevector}を使うこともできます
5060 (@ref{Transcoded ports}参照)。
5061 @c COMMON
5062 @end defun
5063
5064 @defun call-with-input-conversion iport proc :key encoding conversion-buffer-size illegal-output
5065 @defunx call-with-output-conversion oport proc :key encoding conversion-buffer-size illegal-output
5066 @c MOD gauche.charconv
5067 @c EN
5068 These procedures can be used to perform character I/O with
5069 different encoding temporary from the original port's encoding.
5070
5071 @code{call-with-input-conversion} takes an input port @var{iport}
5072 which uses the character encoding @var{encoding}, and
5073 calls @var{proc} with one argument, a conversion input port.
5074 From the port, @var{proc} can read characters in utf-8.
5075 Note that once @var{proc} is called, it has to read all the
5076 characters until EOF; see the note below.
5077
5078 @code{call-with-output-conversion} takes an output port @var{oport}
5079 which expects the character encoding @var{encoding}, and
5080 calls @var{proc} with one argument,
5081 a temporary conversion output port.
5082 To the port, @var{proc} can write characters in utf-8.
5083 When @var{proc} returns, or it exits with an error,
5084 the temporary conversion output port is flushed and closed.
5085 The caller of @code{call-with-output-conversion}
5086 can continue to use @var{oport} with original encoding afterwards.
5087
5088 Both procedure returns the value(s) that @var{proc} returns.
5089 The default value of @var{encoding} is Gauche's internal
5090 encoding. Those procedures don't create a conversion port
5091 when it is not necessary. If @var{conversion-buffer-size} is given,
5092 it is used as the @var{buffer-size} argument when the conversion
5093 port is open.
5094
5095 You shouldn't use @var{iport}/@var{oport} directly
5096 while @var{proc} is active---character encoding is a
5097 stateful process, and mixing I/O from/to the conversion port and
5098 the underlying port will screw up the state.
5099
5100 @emph{Note:} for the @code{call-with-input-conversion}, you can't
5101 use @var{iport} again unless @var{proc} reads EOF from it.
5102 It's because a conversion port needs to buffer the input, and
5103 there's no way to undo the buffered input to @var{iport}
5104 when @var{proc} returns.
5105 @c JP
5106 この2つの手続きを使うと、元のポートのエンコーディングとは異る一時的な
5107 エンコーディングをもつ文字I/Oを行うことが可能です。
5108
5109 @code{call-with-input-conversion} は、文字エンコード@var{encoding} を
5110 もつ入力ポート @var{iport} をとり、@var{proc}を一つの引数、すなわち、
5111 変換入力ポートとともに呼びだします。このポートから、@var{proc} は文字を
5112 Gauche の内部エンコーディングで読み込むことができます。いったん、
5113 @var{proc}が呼ばれたら、EOFまでのすべての文字を読み込まなくてはなりません。
5114 後述の注意を参照してください。
5115
5116 @code{call-with-output-conversion} は、文字エンコーディング @var{encoding}
5117 を期待する出力ポート @var{oport} をとり、@var{proc}を一つの引数、すなわち、
5118 一時的な変換出力ポートとともに呼びだします。このポートへ、@var{proc}は
5119 Gauche の内部エンコーディングをもつ文字を書き込むことができます。
5120 @var{proc} が戻るか、エラーで抜けると、この一時的な変換出力ポートは
5121 フラッシュされて、クローズされます。@code{call-with-output-conversion}
5122 の呼出し側は、その後、元のエンコーディングのポート@var{oport}を使い
5123 続けること可能です。
5124
5125 どちらの手続きも @var{proc} が返す値を返します。@var{encoding}
5126 のデフォルト値は Gauche の内部エンコーディングです。この2つの手続きは
5127 必要がなければ、変換ポートを作成しません。もし
5128 @var{conversion-buffer-size} が与えられていれば、変換ポートがオープン
5129 されるときに、@var{buffer-size} 引数として使われます。
5130
5131 @var{proc} がアクティブであるあいだは、@var{iport}/@var{oport} を直接
5132 使うべきではありません。文字のエンコーディングはステートフルなプロセスで
5133 変換ポート(から/へ)の入出力を混在させると元にあるポートの状態がおかしく
5134 なってしまいます。
5135
5136 @emph{注意:} @code{call-with-input-conversion} については、
5137 @var{proc} が EOF を読むまでは、@var{iport} を再度利用することはできません。
5138 これは、変換ポートがバッファを必要とし、@var{proc} がもどったときに
5139 @var{iport}へのバッファ付き入力をアンドゥする方法がないからです。
5140 @c COMMON
5141 @end defun
5142
5143 @defun with-input-conversion iport thunk :key encoding conversion-buffer-size illegal-output
5144 @defunx with-output-conversion oport thunk :key encoding conversion-buffer-size illegal-output
5145 @c MOD gauche.charconv
5146 @c EN
5147 Similar to @code{call-with-*-conversion},
5148 but these procedures call @var{thunk} without arguments,
5149 while the conversion port is set as the current input or output port,
5150 respectively.
5151 The meaning of keyword arguments are the same as @code{call-with-*-conversion}.
5152 @c JP
5153 @code{call-with-*-conversion} と似ていますが、この2つの手続きは、
5154 @var{thunk} を引数なしで呼びます、また、変換ポートはそれぞれ標準入力、標準
5155 出力のポートにセットされます。
5156 キーワード引数の意味は @code{call-with-*-conversion} と同じです。
5157 @c COMMON
5158 @end defun
5159
5160 @defun wrap-with-input-conversion port from-code :key to-code owner? buffer-size illegal-output
5161 @defunx wrap-with-output-conversion port to-code :key from-code owner? buffer-size illegal-output
5162 @c MOD gauche.charconv
5163 @c EN
5164 Convenient procedures to avoid adding unnecessary conversion port.
5165 Each procedure works like @code{open-input-conversion-port}
5166 and @code{open-output-conversion-port}, respectively,
5167 except if system knows no conversion is needed,
5168 no conversion port is created and @var{port} is returned as is.
5169
5170 When a conversion port is created, @var{port} is always owned by the port.
5171 When you want to close the port, always close the port returned
5172 by @code{wrap-with-*-conversion}, instead the original @var{port}.
5173 If you close the original @var{port} first, the pending conversion
5174 won't be flushed. (Some conversion requires trailing sequence that
5175 is generated only when the conversion port is closing, so simply
5176 calling @code{flush} isn't enough.)
5177
5178 The @var{buffer-size} and @var{illegal-output} arguments are passed to
5179 the @code{open-*-conversion-port}.
5180 @c JP
5181 不要な変換ポートを作らないようにする便利な手続きです。
5182 各手続きはそれぞれ@code{open-input-conversion-port}と
5183 @code{open-output-conversion-port}のように動作します。
5184 但し、指定されたCES間の変換が必要でないとシステムが知っている場合は、
5185 変換ポートは作られず、@var{port}がそのまま返されます。
5186
5187 変換ポートが作られた場合、@var{port}は常に変換ポートに所有されます
5188 (@code{:owner #t}となる)。ポートを閉じる場合は@var{port}ではなく
5189 常に@code{wrap-with-*-conversion}が返したポートを閉じるようにして下さい。
5190 元の@var{port}が先に閉じられた場合、変換中の結果が書き出されない可能性があります。
5191 (変換によっては、ポートが閉じられる時点で終了シーケンスを書き出すものがあるので、
5192 単にポートを@code{flush}するだけでは不十分です)。
5193
5194 @var{buffer-size}と@var{illegal-output}引数はそのまま
5195 変換ポート作成手続きに渡されます。
5196 @c COMMON
5197 @end defun
5198
5199 @c ----------------------------------------------------------------------
5200 @node Collection framework, Configuration parameters, Character code conversion, Library modules - Gauche extensions
5201 @section @code{gauche.collection} - Collection framework
5202 @c NODE コレクションフレームワーク, @code{gauche.collection} - コレクションフレームワーク
5203
5204 @deftp {Module} gauche.collection
5205 @mdindex gauche.collection
5206 @c EN
5207 This module provides a set of generic functions (GFs) that iterate over
5208 various collections. The Scheme standard has some iterative
5209 primitives such as @code{map} and @code{for-each},
5210 and @code{scheme.list} (@pxref{R7RS lists} adds a rich set of such functions,
5211 but they work only on lists.
5212
5213 Using the method dispatch of the object system, this module
5214 efficiently extends those
5215 functions for other collection classes such as vectors and hash tables.
5216 It also provides a simple way for user-defined class to adapt
5217 those operations.
5218 So far, the following operations are defined.
5219 @c JP
5220 このモジュールは、様々なコレクションに対して繰り返し処理を行う総称関数を提供します。
5221 Schemeの規格は@code{map}や@code{for-each}などの繰り返し手続きを定義しており、
5222 また@code{scheme.list}
5223 (@ref{R7RS lists}参照)は更に数多くの繰り返し手続きを提供しますが、
5224 それらはリストに対してしか動作しません。
5225
5226 このモジュールはオブジェクトシステムのメソッドディスパッチを利用して、
5227 これらの手続きをベクタやハッシュテーブルのような一般のコレクションタイプに対しても
5228 効率良く動作するように拡張します。また、ユーザ定義のクラスにこれらの操作を実装するための
5229 簡単な方法も提供します。今のところ、次のような総称関数が提供されています。
5230 @c COMMON
5231
5232 @table @asis
5233 @c EN
5234 @item Mapping
5235 @c JP
5236 @item マッピング
5237 @c COMMON
5238 @code{fold}, @code{fold2}, @code{fold3},
5239 @code{map}, @code{map-to}, @code{map-accum}, @code{for-each}
5240 @c EN
5241 @item Selection and searching
5242 @c JP
5243 @item 選択と探索
5244 @c COMMON
5245 @code{find}, @code{find-min}, @code{find-max}, @code{find-min&max},
5246 @code{filter}, @code{filter-to},
5247 @code{remove}, @code{remove-to}, @code{partition}, @code{partition-to}
5248 @code{group-collection}
5249 @c EN
5250 @item Conversion
5251 @c JP
5252 @item 変換
5253 @c COMMON
5254 @code{coerce-to}
5255 @c EN
5256 @item Miscellaneous
5257 @c JP
5258 @item その他
5259 @c COMMON
5260 @code{size-of}, @code{lazy-size-of}
5261 @c EN
5262 @item Fundamental iterator creator
5263 @c JP
5264 @item 基礎的なイテレータ構築メソッド
5265 @c COMMON
5266 @code{call-with-iterator}, @code{call-with-builder},
5267 @code{with-iterator}, @code{with-builder}, @code{call-with-iterators}.
5268 @end table
5269
5270 @c EN
5271 Those operations work on @emph{collections} and its subclass,
5272 @emph{sequences}. A collection is a certain form of a set
5273 of objects that you can traverse all the object in it in a certain way.
5274 A sequence is a collection that all its elements are ordered, so that
5275 you can retrieve its element by index.
5276 @c JP
5277 これらの操作は、@emph{コレクション}とそのサブクラスである
5278 @emph{シーケンス}に対して動作します。コレクションは、その要素を全て
5279 訪れる方法が用意されているようなオブジェクトの集合です。
5280 シーケンスは、要素間に全順序関係が定義されておりインデックスで要素を取り出すことが
5281 できるようなコレクションです。
5282 @c COMMON
5283
5284 @c EN
5285 The following Gauche built-in objects are treated as collections and/or
5286 sequences.
5287 @c JP
5288 次にあげるGaucheの組み込みオブジェクトはシーケンスあるいはコレクションとして動作します。
5289 @c COMMON
5290 @table @code
5291 @item <list>
5292 @c EN
5293 A sequence.
5294 @c JP
5295 シーケンス
5296 @c COMMON
5297 @item <vector>
5298 @c EN
5299 A sequence.
5300 @c JP
5301 シーケンス
5302 @c COMMON
5303 @item <string>
5304 @c EN
5305 A sequence (of characters)
5306 @c JP
5307 文字のシーケンス
5308 @c COMMON
5309 @item <hash-table>
5310 @c EN
5311 A collection. Each element is a pair of a key and a value.
5312 @c JP
5313 コレクション。各要素はキーと値のペア。
5314 @c COMMON
5315 @item <s8vector>, <u8vector>, @dots{} <f64vector>
5316 @c EN
5317 A sequence (methods defined in @code{gauche.uvector} module,
5318 @pxref{Uniform vectors}).
5319 @c JP
5320 シーケンス。メソッドは@code{gauche.uvector}モジュール内で定義されます。
5321 @ref{Uniform vectors}参照。
5322 @c COMMON
5323 @end table
5324
5325 @c EN
5326 @xref{Sequence framework}, for it adds more sequence specific
5327 methods.
5328 @c JP
5329 @ref{Sequence framework}も参照してください。シーケンス特有のメソッドが
5330 追加されます。
5331 @c COMMON
5332
5333 @c EN
5334 The methods that needs to return a set of objects, i.e.
5335 @code{map}, @code{filter}, @code{remove} and @code{partition}.
5336 returns a list (or lists). The corresponding ``-to'' variant
5337 (@code{map-to}, @code{filter-to}, @code{remove-to} and @code{partition-to}.
5338 takes a collection class argument and returns the collection of the class.
5339 @c JP
5340 オブジェクトの集合を返すようなメソッド、すなわち
5341 @code{map}、@code{filter}、@code{remove}および@code{partition}は、
5342 リストを返します。対応する``-to''がつくメソッド
5343 (@code{map-to}、@code{filter-to}、@code{remove-to}、@code{partition-to})
5344 はコレクションクラスも引数に取り、そのクラスのコレクションを返します。
5345 @c COMMON
5346 @end deftp
5347
5348 @menu
5349 * Mapping over collection::
5350 * Selection and searching in collection::
5351 * Miscellaneous operations on collection::
5352 * Fundamental iterator creators::
5353 * Implementing collections::
5354 @end menu
5355
5356 @node Mapping over collection, Selection and searching in collection, Collection framework, Collection framework
5357 @subsection Mapping over collection
5358 @c NODE コレクションに対するマッピング
5359
5360 @c EN
5361 These generic functions extends the standard mapping procedures.
5362 See also @ref{Mapping over sequences}, if you care the index
5363 as well as elements.
5364 @c JP
5365 これらのジェネリックファンクションは標準のマッピング手続きを拡張します。
5366 要素だけでなくそのインデックスも必要な場合は@ref{Mapping over sequences}を
5367 参照して下さい。
5368 @c COMMON
5369
5370 @deffn {Generic function} fold proc knil coll coll2 @dots{}
5371 @c MOD gauche.collection
5372 @c EN
5373 This is a natural extension of @var{fold} (@pxref{Other list procedures}).
5374 @c JP
5375 @var{fold} (@ref{Other list procedures}参照) の自然な拡張です。
5376 @c COMMON
5377
5378 @c EN
5379 For each element @var{Ei} in the collection @var{coll}, @var{proc} is
5380 called as (@var{proc} @var{Ei} @var{Ri-1}), where @var{Ri-1} is the
5381 result of (@var{i}-1)-th invocation of @var{proc} for @var{i} > 0,
5382 and @var{R0} is @var{knil}. Returns the last invocation of @var{proc}.
5383 @c JP
5384 コレクション@var{coll}の各要素@var{Ei}に対して、手続き@var{proc}が
5385 (@var{proc} @var{Ei} @var{Ri-1}) のように呼ばれます。ここで、
5386 @var{Ri-1} は @var{i} > 0 に対しては (@var{i}-1)番目の@var{proc}の呼び出しの
5387 結果であり、@var{R0}は@var{knil}です。最後の@var{proc}の戻り値を返します。
5388 @c COMMON
5389 @example
5390 (fold + 0 '#(1 2 3 4)) @result{} 10
5391 (fold cons '() "abc") @result{} (#\c #\b #\a)
5392 @end example
5393
5394 @c EN
5395 If the @var{coll} is a sequence, it is guaranteed that
5396 the elements are traversed in order. Otherwise, the order
5397 of iteration is undefined.
5398 @c JP
5399 @var{coll}がシーケンスでもある場合、要素はシーケンスの順に@var{proc}に渡されます。
5400 そうでなければ繰り返しの順序は未定義です。
5401 @c COMMON
5402
5403 @c EN
5404 Note: We don't provide @code{fold-right} on collections, since the order
5405 of elements doesn't matter, so only @code{fold} is sufficient for
5406 meaningful traversal.
5407 However, sequences do have @code{fold-right};
5408 see @ref{Mapping over sequences}.
5409 @c JP
5410 註:コレクションに対する@code{fold-right}は提供されません。コレクションでは
5411 要素の順序は定義されないため、意味のあるトラバースをするのには
5412 @code{fold}だけあれば十分だからです。
5413 しかし、シーケンスに対しては@code{fold-right}が定義されます。
5414 @ref{Mapping over sequences}を参照して下さい。
5415 @c COMMON
5416
5417 @c EN
5418 You can fold more than one collection, although it doesn't make
5419 much sense unless all of the collections are sequences.
5420 Suppose @code{@var{E}(@var{k}, @var{i})} for @var{i}-th element
5421 of @var{k}-th collection. @var{proc} is called as
5422 @c JP
5423 複数のコレクションを@code{fold}に渡すこともできます (但し、その全てがシーケンスで
5424 なければあまり意味のある操作では無いでしょう)。
5425 @var{k}番目のコレクションの@var{i}番目の要素を@code{@var{E}(@var{k}, @var{i})}とするとき、
5426 @var{proc}は以下のように呼ばれます。
5427 @c COMMON
5428 @example
5429 (@var{proc} @var{E}(0,i) @var{E}(1,i) @dots{} @var{E}(K-1,i) @var{Ri-1})
5430 @end example
5431
5432 @c EN
5433 Different types of collections can be mixed together.
5434 @c JP
5435 異なる型のコレクションを混ぜて扱うことができます。
5436 @c COMMON
5437
5438 @example
5439 (fold acons '() "abc" '#(1 2 3))
5440 @result{} ((#\c 3) (#\b 2) (#\a 1))
5441
5442 @c EN
5443 ;; @r{calculates dot product of two vectors}
5444 @c JP
5445 ;; @r{二つのベクタの内積を計算}
5446 @c COMMON
5447 (fold (lambda (a b r) (+ (* a b) r)) 0
5448 '#(3 5 7) '#(2 4 6))
5449 @result{} 68
5450 @end example
5451
5452 @c EN
5453 When more than one collection is given, @code{fold} terminates
5454 as soon as at least one of the collections exhausted.
5455 @c JP
5456 複数のコレクションが与えられた場合、@code{fold}は少なくともひとつのコレクションが
5457 終了した時点で終了します。
5458 @c COMMON
5459 @end deffn
5460
5461 @deffn {Generic function} fold2 proc knil1 knil2 coll coll2 @dots{}
5462 @deffnx {Generic function} fold3 proc knil1 knil2 knil3 coll coll2 @dots{}
5463 @c MOD gauche.collection
5464 @c EN
5465 Like @code{fold}, but they can carry two and three state values
5466 instead of one, respectively. The state values are
5467 initialized by @var{knilN}. The procedure @var{proc} is called
5468 with each element of @var{collN}, and the state values. It must return
5469 two (@code{fold2}) or three (@code{fold3}) values, which will be used
5470 as the state values of next iteration. The values returned in the
5471 last iteration will be the return values of @code{fold2} and @code{fold3}.
5472 @c JP
5473 @code{fold}と似ていますが、1つではなくそれぞれ2, 3個の状態値を
5474 持ち回ります。状態値は@var{knilN}によって初期化されます。
5475 手続き@var{proc}はコレクション@var{collN}の各要素値と状態値を
5476 引数として取り、@code{fold2}の場合は2個、@code{fold3}の場合は3個の
5477 値を返さねばなりません。返された値が次の繰り返しでの状態値として
5478 使われます。最後に返された値が@code{fold2}, @code{fold3}の戻り値と
5479 なります。
5480 @c COMMON
5481
5482 @example
5483 (fold2 (lambda (elt a b) (values (min elt a) (max elt b)))
5484 256 0 '#u8(33 12 142 1 74 98 12 5 99))
5485 @result{} 1 and 142 ;; find minimum and maximum values
5486 @end example
5487
5488 @c EN
5489 See also @code{map-accum} below.
5490 @c JP
5491 下の@code{map-accum}も参照。
5492 @c COMMON
5493 @end deffn
5494
5495
5496 @deffn {Generic function} map proc coll coll2 @dots{}
5497 @c MOD gauche.collection
5498 @c EN
5499 This extends the built-in @code{map} (@pxref{Walking over lists}).
5500 Apply @var{proc} for each element in the collection @var{coll}, and
5501 returns a list of the results.
5502 @c JP
5503 組み込み手続き@code{map} (@ref{Walking over lists}参照) を拡張します。
5504 コレクション@var{coll}の各要素に手続き@var{proc}を適用し、その結果をリストにして
5505 返します。
5506 @c COMMON
5507
5508 @c EN
5509 If the @var{coll} is a sequence, it is guaranteed that
5510 the elements are traversed in order. Otherwise, the order
5511 of iteration is undefined.
5512 @c JP
5513 @var{coll}がシーケンスでもある場合、要素はシーケンスの順に@var{proc}に渡されます。
5514 そうでなければ繰り返しの順序は未定義です。
5515 @c COMMON
5516
5517 @c EN
5518 If more than one collection is passed, @var{proc} is called with
5519 elements for each collection. In such case, @code{map} terminates
5520 as soon as at least one of the collection is exhausted. Note that passing
5521 more than one collection doesn't make much sense unless
5522 all the collections are sequences.
5523 @c JP
5524 複数のコレクションが与えられた場合、@var{proc}は各コレクションからの要素を引数として
5525 呼び出されます。@code{map}はひとつでもコレクションの最後に到達したら終了します。
5526 複数のコレクションを渡すのは、コレクションの全てがシーケンスでないとあまり意味がないでしょう。
5527 @c COMMON
5528
5529 @example
5530 (map (lambda (x) (* x 2)) '#(1 2 3))
5531 @result{} #(2 4 6)
5532
5533 (map char-upcase "abc")
5534 @result{} (#\A #\B #\C)
5535
5536 (map + '#(1 2 3) '#(4 5 6))
5537 @result{} (5 7 9)
5538 @end example
5539
5540 @c EN
5541 @code{map} @emph{always} returns a list. If you want to get the result
5542 in a different type of collection, use @code{map-to} described below.
5543 If you wonder why @code{(map char-upcase "abc")} doesn't return
5544 @code{"ABC"}, read the discussion in the bottom of this subsection.
5545 @c JP
5546 @code{map}は常にリストを返します。別のコレクション型で結果を得たい場合は、
5547 次に示す@code{map-to}を使って下さい。何故@code{(map char-upcase "abc")}が
5548 @code{"ABC"}を返さないのか疑問なら、この最後にあるディスカッションを参照してください。
5549 @c COMMON
5550 @end deffn
5551
5552 @deffn {Generic function} map-to class proc coll coll2 @dots{}
5553 @c MOD gauche.collection
5554 @c EN
5555 This works the same as @code{map}, except the result is returned
5556 in a collection of class @var{class}. @code{Class} must be a
5557 collection class and have a builder interface
5558 (@pxref{Fundamental iterator creators}).
5559 @c JP
5560 @code{map}と同じように動作しますが、結果はクラス@var{class}のインスタンスとして返されます。
5561 @var{class}はコレクションクラスでなければなりません。
5562 また、ビルダーインタフェースを持っている必要があります
5563 (@ref{Fundamental iterator creators}参照).
5564 @c COMMON
5565
5566 @example
5567 (map-to <vector> + '#(1 2 3) '#(4 5 6))
5568 @result{} #(5 7 9)
5569
5570 (map-to <string> char-upcase "def")
5571 @result{} "DEF"
5572
5573 (map-to <vector> char=? "bed" "pet")
5574 @result{} #(#f #t #f)
5575 @end example
5576 @end deffn
5577
5578 @deffn {Generic function} map-accum proc seed coll1 coll2 @dots{}
5579 @c MOD gauche.collection
5580 @c EN
5581 Collects results of @var{proc} over collections, while passing
5582 a state value. @var{proc} is called like this:
5583 @c JP
5584 状態値を持ち回りながら@var{proc}のコレクションの各要素への呼び出しを集めます。
5585 @var{proc}は次のように呼ばれます。
5586 @c COMMON
5587 @example
5588 (@var{proc} @var{elt1} @var{elt2} @dots{} @var{seed})
5589 @end example
5590 @c EN
5591 Where @var{elt1} @var{elt2} @dots{} are the elements of
5592 @var{coll1} @var{coll2} @dots{}.
5593 It must return two values; the first value is collected into
5594 a list (like @code{map}), while the second value is passed as
5595 @var{seed} to the next call of @var{proc}.
5596 @c JP
5597 ここで@var{elt1} @var{elt2} @dots{}は
5598 @var{coll1} @var{coll2} @dots{}の各要素です。
5599 @var{proc}は2つの値を返さねばなりません。最初の値が@code{map}のように
5600 リストへと集められます。2つ目の値は次の@var{proc}の呼び出しの@var{seed}
5601 として使われます。
5602 @c COMMON
5603
5604 @c EN
5605 When one of the collections is exhausted, @code{map-accum} returns
5606 two values, the list of the first return values from @var{proc},
5607 and the second return value of the last call of @var{proc}.
5608 @c JP
5609 いずれかのコレクションの要素を使い切った時点で、@code{map-accum}は
5610 2つの値を返します。最初の値は@var{proc}の最初の戻り値をリストにしたもの、
5611 2番目の値は@var{proc}の最後の呼び出しの2番目の戻り値です。
5612 @c COMMON
5613
5614 @c EN
5615 If the given collections are sequences, it is guaranteed that
5616 @var{proc} is applied in order of the sequence.
5617 @c JP
5618 もし与えられたコレクションがシーケンスであった場合は、
5619 @var{proc}はシーケンスの順序通りに適用されます。
5620 @c COMMON
5621
5622 @c EN
5623 This is similar to Haskell's @code{mapAccumL}, but note that
5624 the order of @code{proc}'s argument and return values are
5625 reversed.
5626 @c JP
5627 この手続きはHaskellの@code{mapAccumL}と似ています。但し、
5628 @code{proc}の引数と戻り値の順が逆転していることに注意して下さい。
5629 @c COMMON
5630 @end deffn
5631
5632
5633 @deffn {Generic function} for-each proc coll coll2 @dots{}
5634 @c MOD gauche.collection
5635 @c EN
5636 Extension of built-in @code{for-each} (@pxref{Walking over lists}).
5637 Applies @var{proc} for each elements in the collection(s).
5638 The result of @var{proc} is discarded. The return value of
5639 @code{for-each} is undefined.
5640 @c JP
5641 組み込み手続き@code{for-each} (@ref{Walking over lists}参照) を拡張します。
5642 コレクション@var{coll}の各要素に手続き@var{proc}を適用します。
5643 @var{proc}の結果は捨てられます。@code{for-each}の結果は未定義です。
5644 @c COMMON
5645
5646 @c EN
5647 If the @var{coll} is a sequence, it is guaranteed that
5648 the elements are traversed in order. Otherwise, the order
5649 of iteration is undefined.
5650 @c JP
5651 @var{coll}がシーケンスでもある場合、要素はシーケンスの順に@var{proc}に渡されます。
5652 そうでなければ繰り返しの順序は未定義です。
5653 @c COMMON
5654
5655 @c EN
5656 If more than one collection is passed, @var{proc} is called with
5657 elements for each collection. In such case, @code{for-each} terminates
5658 as soon as one of the collection is exhausted. Note that passing
5659 more than one collection doesn't make much sense unless
5660 all the collections are sequences.
5661 @c JP
5662 複数のコレクションが与えられた場合、@var{proc}は各コレクションからの要素を引数として
5663 呼び出されます。@code{for-each}はひとつでもコレクションの最後に到達したら終了します。
5664 複数のコレクションを渡すのは、コレクションの全てがシーケンスでないとあまり意味がないでしょう。
5665 @c COMMON
5666 @end deffn
5667
5668
5669 @deffn {Generic Function} fold$ proc
5670 @deffnx {Generic Function} fold$ proc knil
5671 @deffnx {Generic Function} map$ proc
5672 @deffnx {Generic Function} for-each$ proc
5673 @c MOD gauche.collection
5674 @c EN
5675 Partial-application version of @code{fold}, @code{map} and @code{for-each}.
5676 @c JP
5677 @code{fold}、@code{map}、@code{for-each}の部分評価版です。
5678 @c COMMON
5679 @end deffn
5680
5681
5682 @c EN
5683 @emph{Discussion:} It is debatable what type of collection @code{map}
5684 should return when it operates on the collections other than lists.
5685 It may seem more ``natural'' if @code{(map * '#(1 2) '#(3 4))}
5686 returns a vector, and @code{(map char-upcase "abc")} returns a string.
5687 @c JP
5688 @emph{Discussion:} @code{map}がリスト以外に対して適用されたとき、どういう
5689 コレクション型を返すべきでしょう。
5690 @code{(map * '#(1 2) '#(3 4))} がベクタを返し、
5691 @code{(map char-upcase "abc")} が文字列を返すようにするほうが「自然」でしょうか。
5692 @c COMMON
5693
5694 @c EN
5695 Although such interface seems work for simple cases, it'll become
5696 problematic for more general cases. What type of collection should
5697 be returned if a string and a vector are passed? Furthermore,
5698 some collection may only have iterator interface but no builder
5699 interface, so that the result can't be coerced to the argument type
5700 (suppose you're mapping over database records, for example).
5701 And Scheme programmers are used to think @code{map} returns a list,
5702 and the result of @code{map} are applied to the procedures that
5703 takes list everywhere.
5704 @c JP
5705 そのようなインタフェースは単純な場合には動作するように思えますが、
5706 一般的な拡張は困難です。文字列とベクタが同時に渡されたらどうします?
5707 更に、コレクションクラスによっては繰り返しインタフェースは持っていても
5708 ビルダーインタフェースを持っていない場合があり、結果をそのコレクションクラスとして
5709 返せない場合もあります (データベースレコードのコレクションに対してマップする、
5710 といった用法を考えてみて下さい)。また、Schemeプログラマは@code{map}が
5711 リストを返すという事実に慣れ親しんでおり、既存のコードも@var{map}の戻り値を
5712 リストを受け取る手続きに渡すことがよく行われています。
5713 @c COMMON
5714
5715 @c EN
5716 So I decided to add another method, @code{map-to}, to specify
5717 the return type explicitly
5718 The idea of passing the return type is taken from CommonLisp's @code{map}
5719 function, but taking a class metaobject, @code{map-to} is much flexible
5720 to extend using method dispatch.
5721 This protocol (``-to'' variant takes a class metaobject
5722 for the result collection) is used throughout the collection framework.
5723 @c JP
5724 そこで、結果の型を明示的に指定する@code{map-to}という別のメソッドを定義しました。
5725 結果の型を渡すのは、CommonLispの@code{map}関数にならっていますが、
5726 Gaucheではクラスメタオブジェクトを渡すようにしたため、メソッドディスパッチを使って
5727 拡張することが容易です。``-to'' のつくメソッドは結果のコレクションのクラスを
5728 取るというインタフェースはコレクションフレームワーク中で統一的に使われています。
5729 @c COMMON
5730
5731 @node Selection and searching in collection, Miscellaneous operations on collection, Mapping over collection, Collection framework
5732 @subsection Selection and searching in collection
5733 @c NODE コレクションからの選択と探索
5734
5735 @deffn {Generic function} find pred coll
5736 @c MOD gauche.collection
5737 @c EN
5738 Applies @var{pred} for each element of a collection @var{coll} until
5739 @var{pred} returns a true value. Returns the element on which @var{pred}
5740 returned a true value, or @code{#f} if no element satisfies @var{pred}.
5741 @c JP
5742 @var{pred}をコレクション@var{coll}の要素に適用してゆきます。@var{pred}が
5743 真の値を返したらそこで打ち切り、その要素を返します。@var{pred}が真の値を返す
5744 要素が無かった場合は@code{#f}を返します。
5745 @c COMMON
5746
5747 @c EN
5748 If @var{coll} is a sequence, it is guaranteed that @var{pred} is
5749 applied in order. Otherwise the order of application is undefined.
5750 @c JP
5751 @var{coll}がシーケンスでもある場合、要素はシーケンスの順に@var{proc}に渡されます。
5752 そうでなければ繰り返しの順序は未定義です。
5753 @c COMMON
5754
5755 @example
5756 (find char-upper-case? "abcDe") @result{} #\D
5757 (find even? '#(1 3 4 6)) @result{} 4
5758 (find even? '(1 3 5 7)) @result{} #f
5759 @end example
5760 @end deffn
5761
5762 @deffn {Generic function} find-min coll :key key compare default
5763 @deffnx {Generic function} find-max coll :key key compare default
5764 @c MOD gauche.collection
5765 @c EN
5766 Returns a minimum or maximum element in the collection @var{coll}.
5767
5768 A one-argument procedure @var{key}, whose default is @code{identity},
5769 is applied for each element to obtain a comparison value.
5770 Then a comparison value is compared by a two-argument procedure
5771 @var{compare}, whose default is @code{<}.
5772 If the collection has zero or one element, the @var{compare} procedure
5773 is never called.
5774
5775 When the collection is empty, a value given to @var{default} is
5776 returned, whose default is @code{#f}.
5777 @c JP
5778 コレクション@var{coll}から最小もしくは最大の要素を探して返します。
5779
5780 コレクションの各要素に対し、1引数の手続き@var{key}が適用され、
5781 その戻り値が比較対象となります。@var{key}のデフォルトは@code{identity}です。
5782 比較対象の値は2引数の手続き@var{compare}で比較されます。
5783 @var{compare}のデフォルトは@code{<}です。コレクション中の要素数が
5784 1つ以下の場合は@var{compare}は呼ばれません。
5785
5786 コレクションが空の場合は、@var{default}で指定した値が返されます。
5787 @var{default}のデフォルト値は@code{#f}です。
5788 @c COMMON
5789
5790 @example
5791 (find-min '((a . 3) (b . 9) (c . -1) (d . 7)) :key cdr) @result{} (c . -1)
5792 @end example
5793 @end deffn
5794
5795 @deffn {Generic function} find-min&max coll :key key compare default default-min default-max
5796 @c MOD gauche.collection
5797 @c EN
5798 Does @code{find-min} and @code{find-max} simultaneously, and returns
5799 two values, the minimum element and the maximum element.
5800 The keyword arguments @var{key}, @var{compare}, and @var{default} are
5801 the same as @code{find-min} and @code{find-max}. Alternatively
5802 you can give default values for minimum and maximum separately,
5803 by @var{default-min} and @var{default-max}.
5804 @c JP
5805 @code{find-min}と@code{find-max}の動作を同時に行い、
5806 最小と最大の要素をふたつの値として返します。
5807 キーワード引数@var{key}、@var{compare}、@var{default}の意味は
5808 @code{find-min}、@code{find-max}と同じです。
5809 また、@var{default-min}と@var{default-max}を使って
5810 最小要素と最大要素のデフォルト値を別々に指定することもできます。
5811 @c COMMON
5812 @end deffn
5813
5814 @deffn {Generic function} filter pred coll
5815 @c MOD gauche.collection
5816 @c EN
5817 Returns a list of elements of collection @var{coll} that satisfies
5818 the predicate @var{pred}. If the collection is a sequence,
5819 the order is preserved in the result.
5820 @c JP
5821 コレクション@var{coll}中の要素のうち、述語手続き@var{pred}が真の値を返したものの
5822 リストを返します。コレクションがシーケンスであれば、結果の要素の順序は元のシーケンスの
5823 順序と同じになります。
5824 @c COMMON
5825
5826 @example
5827 (filter char-upper-case? "Hello, World")
5828 @result{} (#\H #\W)
5829 (filter even? '#(1 2 3 4)) @result{} (2 4)
5830 @end example
5831 @end deffn
5832
5833 @deffn {Generic function} filter-to class pred coll
5834 @c MOD gauche.collection
5835 @c EN
5836 Same as @code{filter}, but the result is returned
5837 as a collection of class @var{class}.
5838 @c JP
5839 @code{filter}と同じですが、結果のコレクションが@var{class}のインスタンスで
5840 返されます。
5841 @c COMMON
5842
5843 @example
5844 (filter-to <vector> even? '#(1 2 3 4)) @result{} #(2 4)
5845 (filter-to <string> char-upper-case? "Hello, World")
5846 @result{} "HW"
5847 @end example
5848 @end deffn
5849
5850 @deffn {Generic function} remove pred coll
5851 @c MOD gauche.collection
5852 @c EN
5853 Returns a list of elements of collection @var{coll} that does not
5854 satisfy the predicate @var{pred}. If the collection is a sequence,
5855 the order is preserved in the result.
5856 @c JP
5857 コレクション@var{coll}中の要素のうち、述語手続き@var{pred}が偽の値を返したものの
5858 リストを返します。コレクションがシーケンスであれば、結果の要素の順序は元のシーケンスの
5859 順序と同じになります。
5860 @c COMMON
5861
5862 @example
5863 (remove char-upper-case? "Hello, World")
5864 @result{} (#\e #\l #\l #\o #\, #\space #\o #\r #\l #\d)
5865 (remove even? '#(1 2 3 4)) @result{} (1 3)
5866 @end example
5867 @end deffn
5868
5869 @deffn {Generic function} remove-to class pred coll
5870 @c MOD gauche.collection
5871 @c EN
5872 Same as @code{remove}, but the result is returned
5873 as a collection of class @var{class}.
5874 @c JP
5875 @code{remove}と同じですが、結果のコレクションが@var{class}のインスタンスで
5876 返されます。
5877 @c COMMON
5878
5879 @example
5880 (remove-to <vector> even? '#(1 2 3 4)) @result{} #(1 3)
5881 (remove-to <string> char-upper-case? "Hello, World")
5882 @result{} "ello, orld"
5883 @end example
5884 @end deffn
5885
5886 @deffn {Generic function} partition pred coll
5887 @c MOD gauche.collection
5888 @c EN
5889 Does @code{filter} and @code{remove} the same time.
5890 Returns two lists, the first consists of elements of the collection
5891 @var{coll} that satisfies the predicate @var{pred}, and the second
5892 consists of elements that doesn't.
5893 @c JP
5894 @code{filter}と@code{remove}を同時に行います。
5895 二つのリストを返します。最初のリストはコレクション@var{coll}の要素のうち
5896 述語手続き@var{pred}が真の値を返したものから構成され、二つ目のリストは
5897 そうでない要素から構成されます。
5898 @c COMMON
5899
5900 @example
5901 (partition char-upper-case? "PuPu")
5902 @result{} (#\P #\P) @r{and} (#\u #\u)
5903 (partition even? '#(1 2 3 4))
5904 @result{} (2 4) @r{and} (1 3)
5905 @end example
5906 @end deffn
5907
5908 @deffn {Generic function} partition-to class pred coll
5909 @c MOD gauche.collection
5910 @c EN
5911 Same as @code{partition}, except the results are returned
5912 in the collections of class @var{class}.
5913 @c JP
5914 @code{partition}と同じですが、結果がクラス@var{class}のコレクションとして
5915 返されます。
5916 @c COMMON
5917
5918 @example
5919 (partition-to <string> char-upper-case? "PuPu")
5920 @result{} "PP" @r{and} "uu"
5921 (partition-to <vector> even? '#(1 2 3 4))
5922 @result{} #(2 4) @r{and} #(1 3)
5923 @end example
5924 @end deffn
5925
5926 @deffn {Generic function} group-collection coll :key key test
5927 @c MOD gauche.collection
5928 @c EN
5929 Generalized @code{partition}. Groups elements in @var{coll}
5930 into those who has the same key value, and returns the groups as
5931 of lists. Key values are calculated by applying the procedure @var{key}
5932 to each element of @var{coll}. The default value of @var{key} is
5933 @code{identity}. For each element of @var{coll}, @var{key} is applied
5934 exactly once.
5935 The equal-ness of keys are compared by
5936 @var{test} procedure, whose default is @code{eqv?}.
5937 @c JP
5938 @code{partition}を汎化したものです。@var{coll}内の要素を同じキーを
5939 持つ値同士でグループ化し、リストのリストにして返します。
5940 キーの値は要素に手続き@var{key}を適用することで得られます。@var{key}の
5941 デフォルト値は@code{identity}です。@var{coll}の各要素に対して、
5942 @var{key}は正確に一回だけ呼ばれます。
5943 キーの等価性判定には手続き@var{test}が使われます。デフォルト値は@code{eqv?}です。
5944 @c COMMON
5945
5946 @c EN
5947 If @var{coll} is a sequence, then the order of elements in each group
5948 of the result is the same order in @var{coll}.
5949 @c JP
5950 @var{coll}がシーケンスである場合、結果の各グループに含まれる要素の順は
5951 もとのシーケンス内での順と同じになります。
5952 @c COMMON
5953
5954 @example
5955 (group-collection '(1 2 3 2 3 1 2 1 2 3 2 3))
5956 @result{} ((1 1 1) (2 2 2 2 2) (3 3 3 3))
5957
5958 (group-collection '(1 2 3 2 3 1 2 1 2 3 2 3) :key odd?)
5959 @result{} ((1 3 3 1 1 3 3) (2 2 2 2 2))
5960
5961 (group-collection '(("a" 2) ("b" 5) ("c" 1) ("b" 3) ("a" 6))
5962 :key car :test string=?)
5963 @result{} ((("a" 2) ("a" 6)) (("b" 5) ("b" 3)) (("c" 1)))
5964 @end example
5965
5966 @c EN
5967 See also @code{group-sequence} in @code{gauche.sequence}
5968 (@pxref{Other operations over sequences}),
5969 which only groups adjacent elements.
5970 @c JP
5971 @code{gauche.sequence}の@code{group-sequence}も参照して下さい
5972 (@ref{Other operations over sequences}参照)。
5973 隣り合う要素同士でグループ化するものです。
5974 @c COMMON
5975 @end deffn
5976
5977 @deffn {Generic function} group-collection->alist coll :key key value test
5978 @c MOD gauche.collection
5979 @c EN
5980 Similar to @code{group-collection}, but returns the result as an assoc
5981 list keyed by extracted keys of comparison. It's eaiser to see the example:
5982 @c JP
5983 @code{group-collection}に似ていますが、結果を比較に使ったキーでまとめた
5984 連想リストにして返します。例を見るのがわかりやすいでしょう。
5985 @c COMMON
5986
5987 @example
5988 (group-collection->alist '((3 "a") (2 "b") (1 "c") (3 "d") (1 "e"))
5989 :key car :value cadr)
5990 @result{} ((3 "a" "d") (2 "b") (1 "c" "e"))
5991
5992 ;; Compare with this
5993 (group-collection '((3 "a") (2 "b") (1 "c") (3 "d") (1 "e"))
5994 :key car)
5995 @result{} (((3 "a") (3 "d")) ((2 "b")) ((1 "c") (1 "e")))
5996 @end example
5997
5998 @c EN
5999 First, elements in the collection is grouped with the common keys.
6000 Then, a pair @code{(cons @var{key} (map value-proc @var{elements}))}
6001 is computed, where @code{value-proc} is the value extraction procedure
6002 passed by the @var{value} keyword argument. List of those pairs is returned.
6003
6004 If omitted, @var{key} and @var{value} arguments are assumed to be
6005 @code{identity}, and @var{test} argument (used to compare keys)
6006 is assumed to be @code{eqv?}.
6007
6008 If the collection is ordered, the order of the alist is the same
6009 as the order the first element with each key appears in the collection,
6010 and within each alist entry, the values are the same order of appearance
6011 in the collection.
6012 @c JP
6013 まず、コレクション中で共通のキーを持つ要素がグループにまとめられます。
6014 次に各グループについて@code{(cons @var{key} (map value-proc @var{elements}))}
6015 が計算され、そのリストが結果となります。ここで@code{value-proc}はキーワード引数
6016 @var{value}で渡した値抽出手続きです。
6017
6018 キーワード引数@var{key}および@var{value}の省略時の値は@code{identity}、
6019 キーの比較に使われる@var{test}の省略時の値は@code{eqv?}です。
6020 @c COMMON
6021 @end deffn
6022
6023
6024 @node Miscellaneous operations on collection, Fundamental iterator creators, Selection and searching in collection, Collection framework
6025 @subsection Miscellaneous operations on collection
6026 @c NODE コレクションに対する様々な操作
6027
6028 @deffn {Generic function} size-of coll
6029 @c MOD gauche.collection
6030 @c EN
6031 Returns the number of elements in the collection. Default method iterates over
6032 the collection to calculate the size, which is not very efficient
6033 and may diverge if the collection is infinite.
6034 Some collection classes overload the method for faster calculation.
6035 @c JP
6036 コレクションの要素数を返します。
6037 デフォルトのメソッドは、コレクション中の要素をすべて数え上げるものですが、
6038 あまり効率は良くないでしょう。また、無限個の要素を持つコレクションでは
6039 帰ってきません。多くのコレクションクラスはより効率の良い方法でこのメソッドを定義しています。
6040 @c COMMON
6041 @end deffn
6042
6043 @deffn {Generic function} lazy-size-of coll
6044 @c MOD gauche.collection
6045 @c EN
6046 Returns either the size of the collection, or a promise to
6047 calculate it. The intent of this method is to avoid
6048 size calculation if it is expensive. In some cases, the caller
6049 wants to have size just for optimization, and it is not desirable
6050 to spend time to calculate the size. Such caller uses this method
6051 and just discards the information if it is a promise.
6052 @c JP
6053 コレクションの要素数か、もしくはそれを計算するプロミスを返します。
6054 このメソッドの目的は、要素数の計算が高価な場合にそれを避けることにあります。
6055 しばしば、呼び出し側では最適化のための参考値として要素数が欲しい場合があり、
6056 そういった場合は要素数を計算するために時間を費すのは望ましくありません。
6057 このメソッドを代わりに呼び出して、結果がプロミスであればそれを使わない、
6058 という選択ができます。
6059 @c COMMON
6060 @end deffn
6061
6062 @deffn {Generic function} coerce-to class coll
6063 @c MOD gauche.collection
6064 @c EN
6065 Convert a collection @var{coll} to another collection
6066 which is an instance of @var{class}.
6067 If @var{coll} is a sequence and @var{class} is a sequence class,
6068 the order is preserved.
6069 @c JP
6070 コレクション@var{coll}を、クラス@var{class}のインスタンスである
6071 別のコレクションへと変換します。@var{coll}がシーケンスであり、
6072 @var{class}がシーケンスクラスであれば、元のシーケンスの順序は保存されます。
6073 @c COMMON
6074
6075 @example
6076 (coerce-to <vector> '(1 2 3 4))
6077 @result{} #(1 2 3 4)
6078
6079 (coerce-to <string> '#(#\a #\b #\c))
6080 @result{} "abc"
6081 @end example
6082 @end deffn
6083
6084 @node Fundamental iterator creators, Implementing collections, Miscellaneous operations on collection, Collection framework
6085 @subsection Fundamental iterator creators
6086 @c NODE 基礎的なイテレータ構築メソッド
6087
6088 @c EN
6089 These are fundamental methods on which all the rest of
6090 iterative method are built. The method interface is not intended
6091 to be called from general code, but suitable for building
6092 other iterator construct. The reason why I chose this interface
6093 as fundamental methods are explained at the bottom of this subsection.
6094 @c JP
6095 ここに挙げるメソッドは、他のコレクションメソッドの基礎となるものです。
6096 メソッドのインタフェースは一般のコードで使われることよりも、
6097 効率良く他の繰り返しメソッドを記述するのに便利なように設計されています。
6098 何故このインタフェースを基礎のメソッドとして選んだかについてはこの章の最後に説明します。
6099 @c COMMON
6100
6101 @deffn {Generic function} call-with-iterator collection proc :key start
6102 @c MOD gauche.collection
6103 @c EN
6104 A fundamental iterator creator. This creates two procedures
6105 from @var{collection}, both take no argument, and then call
6106 @var{proc} with those two procedures. The first procedure is
6107 terminate predicate, which returns @code{#t} if the iteration
6108 is exhausted, or @code{#f} if there are still elements to be visited.
6109 The second procedure is an incrementer,
6110 which returns one element from the collection and sets the
6111 internal pointer to the next element.
6112 The behavior is undefined if you call the incrementer after
6113 the terminate predicate returns @code{#t}.
6114 @c JP
6115 基礎となるイテレータ構築メソッドです。このメソッドはコレクション@var{collection}
6116 から繰り返しのための二つの手続きを作成し、それらを引数として手続き@var{proc}を
6117 呼びます。作られる最初の手続きは終了判定手続きで、引数無しで呼び出され、繰り返しが
6118 終了していれば@code{#t}を、まだ要素が残っていれば@code{#f}を返します。
6119 作られる二番目の手続きはインクリメント手続きで、呼ばれる度に現在の要素を返し、
6120 内部のポインタを次の要素へと進めます。終了判定手続きが@code{#t}を返した後に
6121 インクリメント手続きを呼んだ場合の動作は未定義です。
6122 @c COMMON
6123
6124 @c EN
6125 If the collection is actually a sequence, the incrementer is guaranteed
6126 to return elements in order, from 0-th element to the last element.
6127 If a keyword argument @var{start} is given, however, the iteration
6128 begins from @var{start}-th element and ends at the last element.
6129 If the collection is not a sequence, the iteration order is
6130 arbitrary, and @var{start} argument has no effect.
6131 @c JP
6132 コレクションがシーケンスでもある場合、インクリメント手続きはシーケンスの順番に要素を取り出します。
6133 キーワード引数@var{start}が与えられていればイテレーションの範囲は
6134 @var{start}番目の要素から最後の要素までとなります。シーケンスでないコレクションに
6135 対しては@var{start}引数は意味を持ちません。
6136 @c COMMON
6137
6138 @c EN
6139 An implementation of @var{call-with-iterator} method may
6140 limit the extent of the iterator inside the dynamic scope of the method.
6141 For example, it allocates some resource (e.g. connect to a database)
6142 before calling @var{proc}, and deallocates it (e.g. disconnect from a database)
6143 after @var{proc} returns.
6144 @c JP
6145 @var{call-with-iterator}のメソッド実装は、イテレータのエクステントを
6146 そのメソッドのダイナミックスコープ内に限ることを許されます。例えば、
6147 メソッドは@var{proc}を呼ぶ前に何らかのリソースを確保し(データベースへのコネクションなど)、
6148 @var{proc}から戻った後でそれを解放するということができます。
6149 @c COMMON
6150
6151 @c EN
6152 This method returns the value(s) @var{proc} returns.
6153 @c JP
6154 このメソッドは @var{proc} が返した値をそのまま返します。
6155 @c COMMON
6156
6157 @example
6158 (call-with-iterator '(1 2 3 4 5)
6159 (lambda (end? next)
6160 (do ((odd-nums 0))
6161 ((end?) odd-nums)
6162 (when (odd? (next)) (inc! odd-nums)))))
6163 @result{} 3
6164 @end example
6165
6166 @c EN
6167 See also @code{with-iterator} macro below, for it is easier to use.
6168 @c JP
6169 下に示す@code{with-iterator}マクロも参照してください。
6170 @c COMMON
6171 @end deffn
6172
6173 @defmac with-iterator (collection end? next args @dots{}) body @dots{}
6174 @c MOD gauche.collection
6175 @c EN
6176 A convenience macro to call @code{call-with-iterator}.
6177 @c JP
6178 @code{call-with-iterator}を簡潔に呼び出すマクロです。
6179 @c COMMON
6180 @example
6181 (with-iterator (coll end? next args @dots{}) body @dots{})
6182 @equiv{}
6183 (call-with-iterator coll
6184 (lambda (end? next) body @dots{})
6185 args @dots{})
6186 @end example
6187 @end defmac
6188
6189 @defun call-with-iterators collections proc
6190 @c MOD gauche.collection
6191 @c EN
6192 A helper function to write n-ary iterator method.
6193 This function applies @code{call-with-iterator} for each @var{collection}s,
6194 and makes two lists, the first consists of terminate predicates
6195 and the second of incrementers. Then @var{proc} is called
6196 with those two lists. Returns whatever @var{proc} returns.
6197 @c JP
6198 N-aryのイテレータメソッドを書くのに便利な手続きです。
6199 この手続きはコレクションのリスト@var{collections}の各コレクションに対して
6200 @code{call-with-iterator}を呼び、二つのリストを作ります。最初のリストには
6201 終了判定手続きが順に集められており、二つ目のリストにはインクリメント手続きが
6202 順に集められています。そして、これらのリストを引数として@var{proc}を呼び出します。
6203 @var{proc}が返した値を返します。
6204 @c COMMON
6205 @end defun
6206
6207 @deffn {Generic function} call-with-builder collection-class proc :key size
6208 @c MOD gauche.collection
6209 @c EN
6210 A fundamental builder creator. Builder is a way to construct
6211 a collection incrementally. Not all collection classes provide
6212 this method.
6213 @c JP
6214 基礎的なビルダー構築メソッドです。ビルダーはコレクションをインクリメンタルに
6215 作成する方法です。コレクションクラスによってはこの手続きを提供しないものもあります。
6216 @c COMMON
6217
6218 @c EN
6219 @var{Collection-class} is a class of the collection to be built.
6220 This method creates two procedures, adder and getter, then calls
6221 @var{proc} with those procedures.
6222 Adder procedure takes one argument and adds it to the collection
6223 being built. Getter takes no argument and returns a built collection object.
6224 The effect is undefined if adder is called after getter is called.
6225 @c JP
6226 @var{Collection-class}は作成されるコレクションのクラスです。
6227 このメソッドは、追加手続きと結果手続きの二つの手続きを作成し、それらを
6228 引数として@var{proc}を呼びます。追加手続きは一つ引数を取り、それを作成中の
6229 コレクションに追加します。結果手続きは引数を取らず、作成されたコレクションを返します。
6230 結果手続きが呼ばれた後で追加手続きを呼んだ場合の動作は未定義です。
6231 @c COMMON
6232
6233 @c EN
6234 A keyword argument @var{size} may be specified if the size of
6235 the result collection is known. Certain collections may be
6236 built much more efficiently if the size is known; other collections
6237 may just ignore it. The behavior is undefined if more than
6238 @var{size} elements are added, or the collection is retrieved before
6239 @var{size} elements are accumulated.
6240 @c JP
6241 作られるコレクションのサイズが分かっている場合、キーワード引数@var{size}を与える
6242 ことができます。コレクションクラスによってはその情報を使って効率的にコレクションを
6243 作成することができます。その情報を単に無視するコレクションクラスもあります。
6244 @var{size}個より多くの要素が追加されたり、@var{size}個の要素が追加される前に
6245 結果手続きが呼ばれたりした場合の動作は未定義です。
6246 @c COMMON
6247
6248 @c EN
6249 If the collection class is actually a sequence class,
6250 adder is guaranteed to add elements in order. Otherwise,
6251 the order of elements are insignificant.
6252 @c JP
6253 コレクションクラスがシーケンスクラスであった場合、追加手続きは要素を
6254 シーケンスの順に追加してゆきます。
6255 @c COMMON
6256
6257 @c EN
6258 Some collection class may take more keyword arguments to
6259 initialize the collection.
6260 @c JP
6261 コレクションクラスによっては、コレクションオブジェクトの初期化のために
6262 他のキーワード引数を取るかもしれません。
6263 @c COMMON
6264
6265 @c EN
6266 This method returns the value(s) @var{proc} returned.
6267 @c JP
6268 このメソッドは@var{proc}が返す値を返します。
6269 @c COMMON
6270
6271 @example
6272 (call-with-builder <list>
6273 (lambda (add! get)
6274 (add! 'a) (add! 'b) (add! 'c) (get)))
6275 @result{} (a b c)
6276
6277 (call-with-builder <vector>
6278 (lambda (add! get)
6279 (add! 'a) (add! 'b) (add! 'c) (get)))
6280 @result{} #(a b c)
6281 @end example
6282
6283 @c EN
6284 See also @code{with-builder} macro below, for it is much easier to use.
6285 @c JP
6286 下に示す@code{with-builder}マクロも参照してください。
6287 @c COMMON
6288 @end deffn
6289
6290 @defmac with-builder (collection add! get args @dots{}) body @dots{}
6291 @c MOD gauche.collection
6292 @c EN
6293 A convenience macro to call @code{call-with-builder}.
6294 @c JP
6295 @code{call-with-builder}を簡潔に呼び出すマクロです。
6296 @c COMMON
6297 @example
6298 (with-builder (coll add! get args @dots{}) body @dots{})
6299 @equiv{}
6300 (call-with-builder coll
6301 (lambda (add! get) body @dots{})
6302 args @dots{})
6303 @end example
6304 @end defmac
6305
6306 @emph{Discussion}:
6307 @c EN
6308 Other iterator methods are built on top of call-with-iterator and
6309 call-with-builder.
6310 By implementing those methods, you can easily adapt your own collection
6311 class to all of those iterative
6312 operations. Optionally you can overload some of higher-level
6313 methods for efficiency.
6314 @c JP
6315 他のイテレータメソッドは全てこのcall-with-iteratorとcall-with-builderの上に構築可能です。
6316 最低限これらのメソッドを定義すれば、そのクラスはコレクションとして振舞うことができます。
6317 もちろん最適化のために他のイテレータメソッドを定義しても構いませんが。
6318 @c COMMON
6319
6320 @c EN
6321 It is debatable that which set of operations should be primitives.
6322 I chose call-with-iterator style for efficiency of the applications
6323 I see most. The following is a discussion of other possible
6324 primitive iterators.
6325 @c JP
6326 どの操作を基礎的なメソッドとするかには議論の余地があります。
6327 Gaucheでは、作者がよく見るパターンで最も効率が良くなるように考えて現在のスタイルを
6328 選びました。以下に、他の基礎的なメソッドの可能性を検討します。
6329 @c COMMON
6330
6331 @table @asis
6332 @item @code{fold}
6333 @c EN
6334 It is possible to make @code{fold} a primitive method, and
6335 build other iterator method on top of it.
6336 Collection-specific iterating states can be kept in the
6337 stack of @code{fold}, thus it runs efficiently. The method
6338 to optimize a procedure that uses @code{fold} as a basic
6339 iterator construct.
6340 However, it is rather cumbersome to derive
6341 generator-style interface from it. It is also tricky
6342 to iterate irregularly over more than one collections.
6343 @c JP
6344 @code{fold}を最も基礎的なメソッドとして、他のイテレータメソッドをその上に
6345 構築することも可能です。繰り返しの状態はスタックに置かれるので効率良く走ります。
6346 @code{fold}を基礎とした繰り返し関数を最適化する方法は良く知られています。
6347 しかし、@code{fold}を元にしてジェネレータスタイルのインタフェースを
6348 作成するのは複雑です。また、複数のコレクションに対しての繰り返しを書くのも
6349 面倒です。
6350 @c COMMON
6351
6352 @item CPS
6353 @c EN
6354 Passes iteratee the continuation procedure that continues
6355 the iteration. The iteratee just returns when it want
6356 to terminate the iteration.
6357 It has resource management problem described in
6358 Oleg Kiselyov's article (@uref{http://okmij.org/ftp/Scheme/enumerators-callcc.html}).
6359 @c JP
6360 繰り返しの中身の手続きに対し、繰り返しを続けるための継続手続きを渡す方法です。
6361 繰り返しを続けたくなければ、手続きは継続を呼ばすにそのまま戻ります。
6362 Oleg Kiselyovの記事(@uref{http://okmij.org/ftp/Scheme/enumerators-callcc.html})に指摘されているような、
6363 リソース管理の問題があります。
6364 @c COMMON
6365
6366 @item Iterator object
6367 @c EN
6368 Like C++ iterator or Common Lisp generator.
6369 Easy to write loop. The problem is that every call of
6370 checking termination or getting next element must be dispatched.
6371 @c JP
6372 C++のイテレータやCommon Lispのジェネレータのようなオブジェクトを使う方法です。
6373 ループを書くのは容易ですが、終了判定や要素取り出しの度にメソッドディスパッチが
6374 起こってしまいます。
6375 @c COMMON
6376
6377 @item Series
6378 @c EN
6379 Common Lisp's series can be very efficient if the compiler can statically
6380 analyze the usage of series. Unfortunately it is not the case in
6381 Gauche. Even if it could, the extension mechanism doesn't blend well
6382 with Gauche's object system.
6383 @c JP
6384 Common Lispのシリーズはコンパイラがシリーズの使われかたを追跡できれば
6385 非常に効率の良いコードに変換できます。Gaucheのコンパイラはそこまでのデータフロー解析を
6386 行っていません。また、それをやったとしても、コレクションクラスを拡張するための方法が
6387 Gaucheのオブジェクトシステムとはうまく調和しません。
6388 @c COMMON
6389
6390 @item Macros
6391 @c EN
6392 Iterator can be implemented as macros, and that will be very efficient;
6393 e.g. Scheme48's iterator macro. It uses macros to extend, however,
6394 and that doesn't blend well with Gauche's object system.
6395 @c JP
6396 効率を気にするなら、イテレータをマクロで書いてしまう方法もあります
6397 (例えばScheme48の@code{iterator}マクロなど)。
6398 効率は良いのですが、拡張するにはマクロを書くことが必要となり、
6399 Gaucheのオブジェクトシステムとうまく調和しません。
6400 @c COMMON
6401 @end table
6402
6403 @c EN
6404 The current implementation is close to the iterator object approach,
6405 but using closures instead of iterator objects so that avoiding
6406 dispatching in the inner loop. Also it allows the iterator
6407 implementor to take care of the resource problem.
6408 @c JP
6409 現在の実装はイテレータオブジェクトアプローチに近いですが、イテレータオブジェクトを
6410 作る代わりにクロージャを使うことで内部のループでのメソッドディスパッチを
6411 避けています。また、現在のインタフェースはリソース管理の問題を解決しています。
6412 @c COMMON
6413
6414 @node Implementing collections, , Fundamental iterator creators, Collection framework
6415 @subsection Implementing collections
6416 @c NODE コレクションの実装
6417
6418 @c EN
6419 The minimum requirements of the collection class implementation
6420 is as follow:
6421 @itemize @bullet
6422 @item
6423 The class inherits @code{<collection>} abstract class.
6424 @item
6425 A method @code{call-with-iterator} is implemented.
6426 @end itemize
6427
6428 This makes iterator methods such as @code{map}, @code{for-each},
6429 @code{find} and @code{filter} to work.
6430 @c JP
6431 コレクションクラスの実装に最低限要求されるものには、以下のものがあります。
6432 @itemize @bullet
6433 @item
6434 抽象クラス@code{<collection>}を継承している。
6435 @item
6436 メソッド@code{call-with-iterator}が実装されている。
6437 @end itemize
6438
6439 これにより、@code{map}、@code{for-each}、@code{find}、@code{filter}などの
6440 イテレータメソッドが動作するようになります。
6441 @c COMMON
6442
6443 @c EN
6444 Optionally, you can specialize other generic functions to optimize
6445 performance. Particularly, we strongly recommend to specialize
6446 @code{size-of}, since its default method iterates entire collection
6447 to find the size, which is O(N). Usually a collection has bette way
6448 to find out its size.
6449 @c JP
6450 パフォーマンスの最適化のために、他のジェネリック関数をオーバロードすることも
6451 できます。特に、@code{size-of}のメソッドは定義しておくことを強くおすすめします。
6452 デフォルトのメソッドはコレクション全体をなめて大きさを計算するのでO(N)かかりますが、
6453 通常、コレクションは大きさをもっと簡単に得られる手段を持っています。
6454 @c COMMON
6455
6456
6457
6458 @c EN
6459 In order to make the constructive methods (e.g. @code{map-to} to
6460 create your collection), you have to implement @code{call-with-builder}
6461 method as well. Note that @code{call-with-builder} method must work
6462 a sort of class method, dispatched by class, rather than normal method
6463 dispatched by instance. In Gauche, you can implement it by using a
6464 metaclass. Then the minimal code will look like this:
6465 @c JP
6466 建設的なメソッド(例えば、コレクションを作るための@code{map-to}など)を
6467 作るためには、メソッド@code{call-with-builder}も実装しなければなりません。
6468 メソッド@code{call-with-builder}は、クラスによりディスパッチされるクラスメソッドの
6469 一種で、インスタンスによりディスパッチされる通常のメソッドとは異なります。
6470 Gaucheでは、これはメタクラスを使うことによって実装できます。
6471 最小限のコードは次のようになります。
6472 @c COMMON
6473
6474 @example
6475 (define-class <your-collection-meta> (<class>) ())
6476
6477 (define-class <your-collection> (<collection>)
6478 (...) ;; @r{slots}
6479 :metaclass <your-collection-meta>)
6480
6481 (define-method call-with-iterator
6482 ((coll <your-collection>) proc . options)
6483 @dots{}
6484 )
6485
6486 (define-method call-with-builder
6487 ((coll <your-collection-meta>) proc . options)
6488 @dots{}
6489 )
6490 @end example
6491
6492
6493 @c ----------------------------------------------------------------------
6494 @node Configuration parameters, Generating build files, Collection framework, Library modules - Gauche extensions
6495 @section @code{gauche.config} - Configuration parameters
6496 @c NODE コンフィグレーション情報, @code{gauche.config} - コンフィグレーション情報
6497
6498 @deftp {Module} gauche.config
6499 @mdindex gauche.config
6500 @c EN
6501 This module allows the Scheme program to access the configuration information
6502 the same as you can get from the @code{gauche-config} program.
6503 @c JP
6504 このモジュールは、@code{gauche-config} プログラム経由で得られるのと
6505 同等の情報をSchemeプログラムから取得すること可能にします。
6506 @c COMMON
6507 @end deftp
6508
6509 @defun gauche-config option
6510 @c MOD gauche.config
6511 @c EN
6512 Returns the configured value of the @var{option}.
6513
6514 See the manual page of @code{gauche-config}
6515 (@pxref{Command to query configuration}), or run @code{gauche-config}
6516 without any argument from the shell, to find out the valid options.
6517 @c JP
6518 @var{option}に対応するコンフィグレーション値を返します。
6519
6520 有効なオプションについては、@code{gauche-config} のマニュアルページ(@ref{Command to query configuration})を見るか、
6521 シェルで @code{gauche-config} を引数なしで実行して下さい。
6522 @c COMMON
6523 @example
6524 (gauche-config "--cc")
6525 @result{} "gcc"
6526 (gauche-config "-L")
6527 @result{} "-L/usr/lib/gauche/0.6.5/i686-pc-linux-gnu"
6528 (gauche-config "-l")
6529 @result{} "-ldl -lcrypt -lm -lpthread"
6530 @end example
6531 @end defun
6532
6533 @c ----------------------------------------------------------------------
6534 @node Generating build files, Connection framework, Configuration parameters, Library modules - Gauche extensions
6535 @section @code{gauche.configure} - Generating build files
6536 @c NODE ビルド用ファイルの生成, @code{gauche.configure} - ビルド用ファイルの生成
6537
6538 @deftp {Module} gauche.configure
6539 @mdindex gauche.configure
6540 @c EN
6541 This is a utility library to write a @file{configure} script.
6542 It is used to check the system properties and generates build files
6543 (usually @file{Makefile}) from templates.
6544 @c JP
6545 このモジュールは@file{configure}スクリプトを書くためのユーティリティライブラリです。
6546 @file{configure}スクリプトはシステムの属性をチェックして、
6547 ビルド用のファイル(通常は@file{makefile})をテンプレートから生成します。
6548 @c COMMON
6549
6550 @c EN
6551 The primary purpose is to replace autoconf-generated
6552 @file{configure} shell scripts
6553 in Gauche extension packages.
6554 @c JP
6555 主な目的は、Gauche拡張パッケージにおいて、autoconfが生成する
6556 @file{configure}シェルスクリプトを置き換えることです。
6557 @c COMMON
6558
6559 @c EN
6560 The advantage of using autoconf is that it generates
6561 a script that runs on most vanilla unix variants, for it only uses minimal
6562 shell features and basic unix commands.
6563 However, when you configure Gauche extension,
6564 you sure have Gauche already, so you don't need to limit
6565 yourself with minimal environment.
6566 @c JP
6567 autoconfを使う利点は、生成されるスクリプトが最小限のシェル機能と基本的なunixコマンドにしか
6568 依存しないため、ほとんど何も入れないunix上でも実行できることです。
6569 けれども、Gauche拡張パッケージをビルドする時には、
6570 既にGaucheはインストールされているわけですから、これを使わない手はありません。
6571 @c COMMON
6572
6573 @c EN
6574 Writing a @file{configure} script directly in Gauche means developers
6575 don't need an extra step to generate @file{configure} before
6576 distribution. They can directly check-in @file{configure} in
6577 the source repo, and anybody who pulls the source tree can
6578 run @file{configure} at once without having autoconf.
6579 @c JP
6580 @file{configure}スクリプトがGaucheで直接書ければ、配布前に
6581 @file{configure}スクリプトを生成するという余分な手間が省けます。
6582 @file{configure}スクリプト自体をリポジトリにチェックインしておけますし、
6583 誰でもソースツリーをチェックアウトしたら(autoconfを使わずに)すぐに
6584 @file{configure}を実行できます。
6585 @c COMMON
6586
6587 @c EN
6588 Currently, @code{gauche.configure} only covers small subset of
6589 autoconf, though, so if you need to write complex tests
6590 you may have to switch back to autoconf. We'll add tests
6591 as needed.
6592 @c JP
6593 ただ、今のところ@code{gauche.configure}はautoconfの機能の小さなサブセット
6594 しかカバーしないので、複雑な機能テストが必要ならautoconfに戻らなければ
6595 ならない場合もあります。必要に応じて機能テストを足して行く予定です。
6596 @c COMMON
6597 @end deftp
6598
6599 @c EN
6600 The core feature of @code{gauche.configure} is the ability to generate files
6601 (e.g. @file{Makefile}) from templates (e.g. @file{Makefile.in}) with replacing
6602 parameters. We follow autoconf convention, so the substitution parameters
6603 in a template is written like @code{@@VAR@@}. You should be able
6604 to reuse @file{Makefile.in} used for autoconf without changing them.
6605 @c JP
6606 @code{gauche.configure}のコアとなる機能は、テンプレート(例: @file{Makefile.in})
6607 から、@code{@@VAR@@}のように書かれたパラメータを置換して
6608 ファイル(例: @file{Makefile})を生成することです。
6609 autoconf用に書いた@file{Makefile.in}はそのまま流用できるはずです。
6610 @c COMMON
6611
6612 @c EN
6613 The API corresponds to autoconf's @code{AC_*} macros, while we use
6614 @code{cf-} prefix instead.
6615 @c JP
6616 autoconfの@code{AC_*}マクロに対応する機能は、プレフィクスを@code{cf-}に置き換えた
6617 名前で提供されています。
6618 @c COMMON
6619
6620 @menu
6621 * Structure of configure script::
6622 * Configure API::
6623 @end menu
6624
6625 @node Structure of configure script, Configure API, Generating build files, Generating build files
6626 @subsection Structure of configure script and build files
6627 @c NODE configureスクリプトの構成とビルドファイル
6628
6629 @c EN
6630 A @file{configure} script tests
6631 running system's properties to determine values of
6632 substitution parameters, then read one or more template build files,
6633 and write out one output build file for each, replacing
6634 substitution parameters for the assigned values.
6635 @c JP
6636 @file{configure}スクリプトは、それを実行しているシステムの特性を調べて
6637 置換パラメータの値を決定し、ビルドファイルのテンプレート中の置換パラメータを
6638 値に書き換えてビルドファイルを生成します。
6639 @c COMMON
6640
6641 @c EN
6642 By convention, a template file has a suffix @code{.in}, and
6643 the corresponding output file is named without the suffix.
6644 For example, @code{Makefile.in} is a template that generates
6645 @code{Makefile}.
6646 @c JP
6647 通常、テンプレートファイルにはサフィックス@code{.in}がつけられ、
6648 対応する出力ファイルはそのサフィックスが除かれたものになります。
6649 例えば@code{Makefile.in}は@code{Makefile}を生成するテンプレートです。
6650 @c COMMON
6651
6652 @c EN
6653 Templates may contain substitution parameters, noted @code{@@PARAMETER_NAME@@}.
6654 This is a fragment of a typical Makefile template:
6655 @c JP
6656 テンプレートファイル中には@code{@@PARAMETER_NAME@@}という形式の
6657 置換パラメータを含めることができます。以下は典型的なMakefileのテンプレートです。
6658 @c COMMON
6659
6660 @example
6661 GAUCHE_PACKAGE = "@@GAUCHE_PACKAGE@@"
6662 SOEXT = @@SOEXT@@
6663 LOCAL_PATHS = "@@LOCAL_PATHS@@"
6664
6665 foo.$(SOEXT): $(foo_SRCS)
6666 $(GAUCHE_PACKAGE) compile \
6667 --local=$(LOCAL_PATHS) --verbose foo $(foo_SRCS)
6668 @end example
6669
6670 @c EN
6671 When processed by @code{configure}, @code{@@GAUCHE_PACKAGE@@},
6672 @code{@@SOEXT@@} and @code{@@LOCAL_PATHS@@} are replaced
6673 with appropriate values. If you know autoconf, you are already
6674 familiar with this.
6675 @c JP
6676 @code{configure}がこのテンプレートを処理する際に、@code{@@GAUCHE_PACKAGE@@}、
6677 @code{@@SOEXT@@}、@code{@@LOCAL_PATHS@@}はそれぞれ適切な値に
6678 置換されます。autoconfを知っている読者には馴染み深い動作でしょう。
6679 @c COMMON
6680
6681 @c EN
6682 The Gauche configure script is structurally similar to autoconf's
6683 @code{configure.in}, but you can use full power of Scheme.
6684 The following is the minimal configure script:
6685 @c JP
6686 Gaucheのconfigureスクリプトはautoconfの@code{configure.in}と
6687 似たような構造をとりますが、フルセットのSchemeの力を使うことができます。
6688 次は最小のconfigureスクリプトです:
6689 @c COMMON
6690
6691 @example
6692 #!/usr/bin/env gosh
6693 (use gauche.configure)
6694 (cf-init-gauche-extension)
6695 (cf-output-default)
6696 @end example
6697
6698 @c EN
6699 This script does several common tasks.
6700 @c JP
6701 このスクリプトはいくつかの共通タスクを行います。
6702 @c EN
6703 The @code{cf-init-gauche-extension} does the following:
6704 @c JP
6705 @code{cf-init-gauche-extension}の仕事は以下のとおりです。
6706 @c COMMON
6707
6708 @itemize @bullet
6709 @item
6710 @c EN
6711 First, it handles command-line arguments given to @file{configure}.
6712 In the default settings, it recognizes standard configure
6713 arguments such as @code{--prefix}, and
6714 @code{--with-local=PATH:PATH:...}
6715 which adds @code{PATH/include}s and @code{PATH/lib}s to
6716 the header and library search paths.
6717 You can handle more arguments by adding
6718 @code{cf-arg-with} and @code{cf-arg-enable} before
6719 @code{cf-init-gauche-extension}.
6720 @c JP
6721 まず、@file{configure}スクリプトに渡されたコマンドライン引数が処理されます。
6722 デフォルトの設定では、@code{--prefix}のようなconfigure標準の引数および、
6723 @code{--with-local=PATH:PATH:...}が認識されます。後者は
6724 @code{PATH/include}と@code{PATH/lib}をそれぞれヘッダとライブラリサーチパスに
6725 追加するものです。@code{cf-arg-with}や@code{cf-arg-enable}を
6726 @code{cf-init-gauche-extension}に使うことで、処理する引数を追加できます。
6727 @c COMMON
6728 @item
6729 @c EN
6730 Then it reads @code{package.scm}. Package name and version are taken
6731 from it. Dependencies are also checked.
6732 @c JP
6733 次に@code{package.scm}が読み込まれます。
6734 パッケージの名前とバージョンはそこから取られます。
6735 依存関係のチェックも行われます。
6736 @c COMMON
6737 @item
6738 @c EN
6739 It sets up global environment to run other configure checks.
6740 @c JP
6741 configureのチェックのためのグローバルな環境が準備されます。
6742 @c COMMON
6743 @item
6744 @c EN
6745 It sets up default values for standard substitution parameters such as
6746 @code{@@prefix@@}.
6747 @c JP
6748 @code{@@prefix@@}などの標準の置換パラメータのデフォルト値が設定されます。
6749 @c COMMON
6750 @end itemize
6751
6752 @c EN
6753 And @code{cf-output-default} does the following:
6754 @c JP
6755 @code{cf-output-default}は次の処理を行います。
6756 @c COMMON
6757
6758 @itemize
6759 @item
6760 @c EN
6761 Generate gpd (Gauche package description) file.
6762 @c JP
6763 gpd (Gauche package description) ファイルを生成します。
6764 @c COMMON
6765 @item
6766 @c EN
6767 Writes package version to @code{VERSION} file.
6768 @c JP
6769 パッケージのバージョンを@code{VERSION}ファイルに書き出します。
6770 @c COMMON
6771 @item
6772 @c EN
6773 Scan @code{Makefile.in}'s in the source directory and its subdirectories,
6774 and process them
6775 to generate @code{Makefile}s.
6776 @c JP
6777 ソースディレクトリ以下にある@code{Makefile.in}を処理して@code{Makefile}を書き出します。
6778 @c COMMON
6779 @c EN
6780 If config header files (typically @code{config.h}) are specified by
6781 @code{cf-config-headers}, process input files
6782 (e.g. @code{config.h.in}) to generate the header files.
6783 @c JP
6784 もしconfigヘッダファイル(通常@code{config.h})が@code{cf-config-headers}により
6785 指定されていたなら、入力(通常@code{config.h.in})を処理してヘッダファイルを
6786 生成します。
6787 @c COMMON
6788 @end itemize
6789
6790 @c EN
6791 In general, a @code{configure} script consists of the following parts:
6792 @c JP
6793 一般的に、@code{configure}スクリプトは以下のようなパーツから構成されます:
6794 @c COMMON
6795
6796 @enumerate
6797 @item
6798 @c EN
6799 Extra argument declarations (optional): Declare @code{--with-PACKAGE}
6800 and/or @code{--enable-FEATURE} options you want to handle, by
6801 @code{cf-with-arg} and @code{cf-enable-arg}, respectively.
6802 @c JP
6803 追加の引数の宣言(省略可): @code{--with-PACKAGE}や@code{--enable-FEATURE}で
6804 処理すべきオプションを、それぞれ@code{cf-with-arg}と@code{cf-enable-arg}で
6805 宣言します。
6806 @c COMMON
6807 @item
6808 @c EN
6809 Initialization. Call to @code{cf-init} or @code{cf-init-gauche-extension}
6810 sets up global context and
6811 parses command-line arguments passed to @code{configure}.
6812 It also process package metainformation in @file{package.scm}, if it exists.
6813 @c JP
6814 初期化。@code{cf-init}か@code{cf-init-gauche-extension}を呼ぶと、
6815 グローバルなコンテキストが設定され、
6816 @code{configure}に与えられた引数がパーズされます。また、
6817 @file{package.scm}が存在していれば、そこからパッケージメタ情報が読み込まれます。
6818 @c COMMON
6819 @item
6820 @c EN
6821 Tests and other substitution parameter settings (optional): Check system
6822 characteristics and sets up substitution parameters and/or
6823 C preprocessor definitions.
6824 @c JP
6825 テストと置換パラメータの設定 (省略可): システムの特性を調べ、
6826 置換すべきパラメータやCプリプロセッサ定義の値を設定します。
6827 @c COMMON
6828 @item
6829 @c EN
6830 Output generation. Call @code{cf-output} or @code{cf-output-default}
6831 to process template files.
6832 @c JP
6833 出力の生成。@code{cf-output}か@code{cf-output-default}を呼び出し、
6834 テンプレートファイルを処理します。
6835 @c COMMON
6836 @end enumerate
6837
6838 @c EN
6839 Most @code{cf-*} API corresponds to autoconf's @code{AC_*} or
6840 @code{AS_*} macros. We need argument declarations
6841 before @code{cf-init} so that it can generate help message
6842 including custom arguments in one pass.
6843 @c JP
6844 多くの@code{cf-*} APIは、autoconfの@code{AC_*}もしくは@code{AS_*}マクロに
6845 対応しています。引数の宣言が@code{cf-init}より前になされなければならないのは、
6846 1パスで@code{cf-init}がカスタム引数の説明を含んだヘルプメッセージを
6847 生成する必要があるからです。
6848 @c COMMON
6849
6850 @node Configure API, , Structure of configure script, Generating build files
6851 @subsection Configure API
6852
6853 @c EN
6854 @subsubheading Initialization
6855 @c JP
6856 @subsubheading 初期化
6857 @c COMMON
6858
6859 @defun cf-init-gauche-extension
6860 @c MOD gauche.configure
6861 @c EN
6862 This is a convenience API that packages several boilerplate @code{cf-*}
6863 function calls in one call. This must be called exactly once in a
6864 configure script.
6865 @c JP
6866 これはいくつかの定形の@code{cf-*}呼び出しをひとつにまとめた便利関数です。
6867 configureスクリプト中で1回だけ呼び出される必要があります。
6868 @c COMMON
6869
6870 @c EN
6871 Specifically, it calls @code{cf-arg-with} to process @code{--with-local},
6872 then calls @code{cf-init} with no arguments to initialize,
6873 then sets the following substitution parameters:
6874 @c JP
6875 この関数はまず@code{cf-arg-with}関数で@code{--with-local}コマンドライン引数の
6876 処理を登録し、次に@code{cf-init}を引数なしで呼んで初期化し、
6877 さらに以下の置換パラメータをセットします:
6878 @c COMMON
6879 @table @code
6880 @item GOSH
6881 @c EN
6882 Path to @code{gosh}.
6883 @c JP
6884 @code{gosh}へのパス
6885 @c COMMON
6886 @item GAUCHE_CONFIG
6887 @c EN
6888 Path to @code{gauche-config}.
6889 @c JP
6890 @code{gauche-config}へのパス
6891 @c COMMON
6892 @item GAUCHE_PACKAGE
6893 @c EN
6894 Path to @code{gauche-package}.
6895 @c JP
6896 @code{gauche-package}へのパス
6897 @c COMMON
6898 @item GAUCHE_INSTALL
6899 @c EN
6900 Path to @code{gauche-install}.
6901 @c JP
6902 @code{gauche-install}へのパス
6903 @c COMMON
6904 @item GAUCHE_CESCONV
6905 @c EN
6906 Path to @code{gauche-cesconv}.
6907 @c JP
6908 @code{gauche-cesconv}へのパス
6909 @c COMMON
6910 @item GAUCHE_PKGINCDIR
6911 @c EN
6912 Result of @code{gauche-config --pkgincdir}
6913 @c JP
6914 @code{gauche-config --pkgincdir}の結果
6915 @c COMMON
6916 @item GAUCHE_PKGLIBDIR
6917 @c EN
6918 Result of @code{gauche-config --pkglibdir}
6919 @c JP
6920 @code{gauche-config --pkglibdir}の結果
6921 @c COMMON
6922 @item GAUCHE_PKGARCHDIR
6923 @c EN
6924 Result of @code{gauche-config --pkgarchdir}
6925 @c JP
6926 @code{gauche-config --pkgarchdir}の結果
6927 @c COMMON
6928 @end table
6929
6930 @c EN
6931 The @code{--with-local} command-line argument should take a parameter, which is
6932 a colon-separated list of paths. It becomes a value of substitution parameter
6933 @code{LOCAL_PATHS}. The default @code{Makefile.in} template passes
6934 its value to @code{gauche-package} via the @code{--local} argument.
6935 When the C extension is compiled and linked, the
6936 @code{include} and @code{lib} subdirectories of the given paths are
6937 searched for headers and libraries, respectively.
6938 For example, if the extension requires a library foo and you install
6939 it under @code{/opt/foo} (that is, headers in @code{/opt/foo/include}
6940 and library objects in @code{/opt/foo/lib}), then you can pass
6941 @code{--with-local=/opt/foo} to configure the extension.
6942 @c JP
6943 @code{--with-local}コマンドライン引数はコロン区切りのパス名をパラメータとして
6944 取ります。その値は置換パラメータ@code{LOCAL_PATHS}にセットされます。
6945 デフォルトの@code{Makefile.in}テンプレートを使っていれば、その値は
6946 @code{gauche-package}の@code{--local}引数に渡され、
6947 C拡張コードがコンパイル・リンクされる際のヘッダファイル、ライブラリオブジェクトが
6948 それぞれ指定されたパス以下の@code{include}、@code{lib}サブディレクトリから探されます。
6949 例えば拡張モジュールがfooライブラリに依存していて、あなたがそれを
6950 @code{/opt/foo}以下にインストールしていたとしましょう(つまり、
6951 ヘッダファイルが@code{/opt/foo/include}に、ライブラリオブジェクトが
6952 @code{/opt/foo/lib}にあります)。その場合、
6953 拡張モジュールをconfigureする際に@code{--with-local=/opt/foo}を渡せばうまくいきます。
6954 @c COMMON
6955
6956 @c EN
6957 If you don't like these default behavior, you can call individual
6958 @code{cf-*} functions instead. See @code{cf-init} below.
6959 @c JP
6960 デフォルトで行われるこれら余分な動作が邪魔な場合は、
6961 この関数を使わずに個々の@code{cf-*}関数を呼び出すこともできます。
6962 下の@code{cf-init}も参照してください。
6963 @c COMMON
6964 @end defun
6965
6966
6967 @defun cf-init :optional package-name package-version maintainer-email homepage-url
6968 @c MOD gauche.configure
6969 @c EN
6970 Initialize the configure system. Corresponds to autoconf's @code{AC_INIT}.
6971 This must be called once in the
6972 configure script, before any feature-test procedures.
6973 (If you call @code{cf-init-gauche-extension}, @code{cf-init} is called
6974 from it.)
6975 @c JP
6976 configureシステムを初期化します。autoconfの@code{AC_INIT}に対応します。
6977 これはconfigureスクリプト中で、
6978 全ての機能テスト手続きに先立って必ず1回呼ばれなければなりません。
6979 (@code{cf-init-gauche-extension}を呼んだ場合、その中から@code{cf-init}が
6980 呼ばれています。)
6981 @c COMMON
6982
6983 @c EN
6984 First, it checks if a file named @file{package.scm} is
6985 in the same directory as the configure script,
6986 and reads the Gauche package description from it. The package description
6987 contains package name, version, dependencies, etc.
6988 @xref{Package metainformation}, for the details.
6989 @c JP
6990 まずこの手続きは、configureスクリプトと同じディレクトリに@file{package.scm}という
6991 ファイルがあるかどうか調べ、あればGaucheパッケージ記述をそこから読み込みます。
6992 パッケージ記述には、パッケージ名、バージョン、依存関係などがかかれています。
6993 詳しくは@ref{Package metainformation}を参照してください。
6994 @c COMMON
6995
6996 @c EN
6997 It then parses the command-line arguments, sets up the configure
6998 environment, and (if @file{package.scm} defines dependencies) check
6999 if the system has required packages.
7000 @c JP
7001 次にこの手続きはコマンドライン引数をパーズし、configureの環境を設定し、
7002 (もし@file{package.scm}が依存関係を定義していれば)必要なパッケージが
7003 既にあるかどうかもチェックします。
7004 @c COMMON
7005
7006 @c EN
7007 The optional arguments are only supported for the backward compatibility
7008 if you don't have @file{package.scm}. You need at least
7009 to provide @var{package-name} and @var{package-version} to tell
7010 what package you're configuring. They are used as the value
7011 of substitution parameter @code{PACKAGE_NAME} and @code{PACKAGE_VERSION}.
7012 The other optional arguments, @var{maintainer-email} and
7013 @var{homepage-url}, are used to initialize @code{PACKAGE_BUGREPORT} and
7014 @code{PACKAGE_URL}. These arguments are compatible to autoconf's
7015 @code{AC_INIT} macro.
7016 @c JP
7017 省略可能引数は以前のバージョンとの互換性のためのものです。@file{package.scm}が
7018 無い場合、少なくとも@var{package-name}と@var{package-version}を与える
7019 必要があります。これらは置換パラメータの@code{PACKAGE_NAME}と@code{PACKAGE_VERSION}
7020 を置換するのに使われます。他の引数@var{maintainer-email}と
7021 @var{homepage-url}は@code{PACKAGE_BUGREPORT}と@code{PACKAGE_URL}に
7022 使われます。これらの引数はautoconfの@code{AC_INIT}マクロと互換です。
7023 @c COMMON
7024
7025 @c EN
7026 We recommend to always use @file{package.scm} and omit all the optional
7027 arguments, because it allows you to maintain the package metainformation
7028 in one place. When @file{package.scm} is read, @code{PACKAGE_BUGREPORT}
7029 is initialized by the first entry of @code{maintainers} slot of
7030 the package description, and @code{PACKAGE_URL} is initialized
7031 by its @code{homepage} slot.
7032 @xref{Package metainformation}, for description of slots of the package
7033 description.
7034 @c JP
7035 推奨される呼び出し方法は、@file{package.scm}を用意し、@code{cf-init}には
7036 引数を渡さないことです。そうすれば、パッケージのメタ情報を一ヶ所(@file{package.scm})で
7037 管理できます。@file{package.scm}が読まれた場合、@code{PACKAGE_BUGREPORT}は
7038 パッケージ記述の@code{maintainers}の最初のエントリで、また
7039 @code{PACKAGE_URL}はパッケージ記述の@code{homepage}で初期化されます。
7040 パッケージ記述についての詳細は@ref{Package metainformation}を見てください。
7041 @c COMMON
7042
7043 @c EN
7044 Note that if there's @file{package.scm} @emph{and} you provide
7045 the optional arguments, they must match, or @code{cf-init} raises an
7046 error. It is to catch errors during transition in which you forgot
7047 to update either one.
7048 @c JP
7049 もし@file{package.scm}が存在し、かつ@code{cf-init}に引数が与えられた場合、
7050 それぞれ対応する情報は一致していなければなりません。一致していなかった場合、
7051 @code{cf-init}はエラーを投げます。これは、@file{package.scm}への移行の途中で、
7052 どちらかの情報をアップデートし忘れたケースを捕まえるためです。
7053 @c COMMON
7054
7055 @c EN
7056 This procedure sets up a bunch of standard substitution parameters
7057 such as @code{prefix}, @code{bindir} or @code{srcdir}. To see what
7058 substitution parameters are set, you can call @code{cf-show-substs}
7059 after @code{cf-init}.
7060 @c JP
7061 この手続きはまた、@code{prefix}、@code{bindir}あるいは@code{srcdir}といった
7062 標準の置換パラメータをたくさん設定します。
7063 どの置換パラメータが設定されるか見たければ、@code{cf-init}の後に
7064 @code{cf-show-substs}を呼んでみてください。
7065 @c COMMON
7066 @end defun
7067
7068 @c EN
7069 @subsubheading Command-line arguments
7070 @c JP
7071 @subsubheading コマンドライン引数
7072 @c COMMON
7073
7074 @defun cf-arg-enable feature help-string :optional proc-if-given proc-if-not-given
7075 @defunx cf-arg-with package help-string :optional proc-if-given proc-if-not-given
7076 @c MOD gauche.configure
7077 @c EN
7078 Make the configure script accept feature selection argument and
7079 package selection argument, respectively. The corresponding
7080 autoconf macros are @code{AC_ARG_ENABLE} and @code{AC_ARG_WITH}.
7081 @c JP
7082 それぞれ、configureスクリプトが、機能選択引数およびパッケージ選択引数を認識するようにします。
7083 autoconfでの対応するマクロは@code{AC_ARG_ENABLE}と@code{AC_ARG_WITH}です。
7084 @c COMMON
7085
7086 @c EN
7087 Those procedures must be called before calling @code{cf-init}
7088 or @code{cf-init-gauche-extension}.
7089 @c JP
7090 これらの手続きは@code{cf-init}もしくは@code{cf-init-gauhce-extension}の前に
7091 呼ばれなければなりません。
7092 @c COMMON
7093
7094 @c EN
7095 The @var{feature} and @var{package} arguments must be a symbol.
7096 @c JP
7097 @var{feature}と@var{package}引数はシンボルでなければなりません。
7098 @c COMMON
7099
7100 @c EN
7101 A feature selection argument is in a form of either
7102 @code{--enable-@var{feature}=@var{val}},
7103 @code{--enable-@var{feature}}, or @code{--disable-@var{feature}}.
7104 The latter two are equivalent to @code{--enable-@var{feature}=yes}
7105 and @code{--enable-@var{feature}=no}, respectively.
7106 It is to select an optional feature provided with the package itself.
7107 @c JP
7108 機能選択引数は、@code{--enable-@var{feature}=@var{val}}、
7109 @code{--enable-@var{feature}}、もしくは@code{--disable-@var{feature}}という
7110 引数です。後のふたつはそれぞれ
7111 @code{--enable-@var{feature}=yes}および
7112 @code{--enable-@var{feature}=no}と同じです。
7113 このconfigure引数は、パッケージ自体が提供しているオプショナルな機能を選択するのに使います。
7114 @c COMMON
7115
7116 @c EN
7117 A package selection argument is in a form of either
7118 @code{--with-@var{package}=@var{val}},
7119 @code{--with-@var{package}} and @code{--without-@var{package}}.
7120 The latter two are equivalent to @code{--with-@var{package}=yes}
7121 and @code{--with-@var{package}=no}, respectively.
7122 It is to select an external software package to be used with
7123 this package.
7124 @c JP
7125 パッケージ選択引数は、@code{--with-@var{package}=@var{val}}、
7126 @code{--with-@var{package}}、もしくは@code{--without--@var{package}}という
7127 引数です。後のふたつはそれぞれ
7128 @code{--with-@var{package}=yes}および
7129 @code{--with-@var{package}=no}と同じです。
7130 このconfigure引数は、このパッケージが使う外部のパッケージを選択するのに使います。
7131 @c COMMON
7132
7133 @c EN
7134 When @code{cf-init} finds these arguments during command-line processing,
7135 it adds entry of @var{feature}
7136 or @var{package} to the global tables, with the value @var{val}.
7137 Those global tables can be accessed with @code{cf-feature-ref} and
7138 @code{cf-package-ref} procedures below.
7139 @c JP
7140 @code{cf-init}がコマンドライン引数処理中にこれらの形の引数を見つけた場合、
7141 @var{feature}または@var{package}と、与えられた@var{val}をグローバルなテーブルに
7142 保存します。このグローバルテーブルは下の@code{cf-feature-ref}および
7143 @code{cf-package-ref}でアクセスできます。
7144 @c COMMON
7145
7146 @c EN
7147 The @var{help-string} argument must be a string and
7148 is used as is to list the help
7149 of the option in part of usage message displayed by
7150 @code{configure --help}. You can use @code{cf-help-string} below
7151 to create a help string that fits nicely in the usage message.
7152 @c JP
7153 @var{help-string}は文字列で、@code{configure --help}で表示される
7154 ヘルプメッセージに使われます。
7155 下の@code{cf-help-string}を使ってヘルプ文字列を整形することができます。
7156 @c COMMON
7157
7158 @c EN
7159 If optional @var{proc-if-given} argument is given, it must be a procedure
7160 that accepts one argument, @var{val}. It is called when @code{cf-init}
7161 finds one of those arguments.
7162 @c JP
7163 省略可能引数@var{proc-if-given}は、与えられたら引数をひとつ取る手続きでなければなりません。
7164 @var{cf-init}が対応するコマンドライン引数を見つけた時に、コマンドラインで与えられた
7165 @var{val}を引数としてこの手続きが呼ばれます。
7166 @c COMMON
7167
7168 @c EN
7169 If optional @var{proc-if-not-given} argument is given, it must be a procedure
7170 that accepts no arguments. It is called when @code{cf-init}
7171 doesn't find any of those arguments.
7172 @c JP
7173 省略可能引数@var{proc-if-not-given}は、与えられたら引数を取らない手続きでなければなりません。
7174 @var{cf-init}が対応するコマンドライン引数を見つけられなかった時に、
7175 この手続きが呼ばれます。
7176 @c COMMON
7177
7178 @c EN
7179 The following is to accept @code{--with-local=@var{PATH}:@var{PATH}:@dots{}}.
7180 (This @code{cf-arg-with} call is included in @code{cf-init-gauche-extension}).
7181 Note that the help string (the second argument) is generated by
7182 @code{cf-help-string} call. The command-line parameter followed by
7183 @code{--with-local} is passed as the argument of the procedure
7184 in the third argument:
7185 @c JP
7186 下は、@code{--with-local=@var{PATH}:@var{PATH}:@dots{}}という形式の
7187 コマンドライン引数を受け取る例です
7188 (この@code{cf-arg-with}呼び出しは@code{cf-init-gauche-extension}に含まれています)。
7189 ヘルプ文字列を生成するのに@code{cf-help-string}を使っているのに注目してください。
7190 また、コマンドライン引数で与えられたオプションの値は、
7191 3番めの引数の手続きへと渡されます。
7192 @c COMMON
7193
7194 @example
7195 (cf-arg-with 'local
7196 (cf-help-string
7197 "--with-local=PATH:PATH..."
7198 "For each PATH, add PATH/include to the include search
7199 paths and PATH/lib to the library search paths. Useful if you have some
7200 libraries installed in non-standard places. ")
7201 (^[with-local]
7202 (unless (member with-local '("yes" "no" ""))
7203 (cf-subst 'LOCAL_PATHS with-local)))
7204 (^[] (cf-subst 'LOCAL_PATHS "")))
7205 @end example
7206 @end defun
7207
7208 @defun cf-help-string item description
7209 @c MOD gauche.configure
7210 @c EN
7211 Return a string formatted suitable to show as an option's help message.
7212 The result can be passed to @var{help-string} argument of
7213 @code{cf-arg-enable} and @code{cf-arg-with}, to ensure that
7214 @code{configure --help} will produce a consistently formatted output.
7215 This corresponds to autoconf's @code{AS_HELP_STRING}.
7216
7217 Call it as follows, and it'll indent and fill the description nicely.
7218 @c JP
7219 コマンドライン引数のヘルプメッセージにふさわしい形式にフォーマットした文字列を
7220 返します。戻り値を@code{cf-arg-enable}や@code{cf-arg-with}の
7221 @var{help-string}引数に渡すことで、
7222 @code{configure --help}が統一的な出力を生成できます。
7223 autoconfの@code{AS_HELP_STRING}に相当します。
7224 @c COMMON
7225
7226 @example
7227 (cf-help-string "--option=ARG" "Give ARG as the value of option")
7228 @end example
7229 @end defun
7230
7231 @defun cf-feature-ref name
7232 @defunx cf-package-ref name
7233 @c MOD gauche.configure
7234 @c EN
7235 Lookup a symbol @var{name} from the global feature table and the
7236 global package table, respectively.
7237 These can be called after @code{cf-init}.
7238 @c JP
7239 グローバルな機能テーブルおよびパッケージテーブルに@var{name}で登録された値を
7240 返します。これらは@code{cf-init}の後で呼べます。
7241 @c COMMON
7242
7243 @c EN
7244 For example, if you've called @code{cf-arg-enable} with @code{foofeature},
7245 and the user has invoked the @code{configure} script with
7246 @code{--with-foofeature=full}, then @code{(cf-feature-ref 'foofeature)}
7247 returns @code{"full"}. If the user hasn't given the command-line
7248 argument, @code{#f} is returned.
7249 @c JP
7250 例えば、@code{cf-arg-enable}で@code{foofeature}という機能に関するコマンドライン
7251 引数を登録したとしましょう。ユーザが@code{configure}スクリプトに
7252 @code{--with-foofeature=full}オプションを与えて起動した場合、
7253 @code{(cf-feature-ref 'foofeature)}は@code{"full"}を返します。
7254 コマンドライン引数が与えられなかった場合は@code{#f}が返ります。
7255 @c COMMON
7256
7257 @c EN
7258 If you add or change the value of features or packages,
7259 you can use generalized @code{set!} as
7260 @code{(set! (cf-feature-ref 'NAME) VALUE)} etc.
7261 @c JP
7262 機能テーブルやパッケージテーブルに値を足したり変更したい場合は一般化@code{set!}を使って
7263 @code{(set! (cf-feature-ref 'NAME) VALUE)}と書くことができます。
7264 @c COMMON
7265 @end defun
7266
7267
7268 @c EN
7269 @subsubheading Messages
7270 @c JP
7271 @subsubheading メッセージ
7272 @c COMMON
7273
7274 @c EN
7275 The @code{cf-init} procedure opens the default log drain
7276 that goes to @code{config.log}, and you can use @code{log-format}
7277 to write to it (@xref{User-level logging}, for the details of logging).
7278 @c JP
7279 @code{cf-init}手続きは@code{config.log}にロギングするデフォルトログドレインを
7280 オープンするので、@code{log-format}を使って@code{config.log}にログを
7281 残すことができます (ロギングの詳細については@ref{User-level logging}参照)。
7282 @c COMMON
7283
7284 @c EN
7285 However, to have consistent message format conveniently, the following
7286 procedures are provided. They emits the message both to log files and
7287 the current output port (in slightly different formats so that the
7288 console messages align nicely visually.)
7289 @c JP
7290 しかし、一貫した形式でメッセージを扱うために、以下の手続きが提供されています。
7291 これらの手続きはログファイルと現在の出力ポートに(見やすいようにそれぞれ若干異なる
7292 形式で)メッセージを出力します。
7293 @c COMMON
7294
7295 @defun cf-msg-checking fmt arg @dots{}
7296 @c MOD gauche.configure
7297 @c EN
7298 Writes out ``checking XXX...'' message. The @var{fmt} and @var{arg} @dots{}
7299 arguments are passed to @code{format} to produce the ``XXX'' part
7300 (@pxref{Formatting output}).
7301 @c JP
7302 ``checking XXX...'' というメッセージを出力します。@var{fmt}と@var{arg} @dots{}
7303 引数は@code{format}に渡されて、``XXX''の部分を生成します
7304 (@ref{Formatting output}参照)。
7305 @c COMMON
7306
7307 @c EN
7308 For the current output port, this does not emit the trailing newline,
7309 expecting @code{cf-msg-result} will be called subsequently.
7310 @c JP
7311 現在の出力ポートに向けては、改行文字は出力されません。
7312 この後で@code{cf-msg-result}が呼ばれることを期待しているからです。
7313 @c COMMON
7314
7315 @c EN
7316 Here's an excerpt of the source that uses @code{cf-msg-checking}
7317 and @code{cf-msg-result}:
7318 @c JP
7319 以下は、@code{cf-msg-checking}と@code{cf-msg-result}を使っているソースからの
7320 抜粋です。
7321 @c COMMON
7322 @example
7323 (define (compiler-can-produce-executable?)
7324 (cf-msg-checking "whether the ~a compiler works" (~ (cf-lang)'name))
7325 (rlet1 result ($ run-compiler-with-content
7326 (cf-lang-link-m (cf-lang))
7327 (cf-lang-null-program-m (cf-lang)))
7328 (cf-msg-result (if result "yes" "no"))))
7329 @end example
7330
7331 @c EN
7332 This produces a console output like this:
7333 @c JP
7334 この例は、次のような出力を生成します:
7335 @c COMMON
7336 @example
7337 checking whether the C compiler works... yes
7338 @end example
7339 @c EN
7340 while the log file records more info:
7341 @c JP
7342 また、ログファイルに対しては次の情報が記録されます:
7343 @c COMMON
7344 @example
7345 checking: whether the C compiler works
7346 @c EN
7347 ... whatever logging message from run-compiler-with-content ...
7348 @c JP
7349 ... run-compiler-with-contentのログ出力 ...
7350 @c COMMON
7351 result: yes
7352 @end example
7353
7354 @c EN
7355 This corresponds to autoconf's @code{AC_MSG_CHECKING}.
7356 @c JP
7357 これはautoconfの@code{AC_MSG_CHECKING}に対応します。
7358 @c COMMON
7359 @end defun
7360
7361 @defun cf-msg-result fmt arg @dots{}
7362 @c MOD gauche.configure
7363 @c EN
7364 The @var{fmt} and @var{arg} @dots{} are passed to @code{format}, and
7365 the formatted message and newline is written out
7366 (@pxref{Formatting output}). Typically, the message is simply
7367 ``yes'' or ``no'', or the name (of a library, a header, etc.) that is found.
7368 For the log file, it records ``result: XXX'' where XXX is the
7369 formatted message. Supposed to be used with @code{cf-msg-checking}; see the
7370 example of @code{cf-msg-checking} above.
7371 This corresponds to autoconf's @code{AC_MSG_RESULT}.
7372 @c JP
7373 @var{fmt}と@var{arg} @dots{}が@code{format}に渡され、フォーマット結果が出力されます。
7374 通常、メッセージは単なる ``yes'' / ``no'' か、見つかった(ライブラリやヘッダの)名前です。
7375 ログファイルに対しては、XXXをフォーマットされたメッセージとして、
7376 ``result: XXX''という文字列が記録されます。
7377 @code{cf-msg-checking}と一緒に使うことを想定しています。
7378 上の@code{cf-msg-checking}の例を見てください。
7379 これはautoconfの@code{AC_MSG_RESULT}に対応します。
7380
7381 @c COMMON
7382 @end defun
7383
7384 @defun cf-msg-notice fmt arg @dots{}
7385 @c MOD gauche.configure
7386 @c EN
7387 Produces formatted message to both console and log. Newline is added.
7388 This corresponds to autoconf's @code{AC_MSG_NOTICE}.
7389 @c JP
7390 フォーマットされたメッセージをコンソールとログファイルの両方に出力します。
7391 最後に改行文字が追加されます。これはautoconfの@code{AC_MSG_NOTICE}に対応します。
7392 @c COMMON
7393 @end defun
7394
7395 @defun cf-msg-warn fmt arg @dots{}
7396 @defunx cf-msg-error fmt arg @dots{}
7397 @c MOD gauche.configure
7398 @c EN
7399 Produces ``Warning: XXX'' and
7400 ``Error: XXX'' messages, respectively.
7401 The @var{fmt} and @var{arg} @dots{} are passed to @code{format} to
7402 generate XXX part (@pxref{Formatting output}).
7403
7404 Additionally, @code{cf-msg-error} exits with exit code 1.
7405 @c JP
7406 それぞれ、``Warning: XXX'' および ``Error: XXX'' というメッセージを出力します。
7407 @var{fmt}と@var{arg} @dots{}は@code{format}に渡されて、
7408 XXXの部分の文字列を生成します (@ref{Formatting output}参照)。
7409
7410 さらに、@code{cf-msg-error}は終了コード1でプロセスを終了します。
7411 @c COMMON
7412
7413 @c EN
7414 These corresponds to
7415 autoconf's @code{AC_MSG_WARN} and @code{AC_MSG_ERROR}.
7416 NB: @code{AC_MSG_ERROR} can specify the exit code,
7417 but @code{cf-msg-error} uses fixed exit code (1) for now.
7418 @c JP
7419 これらは、autoconfの@code{AC_MSG_WARN}と@code{AC_MSG_ERROR}に相当します。
7420 註: @code{AC_MSG_ERROR}は終了コードが指定できますが、
7421 @code{cf-msg-error}は今の所1に固定です。
7422 @c COMMON
7423 @end defun
7424
7425 @defun cf-echo arg @dots{} [> file][>> file]
7426 @c MOD gauche.configure
7427 @c EN
7428 Convenience routine to replace shell's @code{echo} command.
7429
7430 If the argument list ends with @code{> @var{file}} or
7431 @code{>> @var{file}}, where @var{file} is a string file name,
7432 then this works just like shell's @code{echo}; that is,
7433 @var{arg}s except the last two are written to @var{file}, space
7434 separated, newline terminated. Using @code{>} supersedes
7435 @var{file}, while @code{>>} appends to it.
7436
7437 If the argument list doesn't end with those redirection message,
7438 it writes out the argument to both the current output port
7439 and the log file, space separated, newline terminated.
7440 For the log file, the message is prefixed with ``Message:''.
7441 @c JP
7442 シェルの@code{echo}コマンドを置き換える便利手続きです。
7443
7444 引数リストが@code{> @var{file}}もしくは@code{>> @var{file}}で終わっている場合
7445 (@var{file}はファイル名の文字列)、これはシェルの@code{echo}のように動作します。
7446 すなわち、その部分を除く@var{arg} @dots{}が空白文字を間に挟んで
7447 @var{file}に書き出されます。また最後に改行文字も書き出されます。
7448 @code{>}を使った場合は@var{file}は上書きされ、@code{>>}の場合は追記されます。
7449
7450 引数リストが上記リダイレクト指示で終わっていない場合は、
7451 現在の出力ポートとログファイル両方に、@var{arg} @dots{}を空白文字を間に挟んで出力します。
7452 また最後に改行文字も書き出されます。ログファイルに向けては、メッセージの前に
7453 ``Message:''が出力されます。
7454 @c COMMON
7455 @end defun
7456
7457 @c EN
7458 @subsubheading Parameters and definitions
7459 @c JP
7460 @subsubheading パラメータと定義
7461 @c COMMON
7462
7463 @c EN
7464 The configure script maintains two global tables, definition tables
7465 and parameter tables. Definition tables is used for C preprocessor
7466 definitions, and parameter tables are used for @code{@@PARAMETER@@}
7467 substitutions. (Do not confuse substitution parameters with
7468 Scheme's parameter objects (@pxref{Parameters})).
7469 @c JP
7470 configureスクリプトは、定義テーブルと置換パラメータテーブルという
7471 二つのグローバルなテーブルを持っています。
7472 定義テーブルはCプリプロセッサの定義に使われ、置換パラメータテーブルは
7473 @code{@@PARAMETER@@}の置換に使われます。
7474 (置換パラメータをSchemeのパラメータオブジェクト(@ref{Parameters}参照)と
7475 混同しないように!)。
7476 @c COMMON
7477
7478 @defun cf-define symbol :optional value
7479 @c MOD gauche.configure
7480 @c EN
7481 Registers C preprocessor definition of @var{symbol} with @var{value}.
7482 @var{Value} can be any Scheme objects, but it is emitted to a command
7483 line (in @code{-DSYMBOL=VALUE} form) or in @file{config.h}
7484 (in @code{#define SYMBOL VALUE} form) using @code{display}, so
7485 you want to avoid including funny characters. If @var{value} is
7486 omitted, @code{1} is assumed.
7487
7488 NB: To @code{#define} a string value, e.g. @code{#define FOO "foo"},
7489 you have to call as @code{(cf-define 'FOO "\"foo\"")}.
7490 @c JP
7491 @var{symbol}を@var{value}とするCプリプロセッサ定義を登録します。
7492 @var{value}には任意のSchemeオブジェクトを渡せますが、
7493 その@code{display}表記がそのままコンパイラのコマンドライン
7494 (@code{-DSYMBOL=VALUE}という形式)あるいは@file{config.h}内の定義
7495 (@code{#define SYMBOL VALUE}という形式)に使われるので、
7496 妙な文字を入れない方が無難でしょう。@var{value}が省略された場合は
7497 @code{1}が使われます。
7498
7499 註: 文字列を値とする定義、例えば @code{#define FOO "foo"} を生成するには、
7500 @code{(cf-define 'FOO "\"foo\"")} とする必要があります。
7501 @c COMMON
7502
7503 @c EN
7504 This corresponds to autoconf's @code{AC_DEFINE}.
7505 @c JP
7506 これはautoconfの@code{AC_DEFINE}に相当します。
7507 @c COMMON
7508 @end defun
7509
7510 @defun cf-defined? symbol
7511 @c MOD gauche.configure
7512 @c EN
7513 Returns @code{#t} iff @var{symbol} is @code{cf-define}d.
7514 @c JP
7515 @var{symbol}が@code{cf-define}されていれば@code{#t}を、
7516 そうでなければ@code{#f}を返します。
7517 @c COMMON
7518 @end defun
7519
7520 @defun cf-subst symbol :optional value
7521 @c MOD gauche.configure
7522 @c EN
7523 Registers a substitution parameter @var{symbol} with @var{value}.
7524 While processing output files, @var{@@symbol@@} in the template
7525 is substituted with @var{value}.
7526
7527 @var{Value} is usually a string, but can be any Scheme objects;
7528 its @code{display} representation.
7529
7530 If @var{value} is @code{#f} or omitted, it works a bit differently.
7531 If @var{symbol} hasn't been registered as a substitution parameter,
7532 it is registered with an empty string as its value. If @var{symbol} has
7533 already been registered, however, its value is left intact.
7534 @c JP
7535 置換パラメータ@var{symbol}を値@var{value}で定義します。
7536 出力ファイルを生成する時に、テンプレートの@var{@@symbol@@}が
7537 @var{value}に置換されます。
7538
7539 @var{value}は通常文字列ですが、任意のSchemeオブジェクトで構いません。
7540 @code{display}での印字表現が使われます。
7541
7542 @var{value}が省略されるか@code{#f}の場合はちょっと違った動作になります。
7543 @var{symbol}がまだ置換パラメータとして登録されていない場合は、
7544 空文字列を値として置換パラメータを登録します。既に登録されていた場合は値をそのまま残します。
7545 @c COMMON
7546
7547 @c EN
7548 This corresponds to autoconf's @code{AC_SUBST}, but we require
7549 the value (while autoconf can refer to the shell variable value as default).
7550 @c JP
7551 これはautoconfの@code{AC_SUBST}に相当します。ただ、autoconfeでは値を明示しなくても
7552 同名のシェル変数の値が使われますが、Gaucheでは値を陽に与えなければなりません。
7553 @c COMMON
7554 @end defun
7555
7556 @defun cf-subst-prepend symbol value :optional delim default
7557 @defunx cf-subst-append symbol value :optional delim default
7558 @c MOD gauche.configure
7559 @c EN
7560 Prepend or append @var{value} to the substitution parameter @var{symbol},
7561 using delimiter @var{delim}. If the substitution parameter isn't
7562 defined, @var{value} becomes the sole value of the parameter,
7563 except when @var{default} is given and not an empty string.
7564 If @var{delim} is omitted, single whitespace is used.
7565 @c JP
7566 置換パラメータ@var{symbol}の値の前もしくは後に、
7567 @var{delim}を挟んで@var{value}を付け足します。
7568 @var{symbol}がまだ定義されていなかった場合な、
7569 @var{default}が与えられ空文字列でなければあたかもそれが既に設定されていた値であるかのように
7570 動作し、そうでなければ@var{value}が最初の値となります(この場合、@var{delim}は使われません)。
7571 @var{delim}が省略された場合は空白1文字の文字列が使われます。
7572 @c COMMON
7573
7574 @c EN
7575 A substitution parameter is often used to accrue command line arguments
7576 (e.g. @code{-I include-dir} for a compiler), and these procedures
7577 comes handy.
7578 @c JP
7579 置換パラメータにはよくコマンドライン引数をつけ足してゆくので
7580 (例:コンパイラの@code{-I include-dir})、これらの手続きが便利に使えるでしょう。
7581 フラグ
7582 @c COMMON
7583 @end defun
7584
7585 @defspec with-cf-subst (binding @dots{}) body @dots{}
7586 @c MOD gauche.configure
7587 @c EN
7588 Temporarily replace substitution parameters with new values. This
7589 could be useful for example to run some compilation checks with
7590 different parameters.
7591 @c JP
7592 一時的に置換パラメータを新たな値に置き換えて@var{body} @dots{}を実行します。
7593 コンパイルチェックを違うパラメータで実行してみたい時に便利です。
7594 @c COMMON
7595
7596 @c EN
7597 @var{Binding} may be one of the following forms:
7598
7599 @table @code
7600 @item (@var{var} @var{value})
7601 Temporarily substitue parameter @var{var}'s value to @var{value}.
7602 @item (@var{var} + @var{value})
7603 Temporarily append @var{value} to the parameter @var{var}, using
7604 a space as a delimiter. See @code{cf-subst-append} above.
7605 @item (@var{var} @var{value} +)
7606 Temporarily prepend @var{value} to the parameter @var{var}, using
7607 a space as a delimiter. See @code{cf-subst-prepend} above.
7608 @end table
7609 @c JP
7610 @var{binding}は以下のいずれかの形式です。
7611
7612 @table @code
7613 @item (@var{var} @var{value})
7614 一時的に置換パラメータ@var{var}の値を@var{value}で置き換えます。
7615 @item (@var{var} + @var{value})
7616 一時的に置換パラメータ@var{var}の値の後に空白を挟んで@var{value}を追加します。
7617 追加には上記の@code{cf-subst-append}が使われます。
7618 @item (@var{var} @var{value} +)
7619 一時的に置換パラメータ@var{var}の値の前に空白を挟んで@var{value}を前置します。
7620 追加には上記の@code{cf-subst-prepend}が使われます。
7621 @end table
7622 @c COMMON
7623
7624 @example
7625 (with-cf-subst ((LIBS "-L<path> -l<lib>"))
7626 (cf-try-compile-and-link @dots{}))
7627 @end example
7628
7629 @c EN
7630 In autoconf, this pattern is realized by saving the current value
7631 of the substituion parameter, modify it, run checks, and restore the old value.
7632 It is tedious.
7633 @c JP
7634 autoconfではこのパターンは、現在の置換パラメータを保存し、
7635 新たなパラメータに変更してチェックを走らせた後で置換パラメータを元に戻しますが、
7636 とても面倒です。
7637 @c COMMON
7638 @end defspec
7639
7640 @defun cf-have-subst? symbol
7641 @c MOD gauche.configure
7642 @c EN
7643 Returns true iff @var{symbol} is registered as a substitution parameter by
7644 @code{cf-subst}.
7645 @c JP
7646 @var{symbol}が@code{cf-subst}で置換パラメータとして登録されていれば@code{#t}を、
7647 そうでなければ@code{#f}を返します。
7648 @c COMMON
7649 @end defun
7650
7651 @defun cf-arg-var symbol
7652 @c MOD gauche.configure
7653 @c EN
7654 Lookup the environment variable with the name @var{symbol} and if it is found,
7655 use its value as the substitution value. If it is not found, and
7656 if @var{symbol} hasn't been already registered as a substitution parameter,
7657 register it with an empty string as its value; otherwise, do nothing.
7658
7659 For example,
7660 if you call @code{(cf-arg-var 'MYCFLAGS)}, then the user
7661 can provide the value of @code{@@MYCFLAGS@@} as
7662 @code{MYCFLAGS=-g ./configure}.
7663
7664 This corresponds to autoconf's @code{AC_ARG_VAR}, but we lack the ability
7665 of setting the help string. That's because @code{cf-arg-var} must
7666 be run after @code{cf-init}, but the help message is constructed
7667 within @code{cf-init}.
7668 @c JP
7669 名前@var{symbol}を持つ環境変数を探し、見つかればそれを置換パラメータ@var{symbol}の
7670 値とします。環境変数が見つからない場合、まだ@var{symbol}が置換パラメータとして登録されて
7671 いなければ、空文字列を値として登録します。そうでなければ何もしません。
7672
7673 例えば、@code{(cf-arg-var 'MYCFLAGS)}を呼び出しておくと、
7674 ユーザは@code{@@MYCFLAGS@@}の置換を@code{MYCFLAGS=-g ./configure}のようにして
7675 与えることができます。
7676
7677 これはautoconfの@code{AC_ARG_VAR}に相当します。
7678 ただし、autoconfと違ってヘルプ文字列を与えることはできません。
7679 @code{cf-arg-var}は@code{cf-init}より後に呼ばれねばならず、
7680 しかしヘルプ文字列は@code{cf-init}内で構築される必要があるからです。
7681 @c COMMON
7682 @end defun
7683
7684 @defun cf-ref symbol :optional default
7685 @c MOD gauche.configure
7686 @c EN
7687 This looks up the value of the substitution parameter @var{symbol}.
7688 If there's no such substitution parameter registered,
7689 it returns @var{default} when it's provided, otherwise
7690 throws an error.
7691 @c JP
7692 置換パラメータ@var{symbol}の値を返します。該当する置換パラメータが登録されていない場合、
7693 @var{default}が与えられていればそれを返し、そうでなければエラーを投げます。
7694 @c COMMON
7695 @end defun
7696
7697 @defun cf$ symbol
7698 @c MOD gauche.configure
7699 @c EN
7700 Looks up the value of the substitution parameter @var{cf-ref},
7701 but it returns empty string if it's unregistered. Useful
7702 to use within string interpolation, e.g. @code{#"gosh ~(cf$'GOSHFLAGS)"}.
7703 @c JP
7704 @code{cf-ref}と同じように置換パラメータ@var{symbol}の値を返しますが、
7705 該当する置換パラメータが登録されていない場合は空文字列を返します。
7706 文字列補間の中で@code{#"gosh ~(cf$'GOSHFLAGS)"}のように使えるので便利です。
7707 @c COMMON
7708 @end defun
7709
7710 @c EN
7711 @subsubheading Predefined tests
7712 @c JP
7713 @subsubheading 定義済みテスト
7714 @c COMMON
7715
7716 @defun cf-check-prog sym prog-or-progs :key value default paths filter
7717 @defunx cf-path-prog sym prog-or-progs :key value default paths filter
7718 @c MOD gauche.configure
7719 Check if a named executable program exists in search paths, and if it
7720 exists, sets the substitution parameter @var{sym} to the name
7721 of the found program. The name to search is specified by @var{prog-or-progs},
7722 which is either a string or a list of strings.
7723
7724 The difference of @code{cf-check-prog} and @code{cf-path-prog} is that
7725 @code{cf-check-prog} uses the basename of the found program, while
7726 @code{cf-path-prog} uses its full path. These corresponds to
7727 autoconf's @code{AC_CHECK_PROG}, @code{AC_CHECK_PROGS},
7728 @code{AC_PATH_PROG} and @code{AC_PATH_PROGS}.
7729
7730 For example, the following
7731 feature test searches either one of @code{cc}, @code{gcc}, @code{tcc}
7732 or @code{pcc} in @code{PATH} and sets the substitution parameter @code{MY_CC}
7733 to the name of the found one.
7734
7735 @example
7736 (cf-check-prog 'MY_CC '("cc" "gcc" "tcc" "pcc"))
7737 @end example
7738
7739 If multiple program names is given, the search is done in the following
7740 order: First, we search for the first item (@code{cc}, in the above
7741 example) for each of paths, then the second, etc. For example,
7742 if we have @code{/usr/local/bin:/usr/bin:/bin} in @code{PATH} and
7743 we have @code{/usr/local/bin/tcc} and @code{/usr/bin/gcc}, the above
7744 feature test sets @code{MY_CC} to @code{"gcc"}. If you use @code{cf-path-prog}
7745 instead, @code{MY_CC} gets @code{"/usr/bin/gcc"}.
7746
7747 If no program is found, @var{sym} is set to the keyword argument
7748 @var{default} if it is given, otherwise @var{sym} is left unset.
7749
7750 If the @var{value} keyword argument is given, its value is
7751 used instead of the found program name to be set to @var{sym}.
7752
7753 The list of search paths is taken from @code{PATH} environment
7754 variable. You can override the list by the @var{paths} keyword
7755 argument, which must be a list of directory names. It may contain
7756 nonexistent directory names, which are silently skipped.
7757
7758 The @var{filter} keyword argument, if given, must be a predicate
7759 that takes full pathname of the executable program. It is called
7760 when the procedure finds matching executable; the @var{filter} procedure
7761 may reject it by returning @code{#f}, in which case the procedure
7762 keeps searching.
7763
7764 Note: If the substitution parameter @var{sym} is already set
7765 at the time these procedure is called, these procedures do nothing.
7766 Combined with @code{cf-arg-var}, it allows the configure script caller
7767 to override the feature test. For example, suppose you have the
7768 following in the @code{configure} script:
7769
7770 @example
7771 (cf-arg-var 'GREP)
7772 (cf-path-prog 'GREP '("egrep" "fgrep" "grep"))
7773 @end example
7774
7775 A user can override the test by calling @code{configure} like this:
7776
7777 @example
7778 $ ./configure GREP=mygrep
7779 @end example
7780
7781 @end defun
7782
7783 @defun cf-prog-cxx
7784 @c MOD gauche.configure
7785 A convenience feature test to find C++ compiler. This searches
7786 popular names of C++ compilers from the search paths, sets the
7787 substitution parameter @code{CXX} to the compiler's name,
7788 then tries to compile a small
7789 program with it to see it can generate an executable.
7790
7791 This corresponds to autoconf's @code{AC_PROG_CXX}.
7792
7793 @code{CXX} is @code{cf-arg-var}'ed in this procedure. If a user
7794 provide the value when he calls @code{configure}, the searching
7795 is skipped, but the check of generating an executable is still
7796 performed.
7797
7798 If the substitution parameter @code{CXXFLAGS} is set, its value
7799 is used to check if the compiler can generate an executable.
7800 @code{CXXFLAGS} is @code{cf-arg-var}'ed in this procedure.
7801
7802 This procedure also emulates autoconf's @code{AC_PROG_CXX} behavior---
7803 if @code{CXX} is not set, but @code{CCC} is set, then we set
7804 @code{CXX} by the value of @code{CCC} and skip searching.
7805 @end defun
7806
7807 @defun cf-header-available? header :key includes
7808 @defunx cf-check-header header :key includes
7809 @c MOD gauche.configure
7810 Check if a header file @var{header} exists and usable, by
7811 compiling a source program of the current language
7812 that includes the named header file.
7813 Return @code{#t} if the header is usable, @code{#f} if not.
7814
7815 Both procedure does the same thing. The name @code{cf-check-header}
7816 corresponds to autoconf's @code{AC_CHECK_HEADER}.
7817
7818 If @var{header} requires other headers being included or
7819 preprocessor symbols defined before it,
7820 you can pass a list of strings to be emitted before the check
7821 in the @var{includes} keyword arguments. The given strings
7822 are just concatenated and used as a C program fragment.
7823 The default value is provided by @code{cf-includes-default}.
7824
7825 The following example sets C preprocessor symbol @code{HAVE_CRYPT_H} to
7826 1 if @file{crypt.h} is available. (Note: For this kind of common task,
7827 you can use @code{cf-check-headers} below. The advantage of using
7828 @code{cf-check-header} is that you can write other actions in Scheme
7829 depending on the result.)
7830
7831 @example
7832 (when (cf-check-header "crypt.h")
7833 (cf-define "HAVE_CRYPT_H" 1))
7834 @end example
7835 @end defun
7836
7837 @defun cf-check-headers headers :key includes if-found if-not-found
7838 @c MOD gauche.configure
7839 Codify a common pattern of checking the availability of headers and
7840 sets C preprocessor definitions.
7841 This corresponds to autoconf's @code{AC_CHECK_HEADERS}.
7842 This procedure is invoked for the side effects,
7843 and returns an undefined vlaue.
7844
7845 See this example:
7846
7847 @example
7848 (cf-check-headers '("unistd.h" "stdint.h" "inttypes.h" "rpc/types.h"))
7849 @end example
7850
7851 This checks availability of each of listed headers,
7852 and sets C preprocessor definition @code{HAVE_UNISTD_H},
7853 @code{HAVE_STDINT_H}, @code{HAVE_INTTYPES_H} and
7854 @code{HAVE_RPC_TYPES_H} to 1 if the corresponding header
7855 file is available.
7856
7857 A list of strings given to @var{includes} are emitted to the
7858 C source file before the inclusion of the testing header. You can
7859 give necessary headers and/or C preprocessor definitions there;
7860 if omitted, @code{cf-includes-default} provides
7861 the default list of such headers.
7862
7863 The keyword argument @var{if-found} and @var{if-not-found} are
7864 procedures to be called when a header is found to be available or
7865 to be unavailable, respectively. The procedure receives the name
7866 of the header.
7867
7868 The name of the C preprocessor definition is derived from the
7869 header name by upcasing it and replacing non-alphanumeric characters
7870 for @code{_}. Note that this substitution is not injective:
7871 Both @file{gdbm/ndbm.h} and @file{gdbm-ndbm.h} yield
7872 @code{GDBM_NDBM_H}. If you need to distinguish such files
7873 you have to use @code{cf-check-header}.
7874 @end defun
7875
7876 @defun cf-includes-default
7877 @c MOD gauche.configure
7878 Returns a list of strings that are included in the check program by
7879 default. It is actually a combination of C preprocessor @code{#ifdef}s
7880 and @code{#include}s, and would probably be better to be called
7881 @code{cf-prologue-default} or something, but the corresponding
7882 autoconf macro is @code{AC_INCLUDES_DEFAULT} so we stick to this name.
7883
7884 Usually you don't need to call this explicitly. Not giving the
7885 @code{includes} argument to @code{cf-check-header} and
7886 @code{cf-check-headers} will make @code{cf-includes-default}
7887 called implicitly.
7888 @end defun
7889
7890 @defun cf-type-available? type :key includes
7891 @defunx cf-check-type type :key includes
7892 @c MOD gauche.configure
7893 Test if @var{type} is defined as a type name.
7894 Return @code{#t} if @var{type} is defined, @code{#f} otherwise.
7895
7896 Two procedures are the same. The name @code{cf-check-type}
7897 corresponds to @code{AC_CHECK_TYPE}.
7898
7899 A list of strings given to @var{includes} are emitted to the
7900 C source file before the inclusion of the testing header. You can
7901 give necessary headers and/or C preprocessor definitions there;
7902 if omitted, @code{cf-includes-default} provides
7903 the default list of such headers.
7904 @end defun
7905
7906 @defun cf-check-types types :key includes if-found if-not-found
7907 @c MOD gauche.configure
7908 For each type in the list @var{types}, call @code{cf-check-type} to
7909 see it is defined as a type. If it is,
7910 defines @code{HAVE_@var{type}}, and calls @var{if-found} with the
7911 type as an argument if provide. If the type is not defined and
7912 @var{if-not-found} is provided, calls it with the type as an argument.
7913
7914 The argument @var{includes} is passed to @code{cf-check-type}.
7915
7916 This corresponds to autoconf's @code{AC_CHECK_TYPES}.
7917
7918 Returns an undefiend value. This procedure is for side effects.
7919
7920 @example
7921 ;; May define HAVE_PTRDIFF_T and/or HAVE_UNSIGNED_LONG_LONG_INT
7922 ;; depending on its availability:
7923 (cf-check-types '("ptrdiff_t" "unsigned long long int"))
7924
7925 ;; Example of using @var{includes} to add an extra header.
7926 (cf-check-types '("float_t")
7927 :includes `(,@@(cf-includes-default)
7928 "#include <math.h>\n"))
7929 @end example
7930 @end defun
7931
7932 @defun cf-decl-available? symbol :key includes
7933 @defunx cf-check-decl symbol :key includes
7934 @c MOD gauche.configure
7935 Test if @var{symbol} is declared as a cpp macro, a variable,
7936 a constant, or a function.
7937 Return @code{#t} if @var{type} is defined,
7938 @code{#f} otherwise.
7939
7940 Two procedures are the same. The name @code{cf-check-decl} corresponds
7941 to autoconf's @code{AC_CHECK_DECL}.
7942
7943 A list of strings given to @var{includes} are emitted to the
7944 C source file before the inclusion of the testing header. You can
7945 give necessary headers and/or C preprocessor definitions there;
7946 if omitted, @code{cf-includes-default} provides
7947 the default list of such headers.
7948 @end defun
7949
7950 @defun cf-check-decls symbols :key includes if-found if-not-found
7951 @c MOD gauche.configure
7952 For each symbol in @var{symbols}, call @code{cf-check-decl} to see
7953 if it is declared. If it is, define @code{HAVE_DECL_@var{symbol}} to
7954 1, and calls @var{if-found} with the symbol if provided.
7955 If it is not declared, define @code{HAVE_DECL_@var{symbol}} to 0,
7956 and calls @var{if-not-found} with the symbol if provided.
7957 This corresponds to autoconf's @code{AC_CHECK_DECLS}.
7958
7959 The argument @var{includes} is passed to @code{cf-check-decl}.
7960
7961 This procedure returns an undefined value. This procedure is for
7962 side effects.
7963
7964 Note that, unlike other @code{cf-check-*} routines which leave
7965 @code{HAVE_*} macro undefined when the item isn't found, this one
7966 always defines the macro and differentiate the result with its value.
7967 This behavior is the same as @code{AC_CHECK_DECLS}.
7968 @end defun
7969
7970 @defun cf-member-available? aggregate.member :key includes
7971 @defunx cf-check-member aggregate.member :key includes
7972 @c MOD gauche.configure
7973 The @var{aggregate.member} argument is a string of aggregate type name
7974 and its member concatenated by a dot, e.g. @code{"struct password.pw_gecos"}.
7975 It can also be a submember, e.g. @code{"struct foo.bar.baz"}.
7976 The @var{aggregate} part can be any type name (typedef-ed name is ok).
7977
7978 This test checks if @var{member} is a member of @var{aggregate}, and
7979 returns @code{#t} if so, or returns @code{#f} if not.
7980
7981 Two procedures are the same. The name @code{cf-check-member}
7982 corresponds to autoconf's @code{AC_CHECK_MEMBER}.
7983
7984 A list of strings given to @var{includes} are emitted to the
7985 C source file before the inclusion of the testing header. You can
7986 give necessary headers and/or C preprocessor definitions there;
7987 if omitted, @code{cf-includes-default} provides
7988 the default list of such headers.
7989 @end defun
7990
7991 @defun cf-check-members members :key includes if-found if-not-found
7992 @c MOD gauche.configure
7993 For each @var{aggregate.member}
7994 in @var{members}, call @code{cf-check-member}.
7995 If the test passes, defines @code{HAVE_@var{aggregate}_@var{member}},
7996 and calls @var{if-found} with @var{aggregate.member} if provided.
7997 If the test fails, calls @var{if-not-found} with @var{aggregate.member}
7998 if provided.
7999
8000 This corresponds to autoconf's @code{AC_CHECK_MEMBERS}.
8001
8002 The @var{include} argument is passed to @code{cf-check-member}.
8003
8004 @example
8005 ;; Defines HAVE_STRUCT_ST_RDEV and/or HAVE_STRUCT_ST_BLKSIZE
8006 ;; depending on their availability:
8007 (cf-check-members '("struct stat.st_rdev"
8008 "struct stat.st_blksize"))
8009 @end example
8010
8011 This procedure is for side effects, and returns an undefined value.
8012 @end defun
8013
8014 @defun cf-func-available? func
8015 @defunx cf-check-func func
8016 @c MOD gauche.configure
8017 See if a function @var{func} is available. This emits C code
8018 to call @var{func} (with dummy declaration) and tries to compile and link,
8019 using current value of substitution parameter @code{LIBS}.
8020 The value of @code{cf-includes-default} is at the top of the emitted C code.
8021
8022 They return @code{#t} if @var{func} is available, @code{#f} otherwise.
8023
8024 Two procedures are the same. The name @code{cf-check-func}
8025 corresponds to autoconf's @code{AC_CHECK_FUNC}.
8026 @end defun
8027
8028 @defun cf-check-funcs funcs :key if-found if-not-found
8029 @c MOD gauche.configure
8030 For each function name @var{func} in @var{funcs}, call @code{cf-check-func}
8031 to determine availability. If it is available, define
8032 @code{HAVE_@var{func}}, and calls @code{if-found} with @var{func}
8033 if provided. If it is not available, calls @code{if-not-found}
8034 with @var{func} if provided.
8035
8036 This corresponds to autoconf's @code{AC_CHECK_FUNCS}.
8037
8038 This procedure is for side effects, and returns an undefined value.
8039 @end defun
8040
8041 @defun cf-lib-available? lib fn :key other-libs if-found if-not-found
8042 @defunx cf-check-lib lib fn :key other-libs if-found if-not-found
8043 @c MOD gauche.configure
8044 See if a library @var{lib} can be linked and a function @var{fn} in it
8045 is callable. Return @code{#t} it is, @code{#t} if not.
8046
8047 Two procedures are the same. The name @code{cf-check-lib}
8048 corresponds to autoconf's @code{AC_CHECK_LIB}.
8049
8050 Give the name you pass after @code{-l} option to @var{lib};
8051 for example, if you want to check availability of @code{libm}, you can
8052 say as follows:
8053
8054 @example
8055 (cf-check-lib "m" "sin")
8056 @end example
8057
8058 This generates a C source that calls @var{fn} and try to compile and link
8059 it to generate executable. If linking @var{lib} requires additional
8060 libraries, it should be listed in @var{other-libs}:
8061
8062 @example
8063 (cf-check-lib "Xt" "XtDisplay" :other-libs '("-lX11" "-lSM" "-lICE"))
8064 @end example
8065
8066 If compilation and linking succeeds,
8067 @var{if-found} is called at the
8068 tail position with
8069 the library name (@code{"m"} and @code{"Xt"} in the above examples,
8070 respectively) as the argument.
8071 The default behavior is to add
8072 @code{-l@var{lib}} in the left of substitution parameter @code{LIBS},
8073 and set @code{HAVE_LIB@var{lib}} definition, then
8074 returns @code{#t}.
8075
8076 If compilation or linking fails, @var{if-not-found} is called at
8077 the tail position with the library name. The default behavior is
8078 to return @code{#f}.
8079
8080 The default behavior of @var{if-found} and @var{if-not-found} allows
8081 @code{cf-check-lib} to be used as predicate as well. If you merery
8082 want to take an action depending on whether the library is found or
8083 not, you can write like this:
8084
8085 @example
8086 (unless (cf-check-lib "foo" "foo_fn)
8087 ... do something if libfoo isn't available ...)
8088 @end example
8089
8090 Use @var{if-found} and/or @var{if-not-found} only if you want to
8091 override the default behaviors.
8092 @end defun
8093
8094 @defun cf-search-libs fn libs :key other-libs if-found if-not-found
8095 @c MOD gauche.configure
8096 Like @code{cf-check-lib}, but can be used if you're not sure which
8097 library contains desired function.
8098 This corresponds to autoconf's @code{AC_SEARCH_LIBS}. Note that
8099 this takes function name first, while @code{cf-check-lib} takes
8100 function name second---blame autoconf for this inconsistency.
8101
8102 First it tests if @var{fn} is available without any library in @var{libs}
8103 (that is, with the ones already in @code{LIBS} and specified in
8104 @var{other-libs}). If not, it tests each library in @var{libs}
8105 in turn.
8106
8107 If @var{fn} is found, @var{if-found} is called at the tail position,
8108 with the name of
8109 the library as an argument (if @var{fn} is available without any
8110 library, the argument is @code{#f}). If omitted, and a library
8111 is required, then the library is
8112 added to the substitution parameter @code{LIBS}.
8113 The default procedure returns @code{#t}.
8114
8115 If @var{fn} isn't found in any of the libraries, @var{if-not-found}
8116 is called at the tail position
8117 with @code{#f} as the argument. The default procedure
8118 does nothing and just returns @code{#f}.
8119
8120 The default behavior of @var{if-found} and @var{if-not-found} allows
8121 @code{cf-search-libs} to be used as predicate as well. If you give
8122 alternative procedures, keep in mind that their return value
8123 will be returned to @code{cf-search-libs}.
8124 @end defun
8125
8126 @defun cf-path-x
8127 @c MOD gauche.configure
8128 This corresponds to autoconf's @code{AC_PATH_X}. It checks if
8129 X11 is available, and returns three values.
8130
8131 The first value is a boolean value indicates if X11 is available.
8132 The second and third values are strings for the directory name
8133 to find X11 headers and libraries, respectively. The second
8134 and third value can be empty strings if the compiler doesn't
8135 need additional flags to find X11 stuff.
8136
8137 This does not set other substituion parameters.
8138 You typically want to use @code{cf-path-xtra} below instead.
8139
8140 (In autoconf, @code{AC_PATH_X} sets shell variables to tell
8141 the results. In Scheme, it is more natural to use return
8142 values.)
8143 @end defun
8144
8145 @defun cf-path-xtra
8146 @c MOD gauche.configure
8147 Check X11 availability with @code{cf-path-x} above, and
8148 sets up the following substitution parameters:
8149
8150 @table @code
8151 @item X_CFLAGS
8152 Additional CFLAGS needed to build with X11.
8153 @item X_PRE_LIBS
8154 Additional library link flags (@code{-l@var{lib} @dots{}})
8155 that need to come @emph{before} @code{-lX11} flag.
8156 @item X_LIBS
8157 Additional library search flags (@code{-L@var{dir} @dots{}})
8158 to link with X11. (Note: The name is for the compatibility
8159 with autoconf. It should really be named as @code{X_LDFLAGS}.)
8160 @item X_EXTRA_LIBS
8161 Additional library search flags (@code{-L@var{dir} @dots{}})
8162 to link with X11. Those libraries should come after @code{-lX11}
8163 flag.
8164 @end table
8165
8166 This procedure corresponds to autoconf's @code{AC_PATH_XTRA}.
8167
8168 Note that @code{-lX11} is not included in those parameters;
8169 they must be specified explicitly.
8170
8171 If X11 is not available, those parameters get empty strings.
8172 @end defun
8173
8174
8175 @c EN
8176 @subsubheading Running compiler
8177 @c JP
8178 @subsubheading コンパイラを走らせる
8179 @c COMMON
8180
8181 The @code{gauche.configure} module provides a generic mechanism
8182 to construct a small test program, compile it, and run it.
8183 Currently we only support @code{C} and @code{C++}; we'll add support
8184 for other languages as needed.
8185
8186 @deffn {Parameter} cf-lang
8187 @c MOD gauche.configure
8188 Returns a @emph{current language}, which is an opaque object.
8189 Currently C and C++ are supported; see @code{cf-lang-C} and
8190 @code{cf-lang-C++} below.
8191
8192 The current language is used by compiler tests.
8193 @end deffn
8194
8195 @defun cf-lang-C
8196 @defunx cf-lang-C++
8197 @c MOD gauche.configure
8198 Returns an opaque object representing C or C++, respectively.
8199 You can use them to parameterize @code{cf-lang} to run
8200 compiler tests.
8201
8202 @example
8203 (parameterize ([cf-lang (cf-lang-C++)])
8204 ... run compiler tests ...)
8205 @end example
8206 @end defun
8207
8208
8209 @defun cf-lang-program prologue body
8210 @c MOD gauche.configure
8211 Returns a string tree that consists a stand-alone program for
8212 the current language. @var{Prologue} and @var{body} must be a
8213 string or a list of strings. If it is a list, strings are
8214 concatenated with newlines.
8215 @var{Prologue} comes at the beginning of
8216 the source, and @var{body} is included in the part of the program
8217 that's executed. If the current language is C, the code fragment:
8218
8219 @example
8220 (use text.tree)
8221 (write-tree (cf-lang-program '("#include <stdio.h>"
8222 "#include <stdlib.h>")
8223 '("printf(\"()\");")))
8224 @end example
8225
8226 would produce something like this:
8227
8228 @example
8229 #include <stdio.h>
8230 #include <stdlib.h>
8231
8232 int main()@{
8233 printf("()");
8234
8235 ; return 0;
8236 @}
8237 @end example
8238 @end defun
8239
8240 @defun cf-lang-io-program
8241 @c MOD gauche.configure
8242 This is a convenience routine. It returns a string tree
8243 of a program in the current language, that creates a file
8244 named @file{conftest.out}, then exits with zero status on
8245 success, or nonzero status on failure.
8246 @end defun
8247
8248 @defun cf-lang-call prologue func-name
8249 @c MOD gauche.configure
8250 Returns a string tree of a program in the current language,
8251 that calls @var{func-name} as a function with no arguments.
8252 @end defun
8253
8254 @defun cf-try-compile prologue body
8255 @c MOD gauche.configure
8256 The arguments must be a string or a list of strings. If it is
8257 a list, it is taken as a list of lines, concatenated with newlines.
8258
8259 This test generates a program with the given content,
8260 using @code{cf-lang-program}, then try to compile it.
8261 On success, @code{#t} is returned. On failure, @code{#f} is returned.
8262 The generated program, command line, and the result is logged.
8263 @end defun
8264
8265 @defun cf-try-compile-and-link prologue body
8266 @c MOD gauche.configure
8267 The arguments must be a string or a list of strings. If it is
8268 a list, it is taken as a list of lines, concatenated with newlines.
8269
8270 This test generates a program with the given content,
8271 using @code{cf-lang-program}, then try to compile and link it.
8272 On success, @code{#t} is returned. On failure, @code{#f} is returned.
8273 The generated program, command line, and the result is logged.
8274 @end defun
8275
8276
8277 @c EN
8278 @subsubheading Output
8279 @c JP
8280 @subsubheading 出力
8281 @c COMMON
8282
8283 @defun cf-output-default file @dots{}
8284 @c MOD gauche.configure
8285 A convenience routine to produce typical output.
8286 It does the following:
8287
8288 @itemize @bullet
8289 @item
8290 Generate gpd (Gauche package description) file using
8291 @code{cf-make-gpd}.
8292 @item
8293 Generate @code{VERSION} file that contains the value of
8294 @code{PACKAGE_VERSION} substitution parameter.
8295 @item
8296 Search @code{Makefile.in}'s under the source directory
8297 (the value of substitution parameter @code{srcdir}),
8298 and process them to produce @code{Makefile}'s.
8299 If @var{file} @dots{} are given, @code{@var{file}.in} are also
8300 processed as well to produce @var{file}.
8301
8302 See @code{cf-output} below for the details.
8303 @item
8304 If config header is registered by @code{cf-config-headers},
8305 process them as well.
8306 @end itemize
8307 @end defun
8308
8309 @defun cf-output file @dots{}
8310 @c MOD gauche.configure
8311 Generates @var{file}'s from the input templates.
8312 This corresponds to autoconf's @code{AC_OUTPUT}.
8313
8314 For each @var{file}, a file named @file{@var{file}.in} is read
8315 as a template. Within the file, @code{@@PARAMETER@@} is substituted
8316 with the value of @code{(cf$ 'PARAMETER)}. If the named parameter
8317 isn't registered, a warning is issued and the parameter is left
8318 unsubstituted.
8319
8320 If config headers are not registered via @code{cf-config-headers},
8321 a substitution parameter @code{DEFS} is replaced with
8322 all the definitions in the form of @code{-D...}. For example,
8323 if you have checked header files @file{foo/bar.h} and
8324 @file{foo/baz.h}, @code{DEFS} gets the value
8325 @code{-DHAVE_FOO_BAR_H -DHAVE_FOO_BAZ_H}.
8326
8327 If config header is registered by @code{cf-config-headers},
8328 they are processed as well. In such case, the substitution
8329 parameter @code{DEFS} gets the value @code{-DHAVE_CONFIG_H}.
8330 @end defun
8331
8332 @defun cf-config-headers header-or-headers
8333 @c MOD gauche.configure
8334 Sets up config header files to be processed. Usually a config header
8335 file is named @file{config.h}, and contains definitions determined
8336 by feature tests.
8337
8338 The @var{header-or-headers} argument may be a string header-spec
8339 or a list of string header-specs, where each header spec is
8340 a header file name (e.g. @code{"config.h"}) or a header name
8341 and a input file name concatenated with a colon
8342 (e.g. @code{"config.h:config.h.templ"}). If it's just a header name,
8343 input file name is assumed to be the header file name with @code{".in"}
8344 appended.
8345
8346 The input template of config header file contains a bunch of
8347 @code{#undef} directives, such as the following:
8348
8349 @example
8350 /* Gauche ABI version string */
8351 #undef GAUCHE_ABI_VERSION
8352
8353 /* Define if Gauche handles multi-byte character as EUC-JP */
8354 #undef GAUCHE_CHAR_ENCODING_EUC_JP
8355
8356 /* Define if Gauche handles multi-byte character as Shift JIS */
8357 #undef GAUCHE_CHAR_ENCODING_SJIS
8358
8359 /* Define if Gauche handles multi-byte character as UTF-8 */
8360 #undef GAUCHE_CHAR_ENCODING_UTF_8
8361 @end example
8362
8363 Once processed, the generated header file has either
8364 @code{#undef} line is replaced with @code{#define}, or
8365 commented out, depending on the definitions determined by feature
8366 tests.
8367
8368 @example
8369 /* Gauche ABI version string */
8370 #define GAUCHE_ABI_VERSION "0.97"
8371
8372 /* Define if Gauche handles multi-byte character as EUC-JP */
8373 /* #undef GAUCHE_CHAR_ENCODING_EUC_JP */
8374
8375 /* Define if Gauche handles multi-byte character as Shift JIS */
8376 /* #undef GAUCHE_CHAR_ENCODING_SJIS */
8377
8378 /* Define if Gauche handles multi-byte character as UTF-8 */
8379 #define GAUCHE_CHAR_ENCODING_UTF_8 /**/
8380 @end example
8381
8382 Note that the lines other than @code{#undef} are copied as they are.
8383
8384 The substitution parameter @code{DEFS} behaves differently whether
8385 config header is specified or not. If no config header is registered,
8386 The value of @code{DEFS} is a C command-line arguments for definitions,
8387 e.g. @code{-DGAUCHE_ABI_VERSION=0.97 -DGAUCHE_CHAR_ENCODING_UTF8}.
8388 If config header files are registered, the value of @code{DEFS} becomes
8389 simply @code{-DHAVE_CONFIG_H}.
8390 @end defun
8391
8392
8393 @defun cf-show-substs :key formatter
8394 @c MOD gauche.configure
8395 Print all substitution parameters; this is for debugging.
8396
8397 For each substitution parameter name and value,
8398 @var{formatter} is called with them; the default is
8399 @code{(^[k v] (format #t "~16s ~s" k v))}.
8400 @end defun
8401
8402 @defun cf-make-gpd
8403 @c MOD gauche.configure
8404 Generate gpd (Gauche package description) file,
8405 @file{PACKAGE_NAME.gpd}, where @code{PACKAGE_NAME} is the
8406 package's name either taken form @file{package.scm} or
8407 the argument to @code{cf-init}.
8408 @xref{Package metainformation}, for the package description file format.
8409 @end defun
8410
8411
8412 @c ----------------------------------------------------------------------
8413 @node Connection framework, Dictionary framework, Generating build files, Library modules - Gauche extensions
8414 @section @code{gauche.connection} - Connection framework
8415 @c NODE コネクションフレームワーク, @code{gauche.connection} - コネクションフレームワーク
8416
8417 @deftp {Module} gauche.connection
8418 @mdindex gauche.connection
8419 @c EN
8420 A connection is an abstract class to handle full-duplex
8421 communication channel. The actual data I/O is done through
8422 Scheme ports; a channel provides an interface to retrieve those
8423 ports. It also has interface to know endpoint names, and the
8424 way to shutdown the communication.
8425 @c JP
8426 コネクションは双方向コミュニケーションチャネルを抽象化するクラスです。
8427 実際のデータI/OはSchemeポートを使いますが、
8428 コネクションはコミュニケーションに利用できるポートを得るのに使えるほか、
8429 通信相手の名前を得たり、通信をシャットダウンする操作を提供します。
8430 @c COMMON
8431
8432 @c EN
8433 The @code{<socket>} class, for example, implements the connection
8434 framework (@pxref{Networking}). The @code{<tls>} class, which
8435 wraps a socket to provide TLS communication, also implements it.
8436 That means you can write a client code that works both plain
8437 socket connection and secure connection.
8438 You can also abstract communication to the external process
8439 as a connection (@pxref{Process connection}).
8440 @c JP
8441 例えば@code{<socket>}クラスはコネクションフレームワークを実装しています
8442 (@ref{Networking}参照)。
8443 ソケットをラップしてTLS通信を提供する@code{<tls>}クラスも、
8444 コネクションフレームワークを実装しています。
8445 すると、生のソケットでもTLSソケットでも同じように使えるクライアントコードを書くことができます。
8446 また、外部プロセスとの通信をコネクションとして抽象化することもできます
8447 (@ref{Process connection}参照)。
8448 @c COMMON
8449
8450 @c EN
8451 Each of the connection endpoints (@emph{self} for our side,
8452 and @emph{peer} fo the other side) has @emph{addresses},
8453 some object that identifies the endpoint. The framework
8454 doesn't specify the actual type of addresses; it only requires
8455 that addresses can be passed to @code{connection-address-name} method
8456 to get its string representation, so that can be used for logging
8457 and monitoring. The concrete
8458 class can choose suitable address representation. For example,
8459 @code{<socket>} uses @code{<sockaddr>} for the addresses.
8460 @c JP
8461 コネクションのエンドポイント(自分自身を@emph{self}、相手を@emph{peer}と呼びます)は
8462 それぞれエンドポイントを同定する@emph{アドレス}を持ちます。
8463 このフレームワークではアドレスの具体的な型は指定しません。ただ、
8464 アドレスは@code{connection-address-name}に渡せば
8465 わかりやすい文字列表現を得られるので、ロギングやモニタリングに使えます。
8466 コネクションの具体クラスはアドレスをどう表現するかを選べます。
8467 例えば@code{<socket>}は@code{<sockaddr>}をアドレスとして使います。
8468 @c COMMON
8469
8470 @c EN
8471 A concrete class must implement the following methods.
8472 @c JP
8473 具体クラスは以下のメソッドを実装しなければなりません。
8474 @c COMMON
8475
8476 @example
8477 connection-self-address (c <connection>)
8478 connection-peer-address (c <connection>)
8479 connection-input-port (c <connection>)
8480 connection-output-port (c <connection>)
8481 connection-shutdown (c <connection>) how
8482 connection-close (c <connection>)
8483 connection-address-name obj ; optional
8484 @end example
8485
8486 @c EN
8487 At this moment this framework doesn't provide a generic way to
8488 @emph{create} a connection, since the way to do it may greatly vary
8489 depending on the concrete implementation. Each concrete implementation
8490 should provide its own procedure to create and return a new connection.
8491 @c JP
8492 今のところ、このフレームワークはコネクションを作るジェネリックな方法は提供しません。
8493 それは具体的な実装によって大きく異なるからです。
8494 各具体クラスは、新たなコネクションを返す独自の手続きを提供しなければなりません。
8495 @c COMMON
8496 @end deftp
8497
8498
8499 @deffn {Method} connection-self-address connection
8500 @deffnx {Method} connection-peer-address connection
8501 @c MOD gauche.connection
8502 @c EN
8503 Returns the address of this @var{connection}'s endpoint and
8504 its peer's. For sockets and @code{<tls>}, it is an instance
8505 of @code{<sockaddr>}. For processes, it is a string
8506 describing the process.
8507 @c JP
8508 @var{connection}のエンドポイントの自分自身と相手のアドレスをそれぞれ返します。
8509 ソケットと@code{<tls>}オブジェクトでは、アドレスは@code{<sockaddr>}のインスタンスです。
8510 プロセスコネクションでは、プロセスを記述する文字列です。
8511 @c COMMON
8512
8513 @c EN
8514 If @var{connection} is not connected, these methods can return @code{#f}.
8515 @c JP
8516 @var{connection}が接続されていなければ@code{#f}が返されるかもしれません。
8517 @c COMMON
8518
8519 @c EN
8520 The returned value (other than @code{#f}) must be able to
8521 be passed to @code{connection-address-name} method.
8522 @c JP
8523 @code{#f}でない返り値は、@code{connection-address-name}に渡すことができます。
8524 @c COMMON
8525
8526 @c EN
8527 Currently addresses are only used for logging purpose within
8528 the connection framework; however, we may enhance the framework
8529 to add ``connect'' operation, for example, so the concrete class
8530 is encouraged to use objects that can be used to create connections.
8531 @c JP
8532 今のところ、アドレスはロギング用途にのみ使われています。
8533 しかし、将来、``connect'' 操作もこのフレームワークで提供することになるかもしれまえsん。
8534 新たな具体クラスを実装する場合は、可能ならコネクションを作るために渡せるオブジェクトを
8535 アドレスにするのが良いでしょう。
8536 @c COMMON
8537 @end deffn
8538
8539 @deffn {Method} connection-address-name address
8540 @c MOD gauche.connection
8541 @c EN
8542 This method returns a string representation of @var{address}, which is
8543 a returned value from @code{connection-self-address} and
8544 @code{connection-peer-address}. It is for display/logging.
8545 For sockets, a resonable string representation of socket address is
8546 returned. The default method just uses
8547 @var{address}'s @code{display}-representation. If a concrete
8548 class chooses aggregate objects to represent addresses, it should
8549 provide this method as well.
8550 @c JP
8551 このメソッドは、@code{connection-self-address}や@code{connection-peer-address}
8552 から返されるアドレスオブジェクトを取り、その文字列表現を返します。ソケットアドレスの場合は、
8553 読みやすい文字列表示が返されます。デフォルトメソッドはアドレスオブジェクトの
8554 display表示になります。具体クラスはより読みやすい表記を返すメソッドを実装すべきです。
8555 @c COMMON
8556 @end deffn
8557
8558 @deffn {Method} connection-input-port connection
8559 @deffnx {Method} connection-output-port connection
8560 @c MOD gauche.connection
8561 @c EN
8562 Returns an input port and an output port of the connection, respectively.
8563 Writing to the output port sends the data to the peer,
8564 and reading from the input port returns the received data.
8565
8566 If the connection is not connected, or already shutdown or closed,
8567 the return value of these methods are unspecified.
8568 @c JP
8569 コネクションの入力ポートと出力ポートをそれぞれ返します。
8570 出力ポートに書き込むことでデータを送信することができ、
8571 また入力ポートから読み込むことで受信したデータを読み出せます。
8572
8573 コネクションがまだ接続されていなかったり、既にクローズしている場合は
8574 これらのメソッドの戻り値は不定です。
8575 @c COMMON
8576 @end deffn
8577
8578 @deffn {Method} connection-shutdown connection :optional how
8579 @c MOD gauche.connection
8580 @c EN
8581 Shutdown the connection. You can either shutdown the connection
8582 entirely at once, or shutdown only read or write channel of it.
8583
8584 Shutdown is about telling the peer to terminate the communication.
8585 Usually the peer will detect the termination by reading EOF from
8586 their input channel. The port corresponding to the shutdown channel
8587 is closed so no further communication is possible.
8588
8589 Note that merely closing the connection doesn't shutdown the
8590 connection---the process may fork after creating the connection,
8591 and in that case, one process may close the connection without
8592 shutting down.
8593 @c JP
8594 コネクションを遮断します。送受信を同時に遮断することも、
8595 送信か受信どちらかのみを遮断することもできます。
8596
8597 遮断は、通信相手に通信の終了を通知する操作です。
8598 通常、送信を遮断すると、通信相手側では受信データとしてEOFが返されます。
8599 遮断したコネクションに対応するポートは閉じられ、以降の操作に使うことはきません。
8600
8601 コネクションをクローズするだけでは、必ずしも通信が遮断されるとは限らないことに
8602 注意してください。例えばコネクションを作った後でプロセスがforkした場合、
8603 一方のプロセスがコネクションを閉じてももう一方のプロセスのコネクションは遮断されません。
8604 @c COMMON
8605
8606 @c EN
8607 The @var{how} argument must be one of those symbols:
8608 @c JP
8609 @var{how}引数は次のいずれかのシンボルです。
8610 @c COMMON
8611 @table @code
8612 @item read
8613 @c EN
8614 Shutdown read channel of the connection.
8615 @c JP
8616 読み込み(受信)チャネルを遮断します。
8617 @c COMMON
8618 @item write
8619 @c EN
8620 Shutdown write channel of the connection.
8621 @c JP
8622 書き込み(送信)チャネルを遮断します。
8623 @c COMMON
8624 @item both
8625 @c EN
8626 Shutdown both channels of the connection.
8627 @c JP
8628 送受信両方のチャネルを遮断します。
8629 @c COMMON
8630 @end table
8631
8632 @c EN
8633 If omitted, @code{both} is assumed.
8634 @c JP
8635 省略時は@code{both}と同じです。
8636 @c COMMON
8637
8638 @c EN
8639 Shutting down already shut down channel has no effect.
8640 @c JP
8641 既に遮断されたチャネルを再び遮断しても何も起きません。
8642 @c COMMON
8643
8644 @c EN
8645 Note: Some concrete implementation of connection may not allow
8646 to shutdown each channels independently. In such case,
8647 the connection is shut down entirely regardless of @var{how} argument.
8648 @c JP
8649 註: 具体的な実装によっては、送信・受信チャネルを独立して遮断できないかもしれません。
8650 その場合は、@var{how}引数に関わらず送受信両方が遮断されます。
8651 @c COMMON
8652
8653 @c EN
8654 The one-argument case is handled by the default method (it calls
8655 two-argument method with @code{both} as @var{how}). So the
8656 concrete class only need to define two argument method.
8657 @c JP
8658 @var{how}引数が省略された場合はデフォルトメソッドが@var{how}に@code{both}を
8659 指定したメソッドを呼ぶので、具体クラスは2引数のメソッドのみを定義すれば良いです。
8660 @c COMMON
8661 @end deffn
8662
8663 @deffn {Method} connection-close connection
8664 @c MOD gauche.connection
8665 @c EN
8666 Close the connection. This destroys the connection and frees
8667 local resources. Note that this does not shutdown the connection
8668 itself. For example, when a process forks after establishing a connection and
8669 the parent process closes the connection, the child process can still
8670 communicate with the connection.
8671
8672 If this connection is the only endpoint of this side,
8673 the peer will get an error when it tries to communicate.
8674
8675 See @code{connection-shutdown} for the details of shutting down
8676 a connection.
8677 @c JP
8678 コネクションをクローズします。これはローカルのコネクションオブジェクトを破棄して
8679 リソースを開放します。コネクションそのものが遮断されるわけではないことに注意してください。
8680 例えばコネクション接続後にプロセスがforkし、親プロセスがコネクションをクローズしたとしても、
8681 子プロセスは通信を続けることができます。
8682
8683 このコネクションがローカル側の唯一のエンドポイントである場合は、
8684 こちらがクローズした後に相手が通信しようとすると、相手側でエラーになるでしょう。
8685
8686 コネクションの遮断については@code{connection-shutdown}を参照してください。
8687 @c COMMON
8688 @end deffn
8689
8690 @c ----------------------------------------------------------------------
8691 @node Dictionary framework, Low-level file operations, Connection framework, Library modules - Gauche extensions
8692 @section @code{gauche.dictionary} - Dictionary framework
8693 @c NODE ディクショナリフレームワーク, @code{gauche.dictionary} - ディクショナリフレームワーク
8694
8695 @deftp {Module} gauche.dictionary
8696 @mdindex gauche.dictionary
8697 @c EN
8698 A dictionary is an abstract class for objects that can
8699 map a key to a value. This module provides some useful generic
8700 functions for dictionaries, plus generic dictionary classes
8701 built on top of other dictionary classes.
8702 @c JP
8703 ディクショナリはキーから値への写像ができるオブジェクトを表わす抽象クラ
8704 スです。このモジュールではディクショナリに対してよく使うジェネリック関数、
8705 および他のディクショナリクラスの上に構築される汎用的なディクショナリクラスを
8706 提供します。
8707 @c COMMON
8708 @end deftp
8709
8710 @menu
8711 * Generic functions for dictionaries::
8712 * Generic dictionaries::
8713 @end menu
8714
8715 @node Generic functions for dictionaries, Generic dictionaries, Dictionary framework, Dictionary framework
8716 @subsection Generic functions for dictionaries
8717 @c NODE ディクショナリのためのジェネリック関数
8718
8719 @c EN
8720 The @code{gauche.dictionary} module provides the following
8721 generic functions as the dictionary protocol.
8722 (Note that @code{call-with-iterator} and
8723 @code{size-of} are from @code{gauche.collection}).
8724
8725 The functions marked with * should be
8726 specialized by each dictionary's implementation.
8727 The functions marked with + return default value if not specialized.
8728 Other functions have fallback implementation that uses the *-marked
8729 generic functions, but the implementation may provide specialized
8730 method for efficiency.
8731 @c JP
8732 @code{gauche.dictionary}モジュールは、ディクショナリプロトコルとして
8733 以下のジェネリックファンクションを提供します
8734 (@code{call-with-iterator}と@code{size-of}は@code{gauche.collection}
8735 のものです)。
8736
8737 これらのジェネリックファンクションのうち、*がついているものは
8738 各ディクショナリの実装が特定化したメソッドを提供しなければなりません。
8739 +がついているものは、ディクショナリの実装が特定化したメソッドを定義しなければ
8740 適切なデフォルト値が返されます。
8741 それ以外のジェネリックファンクションは、*がついているメソッドを使って
8742 実装されていますが、ディクショナリ実装は効率化のために
8743 特定化されたメソッドを定義しているかもしれません。
8744 @c COMMON
8745
8746 @table @b
8747 @item Predicates
8748 @code{dict-immutable?}(+),
8749 @code{dict-transparent?}(+)
8750
8751 @item Accessors
8752 @code{dict-get}(*), @code{dict-exists?}, @code{size-of}(*),
8753 @code{dict-comparator}(*)
8754
8755 @item Mutators
8756 @code{dict-put!}(*), @code{dict-delete!}(*),
8757 @code{dict-push!}, @code{dict-pop!}, @code{dict-update!},
8758 @code{dict-clear!}
8759 (If the dictionary is immutable, these methods are not specialized
8760 and the default methods throw an error.)
8761
8762 @item Walkers
8763 @code{call-with-iterator}(*),
8764 @code{dict-find}, @code{dict-any},
8765 @code{dict-fold}, @code{dict-fold-right}, @code{dict-for-each},
8766 @code{dict-map}, @code{dict-keys}, @code{dict-values},
8767 @code{dict->alist}
8768 @end table
8769
8770 @c EN
8771 These generic functions are useful to implement algorithms
8772 common to any dictionary-like objects, a data structure
8773 that maps discrete, finite set of keys to values.
8774 (Theoretically we can think of continuous and/or infinite set of
8775 keys, but implementation-wise it is cleaner to limit the dictionary
8776
8777 Among built-in classes, @code{<hash-table>} and @code{<tree-map>}
8778 implement the dictionary interface. All the @code{<dbm>} classes
8779 provided by @code{dbm} module also implement it.
8780 @c JP
8781 これらのジェネリック関数は、ディクショナリ(離散的で有限なキーの集合から値の集合への
8782 写像を表現するデータ構造)に対して共通するアルゴリズムを書くのに便利です。
8783 (理論的には連続した、また無限なキーの集合を考えることもできますが、
8784 実装上は有限集合に限る方がずっと簡潔になります。)
8785
8786 組み込みクラスでは、@code{<hash-table>}と@code{<tree-map>}が
8787 ディクショナリのインタフェースを実装しています。@code{dbm}モジュール群の
8788 提供する@code{<dbm>}クラスもそうです。
8789 @c COMMON
8790
8791 @subsubheading Predicates
8792
8793 @deffn {Generic fucntion} dict-immutable? (dict @code{<dictionary>})
8794 @c MOD gauche.dictionary
8795 @c EN
8796 Returns @code{#t} if @var{dict} is immutable, @code{#f} otherwise.
8797 Methods that tries to mutate an immutable dictionary throws an error.
8798 @c JP
8799 @var{dict}が変更不可なら@code{#t}を、変更可能なら@code{#f}を返します。
8800 変更不可なディクショナリに対して変更を加えるメソッドを呼ぶとエラーが投げられます。
8801 @c COMMON
8802
8803 @c EN
8804 If the dictionary implementation does not specialize this method,
8805 the default method returns @code{#t}.
8806 @c JP
8807 ディクショナリの実装がこのメソッドを特殊化しなければ、
8808 デフォルトメソッドは@code{#t}を返します。
8809 @c COMMON
8810 @end deffn
8811
8812 @deffn {Generic Function} dict-transparent? (dict @code{<dictionary>})
8813 @c MOD gauche.dictionary
8814 @c EN
8815 If this method returns a true value, the pretty printer displays
8816 the dictionary with their contents.
8817 Built-in hashtables, for example, are transparent:
8818 @c JP
8819 このメソッドが真の値を返した場合、プリティプリンタがディクショナリを表示する時に
8820 その内容も一緒に表示されます。例えば組み込みのハッシュテーブルはtransparentです。
8821 @c COMMON
8822
8823 @smallexample
8824 gosh$ (alist->hash-table (map-with-index cons "abcdefghijkl") eqv-comparator)
8825 #<hash-table eqv[12]( (1 . #\b) (8 . #\i) (9 . #\j) (2 . #\c) (3 . #\d)
8826 (10 . #\k) (11 . #\l) (4 . #\e) (5 . #\f) (0 . #\a) (6 . #\g) (7 . #\h))>
8827 @end smallexample
8828
8829 @c EN
8830 Not all dictionaries are like this. For example, a database-backed
8831 dictionary may not want to run the query every time the instance is
8832 printed.
8833 @c JP
8834 全てのディクショナリがこうではありません。例えばデータベースに基づいたディクショナリ
8835 では、インスタンスを表示する度にクエリを走らせたくはないかもしれません。
8836 @c COMMON
8837
8838 @c EN
8839 If the dictionary implementation does not specialize this method,
8840 the default method returns @code{#f}.
8841 @c JP
8842 ディクショナリの実装がこのメソッドを特殊化しなければ、
8843 デフォルトメソッドは@code{#f}を返します。
8844 @c COMMON
8845 @end deffn
8846
8847 @subsubheading Accessors
8848
8849 @deffn {Generic function} dict-get (dict @code{<dictionary>}) key :optional default
8850 @c MOD gauche.dictionary
8851 @c EN
8852 Returns the value corresponding to the @var{key}.
8853 If the dictionary doesn't have an entry with @var{key},
8854 returns @var{default} when it is provided, or raises an error
8855 if not.
8856 @c JP
8857 @var{key}に関連付けられた値を返します。もし@var{key}を持つエントリが
8858 ディクショナリに無い場合、@var{default}が与えられていればそれを返し、
8859 そうでなければエラーが通知されます。
8860 @c COMMON
8861 @end deffn
8862
8863 @deffn {Generic function} dict-exists? (dict @code{<dictionary>}) key
8864 @c MOD gauche.dictionary
8865 @c EN
8866 Returns @code{#t} if the dictionary has an entry with @var{key},
8867 @code{#f} if not.
8868 @c JP
8869 ディクショナリが@var{key}をキーに持つエントリを保持していれば@code{#t}を、
8870 そうでなければ@code{#f}を返します。
8871 @c COMMON
8872 @end deffn
8873
8874 @deffn {Generic function} dict-comparator (dict @code{<dictionary>})
8875 @c MOD gauche.dictionary
8876 @c EN
8877 Should return a comparator used to compare keys.
8878 @c JP
8879 キーを比較するのに使われるcomparatorを返します。
8880 @c COMMON
8881
8882 @c EN
8883 Note: This method may return @code{#f} if a dictionary implementation
8884 doesn't need to compare keys as a whole (e.g. @code{<trie>} compares
8885 keys element-wise, so no direct key comparator is used.
8886 @xref{Trie}). The caller need to handle such cases.
8887 @c JP
8888 註: このメソッドは@code{#t}を返すことがあります。ディクショナリが、
8889 キー同士を直接比較しない場合があるからです
8890 (例: @code{<trie>}はキーの各要素ごとに比較するので、キーまるごとの比較器というのは
8891 使いません。@ref{Trie}参照)。呼び出し側は@code{#f}が返る可能性を常に念頭に置いてください。
8892 @c COMMON
8893 @end deffn
8894
8895 @subsubheading Mutators
8896
8897 @deffn {Generic function} dict-put! (dict @code{<dictionary>}) key value
8898 @c MOD gauche.dictionary
8899 @c EN
8900 Puts the mapping from @var{key} to @var{value} into the dictionary.
8901 @c JP
8902 @var{key}から@var{value}への関連づけをディクショナリに追加します。
8903 @c COMMON
8904 @end deffn
8905
8906 @deffn {Generic function} {(setter dict-get)} (dict @code{<dictionary>}) key value
8907 @c MOD gauche.dictionary
8908 @c EN
8909 This works the same as @code{dict-put!}.
8910 @c JP
8911 @code{dict-put!}と同じ動作です。
8912 @c COMMON
8913 @end deffn
8914
8915 @deffn {Generic function} dict-delete! (dict @code{<dictionary>}) key
8916 @c MOD gauche.dictionary
8917 @c EN
8918 Removes an entry with @var{key} form the dictionary.
8919 If the dictionary doesn't have such an entry, this function is noop.
8920 @c JP
8921 ディクショナリから@var{key}をキーに持つエントリを除去します。
8922 @var{key}を持つエントリが無ければ何もしません。
8923 @c COMMON
8924 @end deffn
8925
8926 @deffn {Generic function} dict-clear! (dict @code{<dictionary>})
8927 @c MOD gauche.dictionary
8928 @c EN
8929 Empties the dictionary. Usually this is much faster than looping
8930 over keys to delete them one by one.
8931 @c JP
8932 ディクショナリを空にします。通常、全キーをループしてひとつづつ消していくよりも
8933 ずっと高速です。
8934 @c COMMON
8935 @end deffn
8936
8937 @deffn {Generic function} dict-push! (dict @code{<dictionary>}) key value
8938 @c MOD gauche.dictionary
8939 @c EN
8940 A shorthand way to say @code{(dict-put! dict key (cons value (dict-get dict key '())))}. A concrete implementation may be more efficient
8941 (e.g. it may not search @var{key} twice.)
8942 @c JP
8943 @code{(dict-put! dict key (cons value (dict-get dict key '())))} と同じ動作をするメソッドです。具体的な実装によってはもっと効率が良いかもしれません
8944 (@var{key}を2度検索しなくても良い、など)。
8945 @c COMMON
8946 @end deffn
8947
8948 @deffn {Generic function} dict-pop! (dict @code{<dictionary>}) key :optional fallback
8949 @c MOD gauche.dictionary
8950 @c EN
8951 If @code{(dict-get dict key)} is a pair @var{p},
8952 the entry value is replaced with @code{(cdr p)} and the procedure
8953 returns @code{(car p)}. If no entry for @var{key} is in the table,
8954 or the entry isn't a a pair, the table isn't modified, and
8955 @var{fallback} is returned if given, or an error is raised.
8956 @c JP
8957 @code{(dict-get dict key)}がペア@var{p}であれば、
8958 そのエントリの値が@code{(cdr p)}で置き換えられ、@code{(car p)}の値が
8959 戻り値となります。@var{key}に該当するエントリが無かったり、ペアで無かった場合は
8960 ディクショナリは変更されず、@var{fallback}があればそれが戻り値となり、
8961 無ければエラーが報告されます。
8962 @c COMMON
8963 @end deffn
8964
8965 @deffn {Generic function} dict-update! (dict @code{<dictionary>}) key proc :optional fallback
8966 @c MOD gauche.dictionary
8967 @c EN
8968 Works like the following code, except that the concrete implementation
8969 may be more efficient by looking up @var{key} only once.
8970 @c JP
8971 次のコードのような動作をしますが、具体的な実装は@var{key}を一度しかルックアップ
8972 しないなどより効率良くなっている場合があります。
8973 @c COMMON
8974 @example
8975 (rlet1 x (proc (dict-get dict key fallback))
8976 (dict-put! dict key x))
8977 @end example
8978 @end deffn
8979
8980 @subsubheading Walkers
8981
8982 @deffn {Generic function} dict-fold (dict @code{<dictionary>}) proc seed
8983 @c MOD gauche.dictionary
8984 @c EN
8985 Calls a procedure @var{proc} over each entry in a dictionary @var{dict},
8986 passing a seed value. Three arguments are given to @var{proc};
8987 an entry's key, an entry's value, and a seed value. Initial
8988 seed value is @var{seed}. The value returned from @var{proc} is used
8989 for the seed value of the next call of @var{proc}. The result of the
8990 last call of @var{proc} is returned from @var{dict-fold}.
8991 @c JP
8992 @var{dict}の各要素に対して@var{proc}を呼びシード値を次に渡します。
8993 @var{proc}は引数を3つとります。エントリーのキー、エントリーの値、それ
8994 にシード値です。最初のシード値は@var{seed}です。@var{proc}からの返り値
8995 は次の@var{proc}の呼び出しでシード値として使われます。最後の@var{proc}
8996 の呼び出しの結果が@var{dict-fold}の返り値として返されます。
8997 @c COMMON
8998
8999 @c EN
9000 If @var{dict} is @code{<ordered-dictionary>}, @var{proc} is called
9001 in the way to keep the following associative order, where
9002 the key is ordered from @var{K0} (minimum) to @var{Kn} (maximum), and
9003 the corresponding values is from @var{V0} to @var{Vn}:
9004 @c JP
9005 @var{dict}が@code{<ordered-dictionary>}であれば、@var{proc}は以下のよ
9006 うな結合で呼ばれます。ここで、キーは@var{K0}(最小)から@var{Kn}(最大)ま
9007 でで、それに対応する値が@var{V0}から@var{Vn}までであるとします。
9008 @c COMMON
9009 @example
9010 (proc Kn Vn (proc Kn-1 Vn-1 ... (proc K0 V0 seed)))
9011 @end example
9012 @end deffn
9013
9014 @deffn {Generic function} dict-fold-right (dict @code{<ordered-dictionary>}) proc seed
9015 @c MOD gauche.dictionary
9016 @c EN
9017 Like @code{dict-fold}, but the associative order of applying @var{proc}
9018 is reversed as follows:
9019 @c JP
9020 @code{dict-fold}と同じですが、@var{proc}を適用する結合の順が以下のよう
9021 に逆になります。
9022 @c COMMON
9023 @example
9024 (proc K0 V0 (proc K1 V1 ... (proc Kn Vn seed)))
9025 @end example
9026
9027 @c EN
9028 This generic function is only defined on @code{<ordered-dictionary>}.
9029 @c JP
9030 このジェネリック関数は@code{<ordered-dictionary>}上にのみ定義されてい
9031 ます。
9032 @c COMMON
9033 @end deffn
9034
9035 @deffn {Generic function} dict-for-each (dict @code{<dictionary>}) proc
9036 @c MOD gauche.dictionary
9037 @c EN
9038 Calls @var{proc} with a key and a value of every entry in
9039 the dictionary @var{dict}. For ordered dictionaries, @var{proc}
9040 is guaranteed to be called in the increasing order of keys.
9041 @c JP
9042 ディクショナリ@var{dict}の各エントリーのキーと値に対して@var{proc}を呼
9043 びます。順序付きディクショナリに対しては@var{proc}がキーの昇順に呼ばれ
9044 ることが保証されています。
9045 @c COMMON
9046 @end deffn
9047
9048 @deffn {Generic function} dict-map (dict @code{<dictionary>}) proc
9049 @c MOD gauche.dictionary
9050 @c EN
9051 Calls @var{proc} with a key and a value of every entry in
9052 the dictionary @var{dict}, and gathers the result into a list
9053 and returns it. For ordered dictionaries, the result is in
9054 the increasing order of keys (it doesn't necessarily mean @var{proc}
9055 is called in that order).
9056 @c JP
9057 ディクショナリ@var{dict}の各エントリーのキーと値に対して@var{proc}を呼
9058 び、結果をリストにまとめて返します。順序付きディクショナリに対しては結
9059 果が最初のキーの順にならびます(が、@var{proc}がキーの昇順に呼ばれるこ
9060 とを保証するものではありません)。
9061 @c COMMON
9062 @end deffn
9063
9064 @deffn {Generic function} dict-keys (dict @code{<dictionary>})
9065 @deffnx {Generic function} dict-values (dict @code{<dictionary>})
9066 @c MOD gauche.dictionary
9067 @c EN
9068 Returns a list of all keys or values of a dictionary @var{dict},
9069 respectively. For ordered dictionaries, the returned list is
9070 in the increasing order of keys.
9071 @c JP
9072 それぞれ@var{dict}内にあるすべてのキーのリスト、すべての値のリストを返
9073 します。順序付きディクショナリについてはリストの要素はキーの昇順になら
9074 んでいます。
9075 @c COMMON
9076 @end deffn
9077
9078 @deffn {Generic function} dict->alist (dict @code{<dictionary>})
9079 @c MOD gauche.dictionary
9080 @c EN
9081 Returns a list of pairs of key and value in the dictionary.
9082 The order of pairs is undefined.
9083 @c JP
9084 ディクショナリ中の各キーと値の対のリストを返します。対の順番は未定義です。
9085 @c COMMON
9086 @end deffn
9087
9088 @subsubsection Defining dictionary protocol
9089
9090 @defmac define-dict-interface dict-class method proc method2 proc2 @dots{}
9091 @c MOD gauche.dictionary
9092 @c EN
9093 Many dictionary-like datatypes already has their own procedures
9094 that directly corresponds to the generic dictionary API, and adding
9095 dictionary interface tends to become a simple repetition of
9096 @code{define-method}s, like this:
9097 @c JP
9098 ディクショナリ的な性質を持つデータ型はそれぞれ独自の操作手続きを持っていて、
9099 しかもその多くはジェネリックなディクショナリAPIに直接対応しています。
9100 そうなると、ディクショナリインタフェースを実装するコードは
9101 ひたすら@code{define-method}で以下のような似たようなコードを並べてゆくことになりがちです。
9102 @c COMMON
9103
9104 @example
9105 (define-method dict-put! ((dict <my-dict>) key value)
9106 (my-dict-put! key value))
9107 @end example
9108
9109 @c EN
9110 The @code{define-dict-interface} macro is a convenient way to
9111 define those methods in a batch. Each @var{method} argument is
9112 a keyword that corresponds to @code{dict-@var{method}}, and @var{proc}
9113 is the name of the datatype-specific procedure. Here's the definition
9114 of dict interface for @code{<tree-map>} and you'll get the idea.
9115 You don't need to provide every dictionary interface.
9116 @c JP
9117 @code{define-dict-interface}はこれらのメソッドを一気に定義する簡単な方法です。
9118 各@var{method}引数は対応する@code{dict-@var{method}}メソッドに対応し、
9119 @var{proc}がそのメソッドの操作を提供するデータ型特有の手続きです。
9120 例えば@code{<tree-map>}のディクショナリインタフェース定義は以下の通りです。
9121 これを見れば要領はわかるでしょう。全てのディクショナリインタフェースをこのマクロで
9122 定義する必要はありません。
9123 @c COMMON
9124
9125 @smallexample
9126 (define-dict-interface <tree-map>
9127 :get tree-map-get
9128 :put! tree-map-put!
9129 :delete! tree-map-delete!
9130 :clear! tree-map-clear!
9131 :comparator tree-map-comparator
9132 :exists? tree-map-exists?
9133 :fold tree-map-fold
9134 :fold-right tree-map-fold-right
9135 :for-each tree-map-for-each
9136 :map tree-map-map
9137 :keys tree-map-keys
9138 :values tree-map-values
9139 :pop! tree-map-pop!
9140 :push! tree-map-push!
9141 :update! tree-map-update!
9142 :->alist tree-map->alist
9143 :transparent? (^_ #t))
9144 @end smallexample
9145 @end defmac
9146
9147
9148 @node Generic dictionaries, , Generic functions for dictionaries, Dictionary framework
9149 @subsection Generic dictionaries
9150 @c NODE 汎用ディクショナリ
9151
9152 @subsubheading Bimap
9153
9154 @deftp {Class} <bimap>
9155 @clindex bimap
9156 @c MOD gauche.dictionary
9157 @c EN
9158 Provides a bidirectional map (@emph{bimap}), a relation between two
9159 set of values, of which you can lookup both ways.
9160 @c JP
9161 2つの値のセットを持ち、一方の値をもう一方の値にマップする
9162 双方向マップ(@emph{bimap})を提供します。
9163 @c COMMON
9164
9165 @c EN
9166 Internally, a bimap consists of two dictionaries, @emph{left} map
9167 and @emph{right} map. Think a bimap as a relation between @var{x}s
9168 and @var{y}s. The left map takes an @var{x} as a key and returns
9169 corresponding @var{y} as its value. The right map takes an @var{y}
9170 as a key and returns corresponding @var{x} as its value.
9171 @c JP
9172 内部的には、bimapは二つのディクショナリ、@emph{left}マップと@emph{right}マップを
9173 持っています。bimapが@var{x}と@var{y}の関係を保持しているとすれば、
9174 leftマップは@var{x}をキーとして対応する@var{y}を返し、
9175 rightマップは@var{y}をキーとして対応する@var{x}を返します。
9176 @c COMMON
9177
9178 @c EN
9179 Currently, @code{<bimap>} only supports strict one-to-one mapping.
9180 Mutating interface (@code{bimap-*-put!}, @code{bimap-*-delete!} etc.)
9181 modifies both left and right maps to maintain this one-to-one mapping.
9182 (In future, we may provide an option to make many-to-one and
9183 many-to-many mappings).
9184 @c JP
9185 @code{<bimap>}は今のところ、厳密な1対1対応のみを扱います。
9186 マップを変更する手続き(@code{bimap-*-put!}, @code{bimap-*-delete!}等)
9187 は両方のマップを変更し、1対1対応が保たれるようにします。
9188 (将来的に、1対nやn対mの対応もサポートするかもしれません)。
9189 @c COMMON
9190
9191 @c EN
9192 A bimap can be used as a dictionary, with the generic dictionary
9193 functions such as @code{dict-get}. In such cases, the left map takes
9194 precedence; that is, the key given to @code{dict-get} etc. is
9195 regarded as the key to the left map.
9196 @c JP
9197 bimapは単なるディクショナリとして、
9198 @code{dict-get}等のディクショナリインタフェースを使って操作することもできます。
9199 その場合はleftマップが見えます。すなわち@code{dict-map}に渡されるキーは
9200 leftマップへのキーとなります。
9201 @c COMMON
9202 @end deftp
9203
9204 @defun make-bimap left-map right-map :key on-conflict
9205 @c MOD gauche.dictionary
9206 @c EN
9207 Creates a new bimap consists of two dictionaries, @var{left-map}
9208 and @var{right-map}. It is the caller's responsibility to
9209 choose appropriate type of dictionaries; for example, if you want
9210 to create a relation between a string and a number, you man want
9211 to create it like this:
9212 @c JP
9213 二つのディクショナリ、@var{left-map}と@var{right-map}から新たなbimapを作って
9214 返します。用途に応じた適切なディクショナリを選ぶのは呼出側の責任です。
9215 例えば文字列と数値の関係を保持したいなら、一つの方法は以下のとおりです。
9216 @c COMMON
9217
9218 @example
9219 (make-bimap (make-hash-table 'string=?) ; string -> number
9220 (make-hash-table 'eqv?)) ; number -> string
9221 @end example
9222
9223 @c EN
9224 The keyword argument @var{on-conflict} specifies what will happen
9225 when the added entry would conflict the existing entries.
9226 The following values are allowed:
9227 @c JP
9228 キーワード引数@var{on-conflict}は、追加されたエントリが既存のエントリと
9229 衝突する場合の振る舞いを指定します。以下の値が有効です。
9230 @c COMMON
9231
9232 @table @code
9233 @item :supersede
9234 @c EN
9235 This is the default behavior. Duplicate relations are silently
9236 removed in order to maintain one-to-one mapping. For example,
9237 suppose a bimap between strings and numbers has had
9238 @code{("foo", 1)} and @code{("bar", 2)}. When you try to
9239 put @code{("bar", 2)} with this option, the first two entries
9240 are removed. Returns @code{#t}.
9241 @c JP
9242 デフォルトの振る舞いです。重複するエントリは、1対1対応を維持するために取り除かれます。
9243 例えば文字列と数値のbimapが、@code{("foo", 1)}および@code{("bar", 2)}という
9244 組み合わせを保持していたとします。ここで@code{("bar", 2)}を追加しようとすると、
9245 最初の2つのエントリは黙って削除され、@code{("bar", 2)}だけがbimapに残ります。
9246 このオプションを与えた場合、変更手続きは常に@code{#t}を返します。
9247 @c COMMON
9248
9249 @item :error
9250 @c EN
9251 Raises an error when duplicate relations can occur.
9252 @c JP
9253 重複エントリが発生する場合はエラーが投げられます。
9254 @c COMMON
9255
9256 @item #f
9257 @c EN
9258 When duplicate relations can occur, does nothing and returns @code{#f}.
9259 @c JP
9260 重複エントリが発生し得る場合は、何も変更を行わず、変更手続きは@code{#f}を返します。
9261 @c COMMON
9262 @end table
9263
9264 @c EN
9265 Note: At this moment, an attempt to add a relation exactly same as the
9266 existing one is regarded as a conflict. This limitation may be
9267 lifted in future.
9268 @c JP
9269 註: 今のところ、既に存在する関係とまったく同じ関係を追加しようとした場合は
9270 衝突とみなされます。これは将来変更されるかもしれません。
9271 @c COMMON
9272 @end defun
9273
9274 @defun bimap-left bimap
9275 @defunx bimap-right bimap
9276 @c MOD gauche.dictionary
9277 @c EN
9278 Returns the left or right map of @var{bimap}, respectively.
9279 Do not mutate the returned map, or you'll break
9280 the consistency of the bimap.
9281 @c JP
9282 bimapのleftマップとrightマップをそれぞれ返します。
9283 返されたディクショナリを呼出側で変更してはなりません。
9284 @c COMMON
9285 @end defun
9286
9287 @defun bimap-left-get bimap key :optional default
9288 @defunx bimap-right-get bimap key :optional default
9289 @c MOD gauche.dictionary
9290 @c EN
9291 Lookup the value corresponding to the @var{key} in the left or right
9292 map of @var{bimap}. If no entry is found for @var{key},
9293 @var{default} is returned if provided, otherwise an error is
9294 raised.
9295 @c JP
9296 それじれ、@var{bimap}のleftマップまたはrightマップから@var{key}をルックアップして
9297 対応する値を返します。@var{key}を持つエントリが無い場合、
9298 @var{default}が与えられていればその値を返し、そうでなければエラーを投げます。
9299 @c COMMON
9300 @end defun
9301
9302 @defun bimap-left-exists? bimap key
9303 @defunx bimap-right-exists? bimap key
9304 @c MOD gauche.dictionary
9305 @c EN
9306 Returns @code{#f} if the left or right map of @var{bimap} has an entry of
9307 the key, @code{#t} otherwise.
9308 @c JP
9309 それぞれ、@var{key}が@var{bimap}のleftマップまたはrightマップに存在すれば
9310 @code{#t}を、そうでなければ@code{#f}を返します。
9311 @c COMMON
9312 @end defun
9313
9314 @defun bimap-put! bimap x y :key on-conflict
9315 @c MOD gauche.dictionary
9316 @c EN
9317 Put a relation (@var{x}, @var{y}) into the bimap.
9318 After this, @code{(bimap-left-get @var{x})} will return @var{y},
9319 and @code{(bimap-right-get @var{y})} will return @var{x}.
9320 @c JP
9321 関係(@var{x}, @var{y})をbimapに格納します。
9322 この呼び出しの後では、@code{(bimap-left-get @var{x})}が@var{y}を、
9323 @code{(bimap-right-get @var{y})}が@var{x}を返すようになります。
9324 @c COMMON
9325
9326 @c EN
9327 If the bimap already have relations with @var{x} and/or @var{y},
9328 the conflict is handled according to the value of @var{on-conflict};
9329 see @code{make-bimap} for the possible values and their meanings.
9330 The @var{on-conflict} keyword argument can override the
9331 bimap's default setting specified at its creation time.
9332 @c JP
9333 bimapの中に既に関係 (@var{x}, _) もしくは関係 (_, @var{y}) が
9334 含まれていた場合、その衝突の解決は@var{on-conflict}引数によって指定できます。
9335 可能な値は@code{make-bimap}の項を参照してください。@var{on-conflict}引数が
9336 与えられなければbimap作成時の@var{on-conflict}の値が使われます。
9337 @c COMMON
9338 @end defun
9339
9340 @defun bimap-left-delete! bimap key
9341 @defunx bimap-right-delete! bimap key
9342 @c MOD gauche.dictionary
9343 @c EN
9344 Deletes an relation with the given left key or right key from @var{bimap}.
9345 Both left and right maps are modified so that the consistency is maintained.
9346 If there's no relations with given key, these are noop.
9347 @c JP
9348 それぞれ、leftマップもしくはrightマップで@var{key}を持つエントリを@var{bimap}から
9349 削除します。エントリが削除されたら、もう逆方向のマップでも対応するエントリが削除され、
9350 一貫性が保たれます。与えられたキーに対応するエントリが無ければ何もしません。
9351 @c COMMON
9352 @end defun
9353
9354 @c EN
9355 @subsubheading Stacked map
9356 @c JP
9357 @subsubheading スタックマップ
9358 @c COMMON
9359
9360 @deftp {Class} <stacked-map>
9361 @c MOD gauche.dictionary
9362 @c EN
9363 Stacked map allows you to stack (layer) multiple maps (dictionaries)
9364 and treat as if they are a single map.
9365 The upper map "shadows" the lower maps. Think of nested scopes, for
9366 example.
9367 @c JP
9368 スタックマップは、複数のマップ(ディクショナリ)を積み重ねてひとつのマップのように見せます。
9369 上にあるマップがより下のマップを「シャドウ」します。
9370 例えばネストしたスコープを思い浮かべてください。
9371 @c COMMON
9372
9373 @c EN
9374 As a dictionary, it behaves as follows:
9375 @c JP
9376 ディクショナリとしては、次のように振る舞います。
9377 @c COMMON
9378
9379 @itemize @bullet
9380 @item
9381 @c EN
9382 The @code{dict-get} operation searches the given key from the top
9383 dictionary to the bottom dictionary, returns the first found entry.
9384 @c JP
9385 @code{dict-get}は与えれたキーを一番上のマップから順に探し、
9386 エントリが見つかれば直ちにその値を返します。
9387 @c COMMON
9388 @item
9389 @c EN
9390 The @code{dict-put!} operation always put the entry to the topmost
9391 dictionary. If there's an entry with the same key exists in a
9392 lower dictionary, it will be shadowed.
9393 If you want to alter the existing entry of non-top dictionary,
9394 use @code{stacked-map-entry-update!}.
9395 @c JP
9396 @code{dict-put!}は常に最上位のマップにエントリを追加します。
9397 より下のマップに同じキーを持つエントリがあった場合、それはシャドウされることになります。
9398 最上位以外のマップのエントリを変更したい場合は、
9399 下の@code{stacked-map-entry-update!}を使ってください。
9400 @c COMMON
9401 @item
9402 @c EN
9403 The @code{dict-delete!} operations deletes all the entries with the
9404 given key from all the dictionaries. This is for consistency as
9405 a dictionary---you don't want an entry pop up after deleting it.
9406 If you want to delete only from the first entry in the stack,
9407 use @code{stacked-map-entry-delete!}.
9408 @c JP
9409 @code{dict-delete!}は、全てのマップから指定のキーを持つエントリを削除します。
9410 これはディクショナリとしての一貫性のためです。最初に見つかったエントリだけを
9411 削除した場合、より下層のマップに同じキーがあれば、消したはずのキーが消えてないという
9412 ことになってしまいます。最初に見つかったエントリだけを消したい場合は
9413 @code{stacked-map-entry-delete!}を使ってください。
9414 @c COMMON
9415 @item
9416 @c EN
9417 The @code{dict-fold} operation traverse all the dictionaries
9418 from top to bottom. When there are duplicate keys, the second and after
9419 will be skipped.
9420 @c JP
9421 @code{dict-fold}は、全てのディクショナリを最上位から順に辿ります。
9422 ただし、複数のマップに同じキーがあった場合、最初のエントリ以外は無視します。
9423 @c COMMON
9424 @end itemize
9425 @end deftp
9426
9427 @defun make-stacked-map dic dic2 @dots{}
9428 @defunx make-stacked-map key-comparator dic dic2 @dots{}
9429 @c MOD gauche.dictionary
9430 @c EN
9431 Creates a new stacked map with the given dictionaries
9432 @var{dic} @var{dic2} @dots{}, where @var{dic} is the topmost dictionary.
9433 You can give a comparator
9434 @var{key-comparator} to be used to compare keys during
9435 traversal with @code{dict-fold}. If @var{key-comparator} is
9436 omitted, the comparator from @var{dic} is used.
9437 The key comparator is returned from @code{dict-comparator}
9438 on the stacked map.
9439 @c JP
9440 与えられたディクショナリ@var{dic} @var{dic2} @dots{}からなる新たなスタックマップを
9441 作って返します。最初に指定されたディクショナリが一番上のディクショナリとなります。
9442 @code{dict-fold}で使われるキーの比較には@var{key-comparator}が使われます。
9443 @var{key-comparator}が省略された場合には、@var{dic}の比較器が使われます。
9444 @code{dict-comparator}をスタックマップに適用するとこのキー比較器が返されます。
9445 @c COMMON
9446 @end defun
9447
9448 @deffn {Method} stacked-map-stack (smap <stacked-map>) (dic <dictionary>)
9449 @c MOD gauche.dictionary
9450 @c EN
9451 Creates a new stacked map, adding @var{dic} on top of the existing
9452 stacked map @var{smap}. The key comparator is inherited from
9453 @var{smap}.
9454 @c JP
9455 スタックマップ@var{smap}の上に@var{dic}を追加した新たなスタックマップを作って返します。
9456 キー比較器は@var{smap}から引き継がれます。
9457 @c COMMON
9458 @end deffn
9459
9460 @deffn {Method} stacked-map-push! (smap <stacked-map>) (dic <dictionary>)
9461 @c MOD gauche.dictionary
9462 @c EN
9463 Adds @var{dic} on top of the dictionaries @var{smap} holds.
9464 @c JP
9465 スタックマップ@var{smap}の保持するディクショナリスタックの一番上に@var{dic}を追加します。
9466 @c COMMON
9467 @end deffn
9468
9469 @deffn {Method} stacked-map-pop! (smap <stacked-map>)
9470 @c MOD gauche.dictionary
9471 @c EN
9472 Remove the topmost dictionary @var{smap} holds. An error is signaled
9473 if you attempt to pop from an @var{smap} that has no dictionaries.
9474 @c JP
9475 スタックマップ@var{smap}の一番上のディクショナリを取り除きます。
9476 @var{smap}のディクショナリリストが空の場合はエラーが投げられます。
9477 @c COMMON
9478 @end deffn
9479
9480 @deffn {Method} stacked-map-depth (smap <stacked-map>)
9481 @c MOD gauche.dictionary
9482 @c EN
9483 Returns a number of dictionaries @var{smap} has.
9484 @c JP
9485 @var{smap}の持つディクショナリの数を返します。
9486 @c COMMON
9487 @end deffn
9488
9489 @deffn {Method} stacked-map-entry-update! (smap <stacked-map>) key proc :optional fallback
9490 @c MOD gauche.dictionary
9491 @c EN
9492 Run @code{(dict-update! d @var{key} @var{proc} @var{fallback})} on the
9493 first dictionary @code{d} that has the given key.
9494 @c JP
9495 与えられたキー@var{key}を持つ最初のディクショナリ@code{d}に対して
9496 @code{(dict-update! d @var{key} @var{proc} @var{fallback})}を呼び出します。
9497 @c COMMON
9498
9499 @c EN
9500 This differs from running @code{dict-update!} on @var{smap}; if the topmost
9501 dictionary doesn't have an entry with @var{key} but some lower dictionary has,
9502 @code{dict-update!} takes the existing value and applies @var{proc} to it,
9503 then insert the result to the topmost dictionary, while the original entry
9504 remains intact.
9505 @c JP
9506 これは@var{smap}に@code{dict-update!}を適用するのとは異なります。
9507 @var{key}が一番上のディクショナリにはなく、しかし他のディクショナリにあった場合、
9508 @code{dict-update!}は@var{proc}を呼び出した後、その結果を
9509 一番上のディクショナリに挿入し、他のエントリはそのままにします。
9510 @c COMMON
9511 @end deffn
9512
9513 @deffn {Method} stacked-map-entry-delete! (smap <stacked-map>) key
9514 @c MOD gauche.dictionary
9515 @c EN
9516 Deletes the first entry with @var{key}. If there's another entry
9517 with @var{key} in a lower dictionary, it will become visible.
9518 @c JP
9519 @var{key}を持つ最初のエントリを削除します。もし他のディクショナリに@var{key}を持つ
9520 エントリがあった場合、以降はそれが見えることになります。
9521 @c COMMON
9522
9523 @c EN
9524 This differs from running @code{dict-delete!} on @var{smap}; it
9525 deletes all entries with @var{key}, so that @code{dict-exists?}
9526 after @code{dict-delete!} is guaranteed to return @code{#f}.
9527 @c JP
9528 これは@var{smap}に@code{dict-delete!}を適用するのとは異なります。
9529 @code{dict-delete!}は@var{key}を持つ全てのエントリを削除します。
9530 従って@code{dict-delete!}の後に@code{dict-exists?}でキーを問い合わせると
9531 必ず@code{#f}が返ります。
9532 @c COMMON
9533 @end deffn
9534
9535
9536 @c ----------------------------------------------------------------------
9537 @node Low-level file operations, Generators, Dictionary framework, Library modules - Gauche extensions
9538 @section @code{gauche.fcntl} - Low-level file operations
9539 @c NODE 低レベルファイル操作, @code{gauche.fcntl} - 低レベルファイル操作
9540
9541 @deftp {Module} gauche.fcntl
9542 @mdindex gauche.fcntl
9543 @c EN
9544 Provides interface for low-level filesystem operations,
9545 including @code{fcntl(2)}.
9546 @c JP
9547 @code{fcntl(2)}を含む、低レベルのファイルシステム操作のインタフェースを提供します。
9548 @c COMMON
9549 @end deftp
9550
9551 @defun sys-fcntl port-or-fd operation :optional arg
9552 @c MOD gauche.fcntl
9553 @c EN
9554 Performs certain operation on the file specified by @var{port-or-fd},
9555 which should be a port object or an integer
9556 that specifies a system file descriptor. If it is a port, it must
9557 be associated to the opened file (i.e. @code{port-type}
9558 returns @code{file}, see @ref{Common port operations}).
9559
9560 The operation is specified by an integer @var{operation}.
9561 Several variables are defined for valid @var{operation}.
9562 @c JP
9563 @var{port-or-fd} で指定されたファイルに対して特定の操作をおこないます。
9564 ファイル指定は、ポートオブジェクトもしくはシステムのファイルディスクリプタ
9565 である整数でなくてはなりません。それがポートである場合には、すでにオープン
9566 されたファイルを結びついていなければなりません。
9567 (@code{port-type} が @code{file} を返すようなポートということです。
9568 @ref{Common port operations}参照。)
9569
9570 操作は整数 @var{operation} で指定します。
9571 いくつかの変数が定義されいて、@var{operation} に使用できます。
9572 @c COMMON
9573
9574 @table @code
9575 @item F_GETFD
9576 @vindex F_GETFD
9577 @vindex FD_CLOEXEC
9578 @c EN
9579 Returns flags associated to the file descriptor of @var{port-or-fd}.
9580 The optional argument @var{arg} is not used. The return value is
9581 an integer whose definition is system specific, except one flag,
9582 @code{FD_CLOEXEC}, which indicates the file descriptor should be
9583 closed on @code{exec}. See the manual entry of @code{fcntl(2)} of
9584 your system for the details.
9585 @c JP
9586 @var{port-or-fd} のファイルディスクリプタに結びついているフラグを返します。
9587 オプション引数の@var{arg}は使われません。返り値は整数で、その定義はシステム
9588 によります。ただし、@code{FD_CLOEXEC}だけは例外で、これは@code{exec}で
9589 クローズされたことを示しています。
9590 詳しくはあなたのシステムの@code{fcntl(2)}のマニュアルエントリを
9591 参照してください。
9592 @c COMMON
9593
9594 @item F_SETFD
9595 @vindex F_SETFD
9596 @c EN
9597 Sets the file descriptor flags given as @var{arg} to @var{port-or-fd}.
9598 For example, the portable way of setting @code{FL_CLOEXEC} flag is
9599 as follows:
9600 @c JP
9601 @var{port-or-fd}のファイルディスクリプタのフラグを与えられた@var{arg}に
9602 します。たとえば、@code{FL_CLOEXEC}フラグを設定する、互換性のある方法では
9603 次のようにします。
9604 @c COMMON
9605 @example
9606 (sys-fcntl port F_SETFD
9607 (logior FD_CLOEXEC
9608 (sys-fcntl port F_GETFD)))
9609 @end example
9610
9611 @item F_GETFL
9612 @vindex F_GETFL
9613 @c EN
9614 Returns flags associated to the open files specified by @var{port-or-fd}.
9615 The flags includes the following information:
9616 @c JP
9617 @var{port-or-fd}によって指定されたオープンしたファイルに結びついている
9618 フラグを返します。このフラグには以下のような情報が含まれています。
9619 @c COMMON
9620
9621 @itemize @bullet
9622 @item
9623 @vindex O_ACCMODE
9624 @vindex O_RDONLY
9625 @vindex O_WRONLY
9626 @vindex O_RDWR
9627 @c EN
9628 File access mode. When masked by @code{O_ACCMODE},
9629 it's either one of @code{O_RDONLY}, @code{O_WRONLY} or @code{O_RDWR}.
9630 @c JP
9631 ファイルのアクセスモード。@code{O_ACCMODE} でマスクしたとき、
9632 これは、@code{O_RDONLY}、@code{O_WRONLY}、@code{O_RDWR}のうちどれかひとつです。
9633 @c COMMON
9634 @item
9635 @vindex O_CREAT
9636 @vindex O_EXCL
9637 @vindex O_TRUNC
9638 @c EN
9639 File creation options. @code{O_CREAT}, @code{O_EXCL} and/or
9640 @c JP
9641 ファイルの作成オプション。@code{O_CREAT}、@code{O_EXCL}のどちらか、または両方。
9642 @c COMMON
9643 @code{O_TRUNC}.
9644 @item
9645 @vindex O_APPEND
9646 @c EN
9647 Whether appending is allowed or not, by @code{O_APPEND}
9648 @c JP
9649 @code{O_APPEND}でマスクしたとき、追記が許されているかどうか。
9650 @c COMMON
9651 @item
9652 @vindex O_CLOEXEC
9653 @c EN
9654 Whether the file is closed automatically on @code{fork}.
9655 @c JP
9656 @code{fork}した時にファイルが自動的にクローズされるかどうか。
9657 @c COMMON
9658 @item
9659 @vindex O_NONBLOCK
9660 @c EN
9661 Whether I/O is blocking or non-blocking, by @code{O_NONBLOCK}.
9662 @c JP
9663 @code{O_NONBLOCK}でマスクしたとき、I/O が非ブロックモードかブロックモードか。
9664 @c COMMON
9665 @item
9666 @vindex O_NOCTTY
9667 @c EN
9668 Whether it grabs terminal control, by @code{O_NOCTTY}.
9669 @c JP
9670 @code{O_NOCTTY}でマスクしたとき、端末制御を切離しているかどうか。
9671 @c COMMON
9672 @item
9673 @vindex O_NOFOLLOW
9674 @c EN
9675 Let the system call fail with @code{ELOOP}
9676 when the pathname is a symbolink link.
9677 @c JP
9678 パス名が指しているものがシンボリックリンクなら、システムコールが@code{ELOOP}で
9679 失敗するようにする。
9680 @c COMMON
9681 @end itemize
9682
9683 @c EN
9684 The system may define system-specific flags.
9685 @c JP
9686 システムが、そのシステム特有のフラグを定義していることがあります。
9687 @c COMMON
9688
9689 @item F_SETFL
9690 @vindex F_SETFL
9691 @c EN
9692 Sets flags to the open files specified by @var{port-or-fd}.
9693 Among the flags listed above, only @code{O_NONBLOCK} and @code{O_APPEND}
9694 can be changed.
9695
9696 Note that @code{F_GETFD}/@code{F_SETFD} concern flags associated
9697 to the file descriptor itself, while @code{F_GETFL}/@code{F_SETFL}
9698 concern flags associated to the opened file itself. This makes difference
9699 when more than one file descriptor points to the same opened file.
9700 @c JP
9701 @var{port-or-fd}で指定したオープンされたファイルのフラグを設定します。
9702 上に列挙されたフラグのうち、@code{O_NONBLOCK} と @code{O_APPEND} だけが
9703 変更可能です。
9704
9705 @code{F_GETFD}/@code{F_SETFD} はファイルディスクリプタそのものに結びついた
9706 フラグについてであり、一方、@code{F_GETFL}/@code{F_SETFL} はオープンされた
9707 ファイルそのものに結びついているフラグについての操作であることに注意して
9708 ください。この違いは、2つ以上のファイルディスクリプタが同じオープンされた
9709 ファイルを指しているような場合にあらわれます。
9710 @c COMMON
9711
9712 @item F_DUPFD
9713 @vindex F_DUPFD
9714 @c EN
9715 Creates new file descriptor that points to the same file referred by
9716 @var{port-or-fd}.
9717 An integer must be provided as @var{arg}, and that specifies
9718 the minimum value of file descriptor to be assigned.
9719 @c JP
9720 @var{port-or-fd}で参照しているのと同じファイルを指す新しいファイル
9721 ディスクリプタを生成します。
9722 @var{arg}で整数を与えなければなりません。この数は割り当てられる
9723 ファイルディスクリプタの最小値を指定します。
9724 @c COMMON
9725
9726 @item F_GETLK
9727 @vindex F_GETLK
9728 @c EN
9729 The third argument must be provided and be an instance of @code{<sys-flock>}
9730 object described below. It searches the lock information specified by
9731 @var{arg}, and modifies @var{arg} accordingly.
9732 @c JP
9733 3つめの引数を与えなければなりません。これは、以下に述べる@code{<sys-flock>}
9734 オブジェクトのインスタンスでなければなりません。@var{arg}で指定された
9735 ロック情報を検索し、それにしかるべく変更します。
9736 @c COMMON
9737
9738 @item F_SETLK
9739 @itemx F_SETLKW
9740 @vindex F_SETLK
9741 @vindex F_SETLKW
9742 @c EN
9743 The third argument must be provided and be an instance of @code{<sys-flock>}
9744 object described below. Sets the advisory file lock according to
9745 @var{arg}. If the lock is successfully obtained, @code{#t} is returned.
9746 If the other process has the lock conflicting the request,
9747 @code{F_SETLK} returns @code{#f}, while @code{F_SETLKW} waits until
9748 the lock is available.
9749 @c JP
9750 3つめの引数を与えなければなりません。これは、以下に述べる@code{<sys-flock>}
9751 オブジェクトのインスタンスでなければなりません。@var{arg}にしたがって、
9752 アドバイザリロックを設定します。ロックの取得に成功すれば、@code{#t}が
9753 返ります。もし、別のプロセスがロックをもっていて要求したものと衝突した
9754 場合には @code{F_SETLK} のときは @code{#f} を返します。一方、@code{F_SETLKW}
9755 のときはロックが利用可能になるまで待ちます。
9756 @c COMMON
9757
9758 @item F_GETOWN
9759 @vindex F_GETOWN
9760 @c EN
9761 Returns the process id or process group that will receive
9762 SIGIO and SIGURG signals for events on the file descriptor.
9763 Process group is indicated by a negative value.
9764 This flag is only available on the systems that has this
9765 feature (BSD and Linux have this).
9766 @c JP
9767 当該ファイルディスクリプタ上のイベント用シグナル、SIGIO および SIGURG を
9768 受けとることになるプロセスのプロセスIDあるいはプロセスグループを返します。
9769 プロセスグループは負の値で表示されます。このフラグはシステムにこのような
9770 機能がある場合にのみ利用可能です(BSD や Linux にはこの機能があります)。
9771 @c COMMON
9772
9773 @item F_SETOWN
9774 @vindex F_SETOWN
9775 @c EN
9776 Sets the process id or process group that will receive SIGIO
9777 and SIGURG signals for events on the file descriptor.
9778 Process group is indicated by a negative value.
9779 This flag is only available on the systems that has this
9780 feature (BSD and Linux have this).
9781 Check out fcntl(2) manpage of your system for the details.
9782 @c JP
9783 当該ファイルディスクリプタ上のイベント用シグナル、SIGIO および SIGURG を
9784 受けとることになるプロセスのプロセスIDあるいはプロセスグループを設定します。
9785 プロセスグループは負の値で表示されます。このフラグはシステムにこのような
9786 機能がある場合にのみ利用可能です(BSD や Linux にはこの機能があります)。
9787 詳細については、お使いのシステムの fcntl(2) のマニュアルページをチェック
9788 してください。
9789 @c COMMON
9790
9791 @end table
9792
9793 @c EN
9794 Other value for @var{operation} causes an error.
9795 @c JP
9796 これ以外の値を @var{operation} で指定しようとするとエラーになります。
9797 @c COMMON
9798 @end defun
9799
9800 @deftp {Builtin Class} <sys-flock>
9801 @clindex sys-flock
9802 @c MOD gauche.fcntl
9803 @c EN
9804 A structure represents POSIX advisory record locking.
9805 Advisory record locking means the system may not prevents the process
9806 from operating on files that it doesn't have an appropriate lock.
9807 All the processes are expected to use @code{fcntl} to check locks
9808 before it operates on the files that may be shared.
9809
9810 The following slots are defined.
9811 @c JP
9812 POSIX のアドバイザリレコードロックを表わす構造体です。アドバイザリレコードロック
9813 というのは、適切なロックをもたないプロセスが対象ファイルを操作しても
9814 システムは関知しない、ということです。すべてのプロセスが、共有される可能性
9815 のあるファイルを操作する前にロックを@code{fcntl}を使って検査することが
9816 期待されています。
9817 @c COMMON
9818
9819 @c EN
9820 Note that @code{fcntl} lock is per-process, per-file. If you try
9821 to lock the same file more than once within the same process, it always
9822 succeeds. But it's not a recursive lock, so the process loses
9823 any locks to the file as soon as any of such lock is released,
9824 or any of such file is closed. It makes @code{fcntl} lock difficult
9825 to use in libraries. See @code{with-lock-file} (@pxref{Lock files}) for
9826 an alternative way to realize inter-process locks.
9827 @c JP
9828 @code{fcntl}によるロックは、プロセスごと、ファイルごとであることに注意してください。
9829 同一プロセス内で同じファイルを複数回ロックすることはできますが、再帰ロックではないので
9830 いずれかのロックがアンロックされるか、どこかでそのファイルがクローズされるかすると
9831 プロセスはそのファイルに対するロックを失います。これは、@code{fcntl}ロックを
9832 ライブラリで使うことを難しくします。プロセス間排他制御を実現する別の方法として
9833 @code{with-lock-file} (@ref{Lock files}参照) があります。
9834 @c COMMON
9835
9836 @defivar {<sys-flock>} type
9837 @c EN
9838 An integer represents lock type. Following variables are predefined
9839 for the valid values:
9840 @c JP
9841 ロックのタイプを表す整数です。利用可能な値として以下の変数があらかじめ
9842 定義されています。
9843 @c COMMON
9844
9845 @table @code
9846 @item F_RDLCK
9847 @vindex F_RDLCK
9848 @c EN
9849 Read locking
9850 @c JP
9851 読み込みのロック
9852 @c COMMON
9853 @item F_WRLCK
9854 @vindex F_WRLCK
9855 @c EN
9856 Write locking
9857 @c JP
9858 書き込みのロック
9859 @c COMMON
9860 @item F_UNLCK
9861 @vindex F_UNLCK
9862
9863 @c EN
9864 To remove a lock by @code{F_SETLK}, or to indicate the record is not
9865 locked by @code{F_GETLK}.
9866 @c JP
9867 @code{F_SETLK}によるロックを除去するか、あるいはレコードが@code{F_GETLK}
9868 でロックされていないことを示す。
9869 @c COMMON
9870 @end table
9871 @end defivar
9872
9873 @defivar {<sys-flock>} whence
9874 @c EN
9875 Indicates from where @code{start} is measured.
9876 @c JP
9877 @code{start}の計測が開始される位置を示す。
9878 @c COMMON
9879 @end defivar
9880
9881 @defivar {<sys-flock>} start
9882 @c EN
9883 The offset of beginning of the locked region.
9884 @c JP
9885 ロックされる領域の開始位置オフセット
9886 @c COMMON
9887 @end defivar
9888
9889 @defivar {<sys-flock>} len
9890 @c EN
9891 The number of bytes to lock. Zero means ``until EOF''.
9892 @c JP
9893 ロックされるバイト数。ゼロは「EOFまで」という意味。
9894 @c COMMON
9895 @end defivar
9896
9897 @defivar {<sys-flock>} pid
9898 @c EN
9899 An integer process id that holding the lock; used only by @code{F_GETLK}.
9900 @c JP
9901 当該のロックをもっている整数のプロセスID。@code{F_GETLK}でのみ使用。
9902 @c COMMON
9903 @end defivar
9904 @end deftp
9905
9906
9907 @defun sys-open path flags :optional mode
9908 @c MOD gauche.fcntl
9909 @c EN
9910 A low-level interface corresponds to POSIX open().
9911 Open a file named by @var{path}, and returns an integer file descriptor.
9912 The file descriptor should be closed with @code{sys-close},
9913 or can be turned into a port by @code{open-@{input|output@}-fd-oprt}
9914 and to be closed when the port is closed.
9915
9916 This is provided for the code that needs to deal with low-level fd.
9917 Unless absolutely necessary, user code should use
9918 high-level @code{open-@{input|output@}-file}.
9919
9920 The @var{flags} argument is a logical ior of
9921 bitmasks @code{O_RDONLY}, @code{O_WRONLY}, @code{O_RDWR},
9922 @code{O_APPEND}, @code{O_CREAT}, @code{O_EXCL}, @code{O_TRUNC},
9923 @code{O_CLOEXEC}, @code{O_NOCTTY}, @code{O_NOFOLLOW},
9924 @code{O_NONBLOCK} and @code{O_ASYNC}. Either one of
9925 @code{O_RDONLY}, @code{O_WRONLY} or @code{O_RDWR} must present.
9926
9927 The @var{mode} argument specifies the permission bits
9928 when a new file is created. The default is @code{#o664}.
9929 @c JP
9930 POSIX open()への低レベルインタフェースです。
9931 @var{path}で指定されるファイルをオープンして、整数のファイルディスクリプタを返します。
9932 ファイルディスクリプタは@code{sys-close}でクローズするか、
9933 @code{open-@{input|output@}-fd-oprt}でポートに変換して
9934 ポートがクローズされた時に一緒にクローズすることができます。
9935
9936 この手続きはfdを直接触る必要がある低レベルコードのために提供されています。
9937 どうしても必要な場合以外には、高レベルの@code{open-@{input|output@}-file}を使ってください。
9938
9939 @var{flags}引数は次のビットマスクの論理和です:
9940 @code{O_RDONLY}, @code{O_WRONLY}, @code{O_RDWR},
9941 @code{O_APPEND}, @code{O_CREAT}, @code{O_EXCL}, @code{O_TRUNC},
9942 @code{O_CLOEXEC}, @code{O_NOCTTY}, @code{O_NOFOLLOW},
9943 @code{O_NONBLOCK}, @code{O_ASYNC}。
9944 このうち@code{O_RDONLY}, @code{O_WRONLY}, @code{O_RDWR}のどれかひとつは
9945 指定しなければなりません。
9946
9947 @var{mode}引数はファイルが新たに作られた時のパーミッションです。
9948 デフォルトは@code{#o664}です。
9949 @c COMMON
9950 @end defun
9951
9952
9953 @defun sys-statvfs path
9954 @defunx sys-fstatvfs port-or-fd
9955 @c MOD gauche.fcntl
9956 @c EN
9957 Interface to POSIX @code{statvfs} and @code{fstatvfs}.
9958
9959 Returns information about the filesystem where @var{path}, or
9960 a file associated to @var{port-or-fd}, as @code{<sys-statvfs>} instance
9961 described below.
9962
9963 These procedures are only defined if the system supports them.
9964 You can use the feature identifier @code{gauche.sys.statvfs}
9965 for the availability (@pxref{Feature conditional}).
9966 @c JP
9967 POSIX @code{statvfs}および@code{fstatvfs}へのインタフェースです。
9968
9969 @var{path}、もしくは@var{port-or-fd}に結びついたファイルが存在するファイルシステムの情報を
9970 下に説明する@code{<sys-statvfs>}のインスタンスとして返します。
9971
9972 これらの手続きは対応するPOSIXシステムコールが提供されているシステムでのみ
9973 定義されます。使えるかどうかは、機能識別子@code{gauche.sys.statvfs}で
9974 検査できます (@ref{Feature conditional}参照)。
9975 @c COMMON
9976
9977 @example
9978 (cond-expand
9979 [gauche.sys.statvfs
9980 (... code using sys-statvfs ...)]
9981 [else
9982 (... alternative code ...)])
9983 @end example
9984 @end defun
9985
9986 @deftp {Builtin Class} <sys-statvfs>
9987 @clindex sys-statvfs
9988 @c MOD gauche.fcntl
9989 @c EN
9990 POSIX @code{struct statvfs}.
9991 This class is only defined if a feature @code{gauche.sys.statvfs} is
9992 provided.
9993 @c JP
9994 POSIXの@code{struct statvfs}です。
9995 機能識別子 @code{gauche.sys.statvfs}が提供されている場合のみ定義されます。
9996 @c COMMON
9997
9998 @defivar {<sys-statvfs>} bsize
9999 @c EN
10000 Filesystem block size.
10001 @c JP
10002 ファイルシステムのブロックサイズ。
10003 @c COMMON
10004 @end defivar
10005
10006 @defivar {<sys-statvfs>} frsize
10007 @c EN
10008 Fragment size.
10009 @c JP
10010 フラグメントサイズ。
10011 @c COMMON
10012 @end defivar
10013
10014 @defivar {<sys-statvfs>} blocks
10015 @defivarx {<sys-statvfs>} bfree
10016 @defivarx {<sys-statvfs>} bavail
10017 @c EN
10018 Number of blocks, number of free blocks, and number of free blocks
10019 for unprivileged users, in @code{frsize} units.
10020 @c JP
10021 ファイルシステムが格納できるブロック数、未使用ブロック数、
10022 非特権ユーザが使える未使用ブロック数を、@code{frsize}を単位として表します。
10023 @c COMMON
10024 @end defivar
10025
10026 @defivar {<sys-statvfs>} files
10027 @defivarx {<sys-statvfs>} ffree
10028 @defivarx {<sys-statvfs>} favail
10029 @c EN
10030 Number of inodes, number of free inodes, and number of free inodes
10031 for unprivileged users.
10032 @c JP
10033 ファイルシステム中の全inode数、未使用inode数、非特権ユーザが使える未使用inode数です。
10034 @c COMMON
10035 @end defivar
10036
10037 @defivar {<sys-statvfs>} fsid
10038 @c EN
10039 An exact integer filesystem ID.
10040 @c JP
10041 ファイルシステムID。正確な整数です。
10042 @c COMMON
10043 @end defivar
10044
10045 @defivar {<sys-statvfs>} flag
10046 @c EN
10047 An exact integer, logical IOR of the bitflags.
10048 Portable bitflag values is provided with constants
10049 @code{ST_NOSUID} a @code{ST_RDONLY}.
10050 @c JP
10051 正確な整数。ビットフラグのORです。
10052 ポータブルなビットフラグ値として、定数@code{ST_NOSUID}と@code{ST_RDONLY}が定義されています。
10053 @c COMMON
10054 @end defivar
10055
10056 @defivar {<sys-statvfs>} namemax
10057 @c EN
10058 Maximum filename length.
10059 @c JP
10060 ファイル名の長さの上限。
10061 @c COMMON
10062 @end defivar
10063 @end deftp
10064
10065 @defvr {Constant} ST_NOSUID
10066 @defvrx {Constant} ST_RDONLY
10067 @c MOD gauche.fcntl
10068 @c EN
10069 Bitflag values that can be used in @code{flag} slot of @code{<sys-statvfs>}.
10070 These constants are only defined if a feature @code{gauche.sys.statvfs} is
10071 provided.
10072
10073 If @code{ST_NOSUID} bit is on, suid and sgid bits of the files on this
10074 filesystem are ignored by @code{exec(3)}.
10075
10076 If @code{ST_RDONLY} bit is on, the filesystem is mounted read-only.
10077 @c JP
10078 @code{<sys-statvfs>}の@code{flag}スロットに使えるビットフラグ値です。
10079 これらは機能識別子 @code{gauche.sys.statvfs}が提供されている場合のみ定義されます。
10080
10081 @code{ST_NOSUID}ビットが立っていたら、@code{exec(3)}はこのファイルシステム中のファイルの
10082 suidビットとsgidビットを無視します。
10083
10084 @code{ST_RDONLY}ビットが立っていたら、このファイルシステムは読み取り専用でマウントされています。
10085 @c COMMON
10086 @end defvr
10087
10088
10089 @c ----------------------------------------------------------------------
10090 @node Generators, Hooks, Low-level file operations, Library modules - Gauche extensions
10091 @section @code{gauche.generator} - Generators
10092 @c NODE ジェネレータ, @code{gauche.generator} - ジェネレータ
10093
10094 @deftp {Module} gauche.generator
10095 @mdindex gauche.generator
10096 @c EN
10097 A generator is merely a procedure with no arguments and works
10098 as a source of a series of values. Every time it is called,
10099 it yields a value. The EOF value indicates the generator is exhausted.
10100 For example, @code{read-char} can be seen as a generator that
10101 generates characters from the current input port.
10102
10103 It is common practice to abstract the source of values in such a way,
10104 so it is useful to define utility procedures that work on the
10105 generators. This module provides them.
10106 @c JP
10107 ジェネレータは、値の列の生成器として動作する、引数を取らない手続きです。
10108 呼ばれる度に列の次の値を返します。列の終端に達した場合はEOFが返されます。
10109 例えば、@code{read-char}は、現在の入力ポートからの入力を一文字づつ返す
10110 ジェネレータと考えることができます。
10111
10112 値の列の生成源を手続きによってジェネレータとして抽象化するのは広く使われるテクニックなので、
10113 このようなジェネレータに共通して使えるユーティリティがあると便利です。
10114 このモジュールはそのために作られました。
10115 @c COMMON
10116
10117 @c EN
10118 SRFI-121 (Generators) is a subset of this module.
10119 Since @code{gauche.generator} predates SRFI-121, we have different
10120 names for some procedures; for the compatibility, we provide
10121 both names. SRFI-151 (Generators and accumulators) adds some more
10122 generator procedures, which is also included (but accumulator procedures
10123 are left to SRFI-158. @xref{R7RS generators}.)
10124 @c JP
10125 SRFI-121 (Generators) はこのモジュールのサブセットです。
10126 @code{gauche.generator}はSRFI-121より前からあったので、
10127 いくつかの手続きについては異なる名前を使っていました。互換性のため、
10128 それらの手続きは両方の名前を定義しています。
10129 SRFI-158 (Generators and accumulators)はさらに追加のジェネレータ手続きを
10130 定義していますが、それらもこのモジュールに含まれています
10131 (ただし、アキュムレータについてはSRFI-158モジュールに分けてあります。
10132 @ref{R7RS generators}参照)。
10133 @c COMMON
10134 @end deftp
10135
10136 @c EN
10137 A generator is very lightweight, and handy to implement simple
10138 on-demand calculations. However, keep in mind that it is
10139 side-effecting construct; you can't safely backtrack, for example.
10140 For more functional on-demand calculation, you can use
10141 lazy sequences (@pxref{Lazy sequences}), which is actually
10142 built on top of generators.
10143 @c JP
10144 ジェネレータは、必要になったら計算を行うようなシステムを簡単に実現でき、
10145 効率も極めて良いですが、副作用に頼った抽象化であることには注意が必要です。
10146 例えば、途中まで列を生成した後に、最初にもどってやり直す、といったことはできません。
10147 より関数的にオンデマンドの計算を行うためには、ジェネレータを使って
10148 構築された、遅延シーケンスを使うのが便利です (@ref{Lazy sequences}参照)。
10149 @c COMMON
10150
10151 @c EN
10152 The typical pattern of using generator is as follows: First you
10153 create a source or sources of the values,
10154 using one of generator constructors
10155 (@pxref{Generator constructors}) or rolling your own one. You
10156 may connect generator operators that modifies the stream of
10157 generated items as you wish (@pxref{Generator operations}).
10158 Eventually you need to extract actual values from the generator
10159 to consume; there are utility procedures provided
10160 (@pxref{Generator consumers}). Overall, you create a pipeline
10161 (or DAG) of generators that works as lazy value-propagation network.
10162 @c JP
10163 ジェネレータの典型的な使い方は次の通りです。まず値の源となる
10164 ジェネレータを作ります。これはジェネレータの生成手続きを使っても良いですし
10165 (@ref{Generator constructors}参照)、自分で一から定義しても良いでしょう。
10166 次に、生成される値を流れの途中で加工するジェネレータ操作手続きを
10167 必要に応じて繋いでゆきます(@ref{Generator operations}参照)。
10168 最終的には、ジェネレータから具体的な値を取り出して消費する必要があります。
10169 そのために便利なジェネレータ消費手続きも用意してあります
10170 @ref{Generator consumers}参照)。このように、ジェネレータ手続きを組み合わせた
10171 パイプライン(あるいは有向非循環グラフ)を作ることで、怠惰な値伝搬ネットワークを
10172 実現できます。
10173 @c COMMON
10174
10175 @menu
10176 * Generator constructors::
10177 * Generator operations::
10178 * Generator consumers::
10179 @end menu
10180
10181 @node Generator constructors, Generator operations, Generators, Generators
10182 @subsection Generator constructors
10183 @c NODE ジェネレータの生成
10184
10185 @c EN
10186 A generator isn't a special datatype but just an ordinary procedure,
10187 so you can make a generator with lambdas. This module provides
10188 some common generator constructors for the convenience.
10189 @c JP
10190 ジェネレータは特別なデータタイプではなく、普通の手続きに過ぎません。つ
10191 まり、ジェネレータはlambdaを使って作ることができます。
10192 このモジュールは、あると便利な
10193 良く使われるジェネレータの構築子を提供します。
10194 @c COMMON
10195
10196 @c EN
10197 If you want to use your procedure as a generator, note that a
10198 generator can be invoked many times even after it returns EOF once.
10199 You have to code it so that once it returns EOF, it keeps returning
10200 EOF for the subsequent calls.
10201 @c JP
10202 自分で定義した手続きをジェネレータとして使うこともできますが、
10203 ジェネレータを扱う手続きは、
10204 一度EOFを返したジェネレータを繰り返して呼び出す可能性があることに注意してください。
10205 その手続きがいったんEOFを返したら、それ以降の呼び出しに対してEOFを
10206 返し続けるよう書かなければなりません。
10207 @c COMMON
10208
10209 @c EN
10210 The result of generator constructors is merely a procedure,
10211 and printing it doesn't show much. In the examples in this section
10212 we use @code{generator->list} to convert the generator to the list.
10213 See @ref{Generator consumers} for the description of @code{generator->list}.
10214 @c JP
10215 ジェネレータ構築子が返すのは単なる手続きであり、そのまま印字しても
10216 中身が何かはわかりません。この節の例では、@code{generator->list}を使って
10217 ジェネレータをリストに変換しています。@code{generator->list}の説明は、
10218 @ref{Generator consumers}を参照してください。
10219 @c COMMON
10220
10221 @defun null-generator
10222 @c MOD gauche.generator
10223 @c EN
10224 An empty generator. Returns just an EOF object when called.
10225 @c JP
10226 空ジェネレータです。呼ばれるたびにEOFオブジェクトを返します。
10227 @c COMMON
10228 @end defun
10229
10230 @defun circular-generator arg @dots{}
10231 [SRFI-158]
10232 @c MOD gauche.generator
10233 @c EN
10234 Returns an infinite generator that repeats the given arguments.
10235 @c JP
10236 与えられた引数を繰り返し生成する、無限ジェネレータを返します。
10237 @c COMMON
10238
10239 @example
10240 (generator->list (circular-generator 1 2 3) 10)
10241 @result{} (1 2 3 1 2 3 1 2 3 1)
10242 @end example
10243
10244 @c EN
10245 Note that the above example limits the length of
10246 the converted list by 10; otherwise
10247 @code{generator->list} won't return.
10248 @c JP
10249 この例では、変換後のリストの長さを10に制限しています。そうしなければ、
10250 @code{generator->list}は制御を返さないでしょう。
10251 @c COMMON
10252 @end defun
10253
10254 @defun giota :optional (count +inf.0) (start 0) (step 1)
10255 @c MOD gauche.generator
10256 @c EN
10257 Like @code{iota} (@pxref{List constructors}), creates a generator
10258 of a series of @var{count} numbers, starting from @var{start}
10259 and increased by @var{step}.
10260 @c JP
10261 @code{iota} (@pxref{List constructors})のような、@var{start}で始まり
10262 @var{step}ずつ増加する、@var{count}個の級数のジェネレータを作成します。
10263 @c COMMON
10264
10265 @example
10266 (generator->list (giota 10 3 2))
10267 @result{} (3 5 7 9 11 13 15 17 19 21)
10268 @end example
10269
10270 @c EN
10271 If both @var{start} and @var{step} are exact, the generator
10272 yields exact numbers; otherwise it yields inexact numbers.
10273 @c JP
10274 @var{start}と@var{end}がともに正確数であれば、ジェネレータは
10275 正確数を生成します。そうでなければ非正確数を生成します。
10276 @c COMMON
10277
10278 @example
10279 (generator->list (giota +inf.0 1/2 1/3) 6)
10280 @result{} (1/2 5/6 7/6 3/2 11/6 13/6)
10281 (generator->list (giota +inf.0 1.0 2.0) 5)
10282 @result{} (1.0 3.0 5.0 7.0 9.0)
10283 @end example
10284 @end defun
10285
10286 @defun grange start :optional (end +inf.0) (step 1)
10287 @c MOD gauche.generator
10288 @c EN
10289 Similar to @code{giota}, creates a generator of a series of
10290 numbers. The series begins with @var{start}, increased by @var{step},
10291 and continues while the number is below @var{end}.
10292 @c JP
10293 @code{giota}と同様、級数ジェネレータを作成します。この級数は
10294 @var{start}に始まり、@var{step}ずつ増加して@var{end}直前まで続きます。
10295 @c COMMON
10296
10297 @example
10298 (generator->list (grange 3 8))
10299 @result{} (3 4 5 6 7)
10300 @end example
10301 @end defun
10302
10303 @defun generate proc
10304 @c MOD gauche.generator
10305 @c EN
10306 Creates a generator from coroutine.
10307 @c JP
10308 コルーチンからジェネレータを作成します。
10309 @c COMMON
10310
10311 @c EN
10312 The @var{proc} argument is a procedure that takes one argument,
10313 @var{yield}. When called, @code{generate} immediately returns
10314 a generator @var{G}. When @var{G} is called, the @var{proc} runs
10315 until it calls @var{yield}. Calling @var{yield} causes to suspend
10316 the execution of @var{proc} and @var{G} returns the value passed
10317 to @var{yield}.
10318 @c JP
10319 引数@var{proc}は、引数@var{yield}ひとつを取る手続きです。
10320 @code{generate}は、呼ばれるとジェネレータ@var{G}をただちに返します。
10321 @var{G}は呼ばれると、その中で@var{yield}が呼ばれるまで@var{proc}を
10322 実行します。@var{yield}が呼ばれると@var{proc}の実行は中断され、
10323 @var{yield}に渡した値が@var{G}から返ります。
10324 @c COMMON
10325
10326 @c EN
10327 Once @var{proc} returns, it is the end of the series---@var{G} returns
10328 eof object from then on. The return value of @var{proc} is ignored.
10329 @c JP
10330 いったん@var{proc}が返ると、それが列の終端となります---それ以降、
10331 @var{G}はEOFオブジェクトを返します。@var{proc}が返す値は無視されます。
10332 @c COMMON
10333
10334 @c EN
10335 The following code creates a generator that produces a series
10336 0, 1, and 2 (effectively the same as @code{(giota 3)} and binds
10337 it to @code{g}.
10338 @c JP
10339 次に挙げるコードは、0、1、2からなる級数を生成するジェネレータを作成し
10340 (事実上、@code{(giota 3)}と同じ)、@code{g}に束縛しています。
10341 @c COMMON
10342
10343 @example
10344 (define g
10345 (generate
10346 (^[yield] (let loop ([i 0])
10347 (when (< i 3) (yield i) (loop (+ i 1)))))))
10348
10349 (generator->list g) @result{} (0 1 2)
10350 @end example
10351 @end defun
10352
10353 @defun list->generator lis :optional start end
10354 @defunx vector->generator vec :optional start end
10355 @defunx reverse-vector->generator vec :optional start end
10356 @defunx string->generator str :optional start end
10357 @defunx uvector->generator uvec :optional start end
10358 @defunx bytevector->generator u8vector :optional start end
10359 [SRFI-158+]
10360 @c MOD gauche.generator
10361 @c EN
10362 Returns a generator that yields each item in the given argument.
10363 A generator returned from @code{reverse-*} procedures runs in
10364 reverse order.
10365 SRFI-121 defines these except @code{uvector->generator}, which can
10366 take any type of uniform vectors. The SRFI-121 version,
10367 @code{bytevector->generator}, limits the argument to @code{u8vector}.
10368 @c JP
10369 実引数の各要素を生成するジェネレータを返します。
10370 @code{reverse-*}は、逆順で値を生成します。
10371 SRFI-121は@code{uvector->generator}以外の手続きを定義しています。
10372 @code{uvector->generator}は全ての種類のユニフォームベクタを取ることができます。
10373 一方、SRFI-121も定義する@code{bytevector->generator}は@code{u8vector}だけを
10374 対象とします。
10375 @c COMMON
10376
10377 @example
10378 (generator->list (list->generator '(1 2 3 4 5)))
10379 @result{} (1 2 3 4 5)
10380 (generator->list (vector->generator '#(1 2 3 4 5)))
10381 @result{} (1 2 3 4 5)
10382 (generator->list (reverse-vector->generator '#(1 2 3 4 5)))
10383 @result{} (5 4 3 2 1)
10384 (generator->list (string->generator "abcde"))
10385 @result{} (#\a #\b #\c #\d #\e)
10386 (generator->list (uvector->generator '#u8(1 2 3 4 5)))
10387 @result{} (1 2 3 4 5)
10388 @end example
10389
10390 @c EN
10391 The generator is exhausted once all items are retrieved;
10392 the optional @var{start} and @var{end} arguments can limit the range
10393 the generator walks across; @var{start} specifies the left bound
10394 and @var{end} specifies the right bound.
10395 @c JP
10396 いったん全ての要素を取り出してしまえば
10397 そのジェネレータは空になります;省略可能引数@var{start}と@var{end}で
10398 ジェネレータがたどる範囲を制限することができます;@var{start}で
10399 左の境界を、@var{end}で右の境界を指定します。
10400 @c COMMON
10401
10402 @c EN
10403 For forward generators, the first value the generator yields
10404 is @var{start}-th element, and it ends right before @var{end}-th element.
10405 For reverse generators, the first value is the item right next
10406 to the @var{end}-th element, and the last value is the @var{start}-th
10407 element.
10408 at the last element, and reverse generators ends at the first element.
10409 @c JP
10410 正順のジェネレータでは、最初の値としてジェネレータが生成するのは
10411 @var{start}番目の要素であり、@var{end}番目の要素の直前の要素が最後に生成する
10412 値となります。逆順のジェネレータでは、最初の値は@var{end}番目の要素の
10413 すぐ隣の要素であり、最後の値が@var{start}番目の要素となります。
10414 @c COMMON
10415
10416 @example
10417 (generator->list (vector->generator '#(a b c d e) 2))
10418 @result{} (c d e)
10419 (generator->list (vector->generator '#(a b c d e) 2 4))
10420 @result{} (c d)
10421 (generator->list (reverse-vector->generator '#(a b c d e) 2))
10422 @result{} (e d c b)
10423 (generator->list (reverse-vector->generator '#(a b c d e) 2 4))
10424 @result{} (d c)
10425 (generator->list (reverse-vector->generator '#(a b c d e) #f 2))
10426 @result{} (b a)
10427 @end example
10428 @end defun
10429
10430 @defun bits->generator n :optional start end
10431 @defunx reverse-bits->generator n :optional start end
10432 @c MOD gauche.generator
10433 @c EN
10434 These procedures take an exact integer and treat it as a sequence of
10435 boolean values (0 for false and 1 for true), as @code{bits->list} does
10436 (@pxref{R7RS bitwise operations}). @code{Bits->generator} takes bits from
10437 LSB, while @code{reverse-bits->generator} takes them from MSB.
10438 @c JP
10439 これらの手続きは正確な整数を引数に取り、
10440 @code{bits->list}と同様に(@ref{R7RS bitwise operations}参照)、
10441 それを真偽値のシーケンス(0が偽、1を真)として扱います。
10442 @code{bits->generator}はLSBから、@code{reverse-bits->generator}は
10443 MSBからビットを取り出します。
10444 @c COMMON
10445
10446 @example
10447 (generator->list (bits->generator #b10110))
10448 @result{} (#f #t #t #f #t)
10449 (generator->list (reverse-bits->generator #b10110))
10450 @result{} (#t #f #t #t #f)
10451 @end example
10452
10453 @c EN
10454 The optional @var{start} and/or @var{end} arguments are used to specify
10455 the range of bitfield, LSB being 0. Unlike @code{list->generator} etc,
10456 @var{start} specifies the rightmost position (inclusive) and
10457 @var{end} specifies the leftmost position (exclusive). It is consistent
10458 with other procedures that accesses bit fields in integers
10459 (@pxref{R7RS bitwise operations}).
10460 @c JP
10461 省略可能引数@var{start}と@var{end}はビットフィールドの範囲を指定します
10462 (LSBが0)。@code{list->generator}等の同名の引数と違って、
10463 @var{start}が右端(含まれる)、@var{end}が左端(含まれない)を指定します。
10464 この指定方法は整数のビットフィールドにアクセスする他の手続きと一貫しています
10465 (@ref{R7RS bitwise operations}参照)。
10466 @c COMMON
10467
10468 @example
10469 (generator->list (bits->generator #x56 0 4)
10470 @result{} (#f #t #t #f) ; takes bit 0, 1, 2 and 3
10471 (generator->list (bits->generator #x56 4 8)
10472 @result{} (#t #f #t #f) ; takes bit 4, 5, 6 and 7
10473
10474 (generator->list (reverse-bits->generator #x56 4 8)
10475 @result{} (#f #t #f #t) ; takes bit 7, 6, 5 and 4
10476 @end example
10477
10478 @c EN
10479 Note: SRFI-151's @code{make-bitwise-generator} is similar to
10480 @code{bits->generator}, except that it produces an infinite generator.
10481 @xref{R7RS bitwise operations}.
10482 @c JP
10483 註: SRFI-151の@code{make-bitwise-generator}は
10484 @code{bits->generator}と似ていますが、生成されるジェネレータは無限ジェネレータになります。
10485 @ref{R7RS bitwise operations}参照。
10486 @c COMMON
10487 @end defun
10488
10489 @defun port->sexp-generator input-port
10490 @defunx port->line-generator input-port
10491 @defunx port->char-generator input-port
10492 @defunx port->byte-generator input-port
10493 @c MOD gauche.generator
10494 @c EN
10495 Returns a generator that reads characters or bytes from the given
10496 port, respectively. They're just
10497 @code{(cut read input-port)},
10498 @code{(cut read-line input-port)},
10499 @code{(cut read-char input-port)}
10500 and @code{(cut read-byte input-port)}, respectively,
10501 but we provide them for completeness.
10502 @c JP
10503 それぞれ文字、バイトを与えられた入力ポートから読み取るジェネレータを
10504 返します。つまり、それぞれ
10505 @code{(cut read input-port)}、
10506 @code{(cut read-line input-port)}、
10507 @code{(cut read-char input-port)}、
10508 @code{(cut read-byte input-port)}
10509 と同じですが、完全性のために提供されています。
10510 @c COMMON
10511 @end defun
10512
10513 @deffn {Generic function} x->generator obj
10514 @c MOD gauche.generator
10515 @c EN
10516 A generic version to convert any collection @var{obj} to a generator
10517 that walks across the @var{obj}. Besides, if @var{obj} is an input port,
10518 @code{port->char-generator} is called.
10519 @c JP
10520 任意のコレクション@var{obj}を、@var{obj}をたどるジェネレータに変換する
10521 ジェネリック関数版です。さらに、@var{obj}が入力ポートである場合は、
10522 @code{port->char-generator}を呼びます。
10523 @c COMMON
10524 @end deffn
10525
10526 @defun file->generator filename reader . open-args
10527 @c MOD gauche.generator
10528 @c EN
10529 Opens a file @var{filename}, and returns a generator
10530 that reads items from the file
10531 by a procedure @var{reader}, which takes one argument, an input port.
10532 The arguments @var{open-args} are passed to @code{open-input-file}
10533 @c JP
10534 ファイル@var{filename}をオープンし、入力ポートを引数に取る手続き
10535 @var{reader}によってそのファイルから読み取るジェネレータを返す。
10536 引数@var{open-args}は、@code{open-input-file}に渡されます
10537 (@ref{File ports}参照)。
10538 @c COMMON
10539
10540 @c EN
10541 The file is closed when the generator is exhausted. If a generator
10542 is abandoned before being read to the end, then the file is kept
10543 open until the generator is garbage-collected. If you want to
10544 make sure the file is closed by a certain point of time, you might want
10545 to use a reader procedure as a generator within the dynamic extent
10546 of @code{with-input-from-file} etc.
10547 @c JP
10548 ファイルは、ジェネレータが尽きたところで閉じられます。最後
10549 まで読み取る前にジェネレータが破棄された場合は、そのジェネレータ
10550 がガベージコレクタに回収されるまでファイルは開かれたままです。
10551 特定の時点までにファイルが確実にクローズしたい場合は、@code{with-input-from-file}
10552 の動的なエクステントの中で、リーダー手続きをジェネレータとして
10553 使うのが良いでしょう。
10554 @c COMMON
10555 @end defun
10556
10557 @defun file->sexp-generator filename . open-args
10558 @defunx file->char-generator filename . open-args
10559 @defunx file->line-generator filename . open-args
10560 @defunx file->byte-generator filename . open-args
10561 @c MOD gauche.generator
10562 @c EN
10563 Returns a generator that reads a series
10564 of sexps, characters, lines and bytes from a file @var{filename},
10565 respectively. These are versions
10566 of @code{file->generator} specialized by @code{read},
10567 @code{read-char}, @code{read-line} and @code{read-byte} as the
10568 @var{reader} argument.
10569 @c JP
10570 ファイル@var{filename}からそれぞれS式、文字、行、バイトの列を読むジェネ
10571 レータを返します。これらは、@code{file->generator}の@var{reader}引数に@code{read}、
10572 @code{read-char}、@code{read-line}、@code{read-byte}を渡して特定化したものです。
10573 @c COMMON
10574
10575 @c EN
10576 Like @code{file->generator}, @var{open-args}
10577 are passed to @code{open-input-file} (@pxref{File ports}).
10578 The file is closed when the generator is exhausted.
10579 @c JP
10580 @code{file->generator}同様、@var{open-args}はそのまま@code{open-input-file}に
10581 引き渡されます(@ref{File ports}参照)。ジェネレータが使い切られると、
10582 ファイルは閉じられます。
10583 @c COMMON
10584 @end defun
10585
10586 @defun gunfold p f g seed :optional tail-gen
10587 @c MOD gauche.generator
10588 @c EN
10589 A generator constructor similar to @var{unfold} (@pxref{R7RS lists}).
10590 @c JP
10591 @var{unfold}に似たジェネレータの構築子です (@ref{R7RS lists}参照)。
10592 @c COMMON
10593
10594 @c EN
10595 @var{P} is a predicate that takes a seed value and determines
10596 where to stop. @var{F} is a procedure that calculates a value
10597 from a seed value. @var{G} is a procedure that calculates the
10598 next seed value from the current seed value. @var{Tail-gen}
10599 is a procedure that takes the last seed value and returns a generator
10600 that generates the tail.
10601 @c JP
10602 @var{P}はシード値を引数に取り、いつ止まるかを決める述語です。
10603 @var{F}はシード値から値を計算する手続きです。@var{G}は現在の
10604 シード値から次のシード値を計算する手続きです。@var{Tail-gen}
10605 は最後のシード値を取り、残りを生成するジェネレータを返します。
10606 @c COMMON
10607
10608 @c EN
10609 For each call of the resulting generator, @var{p} is called with
10610 the current seed value. If it returns a true, then we see we've
10611 done, and @code{tail-gen} is called (if it is given) to get a
10612 generator for the tail. Otherwise,
10613 we apply @var{f} on the current seed value to get the value to
10614 generate, and use @var{g} to update the seed value.
10615 @c JP
10616 この関数から返されたジェネレータが呼ばれるたびに、@var{p}が現在の
10617 シード値とともに呼ばれます。これが真を返せば、やるべき事が終わっ
10618 たことがわかり、(もし与えられていたなら)@code{tail-gen}が残りを
10619 生成するジェネレータを得るために呼ばれます。さもなければ、生成する
10620 値を得るために現在のシード値に@var{f}が適用され、シード値を更新
10621 するために@var{g}が使われます。
10622 @c COMMON
10623
10624 @example
10625 (generator->list (gunfold (^s (> s 5)) (^s (* s 2)) (^s (+ s 1)) 0))
10626 @result{} '(0 2 4 6 8 10)
10627 @end example
10628 @end defun
10629
10630 @defun giterate f seed
10631 @defunx giterate1 f seed
10632 @c MOD gauche.generator
10633 @c EN
10634 Returns a generator of
10635 an infinite sequence of values where the next value is computed
10636 by applying @var{f} on the current value. The first value generated
10637 by @code{giterate} is @var{seed} itself, while the first one by
10638 @code{giterate1} is @code{(@var{f} @var{seed})}.
10639 @c JP
10640 要素が、一つ前の要素に@var{f}を適用して計算されるような値の列を無限に生成する
10641 ジェネレータを返します。@code{giterate}では最初の値は@var{seed}そのものですが、
10642 @code{giterate1}では@code{(@var{f} @var{seed})}が最初の値になります。
10643 @c COMMON
10644
10645 @example
10646 (generator->list (giterate (pa$ * 2) 1) 10)
10647 @result{} (1 2 4 8 16 32 64 128 256 512)
10648 (generator->list (giterate1 (pa$ * 2) 1) 10)
10649 @result{} (2 4 8 16 32 64 128 256 512 1024)
10650 @end example
10651
10652 @c EN
10653 The reason we have @code{giterate1} is that it's pretty efficient
10654 (up to 10% faster than @code{giterate}).
10655
10656 See also @code{literate} in @code{gauche.lazy}
10657 (@pxref{Lazy sequence utilities}).
10658 @c JP
10659 @code{giterate1}を別に用意しているのは、それが極めて速いからです
10660 (@code{giterate}に比べても10%ほど速いです)。
10661
10662 @code{gauche.lazy}の@code{literate}も参照
10663 (@ref{Lazy sequence utilities})。
10664 @c COMMON
10665 @end defun
10666
10667
10668 @subsubheading SRFI-158 compatible procedures
10669
10670 @defun generator item @dots{}
10671 [SRFI-158]
10672 @c MOD gauche.generator
10673 @c EN
10674 Returns a generator that generates @var{item} @dots{}.
10675 @c JP
10676 @var{item} @dots{} を返すジェネレータを作成します。
10677 @c COMMON
10678 @end defun
10679
10680 @defun make-iota-generator count :optional start step
10681 [SRFI-158]
10682 @c MOD gauche.generator
10683 @c EN
10684 Same as @code{giota}, except that the @var{count} argument is
10685 required.
10686 @c JP
10687 @code{giota}とほぼ同じですが、@var{count}引数は必須です。
10688 @c COMMON
10689 @end defun
10690
10691 @defun make-range-generator start :optional end stop
10692 [SRFI-158]
10693 @c MOD gauche.generator
10694 @c EN
10695 Same as @code{grange}.
10696 @c JP
10697 @code{grange}と同じです。
10698 @c COMMON
10699 @end defun
10700
10701 @defun make-coroutine-generator proc
10702 [SRFI-158]
10703 @c MOD gauche.generator
10704 @c EN
10705 Same as @code{generate}.
10706 @c JP
10707 @code{generate}と同じです。
10708 @c COMMON
10709 @end defun
10710
10711 @defun make-for-each-generator for-each obj
10712 [SRFI-158]
10713 @c MOD gauche.generator
10714 @c EN
10715 Given collection @var{obj} and walker @var{for-each}, creates a
10716 generator that retrieves one item at a time from the collection.
10717 Trivially defined as follows:
10718 @c JP
10719 コレクション@var{obj}と、それを一要素づつ処理する@var{for-each}手続きから、
10720 コレクションの要素を一つづつ生成するジェネレータを作って返します。
10721 次の定義を考えると良いでしょう。
10722 @c COMMON
10723
10724 @example
10725 (define (make-for-each-generator for-each coll)
10726 (generate (^[yield] (for-each yield coll))))
10727 @end example
10728
10729 @c EN
10730 If @var{obj} is mutated before the returned generator walks all the values,
10731 the behavior depends on how the @var{for-each} procedure handles the
10732 situation; it may or may not be safe. In general it's better to avoid
10733 mutation until the generator returns EOF. Once the generator is exhausted,
10734 though, it is safe to mutate @code{obj}.
10735 @c JP
10736 作られたジェネレータが全ての値を取り出す前に@var{obj}が変更された場合の振る舞いは、
10737 渡された@var{for-each}手続きがそのケースをどのように処理するかに依存します。
10738 それは安全かもしれないし、安全でないかもしれません。一般的に、ジェネレータが
10739 EOFを返す前に@var{obj}を変更することは避けるのが賢明です。
10740 ジェネレータがEOFを返した後に@var{obj}を変更するのは安全です。
10741 @c COMMON
10742 @end defun
10743
10744 @defun make-unfold-generator stop? mapper successor seed
10745 [SRFI-158]
10746 @c MOD gauche.generator
10747 @c EN
10748 This is the same as @code{gunfold}, except it doesn't take
10749 optional @var{tail-gen} argument.
10750 @c JP
10751 省略可能な@var{tail-gen}引数を取らないことを除けば、
10752 @code{gunfold}と同じです。
10753 @c COMMON
10754 @end defun
10755
10756
10757 @node Generator operations, Generator consumers, Generator constructors, Generators
10758 @subsection Generator operations
10759 @c NODE ジェネレータの操作
10760
10761
10762 @c EN
10763 The following procedures take generators (noted as @var{gen} and
10764 @var{gen2}) and return a generator. For the convenience, they
10765 also accept any collection to @var{gen} and @var{gen2} parameters;
10766 if a collection is passed where a generator is expected,
10767 it is implicitly coerced into a generator.
10768
10769 (NB: This is Gauche's extension. For portable SRFI-121/SRFI-158 programs,
10770 you shouldn't rely on this behavior; instead, explicitly convert
10771 collections to generators.)
10772 @c JP
10773 以下に挙げる手続きは、どれもジェネレータ(@var{gen}や@var{gen2}と記述されて
10774 います)を受け取ってジェネレータを返します。便宜上、これらの手続きは
10775 @var{gen}や@var{gen2}としてコレクションも受けつけます;ジェネレータが
10776 想定されているところにコレクションが渡されると、暗黙のうちにジェネレータ
10777 へと変換されるのです。
10778
10779 (註:これはGauche独自の拡張です。ポータブルなSRFI-121/158プログラムは、
10780 この振る舞いに依存してはいけません。明示的にコレクションをジェネレータに
10781 変換してください。)
10782 @c COMMON
10783
10784 @defun gcons* item @dots{} gen
10785 [SRFI-158]
10786 @c MOD gauche.generator
10787 @c EN
10788 Returns a generator that adds @var{item}s in front of @var{gen}.
10789 @c JP
10790 @var{gen}の前に@var{item}を追加するジェネレータを返します。
10791 @c COMMON
10792
10793 @example
10794 (generator->list (gcons* 'a 'b (giota 2)))
10795 @result{} (a b 0 1)
10796 @end example
10797 @end defun
10798
10799 @defun gappend gen @dots{}
10800 [SRFI-158]
10801 @c MOD gauche.generator
10802 @c EN
10803 Returns a generator that yields the items from the first given
10804 generator, and once it is exhausted, use the second generator, and so on.
10805 @c JP
10806 最初に与えたジェネレータが生成する値を生成し、それが尽きたら2番目に与えた
10807 ジェネレータが生成する値を生成し、という具合に、与えられたジェネレータが
10808 生成する値を順番に生成するジェネレータを返します。
10809 @c COMMON
10810
10811 @example
10812 (generator->list (gappend (giota 3) (giota 2)))
10813 @result{} (0 1 2 0 1)
10814
10815 (generator->list (gappend))
10816 @result{} ()
10817 @end example
10818 @end defun
10819
10820 @defun gconcatenate gen
10821 @c MOD gauche.generator
10822 @c EN
10823 The @var{gen} argument should generate generators and/or sequences.
10824 Returns a generator that yields elements from the first generator/sequence,
10825 then the second one, then the third, etc.
10826
10827 It is similar to @code{(apply gappend (generator->list gen))}, except
10828 that @code{gconcatenate} can work even @var{gen} generates infinite
10829 number of generators.
10830 @c JP
10831 @var{gen}引数は、ジェネレータやシーケンスを生成するジェネレータです。
10832 この関数は、@var{gen}が生成する最初のジェネレータ/シーケンスの要素を次々に
10833 生成し、それが尽きたら二番目のジェネレータ/シーケンスの要素を次々に生成し…
10834 というジェネレータを作って返します。
10835
10836 @code{(apply gappend (generator->list gen))}と似た動作ですが、
10837 @code{gconcatenate}は@var{gen}が無限ジェネレータであっても動作するという
10838 利点があります。
10839 @c COMMON
10840
10841 @example
10842 ($ generator->list $ gconcatenate
10843 $ list->generator `(,(giota 3) ,(giota 2)))
10844 @result{} (0 1 2 0 1)
10845 @end example
10846 @end defun
10847
10848 @defun gflatten gen
10849 [SRFI-158]
10850 @c MOD gauche.generator
10851 @c EN
10852 The argument @var{gen} is a generator that yields lists.
10853 This procedure returns a generator that's yield each element of the lists
10854 one at a time.
10855 @c JP
10856 引数@var{gen}はリストを生成するジェネレータです。
10857 この手続きは、入力が生成するリストの各要素をひとつづつ生成するようなジェネレータを
10858 作成して返します。
10859 @c COMMON
10860
10861 @c EN
10862 Example: The game Tetris determines the next
10863 dropping piece (tetrimino) by the following algorithm: Take a
10864 bag of tetriminos with one for each kind (O, I, T, S, Z, L, J),
10865 permute it, and draw one by one; once the bag is empty, take another
10866 bag and repeat. The algorithm can be implemented by a pipeline
10867 of generates as follows. (Tetris is a registered trademark of
10868 The Tetris Company).
10869 @c JP
10870 例: ゲームのテトリスは、次に落ちてくるピース (テトリミノ) を次の
10871 アルゴリズムで決めています: 各種類(O, I, T, S, Z, L, J)のテトリミノが
10872 一つづつ入った袋をとり、そこからランダムに一つづつ取り出す。袋が空になったら
10873 新たにテトリミノの袋をとり繰り返す。このアルゴリズムは次に示すとおり
10874 ジェネレータのパイプラインで実装できます。(テトリスはThe Tetris Companyの
10875 登録商標です)
10876 @c COMMON
10877
10878 @example
10879 (use gauche.generator)
10880 (use data.random) ; for permutations-of
10881
10882 (define g
10883 ($ gflatten $ permutations-of
10884 $ (circular-generator '(O I T S Z L J))))
10885
10886 (generator->list g 21)
10887 @result{}
10888 (L O Z T J S I J L Z T I O S T L Z S I J O)
10889 @end example
10890
10891 @c EN
10892 Note the subtle difference of this example and the example
10893 in @code{gconcatenate} above---@code{gconcatenate} takes
10894 a generator of generators, while @code{gflatten} takes
10895 a generator of lists.
10896
10897 If we use Haskell-ish type notation, you can see the subtle differences
10898 of those similar procedures:
10899 @c JP
10900 この例と、上のの@code{gconcatenate}の例を比べてみてください。微妙な違いが
10901 あります。@code{gconcatenate}は、ジェネレータを生成するジェネレータを取りますが、
10902 @code{gflatten}はリストを生成するジェネレータを取ります。
10903
10904 Haskell風の型表記を使うと、これら似た手続きの違いをわかりやすく整理することができるでしょう:
10905 @c COMMON
10906
10907 @example
10908 gappend :: (Generator a, Generator a, ...) -> Generator a
10909 (pa$ apply gappend) :: [(Generator a)] -> Generator a
10910 gconcatenate :: Generator Generator a -> Generator a
10911 gflatten :: Generator [a] -> Generator a
10912 @end example
10913 @end defun
10914
10915 @defun gmerge less-than gen gen2 @dots{}
10916 [SRFI-158]
10917 @c MOD gauche.generator
10918 @c EN
10919 Creates a generator that yields elements out of input generators,
10920 with the order determined by a procedure @code{less-than}.
10921 The procedure is called as
10922 @code{(less-than a b)} and
10923 must return @code{#t} iff the element @code{a} must precede
10924 the element @code{b}.
10925
10926 Each input generator must yield an ordered elements by itself;
10927 otherwise the result won't be ordered.
10928
10929 If only one generator is given, it is just returned (after coercing the
10930 input to a generator). In that case, @code{less-than} won't be called at all.
10931 @c JP
10932 入力ジェネレータから生成される要素を、手続き@code{less-than}で決められる順
10933 に生成するジェネレータを作って返します。
10934 @code{less-than}は入力ジェネレータの二つの要素@code{a}, @code{b}に対して
10935 呼び出され、@code{a}が@code{b}に先行すべき時のみ@code{#t}を返します。
10936
10937 入力のジェネレータはそれぞれが要素を正しい順で生成しなければなりません。
10938 そうでない場合、出力が正しい順になっていることは保証されません。
10939
10940 入力が一つだけ渡された場合は、(それをジェネレータへと型変換した後で)それがそのまま
10941 返され、@code{less-than}は呼ばれません。
10942 @c COMMON
10943
10944 @example
10945 (generator->list (gmerge < '(1 3 8) '(5) '(2 4)))
10946 @result{} '(1 2 3 4 5 8)
10947 @end example
10948 @end defun
10949
10950 @defun gmap proc gen gen2 @dots{}
10951 [SRFI-158]
10952 @c MOD gauche.generator
10953 @c EN
10954 Returns a generator that yields a value returned by @var{proc}
10955 applied on the values from given generators. The returned generator
10956 terminates when any of the given generator is exhausted.
10957 @c JP
10958 与えられたジェネレータから得られる値に@var{proc}を適用して得られる値を
10959 生成するジェネレータを返します。返り値となるジェネレータは、引数として
10960 与えられたジェネレータのどれかが尽きたら終了します。
10961 @c COMMON
10962
10963 @c EN
10964 NB: This differs from @code{generator-map} (@pxref{Folding generated values})
10965 which consumes all
10966 values at once and returns the results as a list, while @code{gmap}
10967 returns a generator immediately without consuming input.
10968 @c JP
10969 注意: この手続きは、@code{generator-map} (@ref{Folding generated values}参照)
10970 とは違います。@code{generator-map}は一度に全ての値を消費し、結果をリストとして返しますが、
10971 @code{gmap}はすぐには入力を消費せずにジェネレータを返すのです。
10972 @c COMMON
10973 @end defun
10974
10975 @defun gmap-accum proc seed gen gen2 @dots{}
10976 @c MOD gauche.generator
10977 @c EN
10978 A generator version of @code{map-accum} (@pxref{Mapping over collection}),
10979 mapping with states.
10980 @c JP
10981 状態を持つマッピングを行う@code{map-accum} (@pxref{Mapping over collection})のジェネレータ版
10982 です。
10983 @c COMMON
10984
10985 @c EN
10986 The @var{proc} argument is a procedure that takes as many arguments
10987 as the input generators plus one. It is called as
10988 @code{(proc v v2 @dots{} seed)} where @code{v}, @code{v2}, @dots{} are
10989 the values yielded from the input generators, and @var{seed} is the
10990 current seed value. It must return two values, the yielding value
10991 and the next seed.
10992 @c JP
10993 引数@var{proc}は、入力となるジェネレータの個数プラス1個の引数を取る
10994 手続きで、@code{(proc v v2 @dots{} seed)}のように呼ばれます。
10995 @code{v}, @code{v2}, @dots{} は、入力ジェネレータが生成する値であり、
10996 @var{seed}は現在のシード値です。この手続きは2つの値を返さなければい
10997 けません。生成する値と、次のシード値です。
10998 @c COMMON
10999
11000 @c EN
11001 NB: This is called @code{gcombine} in SRFI-121.
11002 @c JP
11003 註:これはSRFI-121の@code{gcombine}と同じものです。
11004 @c COMMON
11005 @end defun
11006
11007 @defun gcombine proc seed gen gen2 @dots{}
11008 [SRFI-158]
11009 @c MOD gauche.generator
11010 @c EN
11011 An alias of @code{gmap-accum}, provided for the compatibility of SRFI-121.
11012 @c JP
11013 @code{gmap-accum}の別名です。SRFI-121との互換性のため提供されています。
11014 @c COMMON
11015 @end defun
11016
11017 @defun gfilter pred gen
11018 @defunx gremove pred gen
11019 [SRFI-158]
11020 @c MOD gauche.generator
11021 @c EN
11022 Returns a generator that yields the items from the source generator
11023 @var{gen}, except those who makes @var{pred} answers false (@code{gfilter})
11024 or those who makes @var{pred} answers a true value (@code{gremove})
11025 @c JP
11026 ソースジェネレータ@var{gen}が生成する値のうち、
11027 @var{pred}がfalseを返すもの(@code{gfilter}の場合)、
11028 または@var{pred}が真の値を返すもの(@code{gremove}の場合)を
11029 除いた値を生成するジェネレータを返します。
11030 @c COMMON
11031
11032 @example
11033 (generator->list (gfilter odd? (grange 0)) 6)
11034 @result{} (1 3 5 7 9 11)
11035 (generator->list (gremove odd? (grange 0)) 6)
11036 @result{} (0 2 4 6 8 10)
11037 @end example
11038 @end defun
11039
11040 @defun gdelete item gen :optional =
11041 [SRFI-158]
11042 @c MOD gauche.generator
11043 @c EN
11044 Return a generator that yields the items from the source generator
11045 @var{gen}, except those are the same as @var{item}. The comparison
11046 is done by the procedure passed to @var{=}, which defaults to @code{equal?}.
11047 @c JP
11048 ソースジェネレータ@var{gen}が生成する値のうち、@var{item}と等しいものを
11049 取り除いた値を生成するジェネレータを返します。
11050 比較は省略可能引数@var{=}に渡す手続きで行われ、省略時には@code{equal?}が使われます。
11051 @c COMMON
11052
11053 @example
11054 ;; Note: This example relies on auto-coercing list to generator.
11055 ;; SRFI-121 requires list->generator for the second argument.
11056 (generator->list (gdelete 3 '(1 2 3 4 3 2 1)))
11057 @result{} (1 2 4 2 1)
11058 @end example
11059 @end defun
11060
11061 @defun gdelete-neighbor-dups gen :optional =
11062 [SRFI-158]
11063 @c MOD gauche.generator
11064 @c EN
11065 Returns a generator that yields the items from the source generator
11066 @var{gen}, but the consecutive items of the same value is omitted.
11067 The comparison
11068 is done by the procedure passed to @var{=}, which defaults to @code{equal?}.
11069 @c JP
11070 ソースジェネレータ@var{gen}が生成する値を生成するジェネレータを返します。
11071 但し、連続して等しいものはそのうち1つだけが生成されます。
11072 比較は省略可能引数@var{=}に渡す手続きで行われ、省略時には@code{equal?}が使われます。
11073 @c COMMON
11074
11075 @example
11076 ;; Note: This example relies on auto-coercing list to generator.
11077 ;; SRFI-121 requires string->generator for the second argument.
11078 (generator->list (gdelete-neighbor-dups "mississippi"))
11079 @result{} (#\m #\i #\s #\i #\s #\i #\p #\i)
11080 @end example
11081 @end defun
11082
11083 @defun gfilter-map proc gen gen2 @dots{}
11084 [SRFI-158]
11085 @c MOD gauche.generator
11086 @c EN
11087 Works the same as @code{(gfilter values (gmap proc gen gen2 @dots{}))},
11088 only slightly efficiently.
11089 @c JP
11090 @code{(gfilter values (gmap proc gen gen2 @dots{}))}
11091 と同様に動作しますが、若干効率的です。
11092 @c COMMON
11093 @end defun
11094
11095 @defun gstate-filter proc seed gen
11096 [SRFI-158]
11097 @c MOD gauche.generator
11098 @c EN
11099 This allows stateful filtering of a series. The @var{proc} argument
11100 must be a procedure that takes a value @var{V} from the source generator and
11101 a seed value. It should return two values, a boolean flag and the next
11102 seed value. If it returns true for the boolean flag, the generator
11103 yields @var{V}. Otherwise, the generator keeps calling @var{proc},
11104 with updating the seed value, until it sees the true flag value
11105 or the source generator is exhausted.
11106 @c JP
11107 この手続きは、一連の値に対するステートフルなフィルタリングを可能にします。
11108 引数@var{proc}はソースジェネレータからの値@var{v}と、シード値を取る手続きでなければ
11109 なりません。この手続きが真を返す場合に、返り値となるジェネレータは
11110 @var{v}を生成します。そうでない場合、ジェネレータは@var{proc}が真を返すか、ソース
11111 ジェネレータが尽きるまで、シード値を更新しながら@var{proc}を呼び出し続けます。
11112 @c COMMON
11113
11114 @c EN
11115 The following example takes a generator of oscillating values
11116 and yields only values that are greater than their previous value.
11117 @c JP
11118 次に挙げる例は、振動する値を生成するジェネレータを受け取り、直前の値よりも
11119 大きな値のみを生成するジェネレータを返します。
11120 @c COMMON
11121
11122 @example
11123 (generator->list
11124 (gstate-filter (^[v s] (values (< s v) v)) 0
11125 (list->generator '(1 2 3 2 1 0 1 2 3 2 1 0 1 2 3))))
11126 @result{} (1 2 3 1 2 3 1 2 3)
11127 @end example
11128 @end defun
11129
11130 @defun gbuffer-filter proc seed gen :optional tail-gen
11131 @c MOD gauche.generator
11132 @c EN
11133 This procedure allows n-to-m mapping between elements in input and output---
11134 that is, you can take a look at several input elements to generate
11135 one or more output elements.
11136 @c JP
11137 この手続きは入力と出力がn対mで対応するようなフィルタを作ります。つまり、
11138 入力のいくつかを見て、それに応じて1個以上の出力を生成するようなフィルタです。
11139 @c COMMON
11140
11141 @c EN
11142 The procedure @var{proc} receives the next input element and accumulated
11143 seed value. It returns two values: A list of output values, and the next
11144 seed value. If you need to look at more input to generate
11145 output, you can return an empty list as the first value.
11146 @c JP
11147 手続き@var{proc}は、次の入力およびシード値を受け取り、
11148 二つの値を返します:出力値のリスト、及び次のシード値です。
11149 出力を決定するためにもっと入力を読むことが必要なら、
11150 第一の返り値を()にします。
11151 @c COMMON
11152
11153 @c EN
11154 If the input reaches the end, @var{tail-gen} is called with the
11155 current seed value; it should return a list of last output values.
11156 If omitted, the output ends when the output of the last call to @var{proc}
11157 is exhausted (the last seed value is discarded).
11158 @c JP
11159 入力が終端に達したら、手続き@var{tail-gen}が、その時点でのシード値を引数として
11160 呼び出されます。@var{tail-gen}は出力の終端となる値のリストを返します。
11161 @var{tail-gen}が省略された場合は、入力がなくなった時点で最後の@var{proc}が
11162 返した出力のリストが終端となります(最後のシード値は捨てられます)
11163 @c COMMON
11164
11165 @c EN
11166 Suppose you have a text file. Each line contains a command,
11167 but if the line ends with backslash, next line is treated as a
11168 continuation of the current line. The following code creates
11169 a generator that returns @emph{logical} lines, that is,
11170 the lines after such line continuations are taken care of.
11171 @c JP
11172 例えば、テキストファイルがあり、各行にコマンドがかかれているとしましょう。
11173 ただし行がバックスラッシュで終わった場合、次の行へと継続しているものとみなします。
11174 以下のコードは、入力ファイルの各行を読むジェネレータから、
11175 @emph{論理行}(継続行をくっつけたもの)をひとつづつ返すジェネレータを生成します。
11176 @c COMMON
11177
11178 @example
11179 (gbuffer-filter (^[v s]
11180 (if-let1 m (#/\\$/ v)
11181 (values '() (cons (m 'before) s))
11182 (values `(,(string-concatenate-reverse (cons v s))) '())))
11183 '()
11184 (file->line-generator "input-file.txt")
11185 (^[s] `(,(string-concatenate-reverse s))))
11186 @end example
11187 @end defun
11188
11189 @defun gtake gen k :optional padding
11190 @defunx gdrop gen k
11191 [SRFI-158]
11192 @c MOD gauche.generator
11193 @c EN
11194 Returns a generator that takes or drops initial @var{k} elements
11195 from the source generator @var{gen}.
11196 @c JP
11197 それぞれ、ソースジェネレータ@var{gen}が生成する値のうち最初から@var{k}個の値を生成する、
11198 および最初から@var{k}個の値を除いた次の値から生成するようなジェネレータを
11199 作成して返します。
11200 @c COMMON
11201
11202 @c EN
11203 Those won't complain if the source generator is exhausted before generating
11204 @var{k} items. By default, the generator returned by @code{gtake}
11205 terminates as the source ends, but if you give the optional @var{padding}
11206 argument, then the returned generator does yield @var{k} items, using the
11207 value given to @var{padding} to fill the rest.
11208 @c JP
11209 これらの手続きはソースジェネレータが@var{k}個の値を生成する前に尽きたとしても、
11210 何も文句を言いません。デフォルトでは、@code{gtake}が返すジェネレータはソース
11211 ジェネレータが終端に達した時点で終了します。しかし、省略可能引数@code{padding}を与えた
11212 場合、返されるジェネレータは足りない分を@code{padding}で補うことで
11213 常に@var{k}個の値を生成します。
11214 @c COMMON
11215
11216 @c EN
11217 Note: If you pass @var{padding}, @code{gtake} always returns a generator
11218 that generates exactly @var{k} elements even the input generator is already
11219 exhausted---there's no general way to know whether you've reached
11220 the end of the input. If you need to take @var{k} items repeatedly
11221 from the input generator, you may want to use @code{gslices} below.
11222 @c JP
11223 註: @var{fill}引数を渡した場合、たとえ入力ジェネレータが終端に達していたとしても
11224 @code{gtake}が返すジェネレータは@var{k}個の値を生成します。つまりその場合、
11225 入力が使い尽くされたかどうかを判定する汎用的な方法はありません。
11226 「入力が尽きるまで@var{k}個の要素を次々に取り出したい」という場合は
11227 下に説明する@code{gslices}の方が使い勝手が良いかもしれません。
11228 @c COMMON
11229
11230 @c EN
11231 Note for the compatibility: Until 0.9.4, @code{gtake} takes two optional
11232 arguments, @var{fill?} and @var{padding}. That is consistent with
11233 Gauche's builtin @code{take*}, but incompatible to SRFI-121's @code{gtake}.
11234 We think SRFI-121's interface is more compact and intuitive, so we
11235 renamed the original one to @code{gtake*} (emphasizing
11236 the similarity to @code{take*}), and made @code{gtake} compatible to
11237 SRFI-121.
11238 To ease transition, the current @code{gtake} allows two optional arguments
11239 (four in total),
11240 in which case we assume the caller wants to call @code{gtake*}; so
11241 the code that gives two optional arguments to @code{gtake} would work in
11242 both pre-0.9.4 and 0.9.5.
11243 @c JP
11244 互換性への註: 0.9.4までは、@code{gtake}は@var{fill?}と@var{padding}の
11245 ふたつの省略可能引数を取りました。これはもともとGauche組み込み@code{take*}に合わせて
11246 いたのですが、SRFI-121に採用された@code{gtake}とは非互換になりました。
11247 SRFI-121の方が簡潔で直感的なので、0.9.5からは元の@code{gtake}を(@code{take*}との
11248 類似性を強調して)@code{gtake*}とリネームし、@code{gtake}はSRFI-121に合わせることと
11249 しました。
11250 移行をスムースにするため、@code{gtake}は二つの省略可能引数(合計4つの引数)を取ることを
11251 許します。その場合、@code{gtake*}が呼ばれたのと同じ動作になります。
11252 従って、@code{gtake}に4引数を渡している従来のコードは、0.9.5以前でも以降でも
11253 動作します。
11254 @c COMMON
11255 @end defun
11256
11257 @defun gtake* gen k :optional fill? padding
11258 @c MOD gauche.generator
11259 @c EN
11260 A variation of @code{gtake}; instead of single optional @var{padding}
11261 argument, this takes two optional arguments just like @code{take*}
11262 (@xref{List accessors and modifiers}.) Up to 0.9.4 this version
11263 is called @code{gtake}. This is provided for the backward compatibility.
11264 @c JP
11265 @code{gtake}のバリエーションで、一つの省略可能引数@var{padding}のかわりに、
11266 @code{take*}と同じように二つの省略可能引数を取ります
11267 (@ref{List accessors and modifiers}参照)。
11268 0.9.4まではこれが@code{gtake}と呼ばれていました。
11269 互換性のために名前を変えて残してあります。
11270 @c COMMON
11271 @end defun
11272
11273 @defun gtake-while pred gen
11274 @defunx gdrop-while pred gen
11275 [SRFI-158]
11276 @c MOD gauche.generator
11277 @c EN
11278 The generator version of @code{take-while} and @code{drop-while}
11279 (@pxref{List accessors and modifiers}). The generator returned
11280 from @code{gtake-while} yields items from the source generator
11281 as far as @var{pred} returns true for each. The generator returned
11282 from @code{gdrop-while} first reads items from the source generator
11283 while @var{pred} returns true for them, then start yielding items.
11284 @c JP
11285 ジェネレータ版の @code{take-while} と @code{drop-while}
11286 (@ref{List accessors and modifiers}参照) です。
11287 @code{gtake-while}が返すジェネレータは、ソースジェネレータが生成する値に対して
11288 @var{pred}が真を返す限り、その値を生成します。@code{gdrop-while}が返す
11289 ジェネレータは、まずソースジェネレータから値を読み取り、その値に対して
11290 @var{pred}が真を返したら、値の生成を開始します。
11291 @c COMMON
11292 @end defun
11293
11294 @defun gslices gen k :optional (fill? #f) (padding #f)
11295 @c MOD gauche.generator
11296 @c EN
11297 The generator version of @code{slices} (@pxref{List accessors and modifiers}).
11298 This returns a generator, that yields a list of @var{k} items from
11299 the input generator @var{gen} at a time.
11300 @c JP
11301 @code{slices}のジェネレータ版です (@ref{List accessors and modifiers}参照。
11302 入力のジェネレータ@var{gen}から@var{k}要素づつ読み出して、そのリストを生成する
11303 ジェネレータを返します。
11304 @c COMMON
11305
11306 @example
11307 (generator->list (gslices (giota 7) 3))
11308 @result{} ((0 1 2) (3 4 5) (6))
11309 @end example
11310
11311 @c EN
11312 The @var{fill?} and @var{padding} arguments controls how the end
11313 of input is handled, just like @code{gtake}. When @var{fill?} is
11314 @code{#f} (default), the last item from output generator may not
11315 have @var{k} items if the input is short to fill them, as shown
11316 in the above example. If @var{fill?} is true and the input is
11317 short to complete @var{k} items, @var{padding} argument is used
11318 to fill the rest.
11319 @c JP
11320 @var{fill?}引数と@var{padding}引数は、@code{gtake}のそれと同様に、
11321 入力が足りなかった場合の処理を指定します。デフォルトの、@var{fill?}が
11322 @code{#f}の場合、入力が@var{k}要素に満たなければ、出力の要素も
11323 切り詰められます (上の例参照)。@var{fill}が真の値であれば、
11324 入力が足りない分は@var{padding}が当てられ、出力の最後のリストも@var{k}要素になります。
11325 @c COMMON
11326
11327 @example
11328 (generator->list (gslices (giota 6) 3 #t 'x))
11329 @result{} ((0 1 2) (3 4 5))
11330 (generator->list (gslices (giota 7) 3 #t 'x))
11331 @result{} ((0 1 2) (3 4 5) (6 x x))
11332 @end example
11333 @end defun
11334
11335 @defun ggroup gen k :optional padding
11336 [SRFI-158]
11337 @c MOD gauche.generator
11338 @c EN
11339 Returns a generator lists of @var{k} elements taken from @var{gen}.
11340 If @var{padding} is omitted, it works just as @code{(gslices gen k)}.
11341 If @var{padding} is given, it works just as @code{(gslices gen k #t padding)}.
11342
11343 This is defined in SRFI-158, and more portable than @code{gslices}.
11344 @c JP
11345 @var{gen}から@var{k}要素づつ取って作ったリストを次々と生成するジェネレータを返します。
11346 @var{padding}が省略された時は@code{(gslices gen k)}と同じ、
11347 @var{padding}が与えられた時は@code{(gslices gen k #t padding)}と同じになります。
11348
11349 この手続きはSRFI-158で定義されたので、@code{gslices}よりポータブルでしょう。
11350 @c COMMON
11351 @end defun
11352
11353 @defun grxmatch regexp gen
11354 @c MOD gauche.generator
11355 @c EN
11356 The @var{gen} argument must be, after coerced, a generator that
11357 yields characters.
11358 @c JP
11359 @var{gen}は暗黙の変換後、文字を生成するジェネレータでなければなりません。
11360 @c COMMON
11361
11362 @c EN
11363 A generator returned from this procedure
11364 tries to match @var{regexp} from the character sequence
11365 generated by @var{gen}, and once it matches, remember the position after
11366 the match and returns @code{#<rxmatch>} object. If no more match
11367 is found, the generator is exhausted.
11368 @c JP
11369 この手続きが返すジェネレータは、@var{gen}が生成する文字のシーケンスに対して、
11370 @var{regexp}をマッチさせようとする。そして一度マッチすると、その位置を記憶して
11371 @code{#<rxmatch>}オブジェクトを返します。さらにマッチすることがなければ、
11372 ジェネレータは尽きます。
11373 @c COMMON
11374
11375 @example
11376 ($ generator->list
11377 $ gmap rxmatch-substring
11378 $ grxmatch #/\w+/ "The quick brown fox jumps over the lazy dog.")
11379 @result{} ("The" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog")
11380 @end example
11381
11382 @c EN
11383 Note: This procedure is efficient if @var{gen} is a string, in which
11384 case we actually bypass coercing it to a generator. If @var{gen} is other
11385 than a string, the current implementation may need to apply @var{regexp}
11386 as many times as O(n^2) where n is the entire length of the character
11387 sequence generated by @var{gen}, although the coefficient is small.
11388 This may be improved in future, but be careful using this function
11389 on very large input.
11390 @c JP
11391 注意: この手続きは@var{gen}が文字列の場合、ジェネレータへの変換がバイパスされるため
11392 効率的です。@var{gen}が文字列ではない場合、現在の実装では、@var{gen}が生成する文字の
11393 シーケンス全体の長さがnの場合に、係数が小さいとはいえ、必要となる@var{regexp}の適用
11394 回数は、O(n^2)となるかもしれません。この点について、将来改良されるかもしれませんが、
11395 大きな入力に対してこの関数を使う場合は、注意してください。
11396 @c COMMON
11397
11398 @c EN
11399 Note also that, when @var{gen} is not a string, @var{rxmatch} is applied
11400 on some buffered partial input. So @code{rxmatch-after} of the returned
11401 match does not represents the whole ``rest of input'' after the match,
11402 but merely the rest of strings within the buffer.
11403 @c JP
11404 もう一点注意: @var{gen}が文字列でない場合、@var{rxmatch}はバッファリングされた
11405 部分的な入力に対して適用されます。このため、返されたマッチの@code{rxmatch-after}
11406 は、マッチ後の``入力の残り全部''を表現しません。単にバッファの中にある文字列の
11407 残りになります。
11408 @c COMMON
11409 @end defun
11410
11411 @defun gindex vgen igen
11412 [SRFI-158]
11413 @c MOD gauche.generator
11414 @c EN
11415 Both arguments are generators. The @var{igen} generator must
11416 yield monotonically increasing series of exact nonnegative integers.
11417
11418 Returns a generator that generates items from @var{vgen}
11419 indexed by the numbers from @var{igen}, exhausted when either
11420 source generator is exhausted.
11421
11422 An error is thrown when @var{igen} yields a value that doesn't
11423 conform the condition.
11424 @c JP
11425 引数はどちらもジェネレータです。@var{igen}は単調増加する正確な非負整数を
11426 生成しなければなりません。
11427
11428 @var{vgen}から生成される値のうち、@var{igen}からの数字をインデックスとする
11429 値のみを取り出して返すようなジェネレータを作成して返します。
11430 どちらかの入力ジェネレータが終端に達したら、返されるジェネレータも終端に達します。
11431
11432 @var{igen}が条件を満たさない値を生成した場合はその時点でエラーが投げられます。
11433 @c COMMON
11434
11435 @example
11436 ;; This example takes advantage of Gauche's auto-coercing
11437 ;; list to generator. For portable SRFI-121 programs,
11438 ;; you need list->generator for each argument:
11439 (generator->list (gindex '(a b c d e) '(0 2 3)))
11440 @result{} (a c d)
11441 @end example
11442 @end defun
11443
11444 @defun gselect vgen bgen
11445 [SRFI-158]
11446 @c MOD gauche.generator
11447 @c EN
11448 Both arguments are generators. Creates and returns a
11449 generator that yields a value from @var{vgen} but only
11450 the corresponding value from @var{bgen} is true.
11451
11452 The returned generator is exhausted when one of the
11453 source generators is exhausted.
11454 @c JP
11455 引数はどちらもジェネレータです。@var{vgen}からの要素のうち、
11456 対応する@var{bgen}の要素が真の値であるものだけを選んで返す
11457 ようなジェネレータを作成して返します。
11458
11459 ソースジェネレータの一つが終端に達した時に、作成された
11460 ジェネレータも終端に達します。
11461 @c COMMON
11462
11463 @example
11464 ;; This example takes advantage of Gauche's auto-coercing
11465 ;; list to generator. For portable SRFI-121 programs,
11466 ;; you need list->generator for each argument:
11467 (generator->list (gselect '(a b c d e) '(#t #t #f #t #f)))
11468 @result{} (a b d)
11469 @end example
11470
11471 @c EN
11472 Combined with a bitgenerator, you can use @code{gselect}
11473 to extract items using bitmask:
11474 @c JP
11475 ビットジェネレータと一緒に使うと、@code{gselect}でビットマスク
11476 により要素を抽出することができます。
11477 @c COMMON
11478
11479 @example
11480 (generator->list (gselect '(a b c d e)
11481 (reverse-bits->generator #x1a)))
11482 @result{} (a b d)
11483 @end example
11484 @end defun
11485
11486
11487
11488 @node Generator consumers, , Generator operations, Generators
11489 @subsection Generator consumers
11490 @c NODE ジェネレータの消費
11491
11492 @c EN
11493 Some generator consumers are built-in.
11494 @xref{Folding generated values}, for @code{generator-fold},
11495 @code{generator-fold-right}, @code{generator-for-each},
11496 @code{generator-map}, and @code{generator-find}.
11497 @c JP
11498 いくつかのジェネレータ消費手続きは組み込みになっています。
11499 @code{generator-fold}、@code{generator-fold-right}、 @code{generator-for-each}、
11500 @code{generator-map}、@code{generator-find}については、
11501 @ref{Folding generated values}を参照してください。
11502 @c COMMON
11503
11504 @defun generator->list generator :optional k
11505 @defunx generator->reverse-list generator :optional k
11506 [SRFI-158]
11507 @c MOD gauche.generator
11508 @c EN
11509 Reads items from @var{generator} and returns a list of them
11510 (or a reverse list, in case of @code{generator->reverse-list}).
11511 By default, this reads until the generator is exhausted. If
11512 an optional argument @var{k} is given, it must be a nonnegative
11513 integer, and the list ends either @var{k} items are read,
11514 or the generator is exhausted.
11515 @c JP
11516 @var{generator}から項目を読み取り、それらを要素とするリストを返します
11517 (@code{generator->reverse-list}では要素が逆順になります)。
11518 デフォルトでは、ジェネレータを使い切るまで読み取ります。省略可能
11519 引数@var{k}を与える場合、それは非負整数でなければならず、結果のリスト
11520 は、@var{k}個の項目を読み取るか、ジェネレータを使い切ったところで終わり
11521 となります。
11522 @c COMMON
11523
11524 @c EN
11525 Be careful not to pass an infinite generator to this without
11526 specifying @var{k}---this procedure won't return but hogs
11527 all the memory before crash.
11528 @c JP
11529 無限ジェネレータを渡す時は必ず@var{k}を指定しましょう。
11530 さもなくば、この手続きは制御を返さず、全てのメモリを食い尽して
11531 クラッシュするでしょう。
11532 @c COMMON
11533 @end defun
11534
11535 @defun generator-map->list proc gen gen2 @dots{}
11536 [SRFI-158]
11537 @c MOD gauche.generator
11538 @c EN
11539 The @var{proc} argument must be a procedure that takes as many arguments
11540 as the number of given generators.
11541
11542 Returns a list, each of whose element is created by applying @var{proc}
11543 on each element from given generators @var{gen} @var{gen2} @dots{}.
11544 The list ends when any of the generator is exhausted.
11545
11546 Note that the list is created eagerly---if all of the generators are
11547 infinite, this procedure never returns.
11548 @c JP
11549 @var{proc}は与えられたジェネレータの数と同じだけの引数を取る手続きです。
11550
11551 @var{gen} @var{gen2} @dots{}から要素をひとつづつ取ってそれらに@var{proc}を
11552 適用した結果のリストを作って返します。
11553 どれかのジェネレータが終端に達したらリストも終わります。
11554
11555 リストは積極的に作られます。全てのジェネレータが無限だと、この手続きは戻ってきません。
11556 @c COMMON
11557 @end defun
11558
11559 @defun generator->vector gen :optional k
11560 @defunx generator->string gen :optional k
11561 [SRFI-158]
11562 @c MOD gauche.generator
11563 @c EN
11564 Extracts items from the generator @var{gen} up to @var{k} items
11565 or until it exhausts, and create a fresh
11566 vector or string from the extracted items.
11567
11568 When @var{k} is omitted, @var{gen} is called until it exhausts;
11569 note that if @var{gen} is infinite generator this procedure won't return.
11570
11571 For @code{generator->string}, @var{gen} must yield a character, or
11572 an error is reported.
11573 @c JP
11574 @var{gen}から、@var{k}要素もしくは@var{gen}が終端に達するまで要素を読み出し、
11575 それらの要素からなるベクタまたは文字列を作って返します。
11576
11577 @var{k}が省略された場合は@var{gen}が終端に達するまで呼ばれますが、
11578 @var{gen}が無限ジェネレータだと返って来なくなるので注意してください。
11579
11580 @code{generator->string}の場合、@var{gen}が文字以外のものを生成したら
11581 エラーが報告されます。
11582 @c COMMON
11583 @end defun
11584
11585 @defun generator->uvector gen :optional k class
11586 @defunx generator->bytevector gen :optional k
11587 [SRFI-158]
11588 @c MOD gauche.generator
11589 @c EN
11590 Extracts items from the generator @var{gen} up to @var{k} items
11591 or until it exhausts, and create a fresh uniform vector
11592 of class @var{class} filled with those items.
11593 If @var{k} is omitted, @var{gen} is read until it exhausts.
11594
11595 If @var{class} is specified, it must be one of the uniform vector
11596 classes (@pxref{Uniform vectors}). When omitted, @code{<u8vector>} is
11597 assumed.
11598
11599 @code{Generator->bytevector} works like @code{generator->uvector}
11600 except that the class is fixed to @code{<u8vector>}.
11601
11602 The generator must always produce numeric values acceptable to be an
11603 element of the specified uvector; otherwise an error is signalled.
11604 @c JP
11605 ジェネレータ@var{gen}から、@var{k}個の要素、あるいは@var{gen}が終端に達するまで
11606 要素を読み出し、それらの要素からなるユニフォームベクタを作って返します。
11607 @var{k}が省略された場合、@var{gen}は常に最後まで読まれます。
11608
11609 @var{class}が指定された場合、それはユニフォームベクタのクラスのいずれかで
11610 なければなりません(@ref{Uniform vectors}参照)。省略された場合は
11611 @code{<u8vector>}が使われます。
11612
11613 @code{generator->bytevector}は、@var{class}が@code{<u8vector>}に固定されている
11614 以外は@code{generator->uvector}と同じです。
11615
11616 ジェネレータ@var{gen}は、指定されたユニフォームベクタの要素となり得る数値を
11617 生成しなければなりません。それ以外の値が生成された場合はエラーが報告されます。
11618 @c COMMON
11619 @end defun
11620
11621 @defun generator->vector! vector at gen
11622 [SRFI-158]
11623 @c MOD gauche.generator
11624 @c EN
11625 Fill @var{vector} from index @var{at} with the value yielded
11626 from @var{gen}. It terminates when @var{gen} is exhausted or the index
11627 reaches at the end of the vector. Returns the number of items
11628 generated.
11629 @c JP
11630 @var{vector}を、インデックス@var{at}から、@var{gen}が生成する値によって
11631 埋めてゆきます。@var{gen}が終端に達するか、ベクタの最後まで埋められた時点で
11632 終了し、生成された要素の個数が返されます。
11633 @c COMMON
11634
11635 @example
11636 (define v (vector 'a 'b 'c 'd 'e))
11637
11638 (generator->vector! v 2 (giota))
11639 @result{} 3
11640
11641 v @result{} #(a b 0 1 2)
11642 @end example
11643 @end defun
11644
11645 @defun generator->uvector! uvector at gen
11646 @defunx generator->bytevector! u8vector at gen
11647 @c MOD gauche.generator
11648 @c EN
11649 Like @var{generator->vector!}, fill a uniform vector @var{uvector}
11650 starting from index @var{at} with elements read from a generator
11651 @var{gen}. It terminates when @var{gen} is exhausted or the index
11652 reaches at the end of the vector. Returns the number of items
11653 generated.
11654
11655 Any type of uvector can be passed to @code{generator->uvector!}, while
11656 @code{generator->bytevector!} can only accept @code{u8vector}.
11657
11658 The generator must always produce numeric values acceptable to be an
11659 element of the specified uvector; otherwise an error is signalled.
11660 @c JP
11661 @code{generator->vector!}と同様、@var{gen}から読み出した値で、
11662 @var{uvector}を、インデックス@var{at}から順に埋めてゆきます。
11663 ベクタの終端に達するか、@var{gen}が終端に達するまで続けられ、
11664 読み出された要素の個数が戻り値となります。
11665
11666 @code{generator->uvector!}はどんなユニフォームベクタでも取ることができます。
11667 @code{generator->bytevector!}は@code{u8vector}限定です。
11668
11669 ジェネレータ@var{gen}は、指定されたユニフォームベクタの要素となり得る数値を
11670 生成しなければなりません。それ以外の値が生成された場合はエラーが報告されます。
11671 @c COMMON
11672 @end defun
11673
11674 @defmac glet* (binding @dots{}) body body2 @dots{}
11675 @c MOD gauche.generator
11676 @c EN
11677 This captures a monadic pattern frequently appears in the generator
11678 code. It is in a similar spirit of @code{and-let*}, but returns
11679 as soon as the evaluating expression returns EOF, instead of @code{#f}
11680 as @code{and-let*} does.
11681 @c JP
11682 これは、ジェネレータコードに頻繁に現れるモナド的なパターンを表現
11683 するものです。@code{and-let*}の発想に似ていますが、@code{#f}のかわりにEOFを
11684 返す式を評価すると直ちに返ります。
11685 @c COMMON
11686
11687 @c EN
11688 The @var{binding} part can be either @code{(var expr)} or @code{( expr )}.
11689 The actual definition will explain this syntax clearly.
11690 @c JP
11691 @var{binding}部分は@code{(var expr)}か@code{( expr )}の形をとります。
11692 実際の定義を見れば、この構文が明解に理解できるでしょう。
11693 @c COMMON
11694
11695 @example
11696 (define-syntax glet*
11697 (syntax-rules ()
11698 [(_ () body body2 ...) (begin body body2 ...)]
11699 [(_ ([var gen-expr] more-bindings ...) . body)
11700 (let1 var gen-expr
11701 (if (eof-object? var)
11702 var
11703 (glet* (more-bindings ...) . body)))]
11704 [(_ ([ gen-expr ] more-bindings ...) . body)
11705 (let1 var gen-expr
11706 (if (eof-object? var)
11707 var
11708 (glet* (more-bindings ...) . body)))]))
11709 @end example
11710 @end defmac
11711
11712 @defmac glet1 var expr body body2 @dots{}
11713 @c MOD gauche.generator
11714 @c EN
11715 This is to @code{glet*} as @code{let1} is to @code{let*}. In other words,
11716 it is @code{(glet* ([var expr]) body body2 @dots{})}.
11717 @c JP
11718 これと@code{glet*}の関係は、@code{let1}と@code{let*}のそれと同じです。言葉を
11719 変えれば、これは@code{(glet* ([var expr]) body body2 @dots{})}と同じです。
11720 @c COMMON
11721 @end defmac
11722
11723 @defmac do-generator (var gexpr) body @dots{}
11724 @c MOD gauche.generator
11725 @c EN
11726 This is a generator version of @code{dolist} and @code{dotimes}
11727 (@pxref{Binding constructs}).
11728 @c JP
11729 これは、ジェネレータ版の@code{dolist}であり@code{dotimes}です(@ref{Binding constructs}参照)。
11730 @c COMMON
11731
11732 @c EN
11733 @var{Gexpr} is an expression that yields a generator. It is
11734 evaluated once. The resulting generator is called repeatedly
11735 until it returns EOF. Every time the generator is called,
11736 @var{body} @dots{} are evaluated in the scope
11737 where @var{var} is bound to the value yielded from the generator.
11738 @c JP
11739 @var{gexpr}はジェネレータを生成する式であり、一度だけ評価されます。
11740 結果となるジェネレータはEOFを返すまで繰り返し呼ばれます。ジェネレータ
11741 が呼ばれる毎に、ジェネレータが生成する値に束縛される@var{var}の
11742 スコープ内で@var{body} @dots{}が評価されます。
11743 @c COMMON
11744
11745 @c EN
11746 Like @code{dolist} and @code{dotimes}, this macro exists for
11747 side-effects. You can write the same thing with @code{for-each} families,
11748 but sometimes this macro makes the imperative code more readable:
11749 @c JP
11750 @code{dolist}や@code{dotimes}がそうであるように、このマクロも副作用のため
11751 のものです。同じことは@code{for-each}族を使っても書けますが、このマクロを
11752 使って命令的に記述したコードの方が読みやすいこともあるのです。
11753 @c COMMON
11754
11755 @example
11756 (do-generator [line (file->line-generator "filename")]
11757 @c EN
11758 ;; do some side-effecting stuff with line
11759 @c JP
11760 ;; lineを使って何か副作用のある作業をする
11761 @c COMMON
11762 )
11763 @end example
11764 @end defmac
11765
11766 @defun generator-any pred gen
11767 @defunx generator-every pred gen
11768 [SRFI-158]
11769 @c MOD gauche.generator
11770 @c EN
11771 Like @code{any} and @code{every} (@pxref{Walking over lists}), but
11772 works on a generator.
11773 @c JP
11774 @code{any}、@code{every} (@pxref{Walking over lists}) と同じですが、
11775 ジェネレータに対して使えます。
11776 @c COMMON
11777 @end defun
11778
11779 @defun generator-count pred gen
11780 [SRFI-158]
11781 @c MOD gauche.generator
11782 @c EN
11783 Returns the number of items in a generator @var{gen}
11784 that satisfies @var{pred}.
11785 As a side effect, @var{gen} is exhausted.
11786 @c JP
11787 @var{gen}が生成する要素ののうち、@var{pred}を満たすものの個数を返します。
11788 副作用として@var{gen}は使い尽くされます。
11789 @c COMMON
11790 @end defun
11791
11792 @defun generator-unfold gen unfold arg @dots{}
11793 [SRFI-158]
11794 @c MOD gauche.generator
11795 @c EN
11796 Apply @var{unfold} using the values generated from a generator @var{gen}
11797 as seeds. It is equivalent to the following expression:
11798 @c JP
11799 @var{gen}が生成する値をseedとして@var{unfold}を適用します。次の式と同じです:
11800 @c COMMON
11801
11802 @code{(@var{unfold} eof-object? identity (^_ (@var{gen})) (@var{gen}) @var{arg} @dots{})}
11803
11804 @c EN
11805 The @var{unfold} procedure must have the signature
11806 @code{(unfold stop? mapper successor seed arg @dots{})}, like @code{unfold}
11807 in @code{scheme.list} (@pxref{R7RS lists}).
11808 @c JP
11809 @var{unfold}手続きは、
11810 @code{scheme.list}モジュールの@code{unfold}(@pxref{R7RS lists}参照)のように、
11811 次のとおり引数を取らなければなりません:
11812 @code{(unfold stop? mapper successor seed arg @dots{})}。
11813 @c COMMON
11814
11815 @c EN
11816 It can be seen as a general method to convert a generator to a sequence,
11817 an inverse of @code{x->generator}.
11818 @c JP
11819 これはジェネレータをシーケンスに変換する一般的な方法と見ることができます。
11820 @code{x->generator}の反対です。
11821 @c COMMON
11822
11823 @example
11824 (generator-unfold (x->generator "abc") string-unfold)
11825 @result{} "abc"
11826 @end example
11827 @end defun
11828
11829
11830 @c ----------------------------------------------------------------------
11831 @node Hooks, Interactive session, Generators, Library modules - Gauche extensions
11832 @section @code{gauche.hook} - Hooks
11833 @c NODE フック, @code{gauche.hook} - フック
11834
11835 @deftp {Module} gauche.hook
11836 @mdindex gauche.hook
11837 @c EN
11838 Provides a hook object, which manages a list of closures to be
11839 called at certain time.
11840
11841 This API of hooks are upper-compatible of Guile's, with the
11842 following extensions.
11843 @c JP
11844 フックオブジェクトを提供します。これは、特定のタイミングで
11845 呼び出されるクロージャのリストを管理するものです。
11846
11847 フックのAPIはGuileのそれと上方互換で、下記のように拡張されています。
11848 @c COMMON
11849 @itemize @bullet
11850 @item
11851 @c EN
11852 Based on Gauche's object system. Most APIs are methods
11853 so you can extend the hook features.
11854 @c JP
11855 Gaucheのオブジェクトシステムをベースにしています。
11856 ほとんどのAPIはメソッドなので、フックの機能を拡張することが
11857 できます。
11858 @c COMMON
11859 @item
11860 @c EN
11861 Hook object itself is applicable. You don't need to use @code{run-hook}.
11862 @c JP
11863 フックオブジェクトはそれ自身適用可能です。@code{run-hook}を使う必要は
11864 ありません。
11865 @c COMMON
11866 @item
11867 @c EN
11868 The method to remove a procedure from a hook is called @code{delete-hook!},
11869 for consistency with SRFI-1 and others. @code{remove-hook!} is
11870 defined as an alias of @code{delete-hook!} for compatibility with Guile.
11871 @c JP
11872 フックから手続きを削除するメソッドは、SRFI-1やその他との一貫性の
11873 ために@code{delete-hook!}と呼ばれます。
11874 Guileとの互換性のために、@code{remove-hook!}が@code{delete-hook!}の
11875 エイリアスとして定義されています。
11876 @c COMMON
11877 @end itemize
11878
11879 @c EN
11880 If you're writing portable code, SRFI-173 provides the basic
11881 hook functionality (@pxref{Hooks (srfi)}).
11882 @c JP
11883 ポータブルなコードを書いているなら、SRFI-173が基本的なフック機能を
11884 提供しています (@ref{Hooks (srfi)}参照)。
11885 @c COMMON
11886 @end deftp
11887
11888 @deftp {Class} <hook>
11889 @clindex hook
11890 @c MOD gauche.hook
11891 @c EN
11892 A hook class, which keeps a list of procedures to be called at once.
11893
11894 The @code{object-apply} method is defined on @code{<hook>} class,
11895 so you can "apply" a hook object as if it were a procedure---which
11896 causes all the registered procedure to be invoked.
11897 @c JP
11898 フックのクラスで、一度に呼び出される手続きのリストを保持しています。
11899
11900 @code{<hook>}クラスには@code{object-apply}メソッドが定義されているので、
11901 あたかもそれが手続きであるかのようにフックオブジェクトを``適用''できます。
11902 フックオブジェクトを適用すると、登録されている全ての手続きが呼び出されます。
11903 @c COMMON
11904 @end deftp
11905
11906 @defun make-hook :optional (arity 0)
11907 @c MOD gauche.hook
11908 @c EN
11909 Creates a new hook object with given arity, which should be a
11910 non-negative integer.
11911 @c JP
11912 与えられたアリティ(正の整数でなければなりません)とともに新しい
11913 フックオブジェクトを作成します。
11914 @c COMMON
11915 @end defun
11916
11917 @defun hook? obj
11918 @c MOD gauche.hook
11919 @c EN
11920 Returns true if @var{obj} is a hook object.
11921 @c JP
11922 @var{obj}がフックオブジェクトであれば、真を返します。
11923 @c COMMON
11924 @end defun
11925
11926 @defun hook-empty? hook
11927 @c MOD gauche.hook
11928 @c EN
11929 Returns true if @var{hook}'s procedure list is empty.
11930 @c JP
11931 @var{hook}の手続きリストが空なら、真を返します。
11932 @c COMMON
11933 @end defun
11934
11935 @deffn {Method} add-hook! (hook <hook>) proc :optional (append? #f)
11936 @c MOD gauche.hook
11937 @c EN
11938 Adds a procedure @var{proc} to @var{hook}. If @var{append?}
11939 is given and true, @var{proc} is added at the end of the list.
11940 Otherwise, @var{proc} is added at the front of the list.
11941 The @var{proc} has to be called with the arity given
11942 at the @code{make-hook}.
11943 @c JP
11944 手続き@var{proc}を@var{hook}に追加します。
11945 @var{append?}が与えられ真であれば、@var{proc}はリストの最後に
11946 追加されます。そうでなければ、@var{proc}はリストの最初に追加
11947 されます。
11948 @var{proc}は、@code{make-hook}時に与えられたアリティとともに
11949 呼ばれなければなりません。
11950 @c COMMON
11951 @end deffn
11952
11953 @deffn {Method} delete-hook! (hook <hook>) proc
11954 @deffnx {Method} remove-hook! (hook <hook>) proc
11955 @c MOD gauche.hook
11956 @c EN
11957 Removes @var{proc} from the procedure list of @var{hook}.
11958 @code{Remove-hook!} is an alias of @code{delete-hook!} just for
11959 compatibility with Guile.
11960 @c JP
11961 @var{hook}の手続きリストから@var{proc}を削除します。
11962 Guileとの互換性のためだけに、@code{remove-hook!}が@code{delete-hook!}の
11963 エイリアスとなっています。
11964 @c COMMON
11965 @end deffn
11966
11967 @deffn {Method} reset-hook! (hook <hook>)
11968 @c MOD gauche.hook
11969 @c EN
11970 Empties @var{hook}'s procedure list.
11971 @c JP
11972 @var{hook}の手続きリストを空にします。
11973 @c COMMON
11974 @end deffn
11975
11976 @deffn {Method} hook->list (hook <hook>)
11977 @c MOD gauche.hook
11978 @c EN
11979 Returns a copy of @var{hook}'s procedure list.
11980 @c JP
11981 @var{hook}の手続きリストのコピーを返します。
11982 @c COMMON
11983 @end deffn
11984
11985 @deffn {Method} run-hook (hook <hook>) arg @dots{}
11986 @c MOD gauche.hook
11987 @c EN
11988 Calls @var{hook}'s procedures in order, with arguments @var{arg} @dots{}.
11989 The number of arguments must match the arity given at @code{make-hook}.
11990 @c JP
11991 @var{hook}の手続きを、@var{arg} @dots{}を引数として順番に呼び出します。
11992 引数の数は、@code{make-hook}時に与えられたアリティにマッチしなければ
11993 なりません。
11994 @c COMMON
11995 @end deffn
11996
11997 @c ----------------------------------------------------------------------
11998 @node Interactive session, Lazy sequence utilities, Hooks, Library modules - Gauche extensions
11999 @section @code{gauche.interactive} - Utilities for interactive session
12000 @c NODE インタラクティブセッション, @code{gauche.interactive} - インタラクティブセッション
12001
12002 @deftp {Module} gauche.interactive
12003 @mdindex gauche.interactive
12004 @c EN
12005 Provides useful utilities for the interactive session.
12006
12007 This module is automatically loaded when you run @code{gosh}
12008 interactively.
12009
12010 This module also sets autoloads for functions defined in
12011 @code{gauche.reload} module
12012 (see @ref{Reloading modules}), so that
12013 those functions can be used by default in interactive development.
12014 @c JP
12015 インタラクティブセッションで便利なユーティリティ手続きを提供します。
12016
12017 @code{gosh}をインタラクティブモードで起動した場合、
12018 このモジュールは自動的にロードされます。
12019
12020 また、このモジュールは@code{gauche.reload}
12021 (@ref{Reloading modules}参照)で定義される
12022 手続きに対してautoloadを設定し、それらの手続きが
12023 インタラクティブな開発時にデフォルトで使えるようにします。
12024 @c COMMON
12025 @end deftp
12026
12027 @defmac apropos pattern :optional module
12028 @c MOD gauche.interactive
12029 @c EN
12030 Show a list of defined variables whose name matches @var{pattern}.
12031 If you give a module or a module name @var{module}, only the variables
12032 defined in that module are listed. Without @var{module},
12033 the variables "visible" from the current module are listed.
12034 @c JP
12035 名前が@var{pattern}にマッチするような定義された変数のリストを表示します。
12036 @var{module}にモジュールオブジェクトまたはモジュール名を与えた場合は、
12037 そのモジュール内で定義されている変数のみが表示されます。@var{module}が
12038 省略された場合は、カレントモジュールから「見える」変数が全て表示されます。
12039 @c COMMON
12040
12041 @c EN
12042 @var{pattern} may be a symbol or a regexp object.
12043 If it is a symbol, the variables whose name contains the
12044 substring that matches the symbol's name are listed.
12045 If it is a regexp object, the variables whose name matches
12046 the regexp are listed.
12047 @c JP
12048 @var{pattern}はシンボルか正規表現オブジェクトでなければなりません。
12049 シンボルの場合、そのシンボル名を部分文字列として名前に含むような変数が
12050 リストされます。正規表現オブジェクトの場合は、その正規表現にマッチする
12051 名前を持つ変数がリストされます。
12052 @c COMMON
12053
12054 @c EN
12055 Some examples:
12056 @c JP
12057 いくつか例を示します。
12058 @c COMMON
12059 @example
12060 @c EN
12061 ;; @r{List variables that contains "string" in their name}
12062 @c JP
12063 ;; @r{"string"を名前に含む変数を表示}
12064 @c COMMON
12065 (apropos 'string)
12066
12067 @c EN
12068 ;; @r{Search in srfi.14 module}
12069 @c JP
12070 ;; @r{srfi.14モジュールの中のみを検索}
12071 @c COMMON
12072 (apropos 'char 'srfi.14)
12073 @end example
12074 @end defmac
12075
12076 @defun d :optional obj
12077 @c MOD gauche.interactive
12078 @c EN
12079 This is defined as an alias of @code{describe}
12080 (@pxref{Describing instance}, for the details).
12081 The short name is for the convenience, but in REPL you may find
12082 use @code{,d} toplevel command more convenient now.
12083 @c JP
12084 これは@code{describe}の別名として定義されています
12085 (詳しくは@ref{Describing instance}参照)。
12086 短い名前の方がREPLで打ちやすいからですが、
12087 今ではREPLトップレベルコマンド@code{,d}の方が使いやすいでしょう。
12088 @c COMMON
12089 @end defun
12090
12091 @c EN
12092 This module also adds some methods to the generic function @code{describe}
12093 for built-in objects.
12094 @c JP
12095 このモジュールはまた、ジェネリックファンクション@code{describe}にいくつか
12096 組み込みオブジェクト向けのメソッドを追加します。
12097 @c COMMON
12098
12099 @deffn {Method} describe
12100 @c EN
12101 When called without arguments, it describes the object bound to @code{*1},
12102 the last result of REPL.
12103 @c JP
12104 引数なしで呼ばれた場合、REPLでの直近の評価値が束縛されている@code{*1}の値を
12105 describeします。
12106 @c COMMON
12107 @end deffn
12108
12109 @deffn {Method} describe (s <symbol>)
12110 @c EN
12111 Customized describe method for symbols. It shows known bindings
12112 for the symbol as well (it is looked for in the loaded modules).
12113 @c JP
12114 シンボル用にカスタマイズされたdescribeです。
12115 ロードされているモジュール中からそのシンボルへの束縛を探して表示します。
12116 @c COMMON
12117 @example
12118 gosh$ ,d 'filter
12119 filter is an instance of class <symbol>
12120 Known bindings for variable filter:
12121 In module `gauche.collection':
12122 #<generic filter (2)>
12123 In module `gauche':
12124 #<closure (filter pred lis)>
12125 @end example
12126 @end deffn
12127
12128 @deffn {Method} describe (c <char>)
12129 @c EN
12130 Customized describe method for characters.
12131 It shows its Unicode codepoint and general category.
12132 @c JP
12133 文字用にカスタマイズされたdescribeです。
12134 Unicodeコードポイントとジェネラルカテゴリを表示します。
12135 @c COMMON
12136 @example
12137 gosh$ ,d #\π
12138 #\π is an instance of class <char>
12139 (U+03c0, Ll)
12140 @end example
12141 @end deffn
12142
12143 @deffn {Method} describe (n <integer>)
12144 @c EN
12145 Customized describe method for exact integers.
12146 Depending on the value range, it shows several informations: A hexadecimal
12147 notation, 1024-base approximated value (useful for memory and storage
12148 size), character as Unicode codepoint, and
12149 time as Unix time.
12150 @c JP
12151 正確な整数用にカスタマイズされたdescribeです。
12152 値の範囲に応じて、いくつかの情報を示します。
12153 16進数表示、1024単位の概数(メモリやストレージのサイズに便利です)、
12154 Unicodeコードポイントとして見た場合の文字、
12155 そしてUnix timeとして見た場合の時刻です。
12156 @c COMMON
12157 @example
12158 gosh$ ,d 1234
12159 1234 is an instance of class <integer>
12160 (#x4d2, ~ 1.2Ki, #\Ӓ as char, 1970-01-01T00:20:34Z as unix-time)
12161 gosh$ ,d 12345678
12162 12345678 is an instance of class <integer>
12163 (#xbc614e, ~ 11Mi, 1970-05-23T21:21:18Z as unix-time)
12164 gosh$ ,d 12345678901234567890
12165 12345678901234567890 is an instance of class <integer>
12166 (#xab54a98c_eb1f0ad2, ~ 10Ei)
12167 @end example
12168 @end deffn
12169
12170 @deffn {Method} describe (r <rational>)
12171 @c EN
12172 Customized describe method for exact rationals.
12173 It shows the floating point number as coerced into inexact.
12174 @c JP
12175 正確な有理数用にカスタマイズされたdescribeです。
12176 非正確数に変換された場合の小数表示も示します。
12177 @c COMMON
12178 @example
12179 gosh$ ,d 1234/5678
12180 617/2839 is an instance of class <rational>
12181 inexact: 0.2173300457907714
12182 @end example
12183 @end deffn
12184
12185 @deffn {Method} describe (d <real>)
12186 @c EN
12187 Customized describe method for inexact reals.
12188 It shows binary representation of the flonum, and
12189 rational representation as coerced into exact.
12190 @c JP
12191 不正確な実数用にカスタマイズされたdescribeです。
12192 浮動小数点数としてのバイナリ表現と、
12193 正確数に変換された場合の有理数表示も示します。
12194 @c COMMON
12195 @example
12196 gosh$ ,d 3.14159265358979
12197 3.14159265358979 is an instance of class <real>
12198 mantissa: #x+19_21fb_5444_2d11 exponent: -51 hex: #x4009_21fb_5444_2d11
12199 exact: 144029661/45846065
12200 @end example
12201 @end deffn
12202
12203 @deffn {Method} describe (c <complex>)
12204 @c EN
12205 Customized describe method for complex numbers.
12206 It shows polar representation as well.
12207 @c JP
12208 複素数用にカスタマイズされたdescribeです。
12209 極座標形式も表示します。
12210 @c COMMON
12211 @example
12212 gosh$ ,d (expt -2 1/4)
12213 0.8408964152537146+0.8408964152537146i is an instance of class <complex>
12214 polar: 1.1892071150027212@@0.7853981633974483 (@@0.25pi)
12215 @end example
12216 @end deffn
12217
12218 @deffn {Method} describe (p <procedure>)
12219 @deffnx {Method} describe (p <macro>)
12220 @c EN
12221 Customized describe method for procedures and macros,
12222 showing the source location if avaiable.
12223 For the procedure, its type signature is shown as well
12224 (@code{procedure-type}, @pxref{Procedure class and applicability}).
12225 @c JP
12226 手続きとマクロ用にカスタマイズされたdescribeで、
12227 ソースコード位置を(分かれば)表示します。
12228 また、手続きについてはその型も表示します
12229 (@code{procedure-type}、@ref{Procedure class and applicability}参照)。
12230 @c COMMON
12231 @example
12232 gosh> ,d display-filled-text
12233 #<closure (display-filled-text text :key (port (current-output-port))
12234 (indent 0) (hanging 0) (width 65) (lead-in #f) (start-column #f))> is
12235 an instance of class <procedure>
12236 Defined at "/usr/share/gauche-0.98/0.9.15-p1/lib/text/fill.scm":111
12237 type: #<^ <top> * -> *>
12238 slots:
12239 required : 1
12240 optional : #t
12241 optcount : 1
12242 locked : #f
12243 currying : #f
12244 constant : #f
12245 info : (display-filled-text text :key (port (current-output-port))
12246 setter : #f
12247 @end example
12248 @end deffn
12249
12250
12251 @deffn {Method} describe (g <generic>)
12252 @c EN
12253 Customized describe method for generic functions.
12254 It shows the list of known methods, with the specializer list
12255 and the source location of definition if known.
12256 @c JP
12257 ジェネリックファンクション用にカスタマイズされたdescribeです。
12258 メソッドのリストも表示します。
12259 メソッドは、スペシャライザーのリストと、わかれば定義のソース情報が示されます。
12260 @c COMMON
12261 @example
12262 gosh$ ,d describe
12263 #<generic describe (11)> is an instance of class <generic>
12264 slots:
12265 name : describe
12266 sealed : #f
12267 info : describe
12268 methods : (#<method (describe <macro>)> #<method (describe <procedure>
12269 methods:
12270 (<macro>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":223
12271 (<procedure>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":215
12272 (<method>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":208
12273 (<generic>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":189
12274 (<real>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":172
12275 (<rational>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":160
12276 (<integer>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":128
12277 (<char>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":123
12278 (<symbol>) ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":118
12279 () ; "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":116
12280 (<top>)
12281 @end example
12282 @end deffn
12283
12284 @deffn {Method} describe (m <method>)
12285 @c EN
12286 Customized describe method for methods.
12287 It shows the source code location if available.
12288 @c JP
12289 メソッド用にカスタマイズされたdescribeです。
12290 ソースコード位置が分かればそれも表示します。
12291 @c COMMON
12292 @example
12293 gosh$ ,d (car (~ describe'methods))
12294 #<method (describe <macro>)> is an instance of class <method>
12295 Defined at "/usr/share/gauche-0.98/0.9.15-p1/lib/gauche/interactive.scm":223
12296 slots:
12297 required : 1
12298 optional : #f
12299 method-locked: #f
12300 leaf? : #t
12301 generic : #<generic describe (11)>
12302 specializers: (#<class <macro>>)
12303 info : (describe <macro>)
12304 @end example
12305 @end deffn
12306
12307
12308 @defun info symbol
12309 @c MOD gauche.interactive
12310 @c EN
12311 Displays an entry of the named function, syntax, module or class
12312 from Gauche's info document.
12313 If an environment variable @code{INFOPATH} is defined,
12314 this function searches for the info file from the directories in it.
12315 Otherwise, this function guesses info file location from the
12316 @code{gosh}'s library directory. If the info file can't be
12317 found, an error is signaled.
12318 So this function doesn't work if you haven't installed info file.
12319 @c JP
12320 Gaucheのinfoドキュメント中から、
12321 @var{symbol}で指定される手続き、構文要素、モジュールもしくはクラスの
12322 エントリを表示します。
12323 もし環境変数@code{INFOPATH}が定義されていればそこに
12324 示されるディレクトリ中から探され、そうでなければ@code{gosh}のライブラリディレクトリ
12325 から推測されるディレクトリ中から探されます。
12326 infoドキュメントが見付からなかった場合はエラーとなります。
12327 つまり、この手続きはinfoファイルがインストールされていないと動作しません。
12328 @c COMMON
12329
12330 @c EN
12331 If no entry exactly matching with @var{symbol} is found, the procedure tries
12332 to look for similar named entries:
12333 @c JP
12334 もし@var{symbol}に完全に一致するエントリが見つからなかった場合、
12335 類似するエントリがあればそれらがリストされます:
12336 @c COMMON
12337
12338 @example
12339 gosh> (info 'stirng)
12340 There is no entry for stirng.
12341 Did you mean:
12342 string>
12343 string?
12344 string=
12345 string<
12346 string
12347 :string
12348 @end example
12349
12350 @c EN
12351 (If you want to search entries using pattern, see @code{info-serach} below.)
12352 @c JP
12353 (パターンにマッチするエントリを探したい場合は下の@code{info-search}を見てください)
12354 @c COMMON
12355
12356 @c EN
12357 If the current output port is a tty, the info page is displayed by
12358 a paging software. If an environment variable @code{PAGER} is defined,
12359 it is used as a paging software. Otherwise, this function looks for
12360 @code{less} and @code{more} in this order from the directories in
12361 @code{PATH}. If none of them is found, or the output port is not
12362 a tty, this function just displays the page.
12363 @c JP
12364 現在の出力ポートが端末である場合、infoドキュメントの該当ページは
12365 ページングプログラムを用いて表示されます。環境変数@code{PAGER}が指定されていれば
12366 それを用い、そうでなければコマンドサーチパスから@code{less}及び@code{more}を
12367 この順で探します。いずれも見付からなかった場合や、出力ポートが端末では
12368 ない場合には、単にページがそのまま出力されます。
12369 @c COMMON
12370
12371 @c EN
12372 The first invocation of this function in a session takes some time
12373 to parse the info file.
12374 @c JP
12375 この手続きのセッション中での最初の呼び出しは、infoファイルをパーズするために
12376 多少時間がかかります。
12377 @c COMMON
12378
12379 @c EN
12380 NB: When you use @code{less} as a pager, make sure you set
12381 it to handle utf-8 characters (e.g. setting @code{LESSCHARSET}
12382 environment variable to
12383 @code{UTF-8}), or you'll see some escaped sequences on the screen.
12384 @c JP
12385 註: @code{less}をページャに使う場合、@code{less}がutf-8文字を扱えるように
12386 設定してください (例えば@code{LESSCHARSET}環境変数を@code{UTF-8}にする)。
12387 そうでないと画面にエスケープされた文字が表示されて見づらいです。
12388 @c COMMON
12389
12390 @c EN
12391 NB: If you invoke @code{gosh} within the build tree, using @code{-ftest}
12392 option, @code{info} reads the info files in the build tree if they exist.
12393 @c JP
12394 註: @code{gosh}を@code{-ftest}オプションをつけてビルドツリー内で起動した場合、
12395 @code{info}はビルドツリー内のinfoファイルを(もしあれば)読みます。
12396 @c COMMON
12397 @end defun
12398
12399 @defun info-search regexp
12400 @c MOD gauche.interactive
12401 @c EN
12402 Lists info entries matching @var{regexp}. See @code{info} above
12403 about where the info files are searched.
12404 @c JP
12405 @var{regexp}にマッチするinfoのエントリをリストします。
12406 infoファイルがどこから読まれるかについては上の@code{info}の説明を参照してください。
12407 @c COMMON
12408 @end defun
12409
12410 @defun ed filename-or-procedure :key editor load-after
12411 @c MOD gauche.interactive
12412 @c EN
12413 Invoke an external editor to open the named file, or the file containing
12414 the definition of the given procedure (if it can be known).
12415 For the latter, it uses @code{source-location} procedure to find out
12416 the source code location (@pxref{Debugging aid}).
12417 @c JP
12418 外部エディタを起動し、与えられた名前のファイル、もしくは与えられた手続きの定義がある
12419 ファイルを開きます。後者については、与えられた手続きを
12420 @code{source-location}に渡して定義箇所を調べます(@ref{Debugging aid}参照)。
12421 定義箇所がわからなければファイルは開かれません。
12422 @c COMMON
12423
12424 @c EN
12425 The name of the editor to invoke is determined as follows:
12426 @c JP
12427 起動するエディタの名前は次の順序で決定されます。
12428 @c COMMON
12429
12430 @enumerate
12431 @item
12432 @c EN
12433 The @var{editor} keyword argument.
12434 @c JP
12435 キーワード引数@var{editor}。
12436 @c COMMON
12437 @item
12438 @c EN
12439 The value of the variable @code{*editor*} in the @code{user} module,
12440 if defined. This is handy that you can set this in your @code{.gaucherc}.
12441 @c JP
12442 @code{user}モジュール中の変数@code{*editor*}の値。
12443 これは、@code{.gaucherc}内で設定しておくのが便利です。
12444 @c COMMON
12445 @item
12446 @c EN
12447 The value of the environment variable @code{GAUCHE_EDITOR}.
12448 @c JP
12449 環境変数@code{GAUCHE_EDITOR}の値
12450 @c COMMON
12451 @item
12452 @c EN
12453 The value of the environment variable @code{EDITOR}.
12454 @c JP
12455 環境変数@code{EDITOR}の値
12456 @c COMMON
12457 @end enumerate
12458
12459 @c EN
12460 If none of the above is defined or @code{#f}, the procedure prompts the user
12461 to type in the name of the editor.
12462 @c JP
12463 上記のどの値も定義されていないか@code{#f}なら、
12464 手続き@code{ed}はユーザにエディタ名を入力するように促します。
12465 @c COMMON
12466
12467 @c EN
12468 Once the editor name is obtained, it is invoked as a subprocess,
12469 with the following format:
12470 @c JP
12471 エディタの名前がわかったら、それが子プロセスとして次の形式で実行されます。
12472 @c COMMON
12473
12474 @example
12475 EDITOR +lineno filename
12476 @end example
12477
12478 @c EN
12479 The @var{lineno} is an integer line number, 1 being the first line.
12480 The editor is expected to locate the cursor on the specified line.
12481 @c JP
12482 @var{lineno}は整数の行番号で、1が先頭行です。エディタは指定された行の頭に
12483 カーソルを移動することが期待されます。
12484 @c COMMON
12485
12486 @c EN
12487 Once the editor process exits, the procedure checks if the named
12488 file is updated. If so, it may load the file, according to the
12489 value of the @var{load-after} keyword argument. It may take one
12490 of the following values:
12491 @c JP
12492 エディタプロセスが終了したら、@code{ed}はファイルが更新されたかどうかを調べ、
12493 更新された場合は@var{load-after}引数の値によってそのファイルをロードするかどうかを
12494 決定します。@var{load-after}引数の値は以下のいずれかです。
12495 @c COMMON
12496
12497 @table @code
12498 @item #t
12499 @c EN
12500 Load the file automatically if it's updated.
12501 @c JP
12502 ファイルが更新されていれば自動的にロード
12503 @c COMMON
12504 @item #f
12505 @c EN
12506 Do not load the file.
12507 @c JP
12508 ファイルをロードしない
12509 @c COMMON
12510 @item ask
12511 @c EN
12512 The symbol @code{ask} cause the procedure to prompt the user
12513 whether it should load the file. This is the default.
12514 @c JP
12515 シンボル@code{ask}の場合は、ロードすべきかどうかユーザに尋ねる。
12516 これがデフォルトの動作です。
12517 @c COMMON
12518 @end table
12519 @end defun
12520
12521
12522 @c ----------------------------------------------------------------------
12523 @node Lazy sequence utilities, Listener, Interactive session, Library modules - Gauche extensions
12524 @section @code{gauche.lazy} - Lazy sequence utilities
12525 @c NODE 遅延シーケンスユーティリティ, @code{gauche.lazy} - 遅延シーケンスユーティリティ
12526
12527 @deftp {Module} gauche.lazy
12528 @mdindex gauche.lazy
12529 @c EN
12530 This module provides utility procedures that yields lazy sequences.
12531 For the details of lazy sequences, @pxref{Lazy sequences}.
12532 @c JP
12533 このモジュールは、遅延シーケンスを生成するようなユーティリティ手続きの数々を提供します。
12534 遅延シーケンス自体については@ref{Lazy sequences}を参照してください。
12535 @c COMMON
12536 @end deftp
12537
12538 @c EN
12539 Since lazy sequences are forced implicitly and indistinguishable
12540 from ordinary lists, we don't need a separate set of procedures
12541 for @emph{taking} lists and lazy sequences; we can use @code{find}
12542 to search in both ordinary lists and lazy sequences.
12543 @c JP
12544 遅延シーケンスは自動的にforceされ、通常のリストと区別がつかないので、
12545 @emph{引数に}リストを取るか遅延シーケンスを取るかで別々の手続きを用意する必要はありません。
12546 例えば@code{find}は、リストから要素を探すのにも遅延シーケンスから要素を探すのにも使えます。
12547 @c COMMON
12548
12549 @c EN
12550 However, we do need a separate set of procedures
12551 for @emph{returning} either lists or lazy sequences. For example,
12552 @var{lmap} can take any kind of sequences, and
12553 returns lazy sequence (and calls the procedure on demand).
12554 @c JP
12555 しかし、@emph{返り値として}リストを返すか遅延シーケンスを返すかは、
12556 手続きを別にする必要があります。
12557 例えば@var{lmap}は、引数としてはどちらも受け取ることができますが、
12558 返り値は遅延シーケンスになります。(そして、高階手続きは必要な分だけ呼ばれます。)
12559 @c COMMON
12560
12561 @c EN
12562 This distinction is subtle, so I reiterate it. You can use
12563 both @code{map} and @code{lmap} on lazy sequences. If you want
12564 the result list at once, use @code{map}; it doesn't have
12565 overhead of delayed calculation. If you don't know you'll use
12566 the entire result, or you know the result will get very large
12567 list and don't want to waste space for an intermediate list,
12568 you want to use @code{lmap}.
12569 @c JP
12570 この区別は混乱しやすいので、整理しておきます。
12571 @code{map}と@code{lmap}のどちらも、遅延シーケンスに適用することができます。
12572 結果のリストを一度に計算した状態で手に入れたいなら、@code{map}を使います。
12573 その場合、遅延計算のオーバヘッドはかかりません。
12574 もし結果のリスト全てを使うかどうかわからない、
12575 あるいは結果のリストが巨大になるので中間結果の保持のためにメモリを圧迫したくない、
12576 といった場合には@code{lmap}を使いましょう。
12577 @c COMMON
12578
12579 @menu
12580 * Lazy sequence constructors::
12581 * Lazy sequence operations::
12582 * Lazy sequence with positions::
12583 @end menu
12584
12585 @node Lazy sequence constructors, Lazy sequence operations, Lazy sequence utilities, Lazy sequence utilities
12586 @subsection Lazy sequence constructors
12587 @c NODE 遅延シーケンスのコンストラクタ
12588
12589 @c EN
12590 You can construct lazy sequences with
12591 built-in @code{generator->lseq} and @code{lcons}.
12592 This module provides a few more constructors.
12593 @c JP
12594 遅延シーケンスは組み込みの@code{generator->lseq}や@code{lcons}で作ることができます。
12595 このモジュールでは追加でいくつかのコンストラクタを用意しています。
12596 @c COMMON
12597
12598 @defun x->lseq obj
12599 @c MOD gauche.lazy
12600 @c EN
12601 A convenience function to coerce @var{obj} to (possibly lazy) list.
12602 If @var{obj} is a list, it is returned as it is. If @var{obj} is
12603 other type of collection, the return value is a lazy sequence
12604 that iterates over the collection. If @var{obj} is other object,
12605 it is returned as it is (you can think of it as a special case
12606 of dotted list).
12607
12608 If you try @code{x->lseq} in REPL, it looks as if it just
12609 converts the input collection to a list.
12610 @c JP
12611 @var{obj}を(おそらく遅延された)リストに変換する便利な手続きです。
12612 @var{obj}がリストならそのまま返されます。
12613 @var{obj}が他のコレクション型なら、コレクションの各要素を順に返す遅延シーケンスが返されます。
12614 @var{obj}がそれ以外ならやはりそのまま返されます(ドットリストの特別な場合と考えられます)。
12615
12616 REPLで@code{x->lseq}を試すと、単に渡したコレクションをリストに変換しているだけのように見えるでしょう。
12617 @c COMMON
12618
12619 @example
12620 (x->lseq '#(a b c)) @result{} (a b c)
12621 @end example
12622
12623 @c EN
12624 But that's because the lazy sequence is forced by the output
12625 routine of the REPL.
12626 @c JP
12627 実際には、返された遅延シーケンスがREPLの出力ルーチンによってforceされてリストになっています。
12628 @c COMMON
12629 @end defun
12630
12631 @defun lunfold p f g seed :optional tail-gen
12632 @c MOD gauche.lazy
12633 @c EN
12634 A lazy version of @code{unfold} (@pxref{R7RS lists}).
12635 The arguments @var{p}, @var{f} and @var{g} are procedures,
12636 each of which take one argument, the current seed value.
12637 The predicate @var{p} determines when to stop, @var{f} creates
12638 each element, and @var{g} generates the next seed value.
12639 The @var{seed} argument gives the initial seed value.
12640 If @var{tail-gen} is given, it should also be a procedure
12641 that takes one argument, the last seed value (that is, the
12642 seed value @code{(p seed)} returned @code{#f}). It must return
12643 a (possibly lazy) list, that forms the tail of the resulting sequence.
12644 @c JP
12645 @code{unfold}の遅延バージョンです (@ref{R7RS lists}参照)。
12646 @var{p}、@code{f}、@code{g}引数はそれぞれ1引数を取る手続きで、
12647 現在のシード値を受けとります。
12648 @var{p}は生成を停止するかどうかを決める述語、
12649 @var{f}は要素を生成する手続き、そして
12650 @var{g}は次のシード値を生成する手続きです。
12651 @var{seed}引数には最初のシード値を与えます。
12652 @var{tail-gen}が与えられた場合、それは最後のシード値
12653 (つまり、@code{(p seed)}が@code{#f}を返した時のシード値)を
12654 受け取り、リストあるいは遅延シーケンスを返す手続きです。
12655 それが結果のシーケンスの末尾に付け足されます。
12656 @c COMMON
12657
12658 @example
12659 (lunfold ($ = 10 $) ($ * 2 $) ($ + 1 $) 0 (^_ '(end)))
12660 @result{} (0 2 4 6 8 10 12 14 16 18 end)
12661 @end example
12662 @end defun
12663
12664 @defun literate proc seed
12665 @c MOD gauche.lazy
12666 @c EN
12667 Creates an infinite sequence of
12668 @code{(@var{seed} (@var{proc} @var{seed}) (@var{proc} (@var{proc} @var{seed})) @dots{})}.
12669
12670 The same sequence can be created with
12671 @code{(lunfold (^_ #f) identity proc seed)},
12672 but this one is a lot more efficient.
12673
12674 See also @code{util.stream}, which as @code{stream-iterate}
12675 (@pxref{Stream constructors}).
12676 @c JP
12677 @code{(@var{seed} (@var{proc} @var{seed}) (@var{proc} (@var{proc} @var{seed})) @dots{})} という無限シーケンスを作ります。
12678
12679 同じシーケンスは@code{(lunfold (^_ #f) identity proc seed)}でも作れますが、
12680 こちらの方がずっと効率的です。
12681
12682 類似の手続きとして、@code{util.stream}に@code{stream-iterate}があります
12683 (@ref{Stream constructors}参照)。
12684 @c COMMON
12685
12686 @example
12687 (take (literate (pa$ + 1) 0) 10)
12688 @result{} (0 1 2 3 4 5 6 7 8 9)
12689 @end example
12690 @end defun
12691
12692 @defun coroutine->lseq proc
12693 @c MOD gauche.lazy
12694 @c EN
12695 The @var{proc} procedure is called with one argument,
12696 @var{yield}, which is also a procedure that takes one argument.
12697 Whenever @var{yeild} is called, the value passed to it
12698 becomes the next element of resulting lseq.
12699 When @var{proc} returns, lseq ends.
12700 @c JP
12701 @var{proc}引数がひとつの引数@var{yield}を伴って呼び出されます。
12702 @var{yeidl}はそれ自体がひとつの引数を取る手続きで、呼ばれるとそこに渡された
12703 値が、結果のlseqの要素となります。@var{proc}からリターンしたらlseqも終了となります。
12704 @c COMMON
12705
12706 @example
12707 (coroutine->lseq (^[yield] (dotimes [i 10] (yield (square i)))))
12708 @result {} (0 1 4 9 16 25 36 49 64 81)
12709 @end example
12710
12711 @c EN
12712 See also @code{generate} (@ref{Generator constructors}), and
12713 @code{coroutine->cseq} (@ref{Concurrent sequences}).
12714 @c JP
12715 @ref{Generator constructors}の@code{generate}、および
12716 @ref{Concurrent sequences}の@code{coroutine->cseq}も参照。
12717 @c COMMON
12718 @end defun
12719
12720
12721 @node Lazy sequence operations, Lazy sequence with positions, Lazy sequence constructors, Lazy sequence utilities
12722 @subsection Lazy sequence operations
12723 @c NODE 遅延シーケンスの操作
12724
12725 @defun lseq->list obj
12726 @c MOD gauche.lazy
12727 @c EN
12728 Returns @var{obj}, but if it is an lseq, fully computes all values.
12729 It is useful when you need to ensure necessary compuatation is done
12730 by certain moment, e.g. you want to ensure all data is read from a port before
12731 closing it.
12732 @c JP
12733 @var{obj}を返しますが、それがlseqであった場合、その要素を全て計算します。
12734 ある時点までに必要な計算が全て行われることを保証したい場合に便利です。
12735 例えばポートから遅延計算でデータを読み出している場合に、
12736 ポートを閉じる時点で全てのデータが読まれたことを保証したい、といった場合です。
12737 @c COMMON
12738 @end defun
12739
12740 @defun lmap proc seq seq2 @dots{}
12741 @c MOD gauche.lazy
12742 @c EN
12743 Returns a lazy sequence consists of values calculated
12744 by applying @var{proc} to every first element of @var{seq} @var{seq2}
12745 @dots{}, every second element of them, etc., until any of
12746 the input is exhausted.
12747 Application of @var{proc} will be delayed as needed.
12748 @c JP
12749 @var{proc}を@var{seq} @var{seq2} @dots{}の各1番目の要素、各2番目の要素、@dots{}
12750 に適用したものからなる遅延シーケンスを返します。
12751 どれかの入力が尽きた時が結果のシーケンスの終わりとなります。
12752 @var{proc}の適用は必要になるまで遅延されます。
12753 @c COMMON
12754
12755 @example
12756 @c EN
12757 ;; If you use map instead of lmap, this won't return
12758 @c JP
12759 p;; lmapのかわりにmapを使うとこの式の評価は終わらない
12760 @c COMMON
12761 (use math.prime)
12762 (take (lmap (pa$ * 2) *primes*) 10)
12763 @result{} (4 6 10 14 22 26 34 38 46 58)
12764 @end example
12765 @end defun
12766
12767 @defun lmap-accum proc seed seq seq2 @dots{}
12768 @c MOD gauche.lazy
12769 @c EN
12770 The procedure @var{proc} takes one element each from
12771 @var{seq} @var{seq2} @dots{}, plus the current seed value.
12772 It must return two values, a result value and the next seed value.
12773 The result of @code{lmap-accum} is a lazy sequence consists
12774 of the first values returned by each invocation of @var{proc}.
12775 @c JP
12776 @var{proc}は各シーケンス@var{seq} @var{seq2} @dots{}からの要素一つづつと、
12777 現在のシード値を取り、結果の要素値と次のシード値を返す手続きです。
12778 @var{lmap-accum}の結果は、@var{proc}が生成する要素値からなる遅延シーケンスとなります。
12779 @c COMMON
12780
12781 @example
12782 (use math.prime)
12783 (take (lmap-accum (^[p sum] (values sum (+ p sum))) 0 *primes*) 10)
12784 @result{} (0 2 5 10 17 28 41 58 77 100)
12785 @end example
12786
12787 @c EN
12788 This is a lazy version of @code{map-accum} (@pxref{Mapping over collection}),
12789 but @code{lmap-accum} does not return the final seed value. We only
12790 know the final seed value when we have the result sequence to the
12791 end, so it can't be calculated lazily.
12792 @c JP
12793 これは@code{map-accum}の遅延バージョンです(@ref{Mapping over collection}参照)。
12794 ただ、@code{lmap-accum}は最後のシード値を返しません。
12795 最後のシード値を返すためには結果の遅延シーケンスを最後まで計算する必要があるので、
12796 遅延計算にならないからです。
12797 @c COMMON
12798 @end defun
12799
12800 @defun lappend seq @dots{}
12801 @c MOD gauche.lazy
12802 @c EN
12803 Returns a lazy sequence which is concatenation of @var{seq} @dots{}.
12804 Unlike @code{append}, this procedure returns immediately, taking O(1) time.
12805 It is useful when you want to append large sequences but may use
12806 only a part of the result.
12807 @c JP
12808 シーケンス@var{seq} @dots{}をつなぎ合わせた遅延シーケンスを返します。
12809 @code{append}と違い、この手続きはO(1)時間で、すぐに返ります。
12810 従って、大きなシーケンスをつなぎ合わせたいけれど全部使うとは限らない、といった場合に便利です。
12811 @c COMMON
12812 @end defun
12813
12814 @defun lconcatenate seqs
12815 @c MOD gauche.lazy
12816 @c EN
12817 The @var{seqs} argument is a sequence of sequences. Returns
12818 a lazy sequence that is a concatenation of all the sequences in @var{seqs}.
12819
12820 This differs from @code{(apply lappend seqs)}, for @code{lconcatenate}
12821 can handle infinite number of lazy @var{seqs}.
12822 @c JP
12823 @var{seqs}引数はシーケンスのシーケンスです。
12824 それら各シーケンスを全てつなぎ合わせた遅延シーケンスを返します。
12825
12826 これと@code{(apply lappend seqs)}との違いは、@code{lconcatenate}は
12827 無限個の@var{seq}をつなぎ合わせられるということです。
12828 @c COMMON
12829 @end defun
12830
12831 @defun lappend-map proc seq1 seq @dots{}
12832 @c MOD gauche.lazy
12833 @c EN
12834 Lazy version of @code{append-map}. This differs from a simple
12835 composition of @var{lappend} and @var{lmap}, since
12836 @code{(apply lappend (lmap proc seq1 seq @dots{}))} would
12837 evaluate the result of @code{lmap} to the end before passing it to
12838 @code{lappend} (it's because @code{apply} need to determine
12839 the list of arguments before calling @code{lappend}).
12840 @c JP
12841 @code{append-map}の遅延バージョンです。
12842 これは単に@code{lappend}と@code{lmap}を合成したものとは異なります。
12843 というのも、@code{(apply lappend (lmap proc seq1 seq @dots{}))}では、
12844 @code{apply}が引数リストを確定するために@code{lmap}を最後まで評価しなければ
12845 ならないからです。
12846 @c COMMON
12847
12848 @c EN
12849 It also differs from
12850 @code{(lconcatenate (lmap proc seq1 seq @dots{}))} in the subtle way.
12851 @c JP
12852 また、これは@code{(lconcatenate (lmap proc seq1 seq @dots{}))}とも
12853 微妙に異なります。
12854 @c COMMON
12855
12856 @c EN
12857 Remember that Gauche's lazy sequence evaluates one element ahead?
12858 @code{lconcatenate} does that to the result of @code{lmap}.
12859 To see the effect, let's define a procedure with a debug print:
12860 @c JP
12861 Gaucheの遅延シーケンスは1つ要素を余分に評価することを覚えていますか。
12862 @code{lconcatenate}は@code{lmap}の結果に対して「一つ余分に評価」を行います。
12863 この効果を調べるために、デバッグプリントをつけた手続きを使ってみましょう。
12864 @c COMMON
12865
12866 @example
12867 (define (p x) #?=(list x x))
12868 @end example
12869
12870 @c EN
12871 You can see in the following example
12872 that @code{(apply lappend (lmap ...))} wouldn't delay
12873 any of application of @code{p}:
12874 @c JP
12875 次の例で、@code{(apply lappend (lmap ...))}が@code{p}
12876 の適用を遅延しないことがわかります。
12877 @c COMMON
12878
12879 @example
12880 gosh> (car (apply lappend (lmap p '(1 2 3))))
12881 (car (apply lappend (lmap p '(1 2 3))))
12882 #?="(standard input)":4:(list x x)
12883 #?- (1 1)
12884 #?="(standard input)":4:(list x x)
12885 #?- (2 2)
12886 #?="(standard input)":4:(list x x)
12887 #?- (3 3)
12888 1
12889 @end example
12890
12891 @c EN
12892 How about @code{lconcatenate}?
12893 @c JP
12894 @code{lconcatenate}はどうでしょう。
12895 @c COMMON
12896
12897 @example
12898 gosh> (car (lconcatenate (lmap p '(1 2 3))))
12899 (car (lconcatenate (lmap p '(1 2 3))))
12900 #?="(standard input)":4:(list x x)
12901 #?- (1 1)
12902 #?="(standard input)":4:(list x x)
12903 #?- (2 2)
12904 1
12905 @end example
12906
12907 @c EN
12908 Oops, even though we need only the first element, and the first
12909 result of @code{lmap}, @code{(1 1)}, provides the second element, too,
12910 @code{p} is already applied to the second input.
12911 @c JP
12912 おっと、最初の要素だけを取り出しているので、
12913 @code{lmap}の最初の結果である@code{(1 1)}だけが必要なはずなのに、
12914 @code{p}は2番目の入力に対しても適用されてしまいました。
12915 @c COMMON
12916
12917 @c EN
12918 This is because the intermediate lazy list of the result of @code{lmap} is
12919 evaluated ``one element ahead''. On the other hand, @code{lappend-map}
12920 doesn't have this problem.
12921 @c JP
12922 これは、@code{lmap}の結果である中間の遅延リストが「1要素余分に」評価されるためです。
12923 @code{lappend-map}にはこの問題がありません。
12924 @c COMMON
12925
12926 @example
12927 gosh> (car (lappend-map p '(1 2 3)))
12928 (car (lappend-map p '(1 2 3)))
12929 #?="(standard input)":4:(list x x)
12930 #?- (1 1)
12931 1
12932 @end example
12933 @end defun
12934
12935 @defun linterweave seq @dots{}
12936 @c MOD gauche.lazy
12937 @c EN
12938 Returns a lazy seq of the first items from @var{seq} @dots{}, then
12939 their second items, and so on. If the length of shortest sequence
12940 of @var{seqs} is N, the length of the resulting sequence is
12941 @code{(* N number-of-sequences)}. If all of @var{seq}s are infinite,
12942 the resulting sequence is also infinite.
12943 @c JP
12944 @var{seq} @dots{}の最初の要素を順番に取り、次に2番目の要素を順番に取り…として
12945 得られる遅延シーケンスを返します。
12946 入力のシーケンスのうち最も短いシーケンスの長さを@code{N}とすれば、
12947 結果の遅延シーケンスの長さは@code{(* N シーケンスの数)}となります。
12948 もし全ての入力シーケンスが無限長ならば、結果も無限長となります。
12949 @c COMMON
12950
12951 @example
12952 (linterweave (lrange 0) '(a b c d e) (circular-list '*))
12953 @result{} (0 a * 1 b * 2 c * 3 d * 4 e *)
12954 @end example
12955 @end defun
12956
12957 @defun lfilter proc seq
12958 @c MOD gauche.lazy
12959 @c EN
12960 Returns a lazy sequence that consists of non-false values calculated
12961 by applying @var{proc} on every elements in @var{seq}.
12962 @c JP
12963 @var{proc}を@var{seq}の各要素に適用し、@code{#f}でない値だけを集めた遅延シーケンスを
12964 返します。
12965 @c COMMON
12966 @end defun
12967
12968 @defun lfilter-map proc seq seq2 @dots{}
12969 @c MOD gauche.lazy
12970 @c EN
12971 Lazy version of @code{filter-map}.
12972 @c JP
12973 @code{filter-map}の遅延バージョンです。
12974 @c COMMON
12975 @end defun
12976
12977 @defun lstate-filter proc seed seq
12978 @c MOD gauche.lazy
12979 @c EN
12980 Lazy sequence version of @code{gstate-filter} (@pxref{Generator operations}).
12981 @c JP
12982 @code{gstate-filter}の遅延シーケンス版です (@ref{Generator operations}参照)。
12983 @c COMMON
12984 @end defun
12985
12986 @defun ltake seq n :optional fill? padding
12987 @defunx ltake-while pred seq
12988 @c MOD gauche.lazy
12989 @c EN
12990 Lazy versions of @code{take*} and @code{take-while}
12991 (@pxref{List accessors and modifiers}). Note that
12992 @code{ltake} works rather like @code{take*} than @code{take},
12993 that is, it won't complain if the input sequence has less than @var{n}
12994 elements. Because of the lazy nature of @code{ltake}, it can't know
12995 whether input is too short or not before returning the sequence.
12996 @c JP
12997 @code{take*}と@code{take-while}の遅延バージョンです
12998 (@ref{List accessors and modifiers}参照)。
12999 @code{ltake}は@code{take}ではなく@code{take*}のように動作します。
13000 つまり、入力シーケンスの長さが@code{n}以下でもエラーになりません。
13001 というもの、@code{ltake}は怠惰に動作するため、
13002 値を返す時点では入力が足りないかどうかわからないからです。
13003 @c COMMON
13004
13005 @c EN
13006 There are no @code{ldrop} and @code{ldrop-while}; you don't need them.
13007 if you apply
13008 @code{drop} and @code{drop-while} on lazy sequence, they return
13009 lazy sequence.
13010 @c JP
13011 @code{ldrop}と@code{ldrop-white}はありません。必要ないからです。
13012 @code{drop}と@code{drop-white}を遅延シーケンスに適用すれば、
13013 遅延シーケンスが返されます。
13014 @c COMMON
13015 @end defun
13016
13017 @defun lrxmatch rx seq
13018 @c MOD gauche.lazy
13019 @c EN
13020 This is a lazy sequence version of @code{grxmatch}
13021 (@pxref{Generator operations}).
13022
13023 The @var{seq} argument must be a sequence of characters (including
13024 ordinary strings).
13025 The return value is a lazy sequence of @var{<rxmatch>} objects,
13026 each representing strings matching to the regular expression @var{rx}.
13027 @c JP
13028 @code{grxmatch}の遅延シーケンス版です(@ref{Generator operations}参照)。
13029
13030 @var{seq}は文字のシーケンス (文字列を含む) でなければなりません。
13031 返り値は@var{<rxmatch>}オブジェクトからなる遅延シーケンスです。
13032 各要素の@var{<rxmatch>}オブジェクトが、
13033 入力中の@var{rx}にマッチした部分を表現しています。
13034 @c COMMON
13035
13036 @c EN
13037 This procedure is convenient to scan character sequences from
13038 lazy character sequences, but it may be slow if you're looking for
13039 rarely matching string from very large non-string input.
13040 Unless @var{seq} is a string,
13041 @code{lrxmatch} buffers certain length of input,
13042 and if matching phrase isn't found, it extend the buffer and scan
13043 again from the beginning, since the match may span from the end of
13044 previous chunk to the newly added portion.
13045 @c JP
13046 この手続きは遅延文字シーケンス中からマッチするパターンを探すのに便利ですが、
13047 入力が文字列ではなく、パターンが滅多にマッチしない場合に非常に遅くなる危険があることに
13048 注意してください。@code{lrxmatch}は入力をある程度バッファしてスキャンし、
13049 マッチがみつからなければ、バッファを拡張してまた最初からスキャンします。
13050 というのも、新たなマッチが以前のバッファの末尾から新たに追加された部分へと
13051 またがっている可能性があるからです。
13052 @c COMMON
13053 @end defun
13054
13055 @defun lslices seq k :optional fill? padding
13056 @c MOD gauche.lazy
13057 @c EN
13058 Lazy version of @code{slices} (@pxref{List accessors and modifiers}).
13059 @c JP
13060 @code{slices}の遅延バージョンです(@ref{List accessors and modifiers}参照)。
13061 @c COMMON
13062
13063 @example
13064 (lslices '(a b c d e f) 2)
13065 @result{} ((a b) (c d) (e f))
13066 @end example
13067 @end defun
13068
13069 @node Lazy sequence with positions, , Lazy sequence operations, Lazy sequence utilities
13070 @subsection Lazy sequence with positions
13071 @c NODE 位置情報つき遅延シーケンス
13072
13073 @c EN
13074 Treating input data stream as a lazy sequence is a powerful abstraction;
13075 especially, it allows unlimited lookahead with simple list manipulation.
13076 @c JP
13077 入力データストリームを遅延シーケンスとして取り扱うのは強力な抽象化です。
13078 とりわけ、単純なリスト操作を使って制限の無い先読みを実現できます。
13079 @c COMMON
13080
13081 @c EN
13082 However, you'll have a difficulty when you want to know the position
13083 of the input data within the input stream, e.g. for an error message.
13084 Unlike reading from a port, which gives you the current input position,
13085 a lazy sequence just looks like a list and unknown amout of data
13086 may be prefetched from the real source.
13087 @c JP
13088 しかし、データの入力ストリーム内での位置情報を、例えばエラーメッセージのために取りたいといった
13089 ことは難しくなります。ポートから読んでいる場合は、ポートに問い合わせれば現在の位置を
13090 教えてくれます。しかし遅延シーケンスは普通のリストと同じように見え、
13091 入力ソースに問い合わせようにも既にデータは先読みされてしまっているかもしれません。
13092 @c COMMON
13093
13094 @c EN
13095 Gauche has special pair objects, called extended pairs, that can
13096 carry auxiliary information (@pxref{Extended pairs and pair attributes}).
13097 You can create a lazy sequence that carries positional information
13098 using the feature.
13099 @c JP
13100 Gaucheは拡張ペアと呼ばれる、補助的な情報を保持できる特別なペアを持っています
13101 (@ref{Extended pairs and pair attributes}参照)。それを利用して、
13102 遅延シーケンスに入力位置情報を持たせることができます。
13103 @c COMMON
13104
13105 @deftp {Class} <sequence-position>
13106 @c MOD gauche.lazy
13107 @c EN
13108 An immutable structure holding positional information. It is returned
13109 by @code{lseq-position}. The information is queried by
13110 the following procedure.
13111 @c JP
13112 位置情報を保持する変更不可な構造で、@code{lseq-position}から返されます。
13113 情報は以下の手続きでアクセスできます。
13114 @c COMMON
13115 @end deftp
13116
13117 @defun sequence-position-source seqpos
13118 @defunx sequence-position-line seqpos
13119 @defunx sequence-position-column seqpos
13120 @defunx sequence-position-item-count seqpos
13121 @c MOD gauche.lazy
13122 @c EN
13123 Query positional information to a @code{<sequence-position>} instance
13124 @var{seqpos}.
13125 @c JP
13126 @code{<sequence-position>}のインスタンス@var{seqpos}から情報を取り出します。
13127 @c COMMON
13128
13129 @c EN
13130 Returns the source name (usually the source file name),
13131 the line count (starting from 1), the column count (starting from 1),
13132 and the item count (number of characters, starting from 0).
13133 @c JP
13134 それぞれ、ソースの名前(通常はソースファイル名)、
13135 行番号(1から)、カラム番号(1から)、アイテムカウント(読まれた文字数、0から)です。
13136 @c COMMON
13137
13138 @c EN
13139 The source name may be @code{#f} if it is not available.
13140 @c JP
13141 ソース名が不明な場合は@code{#f}になっています。
13142 @c COMMON
13143 @end defun
13144
13145 @defun port->char-lseq/position :optional port :key source-name start-line start-column start-item-count
13146 @c MOD gauche.lazy
13147 @c EN
13148 Like @code{port->char-lseq}, returns a lazy sequence of characters read
13149 from an input port @var{port}. However, the sequence returned by this
13150 procedure has positional info attached, and can be retrieved
13151 by @code{lseq-position}.
13152 @c JP
13153 @code{port->char-lseq}と同じように、@var{port}から読まれる文字の遅延シーケンスを
13154 返します。ただし、そのシーケンスには位置情報が付加されており、
13155 @code{lseq-position}で取り出すことができます。
13156 @c COMMON
13157
13158 @c EN
13159 The @var{source-name}, @var{start-line}, @var{start-column} and
13160 @var{start-item-count} initializes the positional info before
13161 start reading characters. The default values are
13162 @code{(port-name port)}, 1, 1 and 0, respectively.
13163 If you're reading from a freshly opened port, the default values suffice.
13164 Specify these if you've already read some data from the port, for example.
13165 @c JP
13166 @var{source-name}、@var{start-line}、@var{start-column}、
13167 @var{start-item-count}は最初の文字を読み出す前の位置情報の初期化に使われます。
13168 デフォルトはそれぞれ、@code{(port-name port)}、1、1、0で、
13169 オープンしたばかりのポートから読み出す場合はデフォルトが適切な値となっています。
13170 既にポートからいくらか読み出してしまった場合などにこれらの値を指定してください。
13171 @c COMMON
13172 @end defun
13173
13174
13175 @defun generator->lseq/position char-gen :key source-name start-line start-column start-item-count
13176 @c MOD gauche.lazy
13177 @c EN
13178 Like @code{generator->lseq}, returns a lazy sequence of characters
13179 generated by @var{char-gen}. However, the sequence returned by this
13180 procedure has positional info attached, and can be retrieved
13181 by @code{lseq-position}.
13182 @c JP
13183 @code{generator->lseq}と同じように、ジェネレータ@var{char-gen}から生成される
13184 文字からなる遅延シーケンスを返します。ただし、そのシーケンスには位置情報が付加されており、
13185 @code{lseq-position}で取り出すことができます。
13186 @c COMMON
13187
13188 @c EN
13189 The @var{source-name}, @var{start-line}, @var{start-column} and
13190 @var{start-item-count} initializes the positional info before
13191 start reading characters. The default values are
13192 @code{#f}, 1, 1 and 0, respectively.
13193 @c JP
13194 @var{source-name}、@var{start-line}、@var{start-column}、
13195 @var{start-item-count}は最初の文字を読み出す前の位置情報の初期化に使われます。
13196 デフォルトはそれぞれ、@code{(port-name port)}、1、1、0です。
13197 @c COMMON
13198 @end defun
13199
13200 @defun lseq-position seq
13201 @c MOD gauche.lazy
13202 @c EN
13203 If @var{seq} is a lazy sequence with positional info attached,
13204 retrieve it and returns a @code{<sequence-position>} instance.
13205 @c JP
13206 @var{seq}が遅延シーケンスで位置情報が付加されている場合は、
13207 その情報を@code{<sequence-position>}のインスタンスにして返します。
13208 @c COMMON
13209
13210 @c EN
13211 If @var{seq} doesn't have positional info, or not even a sequence,
13212 @code{#f} is returned.
13213 @c JP
13214 @var{seq}に位置情報が付加されていない、あるいは遅延シーケンス以外のオブジェクトであった
13215 場合は@code{#f}が返されます。
13216 @c COMMON
13217 @end defun
13218
13219
13220 @c ----------------------------------------------------------------------
13221 @node Listener, User-level logging, Lazy sequence utilities, Library modules - Gauche extensions
13222 @section @code{gauche.listener} - Listener
13223 @c NODE リスナー, @code{gauche.listener} - リスナー
13224
13225 @deftp {Module} gauche.listener
13226 @mdindex gauche.listener
13227 @c EN
13228 This module provides a convenient way to enable multiple
13229 read-eval-print loop (repl) concurrently.
13230 @c JP
13231 このモジュールは、
13232 複数のread-eval-printループ(repl)を並行して動作させるのに便利な機能を提供します。
13233 @c COMMON
13234
13235 @c EN
13236 An obvious way to run multiple repls is to use threads;
13237 creating as many threads as sessions and calling
13238 @code{read-eval-print-loop} (@pxref{Eval and repl}) from each thread.
13239 Nevertheless, sometimes single threaded implementation is preferred.
13240 For instance, you're using a library which is not MT-safe,
13241 or your application already uses select/poll-based dispatching mechanism.
13242 @c JP
13243 複数のreplを実現する自明な方法は、セッション毎にスレッドを生成して
13244 各スレッド上で@code{read-eval-print-loop} (@ref{Eval and repl}参照)を
13245 呼ぶことですが、シングルスレッドでの実装が好ましい場合もあります。
13246 例えばアプリケーションがMT-safeでないライブラリに大きく依存していたり、
13247 既にアプリケーションがselectやpollをベースにしたディスパッチメカニズムを
13248 持っているような場合です。
13249 @c COMMON
13250
13251 @c EN
13252 To implement repl in the single-threaded selection-base application,
13253 usually you register a handler that is called when data is available
13254 in the listening port. The handler reads the data and add them into
13255 a buffer. Then it examines if the data in the buffer consists a
13256 complete expression, and if so, it reads the expression from the
13257 buffer, evaluates it, then prints the result to the reporting port.
13258 The @code{<listener>} class in this module provides this handler mechanism,
13259 so all you need to do is to register the handler to your dispatching
13260 mechanism.
13261 @c JP
13262 シングルスレッドのselectionベースのアプリケーションでreplを実装するには、
13263 通常、listenしているポートにデータが到着した時に呼ばれるハンドラを登録します。
13264 ハンドラはポートからデータを読み、内部バッファに追加します。
13265 そして内部バッファをスキャンし、データが完全な式を構成した場合は
13266 それをS式として読みだし、評価して結果をポートに流します。
13267 このモジュールの@code{<listener>}クラスはこのハンドラのメカニズムを提供するので、
13268 アプリケーション側はそれを自分のディスパッチメカニズムに登録するだけで済みます。
13269 @c COMMON
13270
13271 @c EN
13272 Note: it may also be desirable to buffer the output sometimes,
13273 but the current version doesn't implement it.
13274 @c JP
13275 註:場合によっては、出力もバッファリングする必要があるかもしれませんが、
13276 現在はそれは実装されていません。
13277 @c COMMON
13278 @end deftp
13279
13280 @subheading Listener API
13281
13282 @deftp {Class} <listener>
13283 @clindex listener
13284 @c MOD gauche.listener
13285 @c EN
13286 An object that maintains the state of a repl session.
13287 It has many external slots to customize its behavior.
13288 Those slot values can be set at construction time
13289 by using the keyword of the same name as the slot,
13290 or can be set by @code{slot-set!} afterwards. However,
13291 most of them should be set before calling
13292 @code{listener-read-handler}.
13293 @c JP
13294 Replセッションの状態を維持するオブジェクトです。
13295 オブジェクトのふるまいをカスタマイズするためにいくつもの外部スロットがあります。
13296 これらのスロットの値は、スロットの名前と同名のキーワード引数を用いて
13297 オブジェクトの構築時に指定することもできますし、オブジェクト構築後に
13298 @code{slot-set!}で設定することもできますが、@code{listener-read-handler}
13299 を呼ぶ前に確定していなければなりません。
13300 @c COMMON
13301
13302 @defivar <listener> input-port
13303 @c EN
13304 Specifies the input port from which the listener get the input.
13305 The default value is the current input port when the object is
13306 constructed.
13307 @c JP
13308 リスナーが入力を受けとる入力ポートを指定します。デフォルト値は、
13309 オブジェクトが構築された時のカレント入力ポートです。
13310 @c COMMON
13311 @end defivar
13312
13313 @defivar <listener> output-port
13314 @c EN
13315 Specifies the output port to which the listener output will go.
13316 The default value is the current output port when the object is
13317 constructed.
13318 @c JP
13319 リスナーが出力をおこなう出力ポートを指定します。デフォルト値は、
13320 オブジェクトが構築された時のカレント出力ポートです。
13321 @c COMMON
13322 @end defivar
13323
13324 @defivar <listener> error-port
13325 @c EN
13326 Specifies the output port to which the listener's error messages will go.
13327 The default value is the current error port when the object is
13328 constructed.
13329 @c JP
13330 リスナーのエラーメッセージを出力するポートを指定します。デフォルト値は、
13331 オブジェクトが構築された時のカレントエラー出力ポートです。
13332 @c COMMON
13333 @end defivar
13334
13335 @defivar <listener> reader
13336 @c EN
13337 A procedure with no arguments. It should read a Scheme expression
13338 from the current input port when called.
13339 The default value is system's @code{read} procedure.
13340 @c JP
13341 引数を取らない手続きです。呼び出し時のカレント入力ポートからScheme式を
13342 読み込まなければなりません。デフォルト値はシステムの@code{read}手続きです。
13343 @c COMMON
13344 @end defivar
13345
13346 @defivar <listener> evaluator
13347 @c EN
13348 A procedure that takes two arguments, a Scheme expression and
13349 an environment specifier. It should evaluate the expression in
13350 the given environment and returns zero or more value(s).
13351 The default value is system's @code{eval} procedure.
13352 @c JP
13353 Scheme式と環境指定子のふたつの引数をとる手続きです。
13354 式を与えられた環境で評価し、0個以上の値を返さなければなりません。
13355 デフォルト値はシステムの@code{eval}手続きです。
13356 @c COMMON
13357 @end defivar
13358
13359 @defivar <listener> printer
13360 @c EN
13361 A procedure that takes zero or more argument(s) and prints them
13362 out to the current output port. The default value is a procedure
13363 that prints each value by @code{write}, followed by a newline.
13364 @c JP
13365 0以上の引数をとり、カレント出力ポートに印字する手続きです。
13366 デフォルト値は、各値を@code{write}で印字したのち、改行する手続きです。
13367 @c COMMON
13368 @end defivar
13369
13370 @defivar <listener> prompter
13371 @c EN
13372 A procedure with no arguments. It should prints a prompt
13373 to the current output port. The output is flushed by the listener
13374 object so this procedure doesn't need to care about it.
13375 The default procedure prints @code{"listener> "}.
13376 @c JP
13377 引数をとらない手続きです。カレント出力ポートにプロンプトを
13378 印字しなければなりません。リスナーは、この手続きが面倒を見なくてよいように、
13379 出力をフラッシュします。
13380 デフォルトの手続きは @code{"listener> "} を印字します。
13381 @c COMMON
13382 @end defivar
13383
13384 @defivar <listener> environment
13385 @c EN
13386 An environment specifier where the expressions will be
13387 evaluated. The default value is the value returned by
13388 @code{(interaction-environment)}.
13389 @c JP
13390 式を評価する環境指定子です。デフォルト値は@code{(interaction-environment)}が
13391 返す値です。
13392 @c COMMON
13393 @end defivar
13394
13395 @defivar <listener> finalizer
13396 @c EN
13397 A thunk that will be called when EOF is read from @code{input-port}.
13398 During the execution of @var{finalizer}, the current input, output
13399 and error ports are restored to the ones when
13400 @code{listener-read-handler} is called.
13401
13402 It can be @code{#f} if no such procedure is needed.
13403 The default value is @code{#f}.
13404 @c JP
13405 @code{input-port}からEOFが読み込まれたときに呼び出されるサンクです。
13406 @var{finalizer}実行中は、現在の入力、出力、エラー出力ポートは、
13407 @code{listener-read-handler}が呼ばれたときのものに戻っています。
13408
13409 このような手続きが必要ない場合は@code{#f}にしておいて構いません。
13410 デフォルトの値は@code{#f}です。
13411 @c COMMON
13412 @end defivar
13413
13414 @defivar <listener> error-handler
13415 @c EN
13416 A procedure that takes one argument, an error exception. It is
13417 called when an error occurs during read-eval-print stage,
13418 with the same dynamic environment as the error is signaled.
13419 The default value is a procedure that simply prints the
13420 error exception by @code{report-error}.
13421 @c JP
13422 エラー例外をひとつ引数としてとる手続きです。read-eval-printの最中に
13423 エラーが発生すると、エラーシグナルが発生すのと同じ動的環境で、
13424 呼び出されます。
13425 デフォルト値はエラー例外を@code{report-error}を使って印字する手続きです。
13426 @c COMMON
13427 @end defivar
13428
13429 @defivar <listener> fatal-handler
13430 @c EN
13431 A procedure that takes one argument, an error exception.
13432 It is called when a @emph{fatal} error occurred (see below
13433 for the precise definition). If this handler is
13434 called, you should assume you can no longer continue the listener
13435 session safely, even write messages to the client. This handler
13436 is to log such condition or to clean up the listener.
13437 During the execution of @var{fatal-handler}, the current input, output
13438 and error ports are restored to the ones when
13439 @code{listener-read-handler} is called.
13440 @c JP
13441 エラー例外をひとつの引数としてとる手続です。
13442 @emph{fatal}エラー(詳しい定義については後述)が発生したときに呼び出され
13443 ます。このハンドラが呼び出された場合、リスナーセッションは安全に続ける
13444 ことはできないと思ってください。クライアントへのメッセージを書くこと
13445 もできません。このハンドラはこういう状況でログを残したりリスナーの
13446 クリーンアップするためのものです。@var{fatal-handler}を実行中は現在の
13447 入力、出力、エラー出力は@code{listener-read-handler}が呼ばれたときのも
13448 のに戻ります。
13449 @c COMMON
13450
13451 @c EN
13452 If @var{fatal-handler} returns @code{#f}, @var{finalizer} is
13453 called afterwards. With this, you can implement a common
13454 cleanup work in @var{finalizer}. If @var{fatal-handler} returns
13455 a true value, @var{finalizer} will not be called.
13456 @c JP
13457 @var{fatal-handler}が@code{#f}を返す場合、@var{finalizer}は後で呼ばれ
13458 ます。これを利用して@var{finalizer}で共通のクリーンアップを実行するよ
13459 うな実装ができます。@var{fatal-handler}が真の値を返した場合には、
13460 @var{finalizer}は呼ばれません。
13461 @c COMMON
13462
13463 @end defivar
13464
13465 @end deftp
13466
13467
13468 @deffn {Method} listener-read-handler (listener <listener>)
13469 @c MOD gauche.listener
13470 @c EN
13471 Returns a thunk that is to be called when a data is available
13472 from @code{input-port} of the listener.
13473
13474 The returned thunk (read handler) does the following steps.
13475 Note that the first prompt is @emph{not} printed by this
13476 procedure. See @code{listener-show-prompt} below.
13477 @enumerate
13478 @item
13479 Reads available data from @code{input-port} and appends it to the
13480 listener's internal buffer.
13481 @item
13482 Scans the buffer to see if it has a complete S-expression.
13483 If not, returns.
13484 @item
13485 Reads the S-expression from the buffer.
13486 The read data is removed from the buffer.
13487 @item
13488 Evaluates the S-expression, then prints the result to
13489 @code{output-port}.
13490 @item
13491 Prints the prompt by prompter procedure to @code{output-port},
13492 then flush @code{output-port}.
13493 @item
13494 Repeats from 2.
13495 @end enumerate
13496 @c JP
13497 リスナーの@code{input-port}から読み込んだデータが正しい時に
13498 呼ばれるサンクを返します。
13499
13500 返されたサンク(readハンドラ)は、以下のように実行されます。
13501 この手続きは最初のプロンプトを印字@emph{しない}ことに
13502 注意してください。これについては後述の@code{listener-show-prompt}を
13503 参照してください。
13504 @enumerate
13505 @item
13506 @code{input-port}にあるデータを読み、これをリスナーの内部バッファに
13507 連結する。
13508 @item
13509 バッファをスキャンして、それが完結したS式であるかを確かめ、
13510 完結していなければ、リターンする。
13511 @item
13512 バッファからそのS式を読み込み、そのバッファからは
13513 そのデータを除去する。
13514 @item
13515 そのS式を評価して、結果を@code{output-port}へ印字する。
13516 @code{output-port}.
13517 @item
13518 プロンプタ手続きを使って、プロンプトを@code{output-port}に印字したのち、
13519 @code{output-port}をフラッシュする。
13520 @item
13521 2から繰り返す。
13522 @end enumerate
13523 @c COMMON
13524 @end deffn
13525
13526 @deffn {Method} listener-show-prompt (listener <listener>)
13527 @c MOD gauche.listener
13528 @c EN
13529 Shows a prompt to the listener's output port, by using
13530 listener's prompter procedure. Usually you want to use
13531 this procedure to print the first prompt, for instance,
13532 when the client is connected to the listener socket.
13533 @c JP
13534 リスナーの出力ポートにプロンプトを表示します。表示にはリスナーの
13535 プロンプタ手続きを使います。通常この手続きは最初のプロンプトを
13536 印字するために使います。たとえば、クライアントがリスナーソケットに
13537 接続してきたときです。
13538 @c COMMON
13539 @end deffn
13540
13541 @defun complete-sexp? str
13542 @c MOD gauche.listener
13543 @c EN
13544 Returns @code{#t} if @var{str} contains a complete S-expression.
13545 This utility procedure is exported as well, since it might be useful
13546 for other purposes.
13547
13548 Note that this procedure only checks syntax of the expressions,
13549 and doesn't rule out erroneous expressions (such as containing
13550 invalid character name, unregistered SRFI-10 tag, etc.).
13551 This procedure may raise an error if the input contains
13552 '@code{#<}' character sequence.
13553 @c JP
13554 もし、@var{str}が完結したS式を含んでいれば@code{#t}を返します。
13555 このユーティリティ手続きは、他の目的にも有用なので、
13556 他の手続きといっしょにエクスポートしてあります。
13557
13558 この手続きは構文のチェックをするだけで、(不正な文字名を含んだり、
13559 登録されていないSRFI-10のタグを含むなど)誤りのある式を判別するわけでは
13560 ないことに注意してください。この手続きは入力が'@code{#<}'文字の
13561 シーケンスを含むと、エラーを発生させます。
13562 @c COMMON
13563 @end defun
13564
13565 @c EN
13566 @subheading Error handling
13567 @c JP
13568 @subheading エラー処理
13569 @c COMMON
13570
13571 @c EN
13572 There are a few error situations the listener handles differently.
13573 @c JP
13574 エラー状況によりリスナーのエラー処理法が異ります。
13575 @c COMMON
13576
13577 @itemize @bullet
13578 @item
13579 @c EN
13580 @emph{Fatal error} - An error situation that the listener session
13581 can no longer go on safely. You cannot even tell so to the
13582 listener client, since the connection to the client may be broken.
13583 All you can do is to clean up the listener session (e.g. removes
13584 the handler). This case happens in (1) a low-level system error
13585 occurs during reading from @var{input-port}. (A syntax error
13586 of the input isn't count as fatal, and handled as REPL error described
13587 below.), (2) a @code{SIGPIPE} signal is raised during writing to
13588 @var{output-port}, or (3) an unhandled error occurred during executing
13589 @var{error-handler}.
13590 @c JP
13591 @emph{致命的エラー} - もはやリスナーセッションを安全に続けることが不可
13592 能なエラー状況です。リスナーのクライアントとの接続が切れてしまうこと
13593 になるので、状況を知らせることもできません。できることはリスナーセッショ
13594 ンをクリーンアップする(たとえばハンドラを削除する)ことだけです。このエ
13595 ラーは以下の場合に発生します。(1) @var{input-port}からの読み込み中に低
13596 レベルのシステムエラーが発生した場合。(入力の構文エラーは致命的エラー
13597 とはみなさず、後述のREPLエラーとして処理されます。) (2)
13598 @var{output-port} へ書き出し中に @code{SIGPIPE} シグナルがあがった場合
13599 (3) @var{error-handler} を実行中に処理未設定エラーが発生した場合。
13600 @c COMMON
13601
13602 @c EN
13603 When this situation happens, the @var{fatal-handler} is called
13604 if it is given. If @var{fatal-handler} returns @code{#f}, or
13605 @var{fatal-handler} isn't given, @var{finalizer} is also called.
13606 @c JP
13607 このような状況が起こると、@var{fatal-handler}が与えられていればそれが
13608 呼ばれます。@var{fatal-handler}が@code{#f}を返すか、
13609 @var{fatal-handler}が与えられていなければ、@var{finalizer}が呼ばれます。
13610 @c COMMON
13611
13612 @item
13613 @c EN
13614 @emph{Leaked error} - If an error occurs during executing
13615 @var{fatal-handler} or @var{finalizer}, we don't have no more
13616 safety net. The error is 'leaked' outside the listener handler,
13617 and should be handled by the user of @code{gauche.listener}.
13618 @c JP
13619 @emph{リークエラー} - @var{fatal-handler}あるいは@var{finalizer}を実行
13620 中にエラーが起こるともはやセーフティネットはありません。このエラーはリ
13621 スナーハンドラの外に漏れだしますので、@code{gauche.listener}のユーザが
13622 自ら処理しなければなりません。
13623 @c COMMON
13624
13625 @c EN
13626 Generally this situation should be considered as a bug of
13627 the program; you should make sure to catch foreseeable errors within
13628 @var{fatal-handler} and @var{finalizer}.
13629 @c JP
13630 一般的にはこのような状況はプログラムのバグだと考えるべきです。したがっ
13631 て、想定されたエラーとして@var{fatal-handler}および@var{finalizer}内で
13632 捕捉されるべきです。
13633 @c COMMON
13634
13635 @item
13636 @c EN
13637 @emph{REPL error} - Other errors are handled by @var{error-handler}.
13638 @c JP
13639 @emph{REPLエラー} - @var{error-handler}で処理されるその他のエラー
13640 @c COMMON
13641 @end itemize
13642
13643 @c EN
13644 @subheading Listener example
13645 @c JP
13646 @subheading リスナーの例
13647 @c COMMON
13648
13649 @c EN
13650 The following code snippet opens a server socket, and opens
13651 a Scheme interactive session when a client is connected.
13652 (Note: this code is just for demonstration. Do not run
13653 this program on the machine accessible from outside network!)
13654 @c JP
13655 以下のコード断片は、サーバソケットをオープンし、クライアントが
13656 接続してきたときにSchemeの対話的セッションをオープンするというものです。
13657 (註: このコードはdemo用のコードです。決して、外のネットワークから
13658 アクセス可能なマシン上で走らせてはいけません!)
13659 @c COMMON
13660
13661 @example
13662 (use gauche.net)
13663 (use gauche.selector)
13664 (use gauche.listener)
13665
13666 (define (scheme-server port)
13667 (let ((selector (make <selector>))
13668 (server (make-server-socket 'inet port :reuse-addr? #t))
13669 (cid 0))
13670
13671 (define (accept-handler sock flag)
13672 (let* ((client (socket-accept server))
13673 (id cid)
13674 (input (socket-input-port client :buffering :none))
13675 (output (socket-output-port client))
13676 (finalize (lambda ()
13677 (selector-delete! selector input #f #f)
13678 (socket-close client)
13679 (format #t "client #~a disconnected\n" id)))
13680 (listener (make <listener>
13681 :input-port input
13682 :output-port output
13683 :error-port output
13684 :prompter (lambda () (format #t "client[~a]> " id))
13685 :finalizer finalize))
13686 (handler (listener-read-handler listener))
13687 )
13688 (format #t "client #~a from ~a\n" cid (socket-address client))
13689 (inc! cid)
13690 (listener-show-prompt listener)
13691 (selector-add! selector input (lambda _ (handler)) '(r))))
13692
13693 (selector-add! selector
13694 (socket-fd server)
13695 accept-handler
13696 '(r))
13697 (format #t "scheme server started on port ~s\n" port)
13698 (do () (#f) (selector-select selector))))
13699 @end example
13700
13701 @c ----------------------------------------------------------------------
13702 @node User-level logging, Instance pools, Listener, Library modules - Gauche extensions
13703 @section @code{gauche.logger} - User-level logging
13704 @c NODE ユーザレベルのロギング, @code{gauche.logger} - ユーザレベルのロギング
13705
13706 @deftp {Module} gauche.logger
13707 @mdindex gauche.logger
13708 @c EN
13709 Provides a simple interface to log the program's activity.
13710 The information can be written to the specified file,
13711 or to the system logger using @code{syslog(3)}.
13712 When a file is used, syslog-like prefix string is added
13713 to each message, which is configurable. It can also takes care of
13714 locking of the file (see the description of @code{lock-policy} below).
13715 @c JP
13716 プログラムからログを書き出す簡単なインタフェースを提供します。
13717 情報は指定されたファイルへ書き出されるか、もしくは@code{syslog(3)}を
13718 使ってシステムログへと送られます。
13719 ファイルに書き出される場合は、
13720 syslogに似たプレフィクスが各メッセージの前に追加されます。
13721 プレフィクスはカスタマイズすることもできます。
13722 また、ログファイルの排他制御も行われます (下の@code{lock-policy}の説明を
13723 参照して下さい)。
13724 @c COMMON
13725 @end deftp
13726
13727 @deftp {Class} <log-drain>
13728 @clindex log-drain
13729 @c MOD gauche.logger
13730 @c EN
13731 Represents the destination of log messages.
13732 There's one implicit global @code{<log-drain>} instance, which is
13733 used by default. However, you can create as many instances
13734 by @code{make} method as you want, in case if you want to log
13735 to more than one destination.
13736 @c JP
13737 ログメッセージの行き先を表現するオブジェクトです。
13738 デフォルトのログの行き先として、グローバルな@code{<log-drain>}のインスタンスが
13739 ひとつ作られます。
13740 ログをいくつかにわけて出力する場合などは@code{make}メソッドを使って
13741 いくつでも@code{<log-drain>}のインスタンスを作ることができます。
13742 @c COMMON
13743
13744 @defivar {<log-drain>} path
13745 @c EN
13746 Designates destination of log output. It can be one of the following
13747 values.
13748
13749 @table @asis
13750 @item @r{string}
13751 Pathname of the log file. The output is written to it.
13752 @item @code{current-error}
13753 @itemx @code{#t}
13754 The output goes to the current error port.
13755 @item @code{current-output}
13756 The output goes to the current output port.
13757 @item @code{syslog}
13758 The output is sent to the system logger.
13759 @item @code{ignore}
13760 Make @code{log-format} does nothing.
13761 @item @code{#f}
13762 The output is turned to a string and returned from
13763 @code{log-format}.
13764 @end table
13765
13766 By default, this slot is @code{#f}.
13767 @c JP
13768 ログの出力先を指定します。以下の値をとることができます。
13769
13770 @table @asis
13771 @item @r{文字列}
13772 ログファイルのパスを指定します。出力はそのファイルへと書き出されます。
13773 @item @code{current-error}
13774 @itemx @code{#t}
13775 出力は現在のエラーポートに向かいます。
13776 @item @code{current-output}
13777 出力は現在の出力ポートに向かいます。
13778 @item @code{syslog}
13779 出力はシステムログへと送られます。
13780 @item @code{ignore}
13781 @code{log-format}が何もしないようにします。
13782 @item @code{#f}
13783 出力は文字列になって@code{log-format}からの戻り値となります。
13784 @end table
13785
13786 このスロットの初期値は@code{#f}です。
13787 @c COMMON
13788 @end defivar
13789
13790 @defivar {<log-drain>} prefix
13791 @c EN
13792 Specifies the prefix string that is attached to the beginning of every
13793 message. If the message spans to several lines, the prefix is
13794 attached to each line. The value of this slot can also be a procedure
13795 that takes @code{<log-drain>} object and returns a string to be used as
13796 the prefix. The procedure is called every time prefix is needed.
13797 @c JP
13798 各メッセージの前に追加されるプレフィクス文字列を指定します。
13799 メッセージが複数行に渡る場合、プレフィクスは各行の頭に追加されます。
13800 またこのスロットには手続きをセットすることもできます。
13801 その場合、プレフィクス文字列が必要とされる度にその手続きが@code{<log-drain>}
13802 を引数として呼び出され、戻り値の文字列がプレフィクスとして使われます。
13803 @c COMMON
13804
13805 @c EN
13806 When the @code{path} slot is a symbol @code{syslog}, the value of this slot
13807 is ignored. System logger will attach an appropriate prefix.
13808 @c JP
13809 @code{path}スロットの値がシンボル@code{syslog}の場合は、
13810 このスロットの値は無視されます。システムのログ機構が適切なプレフィクスを付けるからです。
13811 @c COMMON
13812
13813 @c EN
13814 When the value of the prefix slot is a string, the following character sequences
13815 have special meanings and replaced by @code{log-format} for appropriate
13816 information when written out.
13817 @c JP
13818 prefixスロットの値が文字列の場合、以下に挙げる文字シーケンスは特別な意味を持ち、
13819 @code{log-format}によって置換されます。
13820 @c COMMON
13821
13822 @table @code
13823 @item ~T
13824 @c EN
13825 Current time, in the format of "Mmm DD hh:mm:ss" where "Mmm" is
13826 an abbreviated month, "DD" is the day of month, "hh", "mm" and
13827 "ss" are hours (in 24 hour basis), minutes and seconds, respectively.
13828 This format is compatible with system logs.
13829 @c JP
13830 現在の時刻を"Mmm DD hh:mm:ss"という形式で表したもの。
13831 ここで"Mmm" は英語の月名の省略形、"DD" は日、"hh"、"mm"、
13832 "ss" は時間(24時間制)、分、秒です。
13833 このフォーマットはシステムログと同じです。
13834 @c COMMON
13835
13836 @item ~Y
13837 @c EN
13838 Current 4-digit year.
13839 @c JP
13840 4桁で表した現在の西暦。
13841 @c COMMON
13842
13843 @item ~P
13844 @c EN
13845 The program name. The default value is the basename of
13846 @code{(car (command-line))} (@pxref{Command-line arguments}),
13847 but you can change it by the @code{program-name}
13848 slot described below.
13849 @c JP
13850 プログラム名。初期値は@code{(car (command-line))}の値のbasenameが使われます
13851 (@ref{Command-line arguments}参照)。
13852 下に述べる@code{program-name}スロットの値を変えれば
13853 ここに現れる文字列を変えることができます。
13854 @c COMMON
13855
13856 @item ~$
13857 @c EN
13858 The process id of this program.
13859 @c JP
13860 このプログラムのプロセスID。
13861 @c COMMON
13862
13863 @item ~U
13864 @c EN
13865 The name of the effective user of the process.
13866 @c JP
13867 このプロセスの実行ユーザ名。
13868 @c COMMON
13869
13870 @item ~H
13871 @c EN
13872 The hostname the process is running.
13873 @c JP
13874 このプロセスが走っているホスト名。
13875 @c COMMON
13876 @end table
13877
13878 @c EN
13879 The default value of this slot is "@code{~T ~P[~$]: }". For example,
13880 if a string "this is a log message.\nline 2\nline 3" is given as the
13881 message, it produces something like the following log entry.
13882 @c JP
13883 このスロットの初期値は"@code{~T ~P[~$]: }"です。例えば
13884 "this is a log message.\nline 2\nline 3"というメッセージが
13885 与えられると、次のようなログが書き出されます。
13886 @c COMMON
13887
13888 @example
13889 Sep 1 17:30:23 myprogram[441]: this is a log message
13890 Sep 1 17:30:23 myprogram[441]: line 2
13891 Sep 1 17:30:23 myprogram[441]: line 3
13892 @end example
13893
13894 @end defivar
13895
13896 @defivar {<log-drain>} program-name
13897 @c EN
13898 Specifies the program name written by @code{~P} directive of
13899 the prefix slot.
13900 @c JP
13901 プレフィクス文字列の@code{~P}が置換されるプログラム名を指定します。
13902 @c COMMON
13903 @end defivar
13904
13905 @defivar {<log-drain>} lock-policy
13906 @c EN
13907 Specifies the way the log file should be locked.
13908 If the value of this slot is a symbol @code{fcntl},
13909 the log file is locked using
13910 fcntl() (@pxref{Low-level file operations}).
13911 If the value is a symbol @code{file}, the log file is locked by
13912 creating auxiliary lock file, whose name is generated by appending ".lock"
13913 after the log file path. The logging
13914 process needs a write permission to the log file directory.
13915 Note that if the process is killed forcibly during writing the
13916 log file, a stale lock file may remain. @code{Log-format}
13917 silently removes the lock file if it is unusually old (currently 10 minutes).
13918 If the value is @code{#f}, no locking is performed.
13919
13920 The default value is @code{fcntl}, except MacOSX which doesn't
13921 support fcntl()-style locking and thus @code{file} is default.
13922
13923 The locking isn't performed if the destination is not a file.
13924 @c JP
13925 ログファイルのロックの方法を指定します。
13926 このスロットの値がシンボル@code{fcntl}だった場合は、
13927 fcntl()によるファイルロックが使われます
13928 (@ref{Low-level file operations}参照)。
13929 このスロットの値がシンボル@code{file}だった場合は、
13930 ログファイルのパス名に ".lock" を追加したロックファイルを作成することによる
13931 排他制御が行われます。この場合、ログを行うプロセスはログファイルの
13932 置かれるディレクトリに書き込み権限が必要です。
13933 また、プロセスがログファイル書き込み中に強制的に終了させられた場合、
13934 ロックファイルが残ってしまう恐れがあります。
13935 @code{Log-format}はロックファイルが十分に古い場合(現在は10分をリミットとしています)
13936 ロックファイルを自動的に削除します。
13937 このスロットの値が@code{#f}だった場合は、排他制御は行われません。
13938
13939 デフォルトの値は@code{fcntl}です。但しMacOSXではfcntlスタイルのロックが
13940 サポートされていないため、@code{file}がデフォルト値となります。
13941
13942 ログの行き先がファイルでない場合は排他制御は行われません。
13943 @c COMMON
13944 @end defivar
13945
13946 @defivar {<log-drain>} syslog-option
13947 @defivarx {<log-drain>} syslog-facility
13948 @defivarx {<log-drain>} syslog-priority
13949 @c EN
13950 The value of these slots are used when the destination of the drain
13951 is the system logger. @xref{Syslog}, for the detailed information
13952 about these values. The default values of these slots
13953 are @code{LOG_PID}, @code{LOG_USER} and @code{LOG_INFO}, respectively.
13954 @c JP
13955 これらのスロットの値は、ログの行き先がシステムログの場合にのみ使われます。
13956 これらの値に関する説明は@ref{Syslog}を参照して下さい。
13957 デフォルトの値はそれぞれ@code{LOG_PID}、@code{LOG_USER}、@code{LOG_INFO}です。
13958 @c COMMON
13959 @end defivar
13960 @end deftp
13961
13962
13963 @defun log-open path :key prefix program-name
13964 @c MOD gauche.logger
13965 @c EN
13966 Sets the destination of the default log message to the path @var{path}.
13967 It can be a string or a boolean, as described above.
13968 You can also set prefix and program name by corresponding keyword
13969 arguments. See the @code{<log-drain>} above for those parameters.
13970 @c JP
13971 デフォルトのログの行き先を@var{path}に指定します。
13972 @var{path}は文字列かboolean値あるいはシンボル@code{syslog}で、
13973 上の@code{path}スロットで述べたものと
13974 おなじ意味を持ちます。またプレフィクスとプログラム名をキーワード引数で
13975 指定することもできます。
13976 これらのパラメータの意味については上の@code{<log-drain>}の項を参照して下さい。
13977 @c COMMON
13978
13979 @c EN
13980 Despite its name, this function doesn't open the specified file
13981 immediately. The file is opened and closed every time @code{log-format}
13982 is called.
13983 @c JP
13984 名前に"open"とありますが、この手続きは指定されたファイルをオープンしません。
13985 ファイルは@code{log-format}が呼ばれるたびにオープンされクローズされます。
13986 @c COMMON
13987 @end defun
13988
13989 @deffn {Parameter} log-default-drain
13990 @c MOD gauche.logger
13991 @c EN
13992 When called with no argument, returns the current default log-drain
13993 @code{log-format} uses when the explicit drain is omitted.
13994 It may return @code{#f} if the default log drain hasn't been
13995 opened by @code{log-open}.
13996
13997 Calling with new @code{<log-drain>} object or
13998 @code{#f} alters the default log-drain.
13999 You can also use @code{parameterize} (@ref{Parameters}) to change
14000 the log drain temporary.
14001 @c JP
14002 引数無しで呼ばれると、@code{log-format}が使う、
14003 現在のデフォルトのログの行き先が返されます。
14004 まだデフォルトのログの行き先が@code{log-open}で指定されていない場合は
14005 @code{#f}が返ります。
14006
14007 新たな@code{<log-drain>}オブジェクトか@code{#f}を引数にして呼び出すと、
14008 デフォルトのログの行き先がそれに変更されます。
14009 @code{parameterize} (@ref{Parameters}) を使えば、一時的にデフォルトの
14010 ログの行き先を変更できます。
14011 @c COMMON
14012 @end deffn
14013
14014
14015 @deffn {Method} log-format (format <string>) arg @dots{}
14016 @deffnx {Method} log-format (drain <log-drain>) (format <string>) arg @dots{}
14017 @c MOD gauche.logger
14018 @c EN
14019 Formats a log message by @var{format} and @var{arg @dots{}}, by using
14020 @code{format} (@pxref{Output}). In the first form, the output goes
14021 to the default destination. In the second form, the output goes to
14022 the specified drain.
14023 @c JP
14024 ログメッセージを@code{format}手続きでフォーマットし(@ref{Output}参照)、
14025 指定された行き先に書き出します。最初の形式ではデフォルトの行き先が使われます。
14026 @c COMMON
14027
14028 @c EN
14029 The file is opened and closed every time. You can safely move
14030 the log file while your program that touches the log file is running.
14031 Also @code{log-format} acquires a write lock of the log file by
14032 @code{sys-fcntl} (@pxref{Low-level file operations}).
14033 @c JP
14034 ファイルはこの手続きが呼ばれるたびにオープンされクローズされます。
14035 したがって、ログファイルに書き出すプログラムが走っている最中でも
14036 ログファイルをmoveすることができます。
14037 また、@code{log-format}は@code{sys-fcntl} (@ref{Low-level file operations}参照)
14038 を使ってファイルロックを獲得します。
14039 @c COMMON
14040
14041 @c EN
14042 If the first form of @code{log-format} is called before @code{log-open}
14043 is called, @code{log-format} does nothing.
14044 It is useful to embed debug stubs in your code; once your code is
14045 past the debugging stage, you just comment out @code{log-open} and
14046 the code runs without logging.
14047 @c JP
14048 @code{log-open}が呼ばれる前に@code{log-format}が最初の形式で呼ばれた場合、
14049 @code{log-format}は何もしません。したがって、@code{log-format}をデバッグに
14050 活用し、必要なくなったら@code{log-open}だけをコメントアウトする、というような
14051 使用法も可能です。
14052 @c COMMON
14053 @end deffn
14054
14055 @c ----------------------------------------------------------------------
14056 @node Instance pools, Propagating slot access, User-level logging, Library modules - Gauche extensions
14057 @section @code{gauche.mop.instance-pool} - Instance pools
14058 @c NODE インスタンスプール, @code{gauche.mop.instance-pool} - インスタンスプール
14059
14060 @deftp {Module} gauche.mop.instance-pool
14061 @mdindex gauche.mop.instance-pool
14062 Sometimes, you want to track all instances created from a class.
14063 This module provies tools to do that.
14064
14065 An @emph{instance pool} class is a class that keeps the list of instances
14066 of itself and its subclasses.
14067
14068 A class that inherits @code{<instance-pool-mixin>} directly becomes a 'root'
14069 class of the pool. Instances of the subclass of the root class will
14070 be added to the pool.
14071
14072 An application can have multiple root classes. If a class inherits
14073 from two or more pooled classes, its instances will be added to
14074 all the pools.
14075
14076 The actual implementation of how to manage pools can be customizable
14077 by subclassing @code{<instance-pool-meta>} and overloading methods.
14078
14079 Note that instance pools are global---it keeps all the instances
14080 ever created, unless explicitly cleared.
14081 @end deftp
14082
14083 @deftp {Class} <instance-pool-meta>
14084 @clindex instance-pool-meta
14085 @c MOD gauche.mop.instance-pool
14086 A metaclass that adds a class the capability of tracking its instances.
14087 By default, instance of itself and its subclasses are tracked.
14088 @end deftp
14089
14090 @deftp {Class} <instance-pool-mixin>
14091 @clindex instance-pool-mixin
14092 @c MOD gauche.mop.instance-pool
14093 A mixin class that makes the class that directly inherits this mixin
14094 an instance of @code{<instnace-pool-meta>}. You can use this mixin
14095 class, instead of using metaclass explicitly, to make a class
14096 a root of the pool.
14097 @end deftp
14098
14099 @deffn {Generic Function} instance-pool->list class
14100 @c MOD gauche.mop.instance-pool
14101 Returns a list of instances in the pool of @var{class},
14102 which should be an instance
14103 of @code{<instance-pool-meta>}.
14104 The list is fresly constructuted every time it is called.
14105 The order of instances are not specified.
14106 @end deffn
14107
14108 @deffn {Generic Function} instance-pool-find class pred
14109 @c MOD gauche.mop.instance-pool
14110 Returns an instance of @var{class} which satisfies the predicate @var{pred}.
14111 If no instance satisfies it, @code{#f} is returned.
14112 @end deffn
14113
14114 @deffn {Generic Function} instance-pool-remove! class pred
14115 @c MOD gauche.mop.instance-pool
14116 Remove all instances that satisfies the predicate @var{pred}
14117 from the pool of @var{class}.
14118 @end deffn
14119
14120 @deffn {Generic Function} instance-pool-fold class kons knil
14121 @c MOD gauche.mop.instance-pool
14122 Calls @var{kons} over every instance in the pool of @var{class},
14123 with the current accumulated value. The initial value is @var{knil},
14124 and each return value of @var{kons} is used as the next value.
14125 The last return value of @var{kons} is returned from the function.
14126
14127 It is functionally equivalent with the following, except that it may
14128 be more efficient (without creating intermediate list). Also, the
14129 order of instances are not guaranteed to be the same as
14130 @code{instance-pool->list} returns.
14131 @example
14132 (fold kons knil (instance-pool->list class))
14133 @end example
14134 @end deffn
14135
14136 @deffn {Generic Function} instance-pool-map class proc
14137 @deffnx {Generic Function} instance-pool-for-each class proc
14138 @c MOD gauche.mop.instance-pool
14139 Apply @var{proc} on each instances in the pool of @var{class};
14140 @code{instance-pool-map} gathers the results into a list and returns it,
14141 while @code{instance-pool-for-each} discards the result of @var{proc}.
14142
14143 The order in which instances are visited is not specified.
14144 @end deffn
14145
14146 @c ----------------------------------------------------------------------
14147 @node Propagating slot access, Singleton, Instance pools, Library modules - Gauche extensions
14148 @section @code{gauche.mop.propagate} - Propagating slot access
14149 @c NODE スロットアクセスの伝播, @code{gauche.mop.propagate} - スロットアクセスの伝播
14150
14151 @deftp {Module} gauche.mop.propagate
14152 @mdindex gauche.mop.propagate
14153 @c EN
14154 Provides a metaclass to add @code{:propagated} slot allocation option.
14155
14156 When a slot allocation has @code{:propagated}, access
14157 to the slot is redirected to other object's slot.
14158 It is handy for composite objects to keep external
14159 interface simple, for access to the slot of inner objects
14160 can be disguised as if it is a slot of the parent object.
14161 @c JP
14162 スロットの@code{:allocation}オプションに@code{:propagated}を追加するメタクラスを提供します。
14163
14164 アロケーションが@code{:propagated}であるスロットへのアクセスは、
14165 指定された他のオブジェクトのスロットへのアクセスにリダイレクトされます。
14166 コンポジットしたオブジェクトの外部インタフェースを簡便に保ちたい時に便利です。
14167 内部オブジェクトの持つスロットへのアクセスを、
14168 親オブジェクトのスロットであるかのように見せられるからです。
14169 @c COMMON
14170 @end deftp
14171
14172 @c EN
14173 An example would work better than explanation.
14174 Suppose you have a @code{<rect>} class to represent
14175 generic rectangular area, and you want to use it when you create
14176 a @code{<viewport>} class by composition, instead of
14177 inheritance. A simple way would be as follows:
14178 @c JP
14179 説明よりまず例を示したほうがわかりやすいでしょう。
14180 長方形の領域を表す@code{<rect>}という抽象クラスがある時、
14181 それを継承ではなくコンポジションによって@code{<viewport>}クラスを作ることを
14182 考えます。簡単な方法は次のようになるでしょう:
14183 @c COMMON
14184
14185 @example
14186 (define-class <rect> ()
14187 ((width :init-keyword :width)
14188 (height :init-keyword :height)))
14189
14190 (define-class <viewport> ()
14191 ((dimension :init-form (make <rect>))
14192 ;; ... other slots ...
14193 ))
14194 @end example
14195
14196 @c EN
14197 With this definition, whenever you want to access the viewport's
14198 width or height, you have to go through @code{<rect>} object, e.g.
14199 @code{(~ viewport'dimension'width)}. This is not only cumbersome,
14200 but the users of viewport class have to know that how the
14201 viewport is composed (it's not necessarily a bad thing,
14202 but sometimes you may want to hide it).
14203 @c JP
14204 この定義だと、viewportの高さや幅にアクセスした場合、
14205 @code{(~ viewport'dimension'width)}のように
14206 常に@code{<rect>}オブジェクトを経由しなければならなくなります。
14207 これは煩わしいだけでなく、viewportクラスのユーザが、
14208 viewportがどう構成されているかを知っていなければならないということでもあります
14209 (必ずしも悪いことではないですが、時にはそれを隠したいこともあります)。
14210 @c COMMON
14211
14212 @c EN
14213 Using @code{gauche.mop.propagate}, you can define slots
14214 @code{width} and @code{height} in @code{<viewport>} class
14215 that are proxies of @code{<rect>}'s slots.
14216 @c JP
14217 @code{gauche.mop.propagate}を使うと、
14218 @code{<viewport>}クラスに@code{width}と@code{height}スロットを定義して、
14219 それ経由で内部の@code{<rect>}クラスへアクセスさせることができます。
14220 @c COMMON
14221
14222 @example
14223 (use gauche.mop.propagate)
14224
14225 (define-class <rect> ()
14226 ((width :init-keyword :width)
14227 (height :init-keyword :height)))
14228
14229 (define-class <viewport> (<propagate-mixin>)
14230 ((dimension :init-form (make <rect>))
14231 (width :allocation :propagated :propagate 'dimension
14232 :init-keyword :width)
14233 (height :allocation :propagated :propagate 'dimension
14234 :init-keyword :height)))
14235 @end example
14236
14237 @c EN
14238 With @code{:propagated} allocation, the slots are not actually
14239 allocated in @code{<viewport>} instance, and accesses to the
14240 slots are redirected to the object in the slot specified by
14241 @code{:propagate} slot option---in this case, the @code{dimension} slot.
14242 It is somewhat similar to the virtual slots, but it's more convenient
14243 for you don't explicitly write procedures to redirect the access.
14244 @c JP
14245 @code{:allocation}に@code{:propagated}が指定されると、
14246 そのスロットは@code{<viewport>}インスタンス内にはアロケートされません。
14247 そのスロットへのアクセスは、@code{:propagate}スロットオプションで指定される
14248 スロット(上の例では@code{dimension}スロット)に格納されたオブジェクトへと
14249 リダイレクトされます。
14250 仮想スロットの一種とも言えますが、アクセス手続きを書く必要がありません。
14251 @c COMMON
14252
14253 @c EN
14254 Now you can treat @code{width} and @code{height} as if they
14255 are slots of @code{<viewport>}. You can even make them
14256 initialize via @code{init-keyword} (but you can't use
14257 @code{:init-form} or @code{:init-value}; if you want to specify
14258 default values, give the default values to the actual object).
14259 @c JP
14260 こうすると、@code{width}と@code{height}スロットが@code{<viewport>}クラスの
14261 スロットであるかのように扱えます。@code{init-keyword}による初期化も行えます。
14262 (ただ、@code{:init-form}や@code{:init-value}は使えません。
14263 初期値は実体を持つオブジェクトで指定してください)。
14264 @c COMMON
14265
14266 @example
14267 gosh> (define vp (make <viewport> :width 640 :height 480))
14268 vp
14269 gosh> (d vp)
14270 #<<viewport> 0xc5a1e0> is an instance of class <viewport>
14271 slots:
14272 dimension : #<<rect> 0xc5a130>
14273 width : 640
14274 height : 480
14275 gosh> (set! (~ vp'width) 800)
14276 #<undef>
14277 gosh> (~ vp'width)
14278 800
14279 @end example
14280
14281 @c EN
14282 Here's two classes that enables this feature.
14283 Usually all you have to do is to inherit @code{<propagate-mixin>} class.
14284 @c JP
14285 以下の2つのクラスがこれを可能にしています。
14286 通常、ユーザは@code{<propagate-mixin>}クラスを継承するだけで充分です。
14287 @c COMMON
14288
14289 @deftp {Class} <propagate-meta>
14290 @clindex propagate-meta
14291 @c MOD gauche.mop.propagate
14292 @c EN
14293 Adds @code{:propagated} slot allocation.
14294 The propagated slot has to have @code{:propagate} slot option
14295 which specifies the name of the slot that points to an object
14296 that actually holds the value of the slot.
14297 If a slot has @code{:propagated} slot allocation but
14298 does not have @code{:propagate} slot option, an error is signaled.
14299 @c JP
14300 スロットアロケーションに@code{:propagated}を追加します。
14301 propagatedが指定されたスロットは、実体を持つオブジェクトを指定する
14302 @code{:propagate}スロットオプションを持たねばなりません。
14303 アロケーションが@code{:propagated}スロットであるにもかかわらず
14304 @code{:propagate}スロットオプションが指定されていない場合は、エラーが投げられます。
14305 @c COMMON
14306
14307 @c EN
14308 The @code{:propagate} slot option should have a value
14309 of either a symbol, or a list of two symbols.
14310 @c JP
14311 @code{:propagate}スロットオプションは、シンボルもしくは2つのシンボルからなる
14312 リストを取ります。
14313 @c COMMON
14314
14315 @c EN
14316 If it is a symbol, it names the slot that contains an
14317 object, whose slot with the same name of the propagate slot
14318 holds the value.
14319 @c JP
14320 単なるシンボルであった場合、それは内部オブジェクトを格納しているスロットの名前です。
14321 このスロットへのアクセスは、指定されたスロットが保持する内部オブジェクトの同名の
14322 スロットへのアクセスにリダイレクトされます。
14323 @c COMMON
14324
14325 @c EN
14326 If it is a list of two symbols as @code{(X Y)}, then
14327 the access to this propagated slot actually works as
14328 @code{(slot-ref (slot-ref obj X) Y)}.
14329 @c JP
14330 二つのシンボルからなるリストであった場合、例えばそれを@code{(X Y)}とすると、
14331 このスロットへのアクセスは@code{(slot-ref (slot-ref obj X) Y)}になります。
14332 @c COMMON
14333
14334 @c EN
14335 If you want to make a propagated slot initializable by
14336 init-keywords, make sure the slot holding the actual object
14337 comes before the propagated slots. Slot initialization proceeds
14338 in the order of appearance by default, and you want the
14339 actual object is created before setting values.
14340 @c JP
14341 propagatedスロットを@code{init-keyword}で初期化可能にしたい場合、
14342 propagateするオブジェクトをpropagatedスロットより前に置くようにしてください。
14343 スロットの初期化はデフォルトでスロットの出現順に行われます。
14344 内部オブジェクトの実体が先に作られていないと、そのスロットに初期値を設定できません。
14345 @c COMMON
14346 @end deftp
14347
14348 @deftp {Class} <propagate-mixin>
14349 @clindex propagate-mixin
14350 @c MOD gauche.mop.propagate
14351 @c EN
14352 This is a convenience mixin class. Instead of giving
14353 @code{:metaclass <propagate-meta>}, you can just inherit
14354 this calss to make propagated slots available.
14355 @c JP
14356 これは簡便のためのmixinクラスです。
14357 クラス定義で@code{:metaclass <propagate-meta>}を指定するかわりに、
14358 このmixinクラスを継承すれば、propagatedスロットが使えるようになります。
14359 @c COMMON
14360 @end deftp
14361
14362 @c ----------------------------------------------------------------------
14363 @node Singleton, Slot with validator, Propagating slot access, Library modules - Gauche extensions
14364 @section @code{gauche.mop.singleton} - Singleton
14365 @c NODE シングルトン, @code{gauche.mop.singleton} - シングルトン
14366
14367 @deftp {Module} gauche.mop.singleton
14368 @mdindex gauche.mop.singleton
14369 @c EN
14370 Provides a metaclass to define a singleton class.
14371 @c JP
14372 シングルトンクラスを定義するためのメタクラスを提供します。
14373 @c COMMON
14374 @end deftp
14375
14376 @deftp {Class} <singleton-meta>
14377 @clindex singleton-meta
14378 @c MOD gauche.mop.singleton
14379 @c EN
14380 Creates a singleton class. A singleton class is a class that is
14381 guaranteed to create only one instance.
14382 The first invocation of @code{make} creates the single instance,
14383 and further attempt of creation returns the same instance.
14384 @c JP
14385 シングルトンクラスを生成します。シングルトンクラスはそのインスタンスが
14386 ただ一つしかないことを保証するクラスです。 @code{make} の
14387 最初の呼び出しで、唯一のインスタンスを生成し、その後の呼出しでは
14388 最初に生成したものと同一のインスタンスを返します。
14389 @c COMMON
14390 @example
14391 (define-class single () () :metaclass <singleton-meta>)
14392
14393 (define a (make single))
14394 (define b (make single))
14395
14396 (eq? a b) @result{} #t
14397 @end example
14398
14399 @c EN
14400 The slots of the instance are initialized at the first invocation
14401 of @code{make}. Initargs of @code{make} are effective only in the
14402 fist invocation, and ignored in the subsequent invocation.
14403
14404 The call of initialization in @code{make} is thread-safe.
14405 @c JP
14406 インスタンスのスロットは最初の @code{make} の呼び出し時に
14407 初期化されます。@code{make}への初期引数は最初の呼び出しのときに
14408 だけ効果があり、それ以降の呼び出しでは無視されます。
14409
14410 初期化ルーチンの呼び出しはスレッドセーフです。
14411 @c COMMON
14412 @end deftp
14413
14414 @deffn {Method} instance-of (class <singleton-meta>) :rest initargs
14415 @c MOD gauche.mop.singleton
14416 @c EN
14417 This method just calls @code{make} with the passed arguments.
14418 It is more obvious in the program that you're dealing with singleton.
14419 @c JP
14420 このメソッドは渡された引数とともに @code{make} を呼んでいるだけです。
14421 シングルトンを扱うプログラム中ではこちらの方が分りやすいでしょう。
14422 @c COMMON
14423 @end deffn
14424
14425 @deftp {Class} <singleton-mixin>
14426 @clindex singleton-mixin
14427 @c MOD gauche.mop.singleton
14428 @c EN
14429 An instance of @code{<singleton-meta>}. Instead of specifying
14430 @code{<singleton-meta>} as the @code{:metaclass} argument of
14431 @code{define-class}, you can inherit this class to give your
14432 class the property of singleton.
14433 @c JP
14434 @code{<singleton-meta>}のインスタンスです。@code{<singleton-meta>}
14435 を @code{define-class} の @code{:metaclass} 引数として指定せずに、
14436 このクラスを継承することで、定義しようとするクラスにシングルトンの
14437 性質を与えることができます。
14438 @c COMMON
14439 @end deftp
14440
14441 @c ----------------------------------------------------------------------
14442 @node Slot with validator, Networking, Singleton, Library modules - Gauche extensions
14443 @section @code{gauche.mop.validator} - Slot with validator
14444 @c NODE Validator付きスロット, @code{gauche.mop.validator} - Validator付きスロット
14445
14446 @deftp {Module} gauche.mop.validator
14447 @mdindex gauche.mop.validator
14448 @c EN
14449 Provides a metaclass that adds @code{:validator} and @code{:observer}
14450 slot options.
14451 @c JP
14452 @code{:validator}および@code{:observer}
14453 スロットオプションを追加するメタクラスを提供するモジュールです。
14454 @c COMMON
14455 @end deftp
14456
14457 @deftp {Class} <validator-meta>
14458 @clindex validator-meta
14459 @c MOD gauche.mop.validator
14460 @c EN
14461 This metaclass adds a feature that you can specify callbacks that are
14462 called before and after the slot value is set.
14463 For example, if you want to guarantee
14464 that a certain slot always holds a string value, you can make a procedure
14465 be called before the slot is modified, either by @code{slot-ref} or
14466 by a setter method. In the procedure you can either rejects a
14467 value except string, or coerce the value to a string.
14468
14469 A @emph{validator} procedure is a callback procedure that is called
14470 before the slot value is set. It can be specified by @code{:validator}
14471 slot option. The procedure takes two values, the instance and
14472 the value to be set. Whatever the procedure returns is set to
14473 the actual slot value.
14474
14475 A @emph{observer} procedure is a callback procedure that is called
14476 after the slot value is set. It can be specified by @code{:observer}
14477 slot option. The procedure also takes two values, the instance
14478 and the new value. Result of the observer procedure is discarded.
14479
14480 See the following example:
14481 @c JP
14482 このメタクラスは、スロットの値がセットされる前後に呼ばれるコールバックを
14483 指定する機能を提供します。例えば、あるスロットに常に文字列のみが
14484 セットされているようにしたい場合、そのスロットに、@code{slot-ref}経由であれ
14485 アクセサメソッド経由であれ値がセットされようとした時に指定の手続きが呼ばれるように
14486 し、その手続きの中で、値が文字列でなかったらエラーとするか、強制的に値を
14487 文字列に変換してしまうことができます。その手続きが返した値が実際にスロットに
14488 セットされます。
14489
14490 スロットに値がセットされる前に呼ばれる@emph{validator}手続きは、
14491 @code{:validator}スロットオプションによって指定できます。
14492 手続きは、インスタンスとセットされようとしている値の二つを引数に取ります。
14493 その手続きが返した値が実際にスロットにセットされる値となります。
14494
14495 スロットに値がセットされた後に呼ばれる@emph{observer}手続きは
14496 @code{:observer}スロットオプションによって指定できます。
14497 手続きは、インスタンスとセットされた値の二つを引数に取ります。
14498 戻り値は捨てられます。
14499
14500 下の例を参照して下さい。
14501 @c COMMON
14502
14503 @example
14504 (define-class <v> ()
14505 ((a :accessor a-of
14506 :validator (lambda (obj value) (x->string value)))
14507 (b :accessor b-of
14508 :validator (lambda (obj value)
14509 (if (integer? value)
14510 value
14511 (error "integer required for slot b")))))
14512 :metaclass <validator-meta>)
14513
14514 (define v (make <v>))
14515 (slot-set! v 'a 'foo)
14516 (slot-ref v 'a) @result{} "foo"
14517
14518 (set! (a-of v) 1234)
14519 (a-of v) @result{} "1234"
14520
14521 (slot-set! v 'b 55)
14522 (slot-ref v 'b) @result{} 55
14523
14524 (slot-set! v 'b 3.4) @result{} @r{error}
14525 (set! (b-of v) 3.4) @result{} @r{error}
14526 @end example
14527
14528 @c EN
14529 You can specify default slot value (@code{:init-value} etc.) with
14530 @code{:validator}. In that case, the initialization method of the
14531 instance calls the validator with the specified default value,
14532 if :init-keyword is not given.
14533 @c JP
14534 @code{:validator} が指定されたスロットにも、@code{:init-value}等を
14535 使って既定の初期値を指定しておくことができます。
14536 その場合、インスタンスの初期化ルーチンは、
14537 init-keywordによる初期値指定が無ければ既定の初期値を引数としてvalidator手続きを
14538 呼び出します。
14539 @c COMMON
14540
14541 @example
14542 (define-class <v> ()
14543 ((a :initform 'foo :init-keyword :a
14544 :validator (lambda (obj value) (x->string value)))))
14545
14546 (slot-ref (make <v>) 'a) @result{} "foo"
14547 (slot-ref (make <v> :a 555) 'a) @result{} "555"
14548 @end example
14549
14550 @c EN
14551 It looks similar to the virtual slot, but note that a slot with
14552 validator has an actual storage in the instance, while a virtual
14553 slot doesn't.
14554
14555 It is also a good example of customizing how the slots are accessed
14556 using the metaobject protocol. This feature is implemented by
14557 only a couple of dozen lines of code.
14558 @c JP
14559 仮想スロットに似ていますが、validatorを持つスロットはインスタンス内に実際に
14560 値を格納している点が異なります。
14561
14562 このモジュールはまた、スロットのアクセスをメタオブジェクトプロトコルを使って
14563 カスタマイズする例でもあります。この機能は20行ほどのコードで実現されています。
14564 @c COMMON
14565 @end deftp
14566
14567 @c ----------------------------------------------------------------------
14568 @node Networking, Package metainformation, Slot with validator, Library modules - Gauche extensions
14569 @section @code{gauche.net} - Networking
14570 @c NODE ネットワーキング, @code{gauche.net} - ネットワーキング
14571
14572 @deftp {Module} gauche.net
14573 @mdindex gauche.net
14574 @c EN
14575 Provides a set of functions necessary for network communications
14576 based on BSD socket interface.
14577
14578 The API is provided in two different levels. Lower level routines
14579 reflect traditional BSD socket interface, such as @code{bind(2)}.
14580 Higher level routines provides more convenient way to create
14581 typical connection-oriented server/client sockets.
14582
14583 This module also provides APIs to obtain various information
14584 about hostnames, service ports, and protocols.
14585 @c JP
14586 BSDソケットに基づいたネットワーキングに必要な手続きを提供するモジュールです。
14587
14588 2つのレベルのAPIが定義されています。低レベルの手続きは@code{bind(2)}のような
14589 BSDソケットインタフェースに近いインタフェースを提供し、高レベルの手続きは
14590 典型的なコネクション指向のクライアントサーバアプリケーションに便利な
14591 インタフェースを提供します。
14592
14593 また、ホストネームやプロトコルに関する情報にアクセスするAPIも定義されます。
14594 @c COMMON
14595
14596 @c EN
14597 Gauche can handle IPv6 if it is compiled
14598 with the @code{--enable-ipv6} configuration option.
14599 To check whether IPv6 is enabled or not,
14600 you can use @code{cond-expand} with
14601 @code{gauche.net.ipv6} feature identifier
14602 after loading @code{gauche.net}, as shown below.
14603
14604 @example
14605 (use gauche.net)
14606 (cond-expand
14607 (gauche.net.ipv6
14608 ... code to use ipv6 ...)
14609 (else
14610 ... ipv4 only code ...))
14611 @end example
14612
14613 See @ref{Feature conditional} for the details of @code{cond-expand}.
14614 @c JP
14615 Gaucheは、@code{--enable-ipv6}コンフィギュアオプションつきで
14616 コンパイルされていれば、IPv6を扱うことができます。
14617 IPv6が使えるかどうかを調べるには、
14618 @code{cond-expand}中で@code{gauche.net.ipv6} feature identifierを
14619 使うことができます。次の例を見てください。
14620
14621 @example
14622 (use gauche.net)
14623 (cond-expand
14624 (gauche.net.ipv6
14625 ... ipv6を使うコード ...)
14626 (else
14627 ... ipv4のみのコード ...))
14628 @end example
14629
14630 @code{cond-expand}の詳細については@ref{Feature conditional}を
14631 参照してください。
14632 @c COMMON
14633
14634 @end deftp
14635
14636 @c EN
14637 Note: If you want to write a portable program using network,
14638 take a look at @code{srfi.106} (@pxref{Basic socket interface}).
14639 @c JP
14640 ネットワークを使うポータブルなコードを書きたい場合は、
14641 @code{srfi.106}を見てください (@ref{Basic socket interface}参照)。
14642 @c COMMON
14643
14644 @menu
14645 * Socket address::
14646 * High-level network functions::
14647 * Low-level socket interface::
14648 * Netdb interface::
14649 @end menu
14650
14651 @node Socket address, High-level network functions, Networking, Networking
14652 @subsection Socket address
14653 @c NODE ソケットアドレス
14654
14655 @c EN
14656 @subsubheading Socket address objects
14657 @c JP
14658 @subsubheading ソケットアドレスオブジェクト
14659 @c COMMON
14660
14661 @deftp {Builtin Class} <sockaddr>
14662 @clindex sockaddr
14663 @c MOD gauche.net
14664 @c EN
14665 An abstract base class of socket addresses. Each socket address family
14666 is implemented as a subclass of this class.
14667
14668 Although socket addresses are built-in classes, you can use
14669 @code{make} method to create an instance of a
14670 specific socket address family.
14671 @c JP
14672 ソケットアドレスの抽象ベースクラスです。
14673 ソケットアドレスファミリはこのクラスのサブクラスとして実装されます。
14674
14675 ソケットアドレスはビルトインクラスですが、@code{make}メソッドで
14676 特定のソケットアドレスファミリのインスタンスを作成することができます。
14677 @c COMMON
14678 @end deftp
14679
14680 @deffn {Generic Function} sockaddr-family addr
14681 @c MOD gauche.net
14682 @c EN
14683 Returns a symbol that indicates the family of the socket address
14684 @var{addr}.
14685 @c JP
14686 ソケットアドレス@var{addr}のファミリを表すシンボルを返します。
14687 @c COMMON
14688 @end deffn
14689
14690 @deffn {Generic Function} sockaddr-name addr
14691 @c MOD gauche.net
14692 @c EN
14693 Returns a string which represents the content of the socket address
14694 @var{addr}.
14695 @c JP
14696 ソケットアドレス@var{addr}の名前を表す文字列を返します。
14697 @c COMMON
14698 @end deffn
14699
14700 @deftp {Builtin Class} <sockaddr-in>
14701 @clindex sockaddr-in
14702 @c MOD gauche.net
14703 @c EN
14704 AF_INET family socket address. To create an instance of this class,
14705 use @code{make} method as follows:
14706 @c JP
14707 AF_INETファミリのソケットアドレスです。このクラスのインスタンスを
14708 作成するには、次のようにして@code{make}メソッドを呼びます。
14709 @c COMMON
14710 @example
14711 (make <sockaddr-in> :host @var{host} :port @var{port})
14712 @end example
14713 @c EN
14714 @var{host} can be a string, an integer IP address, a
14715 @code{u8vector} IP address, or one of the keywords
14716 @code{:any}, @code{:broadcast}, @code{:none} or @code{:loopback}.
14717 If it is a string, it is either a host name or a dotted IP notation.
14718 Gauche uses @code{gethostbyname(3)} to obtain the actual IP address from
14719 @var{host} parameter. If it is a keyword @code{:any},
14720 or @code{:broadcast}, the address
14721 uses @code{INADDR_ANY}, or @code{INADDR_BROADCAST}
14722 respectively. The keyword @code{:loopback} is a synonym to the
14723 IPv4 loopback address "127.0.0.1".
14724 @c JP
14725 @var{host}は文字列、整数のIPアドレス、@code{u8vector}のIPアドレス、
14726 もしくは@code{:any}、@code{:broadcast}、@code{:none}、@code{:loopback}の
14727 いずれかのキーワードでなければなりません。
14728 文字列の場合、それはホスト名かIPアドレスのドット表記です。
14729 Gaucheは@code{gethostbyname(3)}を使って実際のIPアドレスを得ます。
14730 この値がキーワード@code{:any}か@code{:broadcast}なら、それぞれ
14731 @code{INADDR_ANY}か@code{INADDR_BROADCAST}がアドレスとして使われます。
14732 キーワード@code{:loopback}はIPv4のループバックアドレス"127.0.0.1"を表します。
14733 @c COMMON
14734
14735 @c EN
14736 @var{port} must be a positive integer indicating the port number.
14737 @c JP
14738 @var{port}はポート番号を示す正の整数です。
14739 @c EN
14740 See also @code{make-sockaddrs} below, to create multiple
14741 socket addresses on the machine which may have more than one
14742 protocol stack.
14743 @c JP
14744 2つ以上のプロトコルスタックを持つようなマシン上で複数のソケットアドレスを
14745 生成するには、後述の @code{make-sockaddrs} も参照してください。
14746 @c COMMON
14747 @end deftp
14748
14749 @deffn {Method} sockaddr-family (addr <sockaddr-in>)
14750 @c MOD gauche.net
14751 @c EN
14752 Returns a symbol @code{inet}.
14753 @c JP
14754 シンボル@code{inet}を返します。
14755 @c COMMON
14756 @end deffn
14757
14758 @deffn {Method} sockaddr-name (addr <sockaddr-in>)
14759 @c MOD gauche.net
14760 @c EN
14761 Returns a string in the form "@var{a}.@var{b}.@var{c}.@var{d}:@var{port}",
14762 where "@var{a}.@var{b}.@var{c}.@var{d}" is dotted decimal notion of
14763 the IP address and @var{port} is the port number.
14764 @c JP
14765 文字列"@var{a}.@var{b}.@var{c}.@var{d}:@var{port}"を返します。
14766 コロンの前はIPアドレスのドット表記で、@var{port}はポート番号です。
14767 @c COMMON
14768 @end deffn
14769
14770 @deffn {Method} sockaddr-addr (addr <sockaddr-in>)
14771 @deffnx {Method} sockaddr-port (addr <sockaddr-in>)
14772 @c MOD gauche.net
14773 @c EN
14774 Returns the IP address and the port number as an integer, respectively.
14775 @c JP
14776 それぞれ、IPアドレスとポート番号を整数で返します。
14777 @c COMMON
14778 @end deffn
14779
14780 @deftp {Builtin Class} <sockaddr-un>
14781 @clindex sockaddr-un
14782 @c MOD gauche.net
14783 @c EN
14784 AF_UNIX family socket address. To create an instance of this class,
14785 use @code{make} method as follows:
14786 @c JP
14787 AF_UNIXファミリのソケットアドレスです。このクラスのインスタンスを作成するには、
14788 @code{make}メソッドを次のように呼んで下さい。
14789 @c COMMON
14790 @example
14791 (make <sockaddr-un> :path @var{path})
14792 @end example
14793 @c EN
14794 @var{path} must be a string specifying pathname of the socket.
14795 @c JP
14796 @var{path}はソケットのパス名を表す文字列です。
14797 @c COMMON
14798 @end deftp
14799
14800 @deffn {Method} sockaddr-family (addr <sockaddr-un>)
14801 @c MOD gauche.net
14802 @c EN
14803 Returns a symbol @code{unix}.
14804 @c JP
14805 シンボル@code{unix}を返します。
14806 @c COMMON
14807 @end deffn
14808
14809 @deffn {Method} sockaddr-name (addr <sockaddr-un>)
14810 @c MOD gauche.net
14811 @c EN
14812 Returns a pathname of the socket address.
14813 @c JP
14814 ソケットアドレスのパス名を返します。
14815 @c COMMON
14816 @end deffn
14817
14818 @deftp {Builtin Class} <sockaddr-in6>
14819 @clindex sockaddr-in6
14820 @c MOD gauche.net
14821 @c EN
14822 AF_INET6 family socket address. This is only available if
14823 gauche is configured with --enable-ipv6 configure option.
14824 The constructor and the slots are the same as @code{<sockaddr-in>}.
14825 @c JP
14826 AF_INET6ファミリのソケットアドレスです。
14827 このクラスはgaucheが--enable-ipv6つきでconfigureされている場合に使えます。
14828 コンストラクタとスロットは@code{<sockaddr-in>}と同じです。
14829 @c EN
14830 See also @code{make-sockaddrs} below, to create multiple
14831 socket addresses on the machine which may have more than one
14832 protocol stack.
14833 @c JP
14834 2つ以上のプロトコルスタックを持つようなマシン上で複数のソケットアドレスを
14835 生成するには、後述の @code{make-sockaddrs} も参照してください。
14836 @c COMMON
14837 @end deftp
14838
14839 @defun make-sockaddrs host port :optional proto
14840 @c MOD gauche.net
14841 @c EN
14842 This is a higher-level utility procedure to create all possible
14843 inet domain socket addresses that point to @code{@var{host}:@var{port}}
14844 of protocol @var{proto}. Particularly, if the specified host has
14845 both IPv4 and IPv6 addresses, and the running system supports both,
14846 then both IPv4 and IPv6 socket addresses are returned. If @var{host} has
14847 multiple IP addresses, socket addresses are created for each of these
14848 IP address. You can make your network application much more portable
14849 among different network stack configurations.
14850
14851 Passing @code{#f} to @var{host} creates the local
14852 (server) address. You can also pass a service name (e.g. @code{"http"})
14853 instead of an integer, to the @var{port} argument.
14854 The value of @var{proto} can be either a symbol @code{tcp} or @code{udp},
14855 and the default is @code{tcp}.
14856
14857 It always returns a list of socket addresses. If the lookup of @var{host}
14858 is failed, null list is returned.
14859 @c JP
14860 これは上位レベルのユーティリティ手続きで、プロトコル @var{proto} の
14861 @code{@var{host}:@var{port}} を指す、可能なすべてのドメインソケット
14862 アドレスを生成します。特に、指定したホストが IPv4 および IPv6 の両方の
14863 アドレスを持ち、稼働中のシステムがその両方をサポートしている場合、IPv4 と
14864 IPv6 の両方のソケットアドレスが返ります。もし、@var{host} が複数の
14865 IP アドレスをもつ場合、ソケットアドレスはそれぞれのIPアドレス毎に生成
14866 されます。自分のネットワークアプリケーションを異るネットワークスタックの
14867 設定の間でこれまでよりはるかにポータブルなものにすることができます。
14868
14869 @var{host} に @code{#f} を渡すと、ローカルな(サーバ)アドレスが生成されます。
14870 @var{port} 引数に整数のかわりに、サービス名(たとえば、@code{"http"})を
14871 わたすこともできます。@var{proto} の値は、@code{tcp} あるいは @code{udp}
14872 のどちらかのシンボルになります。デフォルトでは、@code{tcp} です。
14873
14874 この手続きは常にソケットアドレスのリストを返します。もし、@var{host} の
14875 検索に失敗した場合には、空リストが返ります。
14876 @c COMMON
14877 @end defun
14878
14879 @c EN
14880 @subsubheading Address and string conversion
14881 @c JP
14882 @subsubheading アドレスと文字列との変換
14883 @c COMMON
14884
14885 @defun inet-string->address address
14886 @c MOD gauche.net
14887 @c EN
14888 Converts string representing of the internet address @var{address}
14889 to an integer address. If @var{address} is parsed successfully,
14890 returns two values: the integer address value and the recognized
14891 protocol (the constant value @code{2} (= @code{AF_INET})
14892 for IPv4 addresses, and @code{10} (= @code{AF_INET6})
14893 for IPv6 addresses). If @var{address} can't be
14894 parsed, @code{#f} and @code{#f} are returned.
14895 @c JP
14896 文字列で表現されたインターネットアドレス@var{address}を整数のアドレス
14897 に変換します。@var{address}のパーズが成功した場合には値を2つ返します。
14898 ひとつは整数で表現されたアドレスの値、もうひとつは認識されたプロトコル
14899 (定数値で、@code{2} (= @code{AF_INET})ならIPv4アドレス、@code{10} (=
14900 @code{AF_INET6})ならIPv6アドレス)です。@var{address}のパーズに失敗した
14901 ら、@code{#f}と@code{#f}との2つが返ります。
14902 @c COMMON
14903
14904 @example
14905 (inet-string->address "192.168.1.1")
14906 @result{} 3232235777 and 2
14907 (inet-string->address "::1")
14908 @result{} 1 and 10
14909 (inet-string->address "::192.168.1.1")
14910 @result{} 3232235777 and 10
14911 (inet-string->address "ffe0::1")
14912 @result{} 340116213421465348979261631549233168385 and 10
14913 (inet-string->address "::192.168.1.1")
14914 @result{} 3232235777 and 10
14915 @end example
14916 @end defun
14917
14918 @defun inet-string->address! address buf
14919 @c MOD gauche.net
14920 @c EN
14921 Like @code{inet-string->address}, but fills the given u8vector
14922 @var{buf} by the parsed address instead of returning it as
14923 an integer value. The integer representation of inet addresses
14924 is likely to be a bignum, and you can avoid creating bignums
14925 with this function. The given u8vector @var{buf} must be mutable.
14926 Returns the protocol on success, or @code{#f} on failure.
14927 @c JP
14928 @code{inet-string->address}と同じですが、整数値を返すかわりに、与えら
14929 れたu8vectorである@var{buf}をパーズしたアドレスで埋めるところが違いま
14930 す。inetアドレスの整数表現はbignumと同じやりかたです。この関数を使えば
14931 bignumを生成しなくてすみます。与えられたu8vector@var{buf}は変更可能で
14932 なければなりません。変換に成功した場合はプロトコルが、失敗した場合は
14933 @code{#f}が返ります。
14934 @c COMMON
14935
14936 @c EN
14937 The caller must provide big enough buffer. If @var{buf}
14938 is larger than required, the result is filled from the top
14939 of the u8vector and the rest of the vector remains intact.
14940 @c JP
14941 呼び出し側は格納に十分なバッファを用意しなければなりません。@var{buf}
14942 が必要な分より大きい場合には結果は先頭から詰められ、ベクタの他の部分は
14943 そのままになります。
14944 @c COMMON
14945
14946 @example
14947 (let* ((buf (make-u8vector 16 0))
14948 (proto (inet-string->address! "192.168.1.1" buf)))
14949 (list proto buf))
14950 @result{} (2 #u8(192 168 1 1 0 0 0 0 0 0 0 0 0 0 0 0))
14951 @end example
14952 @end defun
14953
14954
14955 @defun inet-address->string address protocol
14956 @c MOD gauche.net
14957 @c EN
14958 Converts the given @var{address} to its string representation
14959 of the protocol @var{protocol}, which can be either
14960 @code{2} (the constant @code{AF_INET}) or @code{10}
14961 (the constant @code{AF_INET6}).
14962 An integer or a u8vector can be used as @var{address}. If it is
14963 a u8vector, only the necessary portion of the vector is read; i.e.
14964 the vector can be longer than the required length.
14965 @c JP
14966 与えれれた@var{address}をプロトコル@var{protocol}の文字列表現に変換し
14967 ます。プロトコルとしては@code{2} (定数@code{AF_INET})または@code{10}
14968 (定数@code{AF_INET6})が指定可能です。@var{address}としては整数または
14969 u8vectorが使えます。u8vectorをつかった場合には必要な部分だけが読み込ま
14970 れます。したがって、必要な長さ以上あるベクタでもかまいません。
14971 @c COMMON
14972
14973 @example
14974 (inet-address->string 3232235777 AF_INET)
14975 @result{} "192.168.1.1"
14976
14977 (inet-address->string '#u8(192 168 1 1) AF_INET)
14978 @result{} "192.168.1.1"
14979
14980 (inet-address->string 3232235777 AF_INET6)
14981 @result{} "::c0a8:101"
14982 @end example
14983 @end defun
14984
14985
14986 @node High-level network functions, Low-level socket interface, Socket address, Networking
14987 @subsection High-level network functions
14988 @c NODE 高レベルネットワーク手続き
14989
14990 @deftp {Builtin Class} <socket>
14991 @clindex socket
14992 @c MOD gauche.net
14993 @c EN
14994 Abstracts a socket, a communication endpoint.
14995
14996 For a connection-oriented socket, you can access the communication
14997 channel by two ports associated to the socket, one for input and
14998 another for output. @code{socket-input-port} and @code{socket-output-port}
14999 returns those ports, respectively.
15000 @c JP
15001 通信の終端であるところのソケットを表すクラスです。
15002
15003 コネクション型のソケットには、入力用と出力用の2つのポートが結び付いており、
15004 それらを使って通信路にアクセスできます。
15005 @code{socket-input-port}と@code{socket-output-port}はそれぞれ
15006 入力用、出力用のポートを返します。
15007 @c COMMON
15008
15009 @c EN
15010 The @code{<socket>} class implements @code{<connection>} interface.
15011 @xref{Connection framework}, for the details.
15012 The @code{connection-self-address}
15013 and @code{connection-peer-address} methods return
15014 a socket address object.
15015 @c JP
15016 @code{<socket>}クラスはまた、@code{<connection>}インタフェースを実装しています
15017 (詳しくは@ref{Connection framework}参照)。
15018 @code{connection-self-address}と@code{connection-peer-address}は
15019 ソケットアドレスオブジェクトを返します。
15020 @c COMMON
15021 @end deftp
15022
15023 @c EN
15024 The following three functions are convenient ways to create
15025 a connection-oriented socket. Those functions
15026 are to provide an easy methods for typical cases,
15027 but have less control. If you need more than these functions
15028 provide, use low-level interface.
15029 @c JP
15030 以下の3つは手軽にコネクション型のソケットを作成する
15031 ための手続きです。 大抵の場合はこれらの手続きで間に合いますが、
15032 より細かい制御が必要な場合は低レベルAPIを使用して下さい。
15033 @c COMMON
15034
15035 @defun make-client-socket :optional address-spec @dots{}
15036 @c MOD gauche.net
15037 @c EN
15038 Creates and returns a client socket, connected to the address
15039 specified by @var{address-spec} @dots{}.
15040 @c JP
15041 引数@var{address-spec} @dots{}によって指定されるアドレスと接続する
15042 クライアントソケットを作成して返します。
15043 @c COMMON
15044
15045 @table @code
15046 @item (make-client-socket 'unix @var{path})
15047 @c EN
15048 The client socket is connected to the unix domain server socket
15049 of address @var{path}.
15050 @c JP
15051 @var{path}で待っているUnixドメインのサーバーソケットに接続します。
15052 @c COMMON
15053 @item (make-client-socket 'inet @var{host} @var{port})
15054 @c EN
15055 The client socket is connected to the inet domain server socket
15056 with hostname @var{host} and port @var{port}. TCP protocol is
15057 assumed. @var{host} can be either a hostname, or
15058 a dotted decimal notation of IPv4 address.
15059 If gauche is compiled with --enable-ipv6, IPv6 address notation
15060 can also be used. @var{Port} must be an exact integer specifying
15061 a port number, or a string service name (e.g. @code{"http"}).
15062
15063 If gauche is compiled with --enable-ipv6, and the hostname is given,
15064 and the hostname has both IPv6 and IPv4 addresses, then
15065 IPv6 connection is tried first, and IPv4 is used when IPv6 fails.
15066 @c JP
15067 ホスト@var{host}のポート@var{port}にTCPで接続します。
15068 @var{host}はIPv4アドレスのドット表記でもホスト名でも
15069 構いません。Gaucheが--enable-ipv6でコンパイルされていれば、
15070 IPv6形式のアドレス表記も受け付けます。
15071 @var{port}はポート番号を指定する正確な整数か、文字列のサービス名
15072 (@code{"http"}等)でなければなりません。
15073
15074 Gaucheが--enable-ipv6でコンパイルされており、ホスト名が渡されて、
15075 そのホスト名がIPv6とIPv4の両方のアドレスを持っていた場合は、
15076 最初にIPv6での接続が試みられ、それが失敗した場合にIPv4での接続が試みられます。
15077 @c COMMON
15078 @item (make-client-socket @var{host} @var{port})
15079 @c EN
15080 This works the same as above. This form is for compatibility with STk.
15081 @c JP
15082 上と同じです。この形式はSTkとの互換性のために提供されています。
15083 @c COMMON
15084 @item (make-client-socket @var{sockaddr})
15085 @c EN
15086 If an instance of @code{<sockaddr>} is passed,
15087 a socket suitable for @var{sockaddr} is opened and then connected
15088 to the given address.
15089 @c JP
15090 @code{<sockaddr>}クラスのインスタンスが渡された場合には、それに対応する
15091 ソケットをオープンし、そのアドレスへ接続します。
15092 @c COMMON
15093 @end table
15094
15095 @c EN
15096 This function raises an error if it cannot create a socket,
15097 or cannot connect to the specified address.
15098 @c JP
15099 ソケットを作成できなかったり、指定されたアドレスに接続できなかった場合は
15100 エラーが報告されます。
15101 @c COMMON
15102
15103 @example
15104 (make-client-socket 'inet "www.w3.com" 80)
15105 @result{} ;@r{a socket connected to www.w3.com, port 80}
15106 (make-client-socket "127.0.0.1" 23)
15107 @result{} ;@r{a socket connected to localhost, port 23}
15108 (make-client-socket 'unix "/tmp/.sock"
15109 @result{} ;@r{a socket connected to a unix domain socket "/tmp/.sock"}
15110 @end example
15111 @end defun
15112
15113 @defun make-server-socket :optional address-spec @dots{}
15114 @c MOD gauche.net
15115 @c EN
15116 Creates and returns a server socket, listening the address
15117 specified by @var{address-spec}.
15118 @c JP
15119 @var{address-spec}にて接続を待つサーバソケットを作成して返します。
15120 @c COMMON
15121
15122 @table @code
15123 @item (make-server-socket 'unix @var{path} [:backlog @var{num}])
15124 @c EN
15125 The socket is bound to a unix domain socket with a name @var{path}.
15126 The keyword argument @var{backlog} is passed to @code{socket-listen}
15127 to specify the maximum number of connection request the server can keep
15128 before accepting them. The default is 5. If your server is very busy
15129 and you see "connection refused" often, you might want to increase it.
15130 @c JP
15131 パス名@var{path}を持つUnixドメインソケットが作成されます。
15132 キーワード引数@var{backlog}に渡された数値は@code{socket-listen}に渡され、
15133 サーバが接続要求を貯めておくキューの最大長を指定します。
15134 デフォルトは5です。多忙なサーバーで、"connection refused"が頻発する場合は
15135 この数値を増やしてみて下さい。
15136 @c COMMON
15137 @item (make-server-socket 'inet @var{port} [:reuse-addr? @var{flag}] [:sock-init @var{proc}] [:backlog @var{num}])
15138 @c EN
15139 The socket is bound to an inet domain TCP socket, listening
15140 port @var{port}, which must be a non-negative exact integer
15141 or a string service name (e.g. @code{"http"}).
15142 If @var{port} is zero, the system assigns one of available port numbers.
15143 If a keyword argument @var{reuse-addr?} is given and true,
15144 @code{SO_REUSEADDR} option is set to the socket before bound to
15145 the port. This allows the process to bind the server socket
15146 immediately after other process releases the port.
15147 @c JP
15148 ポート@var{port}にて接続を待つInetドメインのTCPソケットが作成されます。
15149 @var{port}は非負の正確な整数か、文字列のサービス名(@code{"http"}等)でなければなりません。
15150 @var{port}が零の場合はシステムが適当なポート番号を割り当てます。
15151 キーワード引数@var{reuse-addr?}に真の値が与えられた場合は、
15152 ソケットに@code{SO_REUSEADDR}オプションがセットされます。
15153 その場合、他のプロセスが解放したばかりの(TCP)ポートでも
15154 エラーとならずに使うことができます。
15155 @c COMMON
15156
15157 @c EN
15158 Alternatively, you can pass a list of positive exact integers to @var{port}.
15159 In that case, Gauche tries to bind each port in the list until it succeeds.
15160 @c JP
15161 あるいは、正の正確な整数のリストを@var{port}に渡すことも出来ます。
15162 その場合、Gaucheは与えられたポート番号で順にbindを試し、成功したらそのソケットを返します。
15163 @c COMMON
15164
15165 @c EN
15166 If keyword argument @code{sock-init} is given, it should be a procedure
15167 that takes two arguments, a created socket and the socket address.
15168 The procedure is called just after the socket is created. It is
15169 useful to set some special socket options.
15170 @c JP
15171 キーワード引数@code{sock-init}が与えられた場合、@code{proc} が出来たての
15172 ソケットとそのソケットアドレスを引数にして呼び出されます。
15173 つまり、@code{proc} はそのような2つの引数を取る手続きでなければなりません。
15174 ソケットに特殊なオプションを設定したいような場合に便利です。
15175
15176 @c EN
15177 The keyword argument @var{backlog} is the same as in unix sockets;
15178 see the description above.
15179 @c JP
15180 キーワード引数@var{backlog}はunixソケットと同じです。上の記述を参照して下さい。
15181
15182 @c COMMON
15183 @item (make-server-socket @var{port} [:reuse-addr? @var{flag}] [:sock-init @var{proc}][:backlog @var{num}])
15184 @c EN
15185 This is a synonym to the above form (except @var{port} must be
15186 an integer). This form is backward-compatible
15187 with STk's @code{make-server-socket}.
15188 @c JP
15189 これは、@var{port}が整数でなければならないことを除けば、
15190 上の形式と同じ動作をします。STkの@code{make-server-socket}との
15191 互換性のために提供されています。
15192 @c COMMON
15193 @item (make-server-socket @var{sockaddr} [:reuse-addr? @var{flag}][:sock-init @var{proc}][:backlog @var{num}])
15194 @c EN
15195 This form explicitly specifies the socket address to listen
15196 by an instance of @code{<sockaddr>}.
15197 @c JP
15198 この形式は、listenするソケットアドレスを@code{<sockaddr>}のインスタンスで
15199 明示的に指定します。
15200 @c COMMON
15201 @end table
15202
15203 @example
15204 (make-server-socket 'inet 8080)
15205 @result{} #<socket (listen "0.0.0.0:8080")>
15206 (make-server-socket 8080)
15207 @result{} #<socket (listen "0.0.0.0:8080")>
15208 (make-server-socket 'inet 0)
15209 @result{} #<socket (listen "0.0.0.0:35628")>
15210 (make-server-socket 'unix "/tmp/.sock")
15211 @result{} #<socket (listen "/tmp/.sock")>
15212 @end example
15213 @end defun
15214
15215 @defun make-server-sockets host port :key reuse-addr? sock-init
15216 @c MOD gauche.net
15217 @c EN
15218 Creates one or more sockets that listen at @var{port}
15219 on all available network interfaces of @var{host}.
15220 You can specify a service name (such as "@code{http}") to
15221 @var{port}, as well as an integer port number.
15222 Returns a list of opened, bound and listened sockets.
15223
15224 This procedure is particularly useful when the host
15225 has multiple protocol stacks, such as IPv4 and IPv6.
15226 In that case, this procedure may return a list of IPv4 socket(s) and
15227 IPv6 socket(s).
15228 (On some OSes, single socket can listen both IPv4 and IPv6. On
15229 such platform, a list of single socket will be returned.)
15230
15231 The meaning of keyword arguments are the same as of @code{make-server-socket}.
15232 @c JP
15233 @var{host} が持つすべての利用可能なネットワークインタフェース上の
15234 @var{port} で接続を待つソケットを生成し、それらのリストを返します。
15235 @var{port} には数字のポート番号のほか、"@code{http}"などの
15236 サービス名も指定できます。
15237
15238 この手続きは、ホストが複数のプロトコルスタック(IPv4とIPv6など)を
15239 持つ場合に特に便利です。その場合、この手続きはIPv4用のソケットと
15240 IPv6用のソケットのリストを返すかもしれません。
15241 (OSによっては、一つのソケットでIPv4もIPv6も両方listenできるものが
15242 あります。そういったOSでは単一のソケットのリストが返るでしょう。)
15243
15244 キーワード引数の意味は@code{make-server-socket}のと同じです。
15245 @c COMMON
15246
15247 @c EN
15248 You can pass 0 to @var{port}, just like @code{make-server-socket},
15249 to let the system choose an available port number. If pass 0 as
15250 port and this procedure returns multiple sockets, it is guaranteed
15251 that all the sockets share the same port number.
15252 @c JP
15253 @code{make-server-socket}と同様、@var{port}に0を渡すことで、
15254 システムに空いているポートを自動的にアサインしてもらうことができます。
15255 @var{port}に0を渡して複数のソケットが返される場合、それらのソケットは
15256 同じポート番号を持つことが保証されます。
15257 @c COMMON
15258 @end defun
15259
15260 @c EN
15261 Several accessors are available on the returned socket object.
15262 @c JP
15263 上記の手続きによって返されたソケットオブジェクトに対して、
15264 以下のようなアクセサがあります。
15265 @c COMMON
15266
15267 @defun socket-address socket
15268 @c MOD gauche.net
15269 @c EN
15270 Returns a socket address associated with @var{socket}.
15271 If no address has been associated to the socket, @code{#f} is returned.
15272 @c JP
15273 ソケット@var{socket}のソケットアドレスを返します。
15274 ソケットにアドレスがまだバインドされていない場合は@code{#f}が返ります。
15275 @c COMMON
15276 @end defun
15277
15278 @defun socket-input-port socket :key (buffering :modest)
15279 @defunx socket-output-port socket :key (buffering :line)
15280 @c MOD gauche.net
15281 @c EN
15282 Returns an input and output port associated with @var{socket},
15283 respectively.
15284 @c JP
15285 それぞれ、@var{socket}からデータを読みだす入力ポート、および
15286 @var{socket}にデータを書き出す出力ポートを返します。
15287 @c COMMON
15288
15289 @c EN
15290 The keyword argument @var{buffering} specifies the buffering mode
15291 of the port. @xref{File ports}, for explanation of the
15292 buffering mode.
15293 @c JP
15294 キーワード引数@var{buffering}はポートのバッファリングモードを
15295 指定します。バッファリングモードの説明は@ref{File ports}にあります。
15296 @c COMMON
15297 @end defun
15298
15299 @defun socket-close socket
15300 @c MOD gauche.net
15301 @c EN
15302 Closes @var{socket}. All the ports associated to
15303 @var{socket} are closed as well.
15304 @c JP
15305 ソケット@var{socket}をクローズします。@var{socket}の入出力ポートも
15306 クローズされます。
15307
15308 @c EN
15309 Note: as of release 0.7.2, this procedure does not shutdown
15310 the connection. It is because @var{socket} may be referenced
15311 by forked process(es) and you might want to close it without
15312 interfering the existing connection. You can call
15313 @code{socket-shutdown} to shutdown the connection explicitly.
15314 @c JP
15315 注意: リリース 0.7.2 より、この手続きは接続をシャットダウンしないように
15316 なりました。その理由は、@var{socket} が fork した別プロセスから参照され
15317 ている可能性があり、既存の接続を妨害することなくクローズしたい場合がある
15318 からです。@code{socket-shutdown} を呼べば接続を明示的にシャットダウンできます。
15319 @c COMMON
15320 @end defun
15321
15322 @defun call-with-client-socket socket proc :key input-buffering output-buffering
15323 @c MOD gauche.net
15324 @c EN
15325 @var{socket} must be a connected client socket. @var{proc} is called
15326 with two arguments, an input port that reads from the socket
15327 and an output port that writes to the socket.
15328 The socket is closed after @var{proc} returns or @var{proc}
15329 raises an error.
15330 @c JP
15331 @var{socket}は接続されたクライアントソケットでなければなりません。
15332 @var{proc}がソケットから読み出す入力ポートと、
15333 ソケットに書き出す出力ポートを引数として呼ばれます。
15334 @var{proc}が正常終了するか、エラーを投げた場合にソケットはクローズされます。
15335 @c COMMON
15336
15337 @c EN
15338 The keyword arguments @var{input-buffering} and @var{output-buffering}
15339 are, if given, passed as the @var{buffering} keyword arguments
15340 of @code{socket-input-port} and @code{socket-output-port}, respectively.
15341 @c JP
15342 キーワード引数@var{input-buffering}と@var{output-buffering}が与えられた場合、
15343 それらはそれぞれ@code{socket-input-port}と@code{socket-output-port}の
15344 @var{buffering}キーワード引数へと渡されます。
15345 @c COMMON
15346 @end defun
15347
15348 @c EN
15349 This is an example of usage of high-level socket functions,
15350 a very simple http client.
15351 @c JP
15352 これは高レベルソケット手続きを使った、非常に単純なhttpクライアントです。
15353 @c COMMON
15354
15355 @example
15356 #!/usr/bin/env gosh
15357 (use gauche.net)
15358
15359 (define (usage)
15360 (display "Usage: swget url\n" (current-error-port))
15361 (exit 1))
15362
15363 ;; Returns three values: host, port, and path.
15364 (define (parse-url url)
15365 (rxmatch-let (rxmatch #/^http:\/\/([-A-Za-z\d.]+)(:(\d+))?(\/.*)?/ url)
15366 (#f host #f port path)
15367 (values host port path)))
15368
15369 (define (get url)
15370 (receive (host port path) (parse-url url)
15371 (call-with-client-socket
15372 (make-client-socket 'inet host (string->number (or port "80")))
15373 (lambda (in out)
15374 (format out "GET ~a HTTP/1.0\r\n" path)
15375 (format out "host: ~a\r\n\r\n" host)
15376 (flush out)
15377 (copy-port in (current-output-port))))))
15378
15379 (define (main args)
15380 (if (= (length args) 2)
15381 (get (cadr args))
15382 (usage))
15383 0)
15384 @end example
15385
15386
15387 @node Low-level socket interface, Netdb interface, High-level network functions, Networking
15388 @subsection Low-level socket interface
15389 @c NODE 低レベルソケットインタフェース
15390
15391 @c EN
15392 These functions provide APIs similar to the system calls.
15393 Those who are familiar to programming with socket APIs will
15394 find these functions useful since you can have more detailed control over
15395 the sockets.
15396 @c JP
15397 ここにある関数群はシステムコールと類似した API を提供します。
15398 ソケット API プログラミングに慣れていれば、ソケットをより細かく
15399 制御できるので、役に立つでしょう。
15400 @c COMMON
15401
15402 @defun make-socket domain type :optional protocol
15403 @c MOD gauche.net
15404 @c EN
15405 Returns a socket with specified parameters.
15406 @c JP
15407 パラメータで指定したソケットを返します。
15408 @c COMMON
15409 @end defun
15410
15411 @defvr {Constant} PF_UNIX
15412 @defvrx {Constant} PF_INET
15413 @defvrx {Constant} PF_INET6
15414 @c MOD gauche.net
15415 @c EN
15416 These constants are bound to the system's constants
15417 @code{PF_UNIX}, @code{PF_INET} and @code{PF_INET6}.
15418 You can use those values for @var{domain} argument of @code{make-socket}.
15419
15420 (@code{PF_INET6} is defined only if the underlying operating
15421 system supports IPv6.)
15422 @c JP
15423 これらの定数はそれぞれシステムが提供する@code{PF_UNIX}、@code{PF_INET}、
15424 @code{PF_INET6}に束縛されています。
15425 これらの値を@var{make-socket}の@var{domain}引数に使うことができます。
15426
15427 (@code{PF_INET6}はオペレーティングシステムがIPv6をサポートしている場合にのみ
15428 定義されます。)
15429 @c COMMON
15430 @end defvr
15431
15432 @defvr {Constant} AF_UNIX
15433 @defvrx {Constant} AF_INET
15434 @defvrx {Constant} AF_INET6
15435 @c MOD gauche.net
15436 @c EN
15437 These constants are bound to @code{AF_UNIX},
15438 @code{AF_INET} and @code{AF_INET6}.
15439
15440 (@code{AF_INET6} is defined only if the underlying operating
15441 system supports IPv6.)
15442 @c JP
15443 これらの定数はそれぞれ、@code{AF_UNIX}、@code{AF_INET}、@code{AF_INET6}
15444 に束縛されています。
15445
15446 (@code{AF_INET6}はオペレーティングシステムがIPv6をサポートしている場合にのみ
15447 定義されます。)
15448 @c COMMON
15449 @end defvr
15450
15451 @defvr {Constant} SOCK_STREAM
15452 @defvrx {Constant} SOCK_DGRAM
15453 @defvrx {Constant} SOCK_RAW
15454 @c MOD gauche.net
15455 @c EN
15456 These constants are bound to @code{SOCK_STREAM}, @code{SOCK_DGRAM}
15457 and @code{SOCK_RAW}, and suitable to pass to the @var{type} argument
15458 of @code{make-socket}.
15459 @c JP
15460 これらの定数はそれぞれ、@code{SOCK_STREAM}、@code{SOCK_DGRAM}、
15461 @code{SOCK_RAW} に束縛されており、
15462 @var{make-socket}の@var{type}引数に使うことができます。
15463 @c COMMON
15464 @end defvr
15465
15466 @defun socket-fd socket
15467 @c MOD gauche.net
15468 @c EN
15469 Returns an integer system file descriptor of the underlying socket.
15470 @c JP
15471 ソケットのもつ整数のシステムファイルディスクリプタを返します。
15472 @c COMMON
15473 @end defun
15474
15475
15476 @defun socket-status socket
15477 @c MOD gauche.net
15478 @c EN
15479 Returns a internal status of @var{socket}, by one of the following
15480 symbols.
15481 @multitable {aaaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}
15482 @item none
15483 @tab The socket is just created.
15484 @item bound
15485 @tab The socket is bound to an address by @code{socket-bind}
15486 @item listening
15487 @tab The socket is listening a connection by @code{socket-listen}
15488 @item connected
15489 @tab The socket is connected by @code{socket-connect} or @code{socket-accept}.
15490 @item shutdown
15491 @tab The socket is shutdown by @code{socket-shutdown}
15492 @item closed
15493 @tab The socket is closed by @code{socket-close}.
15494 @end multitable
15495 @c JP
15496 @var{socket} の内部状態を、以下のシンボルのどれかで返します。
15497 @multitable {aaaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}
15498 @item none
15499 @tab 生成直後
15500 @item bound
15501 @tab @code{socket-bind} によって、あるアドレスに束縛されている
15502 @item listening
15503 @tab @code{socket-listen} によって、接続をリッスンしている
15504 @item connected
15505 @tab @code{socket-connect} あるいは @code{socket-accept} によって接続されている
15506 @item shutdown
15507 @tab @code{socket-shutdown} によってシャットダウンされた
15508 @item closed
15509 @tab @code{socket-close} によってクローズされた
15510 @end multitable
15511 @c COMMON
15512 @end defun
15513
15514 @defun socket-bind socket address
15515 @c MOD gauche.net
15516 @c EN
15517 Binds @var{socket} to the local network address @var{address}.
15518 It is usually used to associate specific address to the server port.
15519 If binding failed, an error is signaled (most likely the address is
15520 already in use).
15521
15522 For the inet domain address, you can pass @var{address} with port=0;
15523 the system assigns the port number and sets the actual address to
15524 the @code{address} slot of @var{socket}.
15525 @c JP
15526 @var{socket} をローカルネットワークアドレス @var{address} に束縛します。
15527 通常は、特定のアドレスをこのサーバのポートに結びつけるのに用います。
15528 もし、束縛が失敗したら(多くの場合、そのアドレスが既に使用されている)、
15529 エラーシグナルが発生します。
15530
15531 INET ドメインアドレスの場合には port=0 とした @var{address} を
15532 渡せます。システムがポート番号を割当て、@var{socket} の
15533 @code{address} スロットに実際のアドレスをセットします。
15534 @c COMMON
15535 @end defun
15536
15537 @defun socket-listen socket backlog
15538 @c MOD gauche.net
15539 @c EN
15540 Listens @var{socket}. The socket must be already bound to some
15541 address. @var{backlog} specifies maximum number of connection
15542 requests to be queued.
15543 @c JP
15544 @var{socket} をリッスンします。ソケットは既になんらかのアドレスに
15545 束縛されていなければなりません。@var{backlog} はキューに入れる
15546 接続要求の最大数を指定します。
15547 @c COMMON
15548 @end defun
15549
15550 @defun socket-accept socket
15551 @c MOD gauche.net
15552 @c EN
15553 Accepts a connection request coming to @var{socket}.
15554 Returns a new socket that is connected to the remote entity.
15555 The original @var{socket} keeps waiting for further connections.
15556 If there's no connection requests, this call waits for one to come.
15557
15558 You can use @code{sys-select} to check if there's a pending connection
15559 request.
15560 @c JP
15561 @var{socket}に来た接続要求をアクセプトします。リモートエンティティへ
15562 接続している新しいソケットを返します。元の @var{socket} は引き続き
15563 次の接続要求を待ちます。接続要求がないとき、これの呼出しは要求が
15564 一つ来るまで待ちます。
15565
15566 接続要求をペンディングしているかどうかをチェックするのに
15567 @code{sys-select}が使えます。
15568 @c COMMON
15569 @end defun
15570
15571 @defun socket-connect socket address
15572 @c MOD gauche.net
15573 @c EN
15574 Connects @var{socket} to the remote address @var{address}.
15575 This is the way for a client socket to connect to the remote entity.
15576 @c JP
15577 @var{socket} をリモートアドレス @var{address} に接続します。
15578 これは、クライアントソケットをリモートエンティティに接続するための
15579 方法です。
15580 @c COMMON
15581 @end defun
15582
15583 @defun socket-shutdown socket how
15584 @c MOD gauche.net
15585 @c EN
15586 Shuts down connection of @var{socket}. If @var{how} is @code{SHUT_RD} (or 0),
15587 the receive channel of @var{socket} is disallowed.
15588 If @var{how} is @code{SHUT_WR} (or 1), the send channel of
15589 @var{socket} is disallowed.
15590 If @var{how} is @code{SHUT_RDWR} (or 2), both receive and send channels are
15591 disallowed. It is an error to call this function on a non-connected socket.
15592
15593 If you shut down the send channel of the socket, the remote peer
15594 sees EOF from its receive channel. This is useful if the remote peer
15595 expects EOF before sending something back to you.
15596 @c JP
15597 @var{socket} の接続をシャットダウンします。@var{how} が@code{SHUT_RD} (0) なら、
15598 @var{socket} の受信チャネルが不許可となります。@var{how} が@code{SHUT_WR} (1)なら、
15599 @var{socket} の送信チャネルが不許可となります。@var{how} が@code{SHUT_RDWR} (2)なら、
15600 @var{socket} の送受信チャネルの両方が不許可となります。
15601 接続していないソケットに対して、この手続きを呼ぶとエラーになります。
15602
15603 ソケットの送信チャネルをシャットダウンすると、リモート側の受信チャネル
15604 に EOF があらわれます。これは、リモート側が何かを送り返す前に EOF
15605 を受けとることを期待している場合、便利です。
15606 @c COMMON
15607 @end defun
15608
15609 @defun socket-getsockname socket
15610 @c MOD gauche.net
15611 @c EN
15612 Returns a @code{<sockaddr>} instance that is the local address of
15613 @var{socket}.
15614 @c JP
15615 @var{socket}のローカル側アドレスを表す@code{<sockaddr>}インスタンスを返します。
15616 @c COMMON
15617 @end defun
15618
15619 @defun socket-getpeername socket
15620 @c MOD gauche.net
15621 @c EN
15622 Returns a @code{<sockaddr>} instance that is the peer address of
15623 @var{socket}.
15624 @c JP
15625 @var{socket}の通信相手のアドレスを表す@code{<sockaddr>}インスタンスを返します。
15626 @c COMMON
15627 @end defun
15628
15629 @defun socket-send socket msg :optional flags
15630 @defunx socket-sendto socket msg to-address :optional flags.
15631 @c MOD gauche.net
15632 @c EN
15633 Interfaces to @code{send(2)} and @code{sendto(2)}, respectively.
15634 Transmits the content of @var{msg} through @var{socket}.
15635 @var{msg} can be either a string or a uniform vector; if you send
15636 binary packets, uniform vectors are recommended.
15637
15638 Returns the number of octets that are actually sent.
15639
15640 When @code{socket-send} is used, @var{socket} must already be connected.
15641 On the other hand, @code{socket-sendto} can be used for non-connected
15642 socket, and the destination address is specified by
15643 a @code{<sockaddr>} instance @var{to-address}.
15644 @c JP
15645 それぞれ、@code{send(2)} および @code{sendto(2)} へのインタフェース。
15646 @var{msg} の内容を @var{socket} を通じて送出します。
15647 @var{msg}は文字列もしくはユニフォームベクタでなければなりません。
15648 バイナリパケットを送る場合はユニフォームベクタの使用を推奨します。
15649
15650 実際に送出されたオクテット数を返します。
15651
15652 @code{socket-send} を使うときには、@var{socket} は既に接続されて
15653 いなければなりません。他方、@code{socket-sendto} は未接続の
15654 ソケットに対して使用でき、送出先アドレスは @code{<sockaddr>} のインスタンス
15655 @var{to-address} で指定します。
15656 @c COMMON
15657
15658 @c EN
15659 The optional @var{flags} can be a bitwise OR of the integer
15660 constants @code{MSG_*}. See the system's manpage of @code{send(2)}
15661 and @code{sendto(2)} for the details.
15662 @c JP
15663 オプション引数 @var{flags} は整数定数 @code{MSG_*} のビット毎のORで
15664 指定できます。詳しくはシステムの man ページ @code{send(2)} および
15665 @code{sendto(2)} を見て下さい。
15666 @c COMMON
15667 @end defun
15668
15669 @defun socket-sendmsg socket msghdr :optional flags
15670 @c MOD gauche.net
15671 @c EN
15672 Sends a packet described by @var{msghdr} through @var{socket}
15673 using @code{sendmsg(3)}. The @var{msghdr} argument must be a
15674 string or u8vector, and it must be prepared as a binary representation
15675 of @code{struct msghdr}. A reliable way to build a @var{msghdr} is
15676 to use @code{socket-buildmsg} described below.
15677
15678 The @var{flags} argument is the same as @code{socket-send} and
15679 @code{socket-sendto}.
15680
15681 Returns number of octets sent.
15682 @c JP
15683 @code{sendmsg(3)}を使って、@var{msghdr}で記述されるパケットを@var{socket}
15684 を通じて送ります。@var{msghdr}引数は文字列かu8vectorで、
15685 @code{struct msghdr}構造体のバイナリ表現でなければなりません。
15686 @var{msghdr}引数に適したデータを構築する確かな方法は、下に述べる
15687 @code{socket-buildmsg}を使うことです。
15688
15689 @var{flags}引数は@code{socket-send}および@code{socket-sendto}と同じです。
15690
15691 送り出されたオクテット数を返します。
15692 @c COMMON
15693
15694 @c EN
15695 This procedure is not yet supported under the Windows native platform.
15696 You can use the feature identifier @code{gauche.os.windows} to check
15697 availability of this procedure (@pxref{Platform-dependent features}).
15698 @c JP
15699 この手続きはWindowsネイティブ環境では(まだ)サポートされません。
15700 これが使えるかどうかは、機能識別子@code{gauche.os.windows}を使って判定
15701 できます (@ref{Platform-dependent features}参照)。
15702 @c COMMON
15703 @end defun
15704
15705 @defun socket-buildmsg addr iov control flags :optional buf
15706 @c MOD gauche.net
15707 @c EN
15708 Builds a binary representation of @code{struct msghdr} which is
15709 suitable to be given to @code{socket-sendmsg}.
15710 You have to be familiar with @code{sendmsg(3)} system call
15711 to understand this procedure.
15712
15713 The @var{addr} argument must be an instance of @code{<sockaddr>}
15714 or @code{#f}. If it is a sockaddr, the @code{msg_name} field
15715 of the msghdr is filled with the address.
15716
15717 The @var{iov} argument must be a vector or @code{#f}. If it is
15718 a vector, each element must be either a string or a u8vector.
15719 They are used to fill @code{msg_iov} field of the msghdr.
15720 Their contents will be concatenated in the kernel to make a payload.
15721
15722 The @var{control} argument represents ancillary data, a.k.a. cmsg.
15723 It can be @code{#f} if you don't need ancillary data. Otherwise,
15724 it must be a list in the following form:
15725 @example
15726 ((@var{level} @var{type} @var{data}) @dots{})
15727 @end example
15728 Where @var{level} and @var{type} are exact integers,
15729 and @var{data} is either a string or a u8vector.
15730 The former two are used to fill cmsg's @code{cmsg_level}
15731 and @code{cmsg_type} fields. The @var{data} is for
15732 cmsg's data (@code{cmsg_len} is calculated from @var{data}).
15733
15734 The @var{flags} argument is used to fill @code{msg_flags}.
15735
15736 If the @var{buf} argument is @code{#f} or omitted, new memories
15737 are allocated to construct the msghdr. If a mutable
15738 u8vector is given to @var{buf}, @code{socket-buildmsg} tries
15739 to use it to construct the msghdr as much as possible; it allocates
15740 memory only if @var{buf} is used up.
15741
15742 Returns the constructed msghdr as a u8vector.
15743 @c JP
15744 @code{struct msghdr}構造体のバイナリ表現を構築します。
15745 作られたmsghdrは@code{socket-sendmsg}に渡すことができます。
15746 この手続きを理解するには、@code{sendmsg(3)}の動作をよく知っていることが必要です。
15747
15748 @var{addr}引数は@code{<sockaddr>}のインスタンスか@code{#f}でなければ
15749 なりません。@code{<sockaddr>}のインスタンスである場合、そのアドレスが
15750 msghdrの@code{msg_name}フィールドに使われます。
15751
15752 @var{iov}引数はベクタか@code{#f}でなければなりません。ベクタの場合、
15753 各要素は文字列かu8vectorでなければなりません。これはmsghdrの
15754 @code{msg_iov}フィールドに使われます。各要素の内容はカーネル内で
15755 結合されてペイロードとなります。
15756
15757 @var{control}引数は補助データ(cmsg)を指定します。補助データが必要ない
15758 場合は@code{#f}を渡せます。そうでなければ、@var{control}引数は
15759 次の形式を持つリストでなければなりません。
15760 @example
15761 ((@var{level} @var{type} @var{data}) @dots{})
15762 @end example
15763 @var{level}と@var{type}は正確な整数で、@var{data}は文字列かu8vectorの
15764 いずれかです。
15765 最初の2つはそれぞれcmsgの@code{cmsg_level}と
15766 @code{cmsg_type}フィールドを指定します。@var{data}はcmsgのデータとなります。
15767 (@code{cmsg_len}は@var{data}から計算されます)。
15768
15769 @var{flags}引数は@code{msg_flags}フィールドに使われます。
15770
15771 @var{buf}引数が省略されるか@code{#f}の場合、msghdrを構築するのに
15772 必要なメモリがアロケートされます。書き換え可能なu8vectorが@var{buf}
15773 に渡されれば、@code{socket-buildmsg}はできるだけそれをバッファに使って
15774 msghdrを構築しようとします。@var{buf}で領域が不足する場合のみ
15775 新たなメモリをアロケートします。
15776
15777 この手続きは構築されたmsghdrをu8vectorとして返します。
15778 @c COMMON
15779
15780 @c EN
15781 This procedure is not yet supported under the Windows native platform.
15782 You can use the feature identifier @code{gauche.os.windows} to check
15783 availability of this procedure (@pxref{Platform-dependent features}).
15784 @c JP
15785 この手続きはWindowsネイティブ環境では(まだ)サポートされません。
15786 これが使えるかどうかは、機能識別子@code{gauche.os.windows}を使って判定
15787 できます (@ref{Platform-dependent features}参照)。
15788 @c COMMON
15789 @end defun
15790
15791 @defun socket-recv! socket buf :optional flags
15792 @c MOD gauche.net
15793 @c EN
15794 Interface to @code{recv(2)}. Receives a message from @var{socket},
15795 and stores it into @var{buf}, which must be a mutable uniform vector.
15796 Returns the number of bytes actually written. @var{socket} must
15797 be already connected. If the size of @var{buf} isn't enough to
15798 store the entire message, the rest may be discarded depending on
15799 the type of @var{socket}.
15800 @c JP
15801 @code{recv(2)}へのインタフェースです。@var{socket}からメッセージを
15802 受信し、それを変更可能なユニフォームベクタ@var{buf}へと書き込みます。
15803 そして実際に書き込まれたバイト数を返します。
15804 @var{socket}は既にコネクトされていなければなりません。
15805 @var{buf}の大きさが受信したメッセージより小さい場合、@var{socket}の
15806 タイプによっては残りのメッセージは捨てられる可能性があります。
15807 @c COMMON
15808
15809 @c EN
15810 The optional @var{flags} can be a bitwise OR of the integer
15811 constants @code{MSG_*}. See the system's manpage of @code{recv(2)}
15812 for the details.
15813 @c JP
15814 オプション引数 @var{flags} は整数定数 @code{MSG_*} のビット毎のORで
15815 指定できます。詳しくはシステムの man ページ @code{recv(2)}を見て下さい。
15816 @c COMMON
15817 @end defun
15818
15819 @defun socket-recvfrom! socket buf addrs :optional flags
15820 @c MOD gauche.net
15821 @c EN
15822 Interface to @code{recvfrom(2)}. Receives a message from
15823 @var{socket}, which may be unconnected, and stores it to
15824 a mutable uniform vector @var{buf}. Like @var{socket-recv},
15825 if the size of @var{buf} isn't enough to store the entire message,
15826 the rest may be discarded depending on the type of @var{socket}.
15827
15828 Returns two values; the number of bytes actually written into
15829 @var{buf}, and an instance of a subclass of @code{<sys-sockaddr>}
15830 which shows the sender's address.
15831
15832 The @var{addrs} argument must be a list of instances of socket
15833 addresses, optionally its last cdr being @code{#t} (as a special
15834 case, if there's zero addresses to pass, just @code{#t} may be given).
15835 The content of each address doesn't matter; if the protocol family
15836 of one of them matches the sender's address, the sender's address
15837 is written into the passed sockaddr object. By listing sockaddrs
15838 of possible families, you can count on @code{socket-recvfrom!}
15839 to allocate no memory on successful operation. It is useful if
15840 you call @code{socket-recvfrom!} in a speed-sensitive inner loop.
15841
15842 If the sender's address family doesn't match any of the addresses
15843 given to @var{addrs}, the behavior depends on whether the list is
15844 terminated by @code{()} or @code{#t}. If it is terminated by @code{()},
15845 (i.e. @var{addrs} is a proper list), the sender's address is simply
15846 discarded and @code{socket-recvfrom!} returns @code{#f} as the
15847 second value. If the list is terminated by @code{#t},
15848 @code{socket-recvfrom!} allocates a fresh sockaddr object and
15849 returns it as the second value.
15850
15851 Two simple cases: If you pass @code{()} to @var{addrs}, the sender's
15852 address is always discarded, which is useful if @var{socket} is
15853 connected (that is, you already know your sender's address).
15854 If you pass @code{#t} to @var{addrs}, a new socket address
15855 object is always allocated for the sender's address,
15856 which is convenient if you don't mind memory allocation.
15857 @c JP
15858 @code{recvfrom(2)}へのインタフェースです。@var{socket}からメッセージを
15859 受け取り、変更可能なユニフォームベクタへ書き込みます。@var{socket}は
15860 コネクトされていなくても構いません。@code{socket-recv}と同様に、
15861 @var{buf}の大きさがメッセージ全てを保持するのに十分でない場合、
15862 @var{socket}のタイプによっては残りのメッセージは捨てられます。
15863
15864 ふたつの値を返します。実際に@var{buf}に書かれたバイト数と、
15865 送信者のアドレスを示す@code{<sys-sockaddr>}のサブクラスのインスタンスです。
15866
15867 @var{addrs}引数はソケットアドレスインスタンスのリストでなければなりません。
15868 ただし、リストの終端 (最後の@code{cdr}) は@code{#t}であっても許されます。
15869 (この特殊な場合として、@var{addrs}引数にただ@code{#t}を渡すことも許されます)。
15870 @var{addrs}引数に渡されたソケットアドレスの中身は何でも構いません。
15871 送信者のアドレスファミリーに一致するソケットアドレスインスタンスが@var{addrs}
15872 中にあった場合、@code{socket-recvfrom!}はそのインスタンスに直接
15873 送信者のアドレスを書き込みます。受信し得る全てのアドレスファミリのソケットアドレスを
15874 リストで渡しておけば、@code{socket-recvfrom!}が(成功時には)
15875 メモリアロケーションを行わないことが保証されます。これは
15876 速度が重要となるタイトなループ内で@code{socket-recvfrom!}を呼ぶ場合に
15877 重要です。
15878
15879 送信者のアドレスファミリに一致するソケットアドレスがあたえられなかった場合、
15880 @code{socket-recvfrom!}の振舞いは@var{addrs}のリスト終端の値によります。
15881 @var{addrs}が@code{()}で終端されていた場合 (@var{addrs}が真性リストで
15882 あった場合)、送信者のアドレスは捨てられ、@code{socket-recvfrom!}は
15883 二番めの値として@code{#f}を返します。@var{addrs}が@code{#t}で終端
15884 されていた場合、@code{socket-recvfrom!}は新たなソケットアドレス
15885 インスタンスを作成して返します。
15886
15887 簡単な場合として次の二つがあります:@var{addrs}に@code{()}が渡された場合、
15888 送信者のアドレスは常に捨てられます。@var{socket}がコネクトされていれば
15889 送信者のアドレスは既にわかっているので、そういう場合に便利でしょう。
15890 一方@var{addrs}に@code{#t}を渡せば、常に新しいソケットアドレスが
15891 アロケートされて返されます。メモリアロケーションについて気にしなくても
15892 良い場合は便利でしょう。
15893 @c COMMON
15894
15895 @c EN
15896 The optional @var{flags} can be a bitwise OR of the integer
15897 constants @code{MSG_*}. See the system's manpage of @code{recvfrom(2)}
15898 for the details.
15899 @c JP
15900 オプション引数 @var{flags} は整数定数 @code{MSG_*} のビット毎のORで
15901 指定できます。詳しくはシステムの man ページ @code{recvfrom(2)}を見て下さい。
15902 @c COMMON
15903 @end defun
15904
15905
15906 @defun socket-recv socket bytes :optional flags
15907 @defunx socket-recvfrom socket bytes :optional flags
15908 @c MOD gauche.net
15909 @c EN
15910 Like @code{socket-recv!} and @code{socket-recvfrom!}, but
15911 these returns the received message as a (possibly incomplete)
15912 string, up to @var{bytes} size. Additionally,
15913 @code{socket-recvfrom} always allocates a socket address
15914 object for the sender's address.
15915 @c JP
15916 @code{socket-recv!}や@code{socket-recvfrom!}と似ていますが、
15917 受け取ったメッセージを(不完全かもしれない)文字列として返します。
15918 @var{bytes}は受信する上限のバイト数を指定します。
15919 @code{socket-recvfrom}はそれに加えて、送信者のアドレスのために
15920 常に新たなソケットアドレスオブジェクトを生成します。
15921 @c COMMON
15922
15923 @c EN
15924 The use of these procedures are discouraged, since they
15925 often returns incomplete strings for binary messages.
15926 Using strings for binary data creates many pitfalls.
15927 Uniform vectors (especially @code{u8vector}s) are for binary data.
15928 (The reason these procedures return strings is merely historical.)
15929 @c JP
15930 これらの手続きの使用はお薦めしません。というのは、バイナリメッセージを
15931 不完全な文字列の形で扱うことになりがちだからです。文字列で
15932 バイナリメッセージを取り扱うことは多くの落とし穴を作ります。
15933 バイナリデータを扱う場合はユニフォームベクタ (特に@code{u8vector})
15934 を使うべきでしょう。
15935 (これらの手続きが文字列を返すのは単に歴史的な理由によります)。
15936 @c COMMON
15937 @end defun
15938
15939 @defvar MSG_CTRUNC
15940 @defvarx MSG_DONTROUTE
15941 @defvarx MSG_EOR
15942 @defvarx MSG_OOB
15943 @defvarx MSG_PEEK
15944 @defvarx MSG_TRUNC
15945 @defvarx MSG_WAITALL
15946 @c MOD gauche.net
15947 @c EN
15948 Pre-defined integer constants to be used as @var{flags} values
15949 for @code{socket-send}, @code{socket-sendto}, @code{socket-recv}
15950 and @code{socket-recvfrom}. Some of these constants may not be
15951 defined if the underlying operating system doesn't provide them.
15952 @c JP
15953 @code{socket-send}、@code{socket-sendto}、@code{socket-recv} および
15954 @code{socket-recvfrom} の @var{flag} として使う定義済み整数定数。
15955 これらの定数のいくつかは、基盤のOSが提供していなければ未定義に
15956 なっています。
15957 @c COMMON
15958 @end defvar
15959
15960 @c EN
15961 Further control over sockets and protocol layers is possible
15962 by getsockopt/setsockopt interface, as described below.
15963 @c JP
15964 以下に解説する getsockopt/setsockopt インタフェースを使えば、
15965 ソケットやプロトコルをさらに制御することができます。
15966 @c COMMON
15967
15968 @defun socket-setsockopt socket level option value
15969 @defunx socket-getsockopt socket level option rsize
15970 @c MOD gauche.net
15971 @c EN
15972 These are the interface to setsockopt() and getsockopt() calls.
15973 The interface is a bit clumsy, in order to allow full access to
15974 those low-level calls.
15975
15976 @var{socket} must be a non-closed socket object.
15977 @var{level} and @var{option} is an exact integer to specify
15978 the level of protocol stack and the option you want to deal with.
15979 There are several variables pre-bound to system constants listed below.
15980
15981 To set the socket option, you can pass either an exact integer or
15982 a string to @var{value}. If it is an integer, the value is passed
15983 to setsockopt(2) as C @code{int} value. If it is a string, the
15984 byte sequence is passed as is. The required type of value depends on
15985 the option, and Gauche can't know if the value you passed is expected
15986 by setsockopt(2); it is your responsibility to pass the correct values.
15987
15988 To get the socket option, you need to tell the maximum length of expected
15989 result by @var{rsize} parameter, for Gauche doesn't know the amount
15990 of data each option returns.
15991 @code{socket-getsockopt} returns the option value as a byte string.
15992 If you know the option value is an integer, you can pass 0 to @var{rsize};
15993 in that case @code{socket-getsockopt} returns the value as an exact integer.
15994
15995 Note about the name: I tempted to name these function socket-@{set|get@}opt
15996 or socket-@{set|get@}-option,
15997 but I rather took the naming consistency. Hence duplicated "sock"s.
15998
15999 @c JP
16000 これらは、setsockopt() および getsockopt() を呼ぶための
16001 インタフェースです。このインタフェースが少々ぎこちないのは、
16002 低レベルの呼び出しすべてにアクセスできるようにしているためです。
16003
16004 @var{socket} および @var{option} は、処理する対象の
16005 プロトコルスタックのレベルおよびオプションを指定する
16006 正確な整数です。以下にリストアップしたシステム定数に束縛された
16007 変数があります。
16008
16009 ソケットオプションを設定するには、@var{value} に正確な整数を渡す方法と
16010 文字列を渡す方法があります。それが、整数なら、その値は、C の
16011 @code{int} として setsockopt (2) に渡されます。文字列なら、バイト列が
16012 そのまま渡されます。どの型の値が要求されるかは、オプションに依存します。
16013 Gauche 側では渡された値が setsockopt (2) で期待された型であるかどうかは
16014 知ることができません。正しい値が渡されるかどうかはプログラマの責任です。
16015
16016 ソケットオプションを知るには、結果として期待する最大の長さを @var{rsize}
16017 を使って教える必要があります。Gauche 側は返されるそれぞれのオプションの
16018 合計を知らないからです。
16019 @code{socket-getsockopt} はオプションの値をバイト列として返します。
16020 オプションの値が整数だと、わかっているなら @var{rsize} に0を渡すこと
16021 ができます。その場合 @code{socket-getsockopt} は正確な整数として値を返します。
16022
16023 関数名に関する註: これらの関数の名前を socket-@{set|get@}opt あるいは
16024 socket-@{set|get@}-option にしようかとも思いましたが、結局、命名の
16025 一貫性をとることにしました。それで、"sock" が重複しています。
16026 @c COMMON
16027
16028 @end defun
16029
16030 @c EN
16031 The following predefined variables are provided.
16032 Note that some of them are not available on all platforms.
16033 See manpages @code{socket(7)}, @code{tcp(7)} or @code{ip(7)} of
16034 your system to find out exact specification of those values.
16035
16036 For ``level'' argument:
16037 @c JP
16038 以下のような定義済みの変数が用意されています。
16039 すべてのプラットフォームで利用できるわけではないものも含まれている
16040 ことに注意してください。
16041 これらの値の正確な使用は、お使いのシステムの man ページ @code{socket(7)}、
16042 @code{tcp(7)} あるいは @code{ip(7)} を参照してください。
16043
16044 ``level'' 引数
16045 @c COMMON
16046 @defvar SOL_SOCKET
16047 @defvarx SOL_TCP
16048 @defvarx SOL_IP
16049 @c MOD gauche.net
16050 @c EN
16051 These variables are bound to @code{SOL_SOCKET}, @code{SOL_TCP} and
16052 @code{SOL_IP}, respectively.
16053 @c JP
16054 これらの変数は、それぞれ、@code{SOL_SOCKET}、@code{SOL_TCP} および
16055 @code{SOL_IP} に束縛されています。
16056 @c COMMON
16057 @end defvar
16058
16059 @c EN
16060 For ``option'' argument:
16061 @c JP
16062 ``option'' 引数
16063 @c COMMON
16064 @defvar SO_KEEPALIVE
16065 @c MOD gauche.net
16066 @c EN
16067 Expects integer value. If it is not zero, enables sending of
16068 keep-alive messages on connection-oriented sockets.
16069 @c JP
16070 整数が期待されています。0でなければ、コネクション指向ソケットに
16071 キープアライブ(keep-alive)メッセージを送ることができます。
16072 @c COMMON
16073 @end defvar
16074
16075 @defvar SO_OOBINLINE
16076 @c MOD gauche.net
16077 @c EN
16078 Expects integer value. If it is not zero, out-of-band data is
16079 directly placed into the receive data stream. Otherwise
16080 out-of-band data is only passed when the
16081 MSG_OOB flag is set during receiving.
16082 @c JP
16083 整数が期待されています。0でなければ、帯域外データは直接
16084 受信データストリームに乗ります。さもなければ、帯域外データは、受信中に
16085 MSG_OOBフラグが設定されてたときにのみ渡されます。
16086 @c COMMON
16087 @end defvar
16088
16089 @defvar SO_REUSEADDR
16090 @c MOD gauche.net
16091 @c EN
16092 Expects integer value. If it is not zero, @code{socket-bind}
16093 allows to reuse local addresses, unless an active listening
16094 socket bound to the address.
16095 @c JP
16096 整数が期待されています。0ではない場合、@code{socket-bind}は、
16097 ローカル・アドレスが、アクティブソケットにリッスンされていない
16098 場合にかぎり、そのアドレスを再利用することを許可されます。
16099
16100 @c COMMON
16101 @end defvar
16102
16103 @defvar SO_TYPE
16104 @c MOD gauche.net
16105 @c EN
16106 Gets the socket type as an integer (like @code{sock_stream}).
16107 Can be only used with @code{socket-getsockopt}.
16108 @c JP
16109 ソケットの型(@code{sock_stream}など)を整数として取得します。
16110 @code{socket-getsockopt}でのみ使用可能です。
16111 @c COMMON
16112 @end defvar
16113
16114 @defvar SO_BROADCAST
16115 @c MOD gauche.net
16116 @c EN
16117 Expects integer value. If it is not zero, datagram sockets
16118 are allowed to send/receive broadcast packets.
16119 @c JP
16120 整数が期待されています。0でなければ、データグラムソケットは
16121 ブロードキャストパケットを送受信することを許されます。
16122 @c COMMON
16123 @end defvar
16124
16125 @defvar SO_PRIORITY
16126 @c MOD gauche.net
16127 @c EN
16128 Expects integer value, specifying the protocol-defined priority
16129 for all packets to be sent on this socket.
16130 @c JP
16131 整数が期待されています。このソケットで送信されるすべてのパケットに
16132 ついてプロトコル定義の優先順位を指定します。
16133 @c COMMON
16134 @end defvar
16135
16136 @defvar SO_ERROR
16137 @c MOD gauche.net
16138 @c EN
16139 Gets and clears the pending socket error as an integer.
16140 Can be only used with @code{socket-getsockopt}.
16141 @c JP
16142 保留状態のソケットエラー(整数値)を取得し、それをクリアします。
16143 @code{socket-getsockopt}でのみ使用可能です。
16144 @c COMMON
16145 @end defvar
16146
16147
16148 @defun inet-checksum packet size
16149 @c MOD gauche.net
16150 @c EN
16151 Calculates one's complement of Internet Checksum (RFC1071) of the
16152 @var{packet}, which must be given as a uniform vector. First
16153 @var{size} bytes of @var{packet} are used for calculation.
16154 Returned value is in network byte order (big-endian).
16155 It is an error if @var{size} is greater than the size of @var{packet}.
16156
16157 Note: The used algorithm assumes @var{packet} is not too big (< 64K).
16158 @c JP
16159 ユニフォームベクタで与えられる@var{packet}のインターネットチェックサム(RFC1071)
16160 の1の補数を計算して返します。@var{packet}の最初の@var{size}バイトのみが
16161 計算の対象となります。返される値はネットワークバイトオーダ (ビッグエンディアン)
16162 です。@var{packet}より大きな値を@var{size}に指定するとエラーとなります。
16163
16164 註: 使われているアルゴリズムは、@var{packet}がそれほど大きくないこと (< 64K) を
16165 仮定しています。
16166 @c COMMON
16167 @end defun
16168
16169
16170 @node Netdb interface, , Low-level socket interface, Networking
16171 @subsection Netdb interface
16172 @c NODE Netdbインタフェース
16173
16174
16175
16176
16177 @deftp {Builtin Class} <sys-hostent>
16178 @clindex sys-hostent
16179 @c MOD gauche.net
16180 @c EN
16181 A class of objects for network hosts. Corresponding to
16182 @code{struct hostent} in C. The following slots are available read-only.
16183 @c JP
16184 このクラスはネットワークホストのオブジェクト用で、
16185 C の @code{struct hostent}
16186 に対応しています。以下のスロットは読み込み専用です。
16187 @c COMMON
16188
16189 @defivar {<sys-hostent>} name
16190 @c EN
16191 The formal name of the host (string).
16192 @c JP
16193 ホストの正式名(文字列)
16194 @c COMMON
16195 @end defivar
16196 @defivar {<sys-hostent>} aliases
16197 @c EN
16198 A list of alias names of the host (list of strings).
16199 @c JP
16200 ホストの別名リスト(文字列のリスト)
16201 @c COMMON
16202 @end defivar
16203 @defivar {<sys-hostent>} addresses
16204 @c EN
16205 A list of addresses (list of strings). Only ipv4 address is
16206 supported currently. Each address is represented by dotted decimal
16207 notation.
16208 @c JP
16209 アドレスのリスト(文字列のリスト)。現時点では IPv4 のアドレスのみサポート
16210 しています。それぞれのアドレスは、ドットつき十進記法で表記されています。
16211 @c COMMON
16212 @end defivar
16213 @end deftp
16214
16215 @defun sys-gethostbyname name
16216 @c MOD gauche.net
16217 @c EN
16218 Looks up a host named @var{name}.
16219 If found, returns a @code{<sys-hostent>} object.
16220 Otherwise, returns @code{#f}.
16221 @c JP
16222 @var{name}という名前のホストを探し、見つかれば、@code{<sys-hostent>}
16223 オブジェクトを返します。見つからなければ、@code{#f} を返します。
16224 @c COMMON
16225 @example
16226 (let ((host (sys-gethostbyname "www.w3c.org")))
16227 (list (slot-ref host 'name)
16228 (slot-ref host 'aliases)
16229 (slot-ref host 'addresses)))
16230 @result{} ("www.w3.org" ("www.w3c.org") ("18.29.1.34" "18.29.1.35"))
16231 @end example
16232 @end defun
16233
16234 @defun sys-gethostbyaddr addr proto
16235 @c MOD gauche.net
16236 @c EN
16237 Looks up a host that has an address @var{addr} of protocol @var{proto}.
16238 @var{addr} is a natural string representation of the address;
16239 for ipv4, it is a dotted decimal notation. @var{proto} is a
16240 protocol number; only @code{AF_INET} is supported currently.
16241 If the host is found, returns a @code{<sys-hostent>} object.
16242 Otherwise, returns @code{#f}.
16243 @c JP
16244 @var{proto}というプロトコルの、@var{addr}というアドレスを持つホストを
16245 探します。@var{addr}はアドレスの自然な文字列表現で、IPv4 については、
16246 ドットつき十進記法です。@var{proto}はプロトコル番号で、現時点では
16247 @code{AF_INET}のみサポートされています。ホストが見つかれば、
16248 @code{<sys-hostent>}オブジェクトを返します。
16249 見つからなければ、@code{#f} を返します。
16250 @c COMMON
16251 @example
16252 (let ((host (sys-gethostbyaddr "127.0.0.1" AF_INET)))
16253 (list (slot-ref host 'name)
16254 (slot-ref host 'aliases)
16255 (slot-ref host 'addresses))
16256 @result{} ("localhost" ("localhost.localdomain") ("127.0.0.1"))
16257 @end example
16258 @end defun
16259
16260 @deftp {Builtin Class} <sys-servent>
16261 @clindex sys-servent
16262 @c MOD gauche.net
16263 @c EN
16264 An entry of the network service database. Corresponding to
16265 @code{struct servent} in C. The following slots are available read-only.
16266 @c JP
16267 ネットワークサービスデータベースのエントリです。
16268 C の @code{struct servent}に対応しています。
16269 以下のスロットは読み込み専用です。
16270 @c COMMON
16271
16272 @defivar {<sys-servent>} name
16273 @c EN
16274 The formal name of the service (string).
16275 @c JP
16276 サービスの正式名(文字列)
16277 @c COMMON
16278 @end defivar
16279 @defivar {<sys-servent>} aliases
16280 @c EN
16281 A list of alias names of the service (list of strings).
16282 @c JP
16283 サービスの別名リスト(文字列のリスト)
16284 @c COMMON
16285 @end defivar
16286 @defivar {<sys-servent>} port
16287 @c EN
16288 A port number registered for this service (exact integer).
16289 @c JP
16290 サービスに割り当てられたポート番号(正確な整数)
16291 @c COMMON
16292 @end defivar
16293 @defivar {<sys-servent>} proto
16294 @c EN
16295 A protocol name for this service (string).
16296 @c JP
16297 このサービス用のプロトコル名(文字列)
16298 @c COMMON
16299 @end defivar
16300 @end deftp
16301
16302 @defun sys-getservbyname name proto
16303 @c MOD gauche.net
16304 @c EN
16305 Looks up the network service database with a service name @var{name} and
16306 a protocol @var{proto}. Both @var{name} and @var{proto} must be a string.
16307 If a service is found, an instance of @code{<sys-servent>} is returned.
16308 Otherwise, @code{#f} is returned.
16309 @c JP
16310 ネットワークサービスデータベースをサービス名 @var{name} および
16311 プロトコル @var{proto} で検索します。@var{name} および @var{proto}
16312 は文字列でなければなりません。サービスが見つかれば、@code{<sys-servent>}
16313 のインスタンスを返します。見つからなければ、@code{#f} を返します。
16314 @c COMMON
16315 @example
16316 (let ((serv (sys-getservbyname "http" "tcp")))
16317 (list (slot-ref serv 'name)
16318 (slot-ref serv 'aliases)
16319 (slot-ref serv 'port)
16320 (slot-ref serv 'proto)))
16321 @result{} ("http" () 80 "tcp")
16322 @end example
16323 @end defun
16324
16325 @defun sys-getservbyport port proto
16326 @c MOD gauche.net
16327 @c EN
16328 Looks up the network service database with a service port @var{port} and
16329 a protocol @var{proto}. @var{port} must be an exact integer, and
16330 @var{proto} must be a string.
16331 If a service is found, an instance of @code{<sys-servent>} is returned.
16332 Otherwise, @code{#f} is returned.
16333 @c JP
16334 ネットワークサービスデータベースをサービス名 @var{port} および
16335 プロトコル @var{proto} で検索します。@var{port} は正確な整数でなければ
16336 なりません。また、@var{proto} は文字列でなければなりません。
16337 サービスが見つかれば、@code{<sys-servent>}
16338 のインスタンスを返します。見つからなければ、@code{#f} を返します。
16339 @c COMMON
16340 @example
16341 (let ((serv (sys-getservbyport 6000 "tcp")))
16342 (list (slot-ref serv 'name)
16343 (slot-ref serv 'aliases)
16344 (slot-ref serv 'port)
16345 (slot-ref serv 'proto)))
16346 @result{} ("x-server" () 6000 "tcp")
16347 @end example
16348 @end defun
16349
16350 @deftp {Builtin Class} <sys-protoent>
16351 @clindex sys-protoent
16352 @c MOD gauche.net
16353 @c EN
16354 An entry of the protocol database. Corresponds to @code{struct protoent}
16355 in C. The following slots are available read-only.
16356 @c JP
16357 プロトコルデータベースのエントリです。C の @code{struct protoent}に
16358 対応しています。以下のスロットは読み込み専用です。
16359 @c COMMON
16360
16361 @defivar {<sys-servent>} name
16362 @c EN
16363 The formal name of the protocol (string).
16364 @c JP
16365 プロトコルの正式名(文字列)
16366 @c COMMON
16367 @end defivar
16368 @defivar {<sys-servent>} aliases
16369 @c EN
16370 A list of alias names of the protocol (list of strings).
16371 @c JP
16372 プロトコルの別名のリスト(文字列のリスト)
16373 @c COMMON
16374 @end defivar
16375 @defivar {<sys-servent>} proto
16376 @c EN
16377 A protocol number (exact integer).
16378 @c JP
16379 プロトコル番号(正確な整数)
16380 @c COMMON
16381 @end defivar
16382 @end deftp
16383
16384 @defun sys-getprotobyname name
16385 @c MOD gauche.net
16386 @c EN
16387 Looks up the network protocol database with a name @var{name},
16388 which must be a string.
16389 If a protocol is found, an instance of @code{<sys-protoent>} is returned.
16390 Otherwise, @code{#f} is returned.
16391 @c JP
16392 名前 @var{name} でネットワークプロトコルデータベースを検索します。
16393 名前 @var{name} は文字列でなければなりません。
16394 プロトコルが見つかれば、@code{<sys-protoent>}
16395 のインスタンスを返します。見つからなければ、@code{#f} を返します。
16396 @c COMMON
16397 @example
16398 (let ((proto (sys-getprotobyname "icmp")))
16399 (list (slot-ref proto 'name)
16400 (slot-ref proto 'aliases)
16401 (slot-ref proto 'proto)))
16402 @result{} ("icmp" ("ICMP") 1)
16403 @end example
16404 @end defun
16405
16406 @defun sys-getprotobynumber number
16407 @c MOD gauche.net
16408 @c EN
16409 Looks up the network protocol database with a protocol number @var{number},
16410 which must be an exact integer.
16411 If a protocol is found, an instance of @code{<sys-protoent>} is returned.
16412 Otherwise, @code{#f} is returned.
16413 @c JP
16414 プロトコル番号 @var{number} でネットワークプロトコルデータベースを検索
16415 する。プロトコル番号 @var{number} は正確な整数でなければなりません。
16416 プロトコルが見つかれば、@code{<sys-protoent>}
16417 のインスタンスを返します。見つからなければ、@code{#f} を返します。
16418 @c COMMON
16419 @example
16420 (let ((proto (sys-getprotobynumber 17)))
16421 (list (slot-ref proto 'name)
16422 (slot-ref proto 'aliases)
16423 (slot-ref proto 'proto)))
16424 @result{} ("udp" ("UDP") 17)
16425 @end example
16426 @end defun
16427
16428 @deftp {Builtin Class} <sys-addrinfo>
16429 @clindex sys-addrinfo
16430 @c MOD gauche.net
16431 @c EN
16432 The new interface to keep address information.
16433 Corresponds to @code{struct addrinfo} in C.
16434 This is only available if gauche is configured with --enable-ipv6 option.
16435 The following slots are provided.
16436 @c JP
16437 アドレス情報を保持する新しいインタフェースです。C の @code{struct addrinfo}
16438 に対応しています。これは gauche が --enable-ipv6 オプションで設定され、
16439 ビルドされた場合にのみ利用可能です。以下のスロットが提供されます。
16440 @c COMMON
16441
16442 @defivar {<sys-addrinfo>} flags
16443 @end defivar
16444 @defivar {<sys-addrinfo>} family
16445 @end defivar
16446 @defivar {<sys-addrinfo>} socktype
16447 @end defivar
16448 @defivar {<sys-addrinfo>} protocol
16449 @end defivar
16450 @defivar {<sys-addrinfo>} addrlen
16451 @end defivar
16452 @defivar {<sys-addrinfo>} addr
16453 @end defivar
16454 @end deftp
16455
16456 @defun sys-getaddrinfo nodename servname hints
16457 @c MOD gauche.net
16458 @c EN
16459 Returns a list of @code{<sys-addrinfo>} instances from the given @var{nodename},
16460 @var{servname} and @var{hints}.
16461 This is only available if gauche is compiled with --enable-ipv6 option.
16462 @c JP
16463 与えられた @var{nodename}、@var{servname} および @var{hints} から
16464 @code{<sys-addrinfo>} のインスタンスのリストを返します。
16465 これは gauche が --enable-ipv6 オプションで設定され、
16466 ビルドされた場合にのみ利用可能です。
16467 @c COMMON
16468 @end defun
16469
16470 @defun sys-ntohs integer
16471 @defunx sys-ntohl integer
16472 @defunx sys-htons integer
16473 @defunx sys-htonl integer
16474 @c MOD gauche.net
16475 @c EN
16476 Utility functions to convert 16bit (@code{s}) or 32bit (@code{l}) integers
16477 between @emph{network} byte order (@code{n}) and @emph{host} byte order
16478 (@code{h}).
16479
16480 Scheme API to the netdb interface calls those byte order conversion
16481 functions internally, so you don't usually need them so much as in C
16482 programs. However, it may be useful when you're constructing or
16483 analyzing binary packets. See also @ref{Packing binary data} to handle
16484 binary data.
16485 @c JP
16486 16bit (@code{s})もしくは32bit (@code{l}) の整数を
16487 ネットワークバイト順 (@code{n}) とホストバイト順 (@code{h}) の間で
16488 相互変換するユーティリティ関数です。
16489
16490 netdbインタフェースのScheme APIは必要な箇所ではこれらの関数を内部的に
16491 呼んでいるので、Cでプログラミングしている時ほどこれらの関数を必要とする
16492 ことはないでしょう。ただ、バイナリデータパケットを構築したり解析したり
16493 する際は便利かもしれません。バイナリデータの扱いについては
16494 @ref{Packing binary data}も参照して下さい。
16495 @c COMMON
16496 @end defun
16497
16498 @c ----------------------------------------------------------------------
16499 @node Package metainformation, Parameters (legacy), Networking, Library modules - Gauche extensions
16500 @section @code{gauche.package} - Package metainformation
16501 @c NODE パッケージメタ情報, @code{gauche.package} - パッケージメタ情報
16502
16503 @deftp {Module} gauche.package
16504 @mdindex gauche.package
16505 @c EN
16506 Gauche manages extra libraries and extension modules as @emph{packages}.
16507 @c JP
16508 Gaucheは外部のライブラリや拡張モジュールを@emph{パッケージ}として管理します。
16509 @c COMMON
16510
16511 @c EN
16512 Each package source tree has @file{package.scm} on top directory, which
16513 contains @code{define-gauche-package} form that provides metainformation
16514 about the package---the package name, version, author, dependencies, etc.
16515 @c JP
16516 各パッケージのソースツリーのトップディレクトリには@file{package.scm}が置かれていて、
16517 その中では@code{define-gauche-package}フォームによってパッケージの
16518 メタ情報が記されています。パッケージ名、バージョン、作者、依存関係等です。
16519 @c COMMON
16520
16521 @c EN
16522 When the package is installed, the standard installation process copies
16523 that information, with additional information such as the version of
16524 Gauche used to build the package, into @file{.packages} subdirectory
16525 of the library installation path, with the name @file{PACKAGENAME.gpd},
16526 where @code{PACKAGENAME} is the name of the package.
16527 @c JP
16528 パッケージのインストールに標準のインストール手順を使えば、
16529 このメタ情報にパッケージをビルドしたGaucheのバージョン情報などが付け加えられ、
16530 ライブラリインストールパスの@file{.packages}サブディレクトリの下に
16531 @file{PACKAGENAME.gpd}という名前で保存されます。ここで
16532 @code{PACKAGENAME}はパッケージの名前です。
16533 @c COMMON
16534
16535 @c EN
16536 We collectively call @file{package.scm} and @file{*.gpd} as
16537 @emph{package description file}.
16538 @c JP
16539 @file{package.scm}と@file{*.gpd}ファイルを@emph{パッケージ記述ファイル}と
16540 総称することにします。
16541 @c COMMON
16542
16543 @c EN
16544 This module provides utility procedures to read and write package
16545 description files, and search installed @file{*.gpd} files.
16546 @c JP
16547 このモジュールはパッケージ記述ファイルの読み書きと、
16548 インストールされたパッケージのパッケージ記述ファイルを探すユーティリティ手続きを
16549 提供します。
16550 @c COMMON
16551 @end deftp
16552
16553 @subheading @file{package.scm}
16554
16555 @c EN
16556 A package file, @file{package.scm}, must contain one package definition
16557 in the following form. It is not evaluated; it is read as a literal data.
16558 @c JP
16559 パッケージファイル@file{package.scm}は、
16560 下に示すひとつのパッケージ定義を含みます。このフォームは評価されません。
16561 単にリテラルデータとして読まれます。
16562 @c COMMON
16563
16564 @c EN
16565 Note that @file{package.scm} may be referenced directly from its
16566 source repository. Gauche packages are uniquely identified by
16567 the repository URL, and its @file{package.scm} file is the
16568 definite source of metainformation of the package.
16569 @c JP
16570 @file{package.scm}はソースリポジトリにあるものが直接参照されることもあります。
16571 GaucheのパッケージはリポジトリURLによって一意に識別され、そのリポジトリにある
16572 @file{package.scm}がメタ情報の一次ソースとして扱われます。
16573 @c COMMON
16574
16575 @deffn {Package definition} define-gauche-package name key-value-list @dots{}
16576 @c EN
16577 Defines a package @var{name}. @var{Name} must be a symbol.
16578 It is followed by a keyword-value list. The following keywords are
16579 recognized.
16580 @c JP
16581 パッケージ@var{name}を定義します。@var{name}はシンボルでなければなりません。
16582 続くのはキーワード-値リストです。以下のキーワードが認識されます。
16583 @c COMMON
16584
16585 @table @code
16586 @item repository
16587 @c EN
16588 (string) A repository URL of the package. This is used as a unique identifier of
16589 the package when the package is published.
16590 @c JP
16591 (文字列) パッケージのソースリポジトリのURL。パッケージを公開する際には、
16592 これがパッケージを一意に識別します。
16593 @c COMMON
16594 @item version
16595 @c EN
16596 (String) The version of the package, e.g. @code{"1.0"}.
16597 @c JP
16598 (文字列) パッケージのバージョン。例: @code{"1.0"}。
16599 @c COMMON
16600 @item description
16601 @c EN
16602 (String) The description of the pacakge. The first line (up to the
16603 first newline character) should be the one-line summary of the package.
16604 @c JP
16605 (文字列) パッケージの説明。最初の行 (最初の改行文字まで) はパッケージの1行のサマリに
16606 なっていなければなりません。
16607 @c COMMON
16608 @item require
16609 @c EN
16610 (List) A list of requirements. Each requirement is
16611 @code{(<package-name> <version-spec>)}, where @code{<package-name>}
16612 is a string package name, and @code{<version-spec>} determines
16613 the accepable versions of the package. @xref{Comparing version numbers},
16614 for the details of @code{<version-spec>}.
16615 @c JP
16616 (リスト) 依存パッケージのリスト。各依存パッケージは、
16617 @code{(<package-name> <version-spec>)}と記述されます。
16618 ここで@code{<package-name>}は文字列のパッケージ名、
16619 @code{<version-spec>}はパッケージの必要なバージョン範囲を示します。
16620 @code{<version-spec>}については@ref{Comparing version numbers}を参照してください。
16621 @c COMMON
16622 @item providing-modules
16623 @c EN
16624 (List) A list of module names in symbols, that this package provides.
16625 @c JP
16626 (リスト) このパッケージが提供するモジュール名(シンボル)のリストです。
16627 @c COMMON
16628 @item authors
16629 @c EN
16630 (List) A list of name and contact info of the authors of this package.
16631 @c JP
16632 (リスト) このパッケージの作者名とコンタクト情報のリストです。
16633 @c COMMON
16634 @item maintainers
16635 @c EN
16636 (List) A list of name and contact info of the maintainers of this package,
16637 if they differ from the @code{authors}.
16638 @c JP
16639 (リスト) このパッケージのメンテナの名前とコンタクト情報のリストです
16640 作者とメンテナが別の場合のみ必要です。
16641 @c COMMON
16642 @item licenses
16643 @c EN
16644 (List) A list of licenses in strings.
16645 @c JP
16646 (リスト) ライセンス(文字列)のリストです。
16647 @c COMMON
16648 @item homepage
16649 @c EN
16650 (String) A homepage URL of the package, if any.
16651 @c JP
16652 (文字列) パッケージのホームページURL (もしあれば)。
16653 @c COMMON
16654 @item superseded-by
16655 @c EN
16656 (String) If the developers stop maintaining this package, but another developer
16657 wants to continue development with a forked repository, the original
16658 developer can officially appoint the successor by specifying
16659 the new repository URL here.
16660 @c JP
16661 (文字列) もし開発者がこのパッケージの開発・メンテナンスをやめることにして、
16662 他の開発者がフォークしたリポジトリで開発の継続を希望した場合、
16663 元の開発者はここに新たなリポジトリのURLを指定することで、
16664 正式にリポジトリの継承を示すことができます。
16665 @c COMMON
16666 @end table
16667 @end deffn
16668
16669 @c EN
16670 @subheading @code{configure} script and @code{*.gpd} file generation
16671 @c JP
16672 @subheading @code{configure}スクリプトと@code{*.gpd}ファイルの生成
16673 @c COMMON
16674
16675 @c EN
16676 If you use @code{configure} script based on @code{gauche.configure}
16677 (@pxref{Generating build files}), a Gauche package description file
16678 (@file{*.gpd}) is created with it. The @code{gpd} file contains
16679 information from @file{package.scm}, plus the information on the
16680 installaion platform gathered by @code{configure}.
16681 @c JP
16682 @code{gauche.configure}を用いた@code{configure}スクリプトを使っている場合
16683 Gaucheパッケージ記述ファイル(@file{*.gpd})はそれによって作成されます
16684 (@pxref{Generating build files})。@code{gpd}ファイルは@file{package.scm}
16685 の情報に加え、@code{configure}スクリプトが集めたインストール先プラットフォームについての
16686 情報を保持しています。
16687 @c COMMON
16688
16689 @c EN
16690 The generated @code{gpd} file is installed with the package itself,
16691 and will be used by @code{gauche-package} command, as well as
16692 retrieved by the following utility APIs.
16693 @c JP
16694 生成された@code{gpd}ファイルはパッケージと一緒にインストールされ、
16695 @code{gauche-package}コマンドで参照できます。
16696 また、プログラム的に扱うためのユーティリティAPIが次のとおり用意されています。
16697 @c COMMON
16698
16699 @c EN
16700 @subheading Utility procedures
16701 @c JP
16702 @subheading ユーティリティ手続き
16703 @c COMMON
16704
16705 @deftp {Class} <gauche-package-description>
16706 @clindex gauche-package-description
16707 @c MOD gauche.package
16708 @c EN
16709 An object to handle package descriptions programatically.
16710 It has the following slots.
16711 @c JP
16712 プログラム的にパッケージ記述を扱うためのオブジェクトです。
16713 以下のスロットを持ちます。
16714 @c COMMON
16715
16716 @defivar {<gauche-package-description>} name
16717 @c EN
16718 The name of the package, a string.
16719 @c JP
16720 パッケージの名前 (文字列)。
16721 @c COMMON
16722 @end defivar
16723
16724 @defivar {<gauche-package-description>} repository
16725 @c EN
16726 An URL to the repository of this package, a string.
16727 A package is primarily identified by the repository URL.
16728 @c JP
16729 このパッケージのリポジトリURL(文字列)。
16730 パッケージはリポジトリURLによってユニークに同定されます。
16731 @c COMMON
16732 @end defivar
16733
16734 @defivar {<gauche-package-description>} version
16735 @c EN
16736 The version of the package, a string, e.g. @code{"1.0"}.
16737 @c JP
16738 パッケージのバージョン(文字列)。例:@code{"1.0"}。
16739 @c COMMON
16740 @end defivar
16741
16742 @defivar {<gauche-package-description>} description
16743 @c EN
16744 The description of the package, a string.
16745 Up to the first newline character may be used as a short summary.
16746 @c JP
16747 パッケージの説明 (文字列)。最初の改行文字までの1行がサマリとして扱われます。
16748 @c COMMON
16749 @end defivar
16750
16751 @defivar {<gauche-package-description>} require
16752 @c EN
16753 A list of @code{(package-name version-spec)}, to specify
16754 the other packages this package requires.
16755 @c JP
16756 @code{(package-name version-spec)}のリストで、
16757 このパッケージが必要とする他のパッケージおよびそのバージョンを指定します。
16758 @c COMMON
16759 @end defivar
16760
16761 @defivar {<gauche-package-description>} providing-modules
16762 @c EN
16763 A list of module names (symbols) that this package provides.
16764 @c JP
16765 このパッケージが提供するモジュール名(シンボル)のリスト。
16766 @c COMMON
16767 @end defivar
16768
16769 @defivar {<gauche-package-description>} authors
16770 @c EN
16771 A list of author's name and contact info.
16772 @c JP
16773 作者の名前と連絡先のリスト。
16774 @c COMMON
16775 @end defivar
16776
16777 @defivar {<gauche-package-description>} maintainers
16778 @c EN
16779 A list of maintainer's name and contact info, if it differs from
16780 @code{authors}.
16781 @c JP
16782 パッケージメンテナが作者と異なる場合、メンテナの名前と連絡先のリスト。
16783 @c COMMON
16784 @end defivar
16785
16786 @defivar {<gauche-package-description>} licenses
16787 @c EN
16788 A list of licenses. E.g. @code{"BSD"},
16789 @code{"MIT"}, @code{"GPL2"}, @code{"GPL3"}, @code{"Apache2"} etc.
16790 @c JP
16791 ライセンスのリスト。例: @code{"BSD"}、
16792 @code{"MIT"}、@code{"GPL2"}、@code{"GPL3"}、@code{"Apache2"}等。
16793 @c COMMON
16794 @end defivar
16795
16796 @defivar {<gauche-package-description>} homepage
16797 @c EN
16798 An URL to the homepage of this package, if any.
16799 @c JP
16800 このパッケージのホームページがあれば、そのURL。
16801 @c COMMON
16802 @end defivar
16803
16804 @defivar {<gauche-package-description>} superseded-by
16805 @c EN
16806 If not @code{#f}, the value is a repository URL of the successor
16807 of this package.
16808 When development of a package is stopped and someone else
16809 succeeded the further development, the original package specifies
16810 the successor here to show the succession ``official''.
16811 @c JP
16812 @code{#f}でなければ、このパッケージを引き継いだパッケージのリポジトリURL。
16813 パッケージの開発が停止し、他の誰かが将来の開発を引き継いだ場合、
16814 元のパッケージはこのスロットで後継者を指定することで「正式に」継承を示すことができます。
16815 @c COMMON
16816 @end defivar
16817
16818 @defivar {<gauche-package-description>} gauche-version
16819 @c EN
16820 Gauche version with which this module is installed.
16821 @c JP
16822 このモジュールがインストールされた時に使われたGaucheのバージョン。
16823 @c COMMON
16824 @end defivar
16825
16826 @defivar {<gauche-package-description>} configure
16827 @c EN
16828 A command-line string keeping how @code{configure} script was run
16829 to build and install this package.
16830 @c JP
16831 このモジュールがビルド/インストールされた時に与えられた@code{configure}の
16832 コマンドライン。
16833 @c COMMON
16834 @end defivar
16835 @end deftp
16836
16837 @defun path->gauche-package-description filename
16838 @c MOD gauche.package
16839 @c EN
16840 The named file must be a @code{gpd} file. This reads the file
16841 and returns an instance of @code{<gauche-package-description>}.
16842
16843 An error is thrown if @var{filename} can't be read, or doesn't
16844 have a proper @code{define-gauche-package} form.
16845 @c JP
16846 @var{filename}は@code{gpd}ファイルでなければなりません。
16847 この手続きはファイルをパーズし、@code{<gauche-package-description>}のインスタンスを
16848 返します。
16849
16850 @var{filename}が読めなかったり、ファイルが正しい@code{define-gauche-package}フォームを
16851 含んでいなかった場合はエラーが投げられます。
16852 @c COMMON
16853
16854 @c EN
16855 To find out installed @code{gpd} file(s), you can use
16856 @code{find-gauche-package-description} below.
16857 @c JP
16858 インストール済みの@code{gpd}ファイルを見つけるには、
16859 下の@code{find-gauche-package-description}が使えます。
16860 @c COMMON
16861 @end defun
16862
16863 @defun write-gauche-package-description description :optional oport
16864 @c MOD gauche.package
16865 @c EN
16866 Write out the content of @code{<gauche-package-description>} instance,
16867 @var{description} as a @code{define-gauche-package} form,
16868 to an output port @var{oport}. If @var{oport} is omitted,
16869 current output port is used.
16870 @c JP
16871 @code{<gauche-package-description>}のインスタンスである
16872 @var{description}の内容を、@code{define-gauche-package}形式として
16873 出力ポート@var{oport}に書き出します。@var{oport}が省略された場合は
16874 現在の出力ポートが使われます。
16875 @c COMMON
16876 @end defun
16877
16878 @defun make-gauche-package-description name :key version description require maintainers authors licenses homepage repository gauche-version configure providing-modules
16879 @c MOD gauche.package
16880 @c EN
16881 Creates and returns a new instance of @code{<gauche-package-description>},
16882 the slots of which is initialized with the given keyword arguments.
16883 @c JP
16884 @code{<gauche-package-description>}の新たなインスタンスを作って返します。
16885 スロットは対応するキーワード引数によって初期化されます。
16886 @c COMMON
16887 @end defun
16888
16889 @defun gauche-package-description-paths :key all-versions
16890 @c MOD gauche.package
16891 @c EN
16892 Gather all the @code{gpd} file paths installed in the standard location
16893 on the system. By default, it collects packages installed in
16894 @code{*load-path*}. If you give a true value to @var{all-version},
16895 it attempts to collect packages installed for other versions of
16896 Gauche as well.
16897 @c JP
16898 システムの標準の場所にインストールされている全ての@var{gpd}ファイルのパスを
16899 探し、そのリストを返します。
16900 デフォルトでは@code{*load-path*}にあるパスにインストールされたパッケージを探します。
16901 @var{all-version}キーワード引数に真の値が指定された場合は、
16902 それ以外のGaucheバージョン向けにインストールされたパッケージも探します。
16903 @c COMMON
16904 @end defun
16905
16906 @defun find-gauche-package-description name :key all-versions
16907 @c MOD gauche.package
16908 @c EN
16909 Try to find a package description of @var{name} (string)
16910 installed in the standard location,
16911 and returns an instance of @code{<gauche-package-description>} if found.
16912 Returns @code{#f} if the named package isn't found.
16913 @c JP
16914 名前@var{name} (文字列) を持つパッケージ記述を、標準的な場所にインストールされている
16915 パッケージから探します。見つかればそのパッケージの
16916 @code{<gauche-package-description>}インスタンスを、
16917 見つからなければ@code{#f}を返します。
16918 @c COMMON
16919
16920 @c EN
16921 By default, it collects packages installed in
16922 @code{*load-path*}. If you give a true value to @var{all-version},
16923 it attempts to collect packages installed for other versions of
16924 Gauche as well.
16925 @c JP
16926 デフォルトでは@code{*load-path*}に含まれるディレクトリにインストールされた
16927 パッケージから探します。@var{all-version}キーワード引数に真の値が与えられた
16928 場合は、それに加えて他のGaucheバージョンのためにインストールされたパッケージも
16929 探します。
16930 @c COMMON
16931 @end defun
16932
16933 @c ----------------------------------------------------------------------
16934 @node Parameters (legacy), Parsing command-line options, Package metainformation, Library modules - Gauche extensions
16935 @section @code{gauche.parameter} - Parameters (legacy)
16936 @c NODE パラメータ(レガシー), @code{gauche.parameter} - パラメータ(レガシー)
16937
16938 @deftp {Module} gauche.parameter
16939 @mdindex gauche.parameter
16940 @c EN
16941 This module is only provided for the backward compatibility.
16942 @emph{We strongly discourage using this module}.
16943
16944 Parameters are now built-in, so you no longer need to @code{use} this
16945 module for basic parameter functionalities. However, they have
16946 slightly different semantics from the legacy parameters Gauche had.
16947 The parameters provided in this module is backward compatible, so that
16948 you can run legacy code without changes.
16949
16950 When you use this module, those two identifiers are rebound
16951 to the backward-compatibility API.
16952
16953 @table @code
16954 @item make-parameter
16955 This becomes an alias of @code{make-legacy-parameter}.
16956 @item parameterize
16957 This becomes an alias of @code{parameterize/dynwind}
16958 @end table
16959
16960 @xref{Parameters and dynamic states}, for the details of
16961 the difference.
16962 @c JP
16963 このモジュールは後方互換性のためだけに提供されています。
16964 @emph{このモジュールを使うことはできるだけ避けてください。}
16965
16966 パラメータは組み込みになったので、パラメータの基本機能を使うだけなら
16967 このモジュールを@code{use}する必要はありません。
16968 ただ、組み込みのパラメータは従来のGaucheのパラメータと若干異なる動作をします。
16969 このモジュールのパラメータは以前のものと互換なので、古いコードをそのまま
16970 動かすことができます。
16971
16972 このモジュールをuseした場合、次の2つの識別子が互換性のあるものに再束縛されます。
16973
16974 @table @code
16975 @item make-parameter
16976 これは@code{make-legacy-parameter}の別名となります。
16977 @item parameterize
16978 これは@code{parameterize/dynwind}の別名となります。
16979 @end table
16980
16981 新旧パラメータの違いについて詳しくは
16982 @pxref{Parameters and dynamic states}を参照してください。
16983 @c COMMON
16984 @end deftp
16985
16986 @c EN
16987 Legacy parameters also had a feature called @emph{observers}, a callback
16988 procedure to be called when the parameter's value is modified.
16989 You can add/delete observers by the following API.
16990
16991 Note that observers are only attachable to legacy parameters.
16992 We plan to remove it eventually, so new code shouldn't use it.
16993 @c JP
16994 旧パラメータはまた、@emph{オブザーバ}という、パラメータの値が変わる時に
16995 呼ばれるコールバックを登録することができました。下のAPIはそのためのものです。
16996
16997 オブザーバは旧パラメータのみに付加できます。
16998 この機能はいずれ取り除く予定なので、新規コードでは使わないようにしてください。
16999 @c COMMON
17000
17001 @defun parameter-observer-add! p proc :optional when where
17002 @c MOD gauche.parameter
17003 @c DEPRECATED
17004 @c EN
17005 Adds @var{proc} to "observer" procedures of a parameter @var{p}.
17006 Observer procedures are called either (1) just before
17007 a new value is set to the parameter, or (2) just after the new value
17008 is set to the parameter. In case of (1), a filter procedure is
17009 already applied before a callback is called.
17010 In either case, observer procedures are called with two arguments,
17011 the old value and the new value. The return value(s) of observer
17012 procedures are discarded.
17013 @c JP
17014 @var{proc}をパラメータ@var{p}の``オブザーバ''手続きに追加します。
17015 オブザーバ手続きは、(1)パラメータに新しい値がセットされる直前、
17016 あるいは(2)パラメータに新しい値がセットされた直後、に呼ばれます。
17017 (1)の場合、コールバックが呼ばれる前にフィルタ手続きがすでに適用
17018 されています。どちらの場合も、オブザーバ手続きは、古い値と新しい
17019 値の2引数を伴って呼ばれます。オブザーバ手続きの戻り値は無視されます。
17020 @c COMMON
17021
17022 @c EN
17023 The optional @var{when} argument must be either a symbol @code{before}
17024 or @code{after}, to specify whether @var{proc} should be called
17025 before or after the value is changed. If omitted, @code{after} is
17026 assumed.
17027 @c JP
17028 オプショナル引数@var{when}は、シンボル@code{before}か@code{after}の
17029 いずれかでなければならず、値が変更された前と後のどちらで@var{proc}が
17030 呼ばれるかを指定します。省略されると、@code{after}を指定したものと
17031 されます。
17032 @c COMMON
17033
17034 @c EN
17035 The optional @var{where} argument must be either a symbol
17036 @code{append} or @code{prepend}, to specify whether @var{proc} should
17037 be prepended or appended to the existing observer procedure list.
17038 If omitted, @code{append} is assumed.
17039 @c JP
17040 オプショナル引数@var{where}は、シンボル@code{append}か@code{prepend}の
17041 いずれかでなければならず、@var{proc}が既存のオブザーバ手続きのリストの
17042 前に追加されるか後に追加されるかを指定します。省略されると、@code{append}
17043 を指定したものとされます。
17044 @c COMMON
17045
17046 @c EN
17047 @emph{Note}: Although the parameter value itself is thread-local,
17048 the observer list is shared by all threads.
17049 @c JP
17050 @emph{注意}: パラメータの値自身がスレッドローカルであっても、
17051 オブザーバのリストは全てのスレッドで共有されます。
17052 @c COMMON
17053 @end defun
17054
17055
17056 @defun parameter-observer-delete! p proc :optional when
17057 @c MOD gauche.parameter
17058 @c DEPRECATED
17059 @c EN
17060 Deletes @var{proc} from observer procedure list of a parameter @var{p}.
17061 If @var{proc} is not in the list, nothing happens.
17062 You can give either a symbol @code{before} or @code{after} to
17063 @var{when} argument to specify from which list @var{proc} should be
17064 deleted. If @var{when} argument is omitted, @var{proc} is deleted
17065 from both lists.
17066 @c JP
17067 パラメータ@var{p}のオブザーバ手続きのリストから@var{proc}を削除します。
17068 @var{proc}がリストになければ、何も起こりません。
17069 @var{when}引数にシンボル@code{before}か@code{after}を与えて、
17070 @var{proc}をどちらのリストから削除するかを指定することができます。
17071 @var{when}引数が省略されると、@var{proc}は両方のリストから削除されます。
17072 @c COMMON
17073 @end defun
17074
17075 @defun parameter-pre-observers p
17076 @defunx parameter-post-observers p
17077 @c MOD gauche.parameter
17078 @c DEPRECATED
17079 @c EN
17080 Returns a hook object (@pxref{Hooks}) that keeps
17081 "before" or "after" observers, respectively.
17082
17083 @emph{Note}: Although the parameter value itself is thread-local,
17084 these hook objects are shared by all threads.
17085 @c JP
17086 ``before''か``after''オブザーバをそれぞれキープするフックオブジェクト
17087 (@ref{Hooks}参照)を返します。
17088
17089 @emph{注意}: パラメータの値自身がスレッドローカルであっても、
17090 オブザーバのリストは全てのスレッドで共有されます。
17091 @c COMMON
17092 @end defun
17093
17094
17095 @c ----------------------------------------------------------------------
17096 @node Parsing command-line options, Partial continuations, Parameters (legacy), Library modules - Gauche extensions
17097 @section @code{gauche.parseopt} - Parsing command-line options
17098 @c NODE コマンドライン引数の解析, @code{gauche.parseopt} - コマンドライン引数の解析
17099
17100 @deftp {Module} gauche.parseopt
17101 @mdindex gauche.parseopt
17102 @c EN
17103 This module defines a convenient way to parse command-line options.
17104 The interface is hinted by Perl, and conveniently handles long-format
17105 options with multiple option arguments.
17106
17107 Actually, you have a few choices to parse command-line
17108 options in Gauche.
17109 SRFI-37 (@pxref{A program argument processor}) provides
17110 functional interface to parse POSIX/GNU compatible argument syntax.
17111 SLIB has @code{getopt}-compatible utility.
17112 Required features may differ from application to application,
17113 so choose whichever fits your requirement.
17114 @c JP
17115 このモジュールでは、コマンドラインオプションをパースするための便利な方法を定義
17116 しています。インタフェースは Perl にヒントを受けたもので、複数のオプション引数を
17117 伴う長い形式のオプションを便利に扱うことができます。
17118
17119 実際、Gauche でコマンドラインオプションをパースするにはいくつかの選択肢が
17120 あります。SRFI-37 (@ref{A program argument processor}参照)では、
17121 POSIX/GNU 互換の引数構文をパースするための関数的なインタフェースを提供しています。
17122 SLIB は、@code{getopt} 互換のユーティリティを持っています。
17123 要求される機能はアプリケーションごとに異なるので、
17124 あなたの要求にフィットするものを選んで下さい。
17125 @c COMMON
17126 @end deftp
17127
17128 @c EN
17129 @subheading High-level API
17130 @c JP
17131 @subheading 高レベルAPI
17132 @c COMMON
17133
17134 @defmac let-args args (bind-spec @dots{} [. rest]) body @dots{}
17135 @c MOD gauche.parseopt
17136 @c EN
17137 This macro captures the most common pattern of argument processing.
17138 It takes a list of arguments, @var{args}, and scans it to find
17139 Unix-style command-line options and binds their values to local
17140 variables according to @var{bind-spec}, then executes @var{body} @dots{}.
17141 @c JP
17142 このマクロはコマンドライン引数処理の最も典型的なパターンを扱います。
17143 引数のリスト@var{args}を取り、@var{bind-spec}で示される仕様をもとに
17144 コマンドラインオプションを探してその値を変数に束縛し、それから
17145 @var{body} @dots{}を実行します。
17146 @c COMMON
17147
17148 @c EN
17149 Let's look at a simple example first, which gives you a good idea of
17150 what this form does. (See the ``Examples'' section below for more
17151 examples).
17152 @c JP
17153 まず簡単な例を見てみましょう。このフォームが何をするか、だいたい想像できるのでは
17154 ないかと思います。(より多くの例については下の``Examples''の項を参照して
17155 ください)。
17156 @c COMMON
17157
17158 @example
17159 (define (main args)
17160 (let-args (cdr args)
17161 ((verbose "v|verbose" ? "Run verbosely.")
17162 (outfile "o|outfile=s@{FILE@}" ? "Write output to @{FILE@}.")
17163 (debug-level "d|debug-level=i@{LEVEL@}" 0 ? "Set debug level.")
17164 (help "h|help" => (cut show-help (car args))
17165 ? "Show help message and exit.")
17166 . restargs
17167 )
17168 ....))
17169
17170 (define (show-help progname)
17171 (print "Usage: ....")
17172 (pritn "Options:")
17173 (print (option-parser-help-string))
17174 (exit 0))
17175 @end example
17176
17177 @c EN
17178 The local variable @var{verbose} will be bound to @code{#t} if
17179 a command-line argument @code{-v} or @code{--verbose} is given,
17180 and to @code{#f} otherwise.
17181 The variable @var{output} is specified to take one option argument;
17182 if the command-line arguments are given like @code{-o out.txt},
17183 @var{outfile} receives
17184 @code{"out.txt"}. The @var{debug-level} one is similar, but the
17185 option argument is coerced to an integer, and also it has default
17186 value 0 when the option isn't given. The @var{help} clause
17187 invokes an action rather than merely binding the value.
17188 @c JP
17189 ローカル変数@var{verbose}は、コマンドラインオプション@code{-v}や@code{--verbose}
17190 が与えられれば@code{#t}に、そうでなければ@code{#f}に束縛されます。
17191 変数@var{output}はオプション引数を取ると指定されており、例えば
17192 @code{-o out.txt}のようにコマンドラインに指定されれば値@code{"out.txt"}が
17193 束縛されます。@var{debug-level}も似ていますが、オプション引数は
17194 整数へと変換され、またデフォルト値0が指定されています。
17195 @var{help}節では、単に値を束縛するだけでなくアクションを起動しています。
17196 @c COMMON
17197
17198 @c EN
17199 (Note: Currently @code{let-args} does not distinguish so-called
17200 short and long options, e.g. @code{-v} and @code{--v} have the same
17201 effect, so as @code{-verbose} and @code{--verbose}. In future we
17202 may add an option to make it compatible with @code{getopt_long(3)}.)
17203 @c JP
17204 (註: 今のところ@code{let-args}は@code{-v}と@code{--v}を区別しません。
17205 @code{-verbose}と@code{--verbose}も同様です。将来、@code{getopt_long(3)}と
17206 互換になるオプションを追加するかもしれません。)
17207 @c COMMON
17208
17209 @c EN
17210 The string after @code{?} is used as a help string for the option.
17211 You can get a formatted help string with
17212 @code{option-parser-help-string}.
17213 @c JP
17214 @code{?}の後の文字列はオプションのヘルプ文字列です。
17215 @code{option-parser-help-string}でフォーマットされたオプションのヘルプを
17216 得ることができます。
17217 @c COMMON
17218
17219 @c EN
17220 The final @var{restargs} variable after the dot receives a list of
17221 non-optional command-line arguments.
17222 @c JP
17223 最後のドットの後の@var{restargs}は、オプションでないコマンドライン引数のリストを
17224 受け取ります。
17225 @c COMMON
17226
17227 @c EN
17228 Let's look at @var{bind-spec} in detail.
17229 It must be one of the following forms.
17230 @c JP
17231 @var{bind-spec}について詳しく見てみましょう。
17232 @var{bind-spec}は次のいずれかの形式でなければなりません。
17233 @c COMMON
17234
17235 @example
17236 1. (@var{var} @var{option-spec} [@var{default}] [? @var{helpstr}])
17237 2. (@var{var} @var{option-spec} [@var{default}] => @var{callback} [? @var{helpstr}])
17238
17239 3. (else => @var{fallback})
17240 4. (else @var{formals} @var{body} ...)
17241 @end example
17242
17243 @c EN
17244 A list of command-line arguments passed to @var{args} are parsed
17245 according to @var{option-spec}s. If the corresponding option
17246 is given, the option's ``value'' is determined as follows:
17247
17248 @example
17249 (a) If the @var{bind-spec} is 1., then
17250 (a1) If @var{option-spec} doesn't require an argument, then @code{#t}:
17251 (a2) If @var{option-spec} requires one argument, then the value of
17252 the argument:
17253 (a3) If @var{option-spec} requires more than one argument,
17254 the list of the values of the arguments.
17255 (b) If the @var{bind-spec} is 2., then @var{callback} is called with
17256 the value(s) of arguments, and its return value.
17257 @end example
17258 @c JP
17259 コマンドライン引数のリストが@var{args}に渡されると、それが
17260 @var{option-spec}に基づいてパーズされます。該当するオプションが見付かれば、
17261 オプションの「値」が次のとおり決定されます。
17262
17263 @example
17264 (a) @var{bind-spec}の形式が上の1. の場合:
17265 (a1) @var{option-spec}が引数を要求しない場合は、@code{#t}。
17266 (a2) @var{option-spec}がひとつの引数を要求する場合は、その引数の値。
17267 (a3) @var{option-spec}がそれ以上の引数を要求する場合は、引数の値のリスト。
17268 (b) @var{bind-spec}の形式が上の2.の場合、@var{callback}を引数の値を伴って呼び出し、その戻り値。
17269 @end example
17270 @c COMMON
17271
17272 @c EN
17273 An option can be singular, meaning at most one appearance is effective,
17274 or it can be plural, meaning multiple apperances are considered.
17275 If an option is singular, @code{var} is bound to the value determined
17276 as above. If an option is plural, @var{var} is bound to the list of
17277 above values from all occurrences.
17278 @c JP
17279 オプションには、「単数」、つまりたかだか一回までの指定が有効か、
17280 「複数」、つまりコマンドラインに複数現れたらそれを全て考慮されるかがあります。
17281 単数オプションでは、@var{var}は上で決定される値がそのまま束縛されます。
17282 複数オプションでは、@var{var}は上で決定される値のリストが束縛されます。
17283 @c COMMON
17284
17285 @c EN
17286 We'll explain the details of @var{option-spec} later.
17287 @c JP
17288 @var{option-spec}の詳細については後で説明します。
17289 @c COMMON
17290
17291 @c EN
17292 As a special case, @var{var} can be @code{#f}, in which case
17293 the value is ignored. It is only useful for side effects in
17294 @var{callback}.
17295 @c JP
17296 特別な場合として、@var{var}を@code{#f}とすることもできます。
17297 その場合、値は無視されます。
17298 @var{callback}での副作用だけに関心がある場合に使えるでしょう。
17299 @c COMMON
17300
17301 @c EN
17302 If the corresponding option is not given in @var{args},
17303 @var{var} is bound to @var{default} if it is given,
17304 @code{#f} otherwise.
17305 @c JP
17306 対応するオプションが@var{args}に与えられなかった場合、
17307 @var{var}は@var{default}が与えられていればその値に、
17308 そうでなければ@code{#f}に束縛されます。
17309 @c COMMON
17310
17311 @c EN
17312 The last @var{bind-spec} may be the form 3 or 4. in which case
17313 the clause is selected when no other @var{option-spec} matches
17314 a given command-line option.
17315 In the form 3, @var{fallback} will be called with three arguments;
17316 the given option, a list of remaining command-line arguments,
17317 and a continuation procedure. The @var{fallback}
17318 is supposed to handle the given option, and it may call the
17319 continuation procedure with the remaining arguments to continue
17320 processing, or it may return a list of arguments which will
17321 be treated as non-optional command-line arguments.
17322 The form 4 is a shorthand notion of
17323 @code{(else => (lambda @var{formals} @var{body} ...))}.
17324 @c JP
17325 最後の@var{bind-spec}には3か4の形式も許されます。
17326 この節は、どの@var{option-spec}にもマッチしないコマンドラインオプションが
17327 与えられた場合に選択されます。
17328 3番目の形式では、@var{fallback}が3つの引数を伴って呼び出されます。
17329 引数は、マッチしなかったコマンドラインオプション、
17330 残りのコマンドライン引数、そして引数処理に戻るための継続手続きです。
17331 @var{fallback}は与えられたコマンドラインオプションを処理した後、
17332 オプション処理を続けたければ継続手続きに残りのコマンドライン引数を渡し、
17333 オプション処理を打ちきりたければ残りのコマンドライン引数を戻り値として
17334 返します。返された値は通常の(オプションでない)コマンドライン引数として扱われます。
17335 4番目の形式は@code{(else => (lambda @var{formals} @var{body} ...))}の簡略表記です。
17336 @c COMMON
17337
17338 @c EN
17339 The @var{bind-spec} list can be an improper list, whose last cdr is
17340 a symbol. In which case, a list of the rest of the command-line arguments
17341 is bound to the variable named by the symbol.
17342 @c JP
17343 束縛リストは、最後のcdrにシンボルを持つ不完全なリストであっても良く、
17344 その場合はコマンドライン引数の残りのリストがその変数にと束縛されます。
17345 @c COMMON
17346
17347 @c EN
17348 Note that the @var{default}, @var{callback}, and forms in @code{else}
17349 clause is evaluated outside of the scope of binding of @var{var}s
17350 (as the name @code{let-args} implies).
17351 @c JP
17352 @var{default}、@var{callback}、@code{else}節のフォーム等は
17353 @var{var}の束縛の外側のスコープで評価されることに注意して下さい。
17354 @c COMMON
17355
17356 @c EN
17357 Unlike typical @code{getopt} or @code{getopt_long} implementation in C,
17358 @code{let-args} does not permute the given command-line arguments.
17359 It stops parsing when it encounters a non-option argument (argument without
17360 starting with a minus sign).
17361 @c JP
17362 C における典型的な @code{getopt} や @code{getopt_long} の実装とは異なり、
17363 @code{let-args} は与えられたコマンドライン引数の順番を変えません。
17364 オプションでない引数(ハイフンで始まらない引数)に遭遇した時点でパースを
17365 中止します。
17366 @c COMMON
17367
17368 @c EN
17369 If the parser encounters an argument with only two minus signs `@code{--}',
17370 it stops argument parsing and treats the rest of arguments as non-option
17371 command-line arguments.
17372 @c JP
17373 パーサは、ハイフン2つのみの引数 `@code{--}' に遭遇すると、引数パーシングを
17374 中止して`@code{--}' の後の引数リストをオプションでない引数リストとして扱います。
17375 @c COMMON
17376
17377 @c EN
17378 After all the bindings is done, @var{body} @dots{} are evaluated.
17379 @var{Body} may began with internal define forms.
17380 @c JP
17381 全ての束縛が終了した後、@var{body} @dots{} が評価されます。
17382 @var{body}は内部defineで始まっていても構いません。
17383 @c COMMON
17384
17385 @c EN
17386 Internally, @code{let-args} creates an ``option-parser'' object,
17387 which is available within the dynamic extent of @code{let-args}
17388 from the parameter @code{current-option-parser}. See below.
17389 @c JP
17390 内部的に、@code{let-args}は「オプションパーザ」オブジェクトを作り、
17391 それは@code{let-args}の動的エクステント中、@code{current-option-parser}パラメータで
17392 取り出すことができます。下記参照。
17393 @c COMMON
17394
17395 @end defmac
17396
17397 @deffn {Parameter} current-option-parser
17398 @c MOD gauche.parseopt
17399 @c EN
17400 In the dynamic extent of @code{let-args}, this parameter
17401 holds an option parser object that parses the command line
17402 and stores the options' apparance and argument values.
17403 It should be treated as an opaque object. Its only public use
17404 is to pass to @code{option-parser-help-string} to get a formatted
17405 option help strings, which is done by default.
17406 @c JP
17407 @code{let-args}の動的エクステント中、
17408 このパラメータは「オプションパーザ」オブジェクトに束縛されます。
17409 オプションパーザはコマンドライン引数をパーズして、各オプションの出現および
17410 引数の値を保持します。
17411 このオブジェクトは不透明なオブジェクトとして扱われなければならず、
17412 唯一の用途は@code{option-parser-help-string}に渡して
17413 フォーマットされたオプションのヘルプ文字列を得ることです。
17414 @c COMMON
17415 @end deffn
17416
17417 @defun option-parser-help-string :key option-parser omit-options-without-help @
17418 option-indent description-indent width
17419 @c MOD gauche.parseopt
17420 @c EN
17421 Returns a formatted help string of command-line option of an option parser
17422 object @var{option-parser}. Its default value is the value
17423 of parameter @code{current-option-parser}, so if you invoke this
17424 procedure in the dynamic extent of @code{let-args} to get
17425 its help string, you don't need to pass the @var{option-parser}
17426 argument explicitly.
17427
17428 With the example shown in the @code{let-args} above,
17429 calling this procedure produces the following string:
17430 @c JP
17431 @var{option-parser}で指定されるオプションパーザの、コマンドラインオプション
17432 ヘルプ文字列を返します。@var{option-parser}のデフォルト値は
17433 パラメータ@code{current-option-parser}の値なので、
17434 @code{let-args}で作られるオプションパーザのヘルプを
17435 @code{let-args}の動的エクステント内で表示する場合は
17436 @var{option-parser}引数を明示的に与える必要はありません。
17437
17438 上の@code{let-args}にあるコマンドラインオプション仕様の例では、
17439 以下のようなヘルプ文字列が生成されます。
17440 @c COMMON
17441
17442 @example
17443 -v, --verbose
17444 Run verbosely.
17445 -o, --outfile FILE
17446 Write output to FILE.
17447 -d, --debug-level LEVEL
17448 Set debug level.
17449 -h, --help Show help message and exit.
17450 @end example
17451
17452 @c EN
17453 If the name of an option argument is given as surrounded by
17454 curly braces in the option spec,
17455 e.g. @code{"o|outfile=s@{FILE@}"}, the name is used
17456 in the help message (see ``Option spec'' below).
17457 Otherwise, the argument type character is
17458 used. In the help message, it is recommended to enclose the
17459 reference to the option argument with curly braces. Those braces
17460 are simply removed in the help string. However, in future, it
17461 may be rendered differently if the output device has richer
17462 presentation.
17463 @c JP
17464 オプション指定の中でオプション引数の名前がカーリーブレースで囲んで指定されて
17465 いた場合は、その名前がヘルプ文字列に使われます
17466 (例: @code{"o|outfile=s@{FILE@}"})。詳しくは下の「オプション指定」を
17467 見てください。ヘルプメッセージ中でオプション引数の名前を参照する時にも、
17468 その名前をカーリーブレースで囲んでおくことを推奨します。
17469 今は単にそのカーリーブレースは除かれるだけですが、
17470 将来、よりリッチな表現を許すデバイス向けにヘルプ文字列を生成する機会があれば、
17471 別の表示が可能になるかもしれません。
17472 @c COMMON
17473
17474 @c EN
17475 If the @var{omit-options-without-help} keyword argument is true,
17476 options without help string isn't included in the help string.
17477 It is useful if you have an experimental options you don't want
17478 to advertise for users. The default is @code{#f}, which shows
17479 @code{(No help available)} for such options.
17480 @c JP
17481 もし@var{omit-options-without-help}引数に真の値が与えられたら、
17482 ヘルプ文字列が指定されていないオプションは返り値から除外されます。
17483 実験的にオプションを追加して、でもユーザには広報したくない場合に便利です。
17484 デフォルトは@code{#f}で、その場合、ヘルプ文字列が指定されていないオプションには
17485 @code{(No help available)}と表示されます。
17486 @c COMMON
17487
17488 @c EN
17489 The arguments @var{option-indent}, @var{description-indent}, and
17490 @var{width} controls the formatting. Option names are
17491 indented with @var{option-indent} characters, and their descriptions
17492 are indented with @var{description-indent}. The overall width
17493 of text is governed by @var{width}. The help string is formatted
17494 with @code{text.fill} (@pxref{Text filling}).
17495 @c JP
17496 引数@var{option-indent}、@var{description-indent}、@var{width}は
17497 ヘルプ文字列のフォーマットを制御します。各オプション名は
17498 @var{option-indent}文字だけ、その記述は
17499 @var{description-indent}文字だけインデントされ、
17500 @var{width}が全体の幅を指定します。
17501 ヘルプ文字列は@code{text.fill}の機能によってフォーマットされます
17502 (@ref{Text filling}参照)。
17503 @c COMMON
17504 @end defun
17505
17506 @c EN
17507 @subheading Option spec
17508 @c JP
17509 @subheading オプション指定
17510 @c COMMON
17511
17512 @c EN
17513 @var{option-spec} is a string that specifies the name of the option and
17514 how the option takes the arguments. An alphanumeric characters, underscore,
17515 plus and minus sign is allowed for option's names, except that
17516 minus sign can't be the first character, i.e. the valid option name
17517 matches a regexp @code{#/[\w+][-\w+]*/}.
17518 @c JP
17519 @var{option-spec} は、オプションの名前とそのオプションがどのように引数を取るか
17520 を指定する文字列です。オプションの名前には、アルファベット文字、数字、
17521 アンダースコア、プラス記号、ハイフンが許されますが、ハイフンは最初の文字としては
17522 使えません。すなわち、有効なオプションの名前は、@code{#/[\w+][-\w+]*/} という
17523 正規表現にマッチするものです。
17524 @c COMMON
17525
17526 @c EN
17527 If the option takes argument(s), it can be specified by attaching
17528 equal character and a character (or characters) that represents
17529 the type of the argument(s) after the name. The option
17530 can take more than one arguments.
17531 The following characters are recognized as a type specifier of
17532 the option's argument.
17533 @c JP
17534 オプションが引数を取る場合、名前の後ろに等号文字と引数の型を表現する文字を
17535 付けることで指定できます。オプションは一つ以上の引数を取ることができます。
17536 以下の文字がオプションの引数の型を表現するものとして認識されます。
17537 @c COMMON
17538
17539 @table @code
17540 @item s
17541 @c EN
17542 String.
17543 @c JP
17544 文字列。
17545 @c COMMON
17546 @item n
17547 @c EN
17548 Number.
17549 @c JP
17550 数値。
17551 @c COMMON
17552 @item f
17553 @c EN
17554 Real number (coerced to flonum).
17555 @c JP
17556 実数 (flonumに変換されます)。
17557 @c COMMON
17558 @item i
17559 @c EN
17560 Exact integer.
17561 @c JP
17562 正確な整数。
17563 @c COMMON
17564 @item e
17565 @c EN
17566 S-expression.
17567 @c JP
17568 S式。
17569 @c COMMON
17570 @item y
17571 @c EN
17572 Symbol (argument is converted by @code{string->symbol}).
17573 @c JP
17574 シンボル (引数は@code{string->symbol}により変換される)。
17575 @c COMMON
17576 @end table
17577
17578 @c EN
17579 Let's see some examples of @var{option-spec}:
17580 @c JP
17581 @var{option-spec}の例を見てみましょう:
17582 @c COMMON
17583
17584 @table @code
17585 @item "@var{name}"
17586 @c EN
17587 Specifies option @var{name}, that doesn't take any argument.
17588 @c JP
17589 引数を取らないオプションの @var{name} を指定します。
17590 @c COMMON
17591
17592 @item "@var{name}=s"
17593 @c EN
17594 Option @var{name} takes one argument, and it is passed as a string.
17595 @c JP
17596 オプション @var{name} は引数を一つ取り、それは文字列として渡されます。
17597 @c COMMON
17598
17599 @item "@var{name}=i"
17600 @c EN
17601 Option @var{name} takes one argument, and it is passed as an exact integer.
17602 @c JP
17603 オプション @var{name} は引数を一つ取り、それは正確整数として渡されます。
17604 @c COMMON
17605
17606 @item "@var{name}=ss"
17607 @c EN
17608 Option @var{name} takes two arguments, both string.
17609 @c JP
17610 オプション @var{name} は引数を二つ取り、両方とも文字列です。
17611 @c COMMON
17612
17613 @item "@var{name}=iii"
17614 @c EN
17615 Option @var{name} takes three integer arguments.
17616 @c JP
17617 オプション @var{name} は3つの整数の引数を取ります。
17618 @c COMMON
17619
17620 @item "@var{name}=sf"
17621 @c EN
17622 Option @var{name} takes two arguments, the first is a string and the
17623 second is a number.
17624 @c JP
17625 オプション @var{name} は2つの引数を取ります。一つ目は文字列で、
17626 二つ目は数値です。
17627 @c COMMON
17628 @end table
17629
17630 @c EN
17631 Each option argument letter can be follwed by an option argument
17632 name, enclosed with curly braces. Those names don't affect command-line
17633 argument parsing, but are used to generate help string
17634 (see @code{option-parser-help-string} above).
17635 @c JP
17636 各オプション引数文字の後に、カーリーブレースで囲んだオプション引数名を書いておくことが
17637 できます。オプション引数名はコマンドライン引数のパーズには影響を与えませんが、
17638 ヘルプ文字列を生成する時に使われます
17639 (上の@code{option-parser-help-string}を参照)。
17640 @c COMMON
17641
17642 @example
17643 --file=s@{FILENAME@}
17644 --origin=f@{XCOORD@}f@{YCOORD@}f@{ZCOORD@}
17645 @end example
17646
17647 @c EN
17648 If the option has alternative names, they can be concatenated by "|".
17649 For example, an option spec @code{"h|help"} will match both
17650 "h" and "help".
17651 @c JP
17652 オプションにいくつかの別名がある場合は、"|" でつなげて書いておくことができます。
17653 例えば@code{"h|help"}という@var{option-spec}は
17654 "h"にも"help"にもマッチします。
17655 @c COMMON
17656
17657 @c EN
17658 If an asterisk @code{*} is followed by the name(s) of the option,
17659 the option is plural, that is, it can be specified multiple times and
17660 you can get the values as a list. For example, @code{I|incdir*=s} means
17661 @code{-I} and @code{-incdir} option can appear more than once in
17662 the command line, and its final value would be a list of string argument
17663 given to all of the options.
17664 @c JP
17665 オプションの名前の後に@code{*}を置くと、オプションが複数であること、
17666 つまり複数回指定できて、その値のリストを受け取れることを示します。
17667 例えば@code{I|incdir*=s}という指定は、
17668 @code{-I}や@code{-incdir}オプションがコマンドラインで複数回指定できて、
17669 その最終的な値は与えられた文字列引数のリストになります。
17670 @c COMMON
17671
17672 @c EN
17673 In the command line, the option may appear with preceding
17674 single or double minus signs. The option's argument may be combined
17675 by the option itself with an equal sign. For example, all the following
17676 command line arguments match an option spec @code{"prefix=s"}.
17677 @c JP
17678 コマンドラインでは、オプションは一つか二つのハイフンに続いて与えられます。
17679 オプションの引数は、オプションそのものと等号記号でつながれていても構いません。
17680 例えば、以下の全てのコマンドライン引数は、オプションの仕様、@code{"prefix=s"} に
17681 マッチします。
17682 @c COMMON
17683 @example
17684 -prefix /home/shiro
17685 -prefix=/home/shiro
17686 --prefix /home/shiro
17687 --prefix=/home/shiro
17688 @end example
17689
17690 @c EN
17691 If the option consists of a single letter and takes arguments,
17692 the first argument can follow immediately after the option letter
17693 without a whitespace. If you have an option spec @code{"I=s"},
17694 all the following command line arguments are recognized:
17695 @c JP
17696 オプションが一文字からなり、引数を取る場合、
17697 最初の引数はスペースなしでオプション文字の直後に置かれても構いません。
17698 例えばオプション仕様@code{"I=s"}は、以下のコマンドライン引数のいずれも認識します。
17699 @c COMMON
17700 @example
17701 -I/foo
17702 -I /foo
17703 -I=/foo
17704 --I/foo
17705 --I /foo
17706 --I=/foo
17707 @end example
17708
17709 @c EN
17710 If there's an ambiguity between a long option and a single-letter
17711 option plus an argument, the long option takes precedence.
17712 If you have an option spec @code{"long"} and @code{"l=s"}, command
17713 line arguments @code{-long} is recognized as the former,
17714 not @code{-l} option with arguments @code{ong}.
17715 @c JP
17716 長いオプション名と、一文字のオプション+引数、の間で曖昧性が生じた場合は、
17717 長いオプションの方が優先されます。例えば@code{"long"}および@code{"l=s"}という
17718 オプション仕様があった場合、コマンドライン引数@code{-long}は
17719 @code{-l}オプション+引数@code{ong}@emph{ではなく}、ひとつのオプション@code{-long}と
17720 解釈されます。
17721 @c COMMON
17722
17723 @c EN
17724 @subheading Error handling
17725 @c JP
17726 @subheading エラー処理
17727 @c COMMON
17728
17729 @deftp {Condition Type} <parseopt-error>
17730 @c MOD gauche.parseopt
17731 @c EN
17732 When @code{let-args} encounters an argument that cannot be
17733 processed as specified by option specs, an error of condition type
17734 @code{<parseopt-error>} is raised. The cases include
17735 when a mandatory option argument is missing, or when
17736 an option argument has a wrong type.
17737 @c JP
17738 @code{let-args}が、@code{option-spec}に従わない引数を見つけた場合は、
17739 コンディションタイプ@code{<parseopt-error>}のエラーを投げます。
17740 例えば、必須のオプション引数が与えられていなかったり、異なる型であった
17741 場合などです。
17742 @c COMMON
17743
17744 @example
17745 (let-args '("-a" "foo") ((a "a=i")) ; option a requires integer
17746 (list a))
17747 @result{} @r{parseopt-error}
17748 @end example
17749
17750 @c EN
17751 Note that this condition is about parsing the given @var{args}.
17752 If an invalid @var{option-spec} is given,
17753 an ordinary error is thrown.
17754 @c JP
17755 このコンディションはあくまで@var{args}に渡された引数をパーズする際に発生するものです。
17756 @var{option-spec}が不正であった場合は通常のエラーが投げられます。
17757 @c COMMON
17758 @end deftp
17759
17760 @c EN
17761 @subheading Examples
17762 @c JP
17763 @subheading 例
17764 @c COMMON
17765
17766 @c EN
17767 This example is taken from @code{gauche-install} script.
17768 The @var{mode} option takes numbers in octal, so it
17769 uses the callback procedure to convert it.
17770 See also the @code{else} clause how to handle unrecognized option.
17771 @c JP
17772 これは@code{gauche-install}スクリプトから取った例です。
17773 @var{mode}オプションは8進数のオプション引数を取るので、コールバック
17774 手続きを使って変換しています。また、認識できないオプションをelse節で
17775 処理しています。
17776 @c COMMON
17777
17778 @example
17779 (define (main args)
17780 (let-args (cdr args)
17781 ([mkdir "d|directory"
17782 ? "Creates directories listed in the arguments. \
17783 (3rd format only)."]
17784 [mode "m|mode=s@{MODE@}" #o755 => (cut string->number <> 8)
17785 ? "Change mode of the installed file."]
17786 [owner "o|owner=s@{OWNER@}"
17787 ? "Change owner of the installed file(s)."]
17788 [group "g|group=s@{GROUP@}"
17789 ? "Change group of the installed file(s)."]
17790 [csfx "C|canonical-suffix"
17791 ? "If installed file has a suffix *.sci, replace it for \
17792 *.scm. This is Gauche specific convention."]
17793 [srcdir "S|srcdir=s@{DIR@}"
17794 ? "Look for files within @{DIR@}; useful if VPATH is used."]
17795 [target "T|target=s@{DIR@}"
17796 ? "Installs files to the @{DIR@}, creating paths if needed. \
17797 Partial path of files are preserved. (4th format only)."]
17798 [utarget "U|uninstall=s@{DIR@}"
17799 ? "Reverse of -T, e.g. removes files from its destination."]
17800 [shebang "shebang=s@{PATH@}"
17801 ? "Adds #!@{PATH@} before the file contents. \
17802 Useful to install scripts."]
17803 [verb "v|verbose" ? "Work verbosely"]
17804 [dry "n|dry-run" ? "Just prints what actions to be done."]
17805 [sprefix "p|strip-prefix=s@{PREFIX@}"
17806 ? "Strip prefix dirs from FILEs before \
17807 installation. (4th/5th format only)."]
17808 [#f "h|help" => usage ? "Show this help message."]
17809 [#f "c" ? "This option is ignored. Recognized for the \
17810 compatibility."]
17811 [else (opt . _) (print "Unknown option : " opt) (usage)]
17812 . args)
17813 ...)
17814 )
17815 @end example
17816
17817 @c EN
17818 The next example is a small test program to show the usage of
17819 @code{else} clause. It gathers all options into the variable @var{r},
17820 except that when it sees @code{-c} it stops argument processing and
17821 binds the rest of the arguments to @var{restargs}.
17822 @c JP
17823 次の例は@code{else}節の使い方を示す小さなプログラムです。
17824 コマンドラインオプションを変数@var{r}に集めてゆきますが、
17825 オプション @code{-c} に出会うとオプション処理を中止して残りを
17826 @var{restargs}へと渡します。
17827 @c COMMON
17828
17829 @example
17830 (use gauche.parseopt)
17831
17832 (define (main args)
17833 (let1 r '()
17834 (let-args (cdr args)
17835 ((else (opt rest cont)
17836 (cond [(equal? opt "c") rest]
17837 [else (push! r opt) (cont rest)]))
17838 . restargs)
17839 (print "options: " r)
17840 (print "restargs: " restargs)
17841 0)))
17842 @end example
17843
17844 @c EN
17845 Sample session of the above script (suppose it is saved as @file{example}).
17846 @c JP
17847 上のスクリプトの実行例です (@file{example}というファイル名で保存されていると
17848 します)。
17849 @c COMMON
17850
17851 @example
17852 $ ./example -a -b -c -d -e foo
17853 options: (a b)
17854 restargs: (-d -e foo)
17855 $ ./example -a -b -d -e foo
17856 options: (a b d e)
17857 restargs: (foo)
17858 @end example
17859
17860 @c EN
17861 @subheading Low-level API
17862 @c JP
17863 @subheading 低レベルAPI
17864 @c COMMON
17865
17866 @c EN
17867 Internally, @code{let-args} creates an option parser object
17868 and option spec objects which does the actual parsing work.
17869 Those classes are internal, but a few procedures are exported
17870 so that you can build your own parser.
17871 @c JP
17872 内部的に、@code{let-args}はオプションパーザオブジェクトと
17873 オプション指定オブジェクトを作ってコマンドライン引数をパーズします。
17874 これらのクラスの詳細は公開していませんが、それらを扱うためのいくつかの手続きが
17875 提供されています。独自のパーザを作りたい時に便利です。
17876 @c COMMON
17877
17878 @defun make-option-spec option-spec :key default callback help-string
17879 @c MOD gauche.parseopt
17880 @c EN
17881 Parse a string @var{option-spec} (see ``Option spec'' above)
17882 and returns an option spec object, which should
17883 be treated as opaque.
17884
17885 The keyword arguments corresponds to the values in the @var{bind-spec}
17886 of @code{let-args} form.
17887 @c JP
17888 @var{option-spec}にあるオプション指定文字列(上の「オプション指定」の項参照)を解析し、
17889 オプション指定オブジェクトを作って返します。
17890 オプション指定オブジェクトは不透明なオブジェクトとして扱ってください。
17891
17892 キーワード引数は@code{let-args}形式の@var{bind-spec}で指定するものに相当します。
17893 @c COMMON
17894 @end defun
17895
17896 @defun build-option-parser specs :key fallback
17897 @c MOD gauche.parseopt
17898 @c EN
17899 Given a list of option spec objects creates and returns
17900 an option parser object. Each option spec object can be created
17901 with @code{make-option-spec}.
17902
17903 The returned option parser object can be passed to
17904 @code{run-option-parser} to handle the actual command-line argument list.
17905
17906 The optional @var{fallback} argument must be a procedure if provided.
17907 See @code{run-option-parser}, for how and when it is called.
17908 @c JP
17909 オプション指定オブジェクトのリストを取り、オプションパーザオブジェクトを作って返します。
17910 オプション指定オブジェクトは@code{make-option-spec}で作ることができます。
17911
17912 作られたオプションパーザオブジェクトは@code{run-option-parser}に渡して、
17913 コマンドライン引数を処理するのに使えます。
17914
17915 省略可能な@var{fallback}引数は、渡す場合は手続きでなければなりません。
17916 それがいつどのように呼ばれるかは@code{run-option-parser}を参照してください。
17917 @c COMMON
17918 @end defun
17919
17920 @defun run-option-parser option-parser args :optionap fallback
17921 @c MOD gauche.parseopt
17922 @c EN
17923 Handle command-line argument list @var{args}, which must be a
17924 list of string, with an option parser @var{option-parser}.
17925 @c JP
17926 文字列のリストで表されたコマンドライン引数のリスト@var{var}を、
17927 オプションパーザオブジェクト@var{option-parser}によって処理します。
17928 @c COMMON
17929
17930 @c EN
17931 It handles the command-line options in @var{args} if any, and set up
17932 each option's value in the option spec, then returns the rest of
17933 the argument list.
17934 @c JP
17935 @var{args}の中にコマンドラインオプションが含まれていればそれを処理し、
17936 その値を該当するオプション指定オブジェクトに保存します。
17937 そしてオプションとその引数を取り除いた残りのコマンドライン引数リストを返します。
17938 @c COMMON
17939
17940 @c EN
17941 It looks for elements in @var{args} from left to right. If it encounters
17942 a string beginning with @code{-}, it thinks the string is a command-line
17943 option and search option specs in @var{option-parser}.
17944 Note that a string @code{--} marks the end of the option list; it is
17945 consumed, and the remaining arguments are immediately returned.
17946 @c JP
17947 この手続きは、@var{args}の要素を順に見てゆきます。
17948 引数が@code{-}で始まっていたら、それをコマンドラインオプションとみなし、
17949 @var{option-parser}の持つオプション指定オブジェクトに該当するものを探します。
17950 ただし、@code{--}だけの引数は特別で、コマンドラインオプションの終了とみなされ、
17951 それ以降の引数リストが直ちに返されます。
17952 @c COMMON
17953
17954 @c EN
17955 If there's a matching option spec, the option itself and the option's
17956 argument(s) (if the option takes ones) are taken out from @var{args}.
17957 Then, the option's value is determined as follows.
17958 @c JP
17959 マッチするオプション指定があれば、オプションおよび(そのオプションが引数を取るなら)
17960 オプション引数が@var{args}から除かれ、オプションの値が次のとおり決められます。
17961 @c COMMON
17962
17963 @itemize @bullet
17964 @item
17965 @c EN
17966 If the option spec has a handler, the handler is called with the option's
17967 argument(s), and its return value becomes the option's value.
17968 @c JP
17969 オプション指定がハンドラを持っている場合は、オプション引数を引数にしてハンドラが呼ばれ、
17970 その戻り値がオプションの値となります。
17971 @c COMMON
17972 @item
17973 @c EN
17974 Otherwise, if the option does not take an argument, @code{#t}.
17975 @c JP
17976 そうでなく、オプションが引数を取らない場合は、@code{#t}。
17977 @c COMMON
17978 @item
17979 @c EN
17980 Otherwise, if the option takes a single argument, the given argument itself.
17981 @c JP
17982 そうでなく、オプションが一つだけ引数を取る場合は、その与えられた引数。
17983 @c COMMON
17984 @item
17985 @c EN
17986 Otherwise, the list of arguments.
17987 @c JP
17988 そうでなければ、与えられた引数のリスト。
17989 @c COMMON
17990 @end itemize
17991
17992 @c EN
17993 Furthermore, the option has plural flag, the final result of
17994 the option's value is a list of all option values.
17995 Otherwise, the option's value
17996 is overwritten as the last value of the option.
17997 @c JP
17998 さらに、オプションが複数回指定可能な場合は、オプションの値がリストにまとめられます。
17999 複数回指定不可の場合、最後の値が最終的なオプションの値となります。
18000 @c COMMON
18001
18002 @c EN
18003 If the given option-like string does not match any of the option specs,
18004 a fallback procedure is called. A fallback procedure can be given
18005 by @var{fallback} optional argument, or the fallback argument
18006 given to @code{build-option-parser}. The fallback procedure is
18007 called with three arguments: the unrecognized option string (without
18008 preceding hyphen(s)), the argument list following it, and
18009 a closure that takes an argument list to continue the parsing.
18010 @c JP
18011 オプションに見えるコマンドライン引数がオプション指定のいずれにもマッチしない場合、
18012 fallback手続きが呼ばれます。fallback手続きは、省略可能な@var{fallback}引数に
18013 与えられていればそれを、そうでなければ@code{build-option-parser}に与えられた
18014 @var{fallback}が呼ばれます。fallback手続きは3つの引数を取ります:
18015 認識されなかったオプション引数 (先行するハイフンを除いたもの)、
18016 その後に続く引数リスト、そして、処理を続けるための継続手続きです。
18017 @c COMMON
18018
18019 @c EN
18020 The fallback procedure may process the unknown option as it pleases.
18021 Whatever the fallback procedure returns becomes the return value
18022 of @code{run-option-parser}. If the fallback procedure wants to continue
18023 processing the rest of the arugment list, tail call the third argument.
18024 @c JP
18025 fallback手続きは、好きなように未知のオプションを処理できます。
18026 fallback手続きが返した値がそのまま@code{run-option-parser}の返り値となります。
18027 もしfallback手続きが残りの引数リストに対してコマンドライン引数処理を継続したい場合は、
18028 残りの引数リストを引数として継続手続きを末尾呼び出ししてください。
18029 @c COMMON
18030
18031 @c EN
18032 If no fallback argument is given to @code{run-option-parser} nor
18033 @code{build-option-parser}, the default fallback procedure is called,
18034 which throws ``unrecognized option'' @code{<parseopt-error>} error.
18035 @c JP
18036 @code{run-option-parser}にも@code{build-option-parser}にもfallback手続きが
18037 与えられなかった場合はデフォルトの手続きが呼ばれます。それは
18038 ``unrecognized option''をメッセージとする@code{<parseopt-error>}エラーを
18039 投げます。
18040 @c COMMON
18041 @end defun
18042
18043 @defun get-option-spec option-parser option-name
18044 @c MOD gauche.parseopt
18045 @c EN
18046 Returns an option spec object that has the option name @var{option-name}
18047 from @var{option-parser}. After @code{run-option-parser},
18048 you need to get an option spec to retrieve the option's value.
18049
18050 If no option spec matches @var{option-name}, @code{#f} is returned.
18051 @c JP
18052 @var{option-parser}の持つオプション指定オブジェクトから、@var{option-name}
18053 にマッチするものを返します。@code{run-option-parser}を実行した後、
18054 オプションの値を取り出すためにはオプション指定オブジェクトを得る必要があります。
18055
18056 @var{option-name}にマッチするオプション指定が無い場合は@code{#f}が返されます。
18057 @c COMMON
18058 @end defun
18059
18060 @defun option-spec-appeared? optspec
18061 @c MOD gauche.parseopt
18062 @c EN
18063 Returns true if an option spec @var{optspec} has appeared
18064 in the command-line argument list. This must be called after
18065 @code{run-option-parser}.
18066 @c JP
18067 オプション指定@var{optspec}で表されるオプションがコマンドライン引数に現れたかどうかを
18068 真偽値で返します。これは@code{run-option-parser}呼び出しの後で呼ばなければなりません。
18069 @c COMMON
18070 @end defun
18071
18072 @defun option-spec-value optspec
18073 @c MOD gauche.parseopt
18074 @c EN
18075 Returns the option's value of an option spec @var{optspec}.
18076 This must be called after @code{run-option-parser}.
18077 @c JP
18078 オプション指定@var{optspec}の値を返します。
18079 これは@code{run-option-parser}呼び出しの後で呼ばなければなりません。
18080 @c COMMON
18081
18082 @c EN
18083 The option's value is determined as follows.
18084 @c JP
18085 オプションの値は次のとおり決定されます。
18086 @c COMMON
18087
18088 @itemize @bullet
18089 @item
18090 @c EN
18091 If the option didn't appear in the command-line argument list,
18092 the ``default'' value given to the @code{make-option-spec}.
18093 @c JP
18094 オプションがコマンドライン引数リストに現れなければ、
18095 @code{make-option-spec}に与えたデフォルト値。
18096 @c COMMON
18097 @item
18098 @c EN
18099 If the option did appear in the comamnd-line argument list,
18100 the value of each occurrence is determined as follows:
18101 @c JP
18102 オプションがコマンドライン引数リストに現れた場合は、
18103 次のいずれか:
18104 @c COMMON
18105 @itemize @minus
18106 @item
18107 @c EN
18108 If the option doesn't take an argument, @code{#t}.
18109 @c JP
18110 オプションが引数を取らない場合は@code{#t}。
18111 @c COMMON
18112 @item
18113 @c EN
18114 If the option takes one argument, the given argument.
18115 @c JP
18116 オプションが引数をひとつ取る場合は、与えられた引数。
18117 @c COMMON
18118 @item
18119 @c EN
18120 If the option takes multiple arguments, the list of the given arguments.
18121 @c JP
18122 オプションが複数の引数を取る場合は、与えられた引数のリスト。
18123 @c COMMON
18124 @end itemize
18125 @c EN
18126 Then, if the option is plural, all the value from occurrences
18127 are gathered to a list in the order of appearance;
18128 otherwise, the value form the last occurrence is kept.
18129 @c JP
18130 さらに、オプションが複数回指定可能な場合は、
18131 全てのオプションの値がコマンドラインに出現した順でリストにまとめられます。
18132 そうでない場合は、最後のオプションの値が保持されます。
18133 @c COMMON
18134 @end itemize
18135 @end defun
18136
18137 @c EN
18138 @subheading Deprecated API
18139 @c JP
18140 @subheading 非推奨API
18141 @c COMMON
18142
18143 @c EN
18144 The following macros are supersede by @code{let-args}.
18145 New code should not use them.
18146 @c JP
18147 以下のマクロは@code{let-args}に置き換えられました。
18148 新規コードでは使わないでください。
18149 @c COMMON
18150
18151 @defmac parse-options args (option-clause @dots{})
18152 @c MOD gauche.parseopt
18153 @c DEPRECATED
18154 @c EN
18155 @var{args} is an expression that contains a list of command-line arguments.
18156 This macro scans the command-line options (an argument that begins with
18157 `@code{-}') and processes it as specified in @var{option-clause}s, then
18158 returns the remaining arguments.
18159 @c JP
18160 @var{args} は、コマンドライン引数のリストを含む式です。
18161 このマクロは、コマンドラインオプション(`@code{-}' で始まる引数)をスキャンし、
18162 @var{option-clause} の指定に従って処理し、残りの引数を返します。
18163 @c COMMON
18164
18165 @c EN
18166 Each @var{option-clause} is consisted by a pair of @var{option-spec}
18167 and its action.
18168
18169 If a given command-line option matches one of @var{option-spec}, then
18170 the associated action is evaluated. An action can be one of the
18171 following forms.
18172 @c JP
18173 それぞれの @var{option-clause} は、@var{option-spec} とそのアクションのペアで
18174 構成されます。
18175
18176 与えられたコマンドラインオプションが @var{option-spec} の一つにマッチすると、
18177 関連付けられたアクションが評価されます。アクションは以下のフォームの一つです。
18178 @c COMMON
18179
18180 @table @code
18181 @item @var{bind-spec} @var{body} @dots{}
18182 @c EN
18183 @var{bind-spec} is a proper or dotted list of variables like lambda-list.
18184 The option's arguments are bound to @var{bind-spec}, then
18185 then @var{body} @dots{} is evaluated.
18186 @c JP
18187 @var{bind-spec} は、ラムダリストのような変数の正しいリストかドット対リストです。
18188 オプションの引数は @var{bind-spec} に束縛され、@var{body} @dots{} が評価されます。
18189 @c COMMON
18190
18191 @item => @var{proc}
18192 @c EN
18193 If a command-line option matches @var{option-spec}, calls a procedure
18194 @var{proc} with a list of the option's arguments.
18195 @c JP
18196 コマンドラインオプションが @var{option-spec} にマッチすると、
18197 @var{proc} がオプションの引数のリストとともに呼び出されます。
18198 @c COMMON
18199 @end table
18200
18201 @c EN
18202 If a symbol @code{else} is at the position of @var{option-spec},
18203 the clause is selected when no other option clause matches a given
18204 command-line option. Three ``arguments'' are associated to
18205 the clause; the unmatched option, the rest of arguments, and
18206 a procedure that represents the option parser.
18207 @c JP
18208 シンボル @code{else} が @var{option-spec} の位置にある場合、その節は、
18209 与えられたコマンドラインオプションにマッチする他のオプション節が
18210 ない場合に選択されます。その節には3つの``引数''が関連付けられます。
18211 それらは、マッチしなかったオプション、引数の残り、オプションパーサを
18212 表す手続きです。
18213 @c COMMON
18214
18215 @end defmac
18216
18217 @defmac make-option-parser (option-clause @dots{})
18218 @c MOD gauche.parseopt
18219 @c DEPRECATED
18220 @c EN
18221 This is a lower-level interface. @var{option-clause}s are the
18222 same as @code{parse-options}. This macro returns a procedure
18223 that can be used later to parse the command line options.
18224
18225 The returned procedure takes one required argument and one
18226 optional argument. The required argument is a list of strings,
18227 for given command-line arguments. The optional argument may
18228 be a procedure that takes more than three arguments, and if given,
18229 the procedure is used as if it is the body of @code{else} option clause.
18230 @c JP
18231 これは低レベルのインタフェースです。@var{option-clause} は、
18232 @code{parse-options} と同じです。このマクロは、コマンドラインオプションを
18233 後でパースするために使うことができる手続きを返します。
18234
18235 返される手続きは、一つの必須の引数と一つのオプション引数を取ります。
18236 必須の引数は、与えられたコマンドライン引数としての文字列のリストです。
18237 オプションの引数は、三つ以上の引数を取る手続きで、それが与えられると
18238 手続きはそれが @code{else} オプション節のボディであるかのように使われます。
18239 @c COMMON
18240 @end defmac
18241
18242 @c ----------------------------------------------------------------------
18243 @node Partial continuations, High-level process interface, Parsing command-line options, Library modules - Gauche extensions
18244 @section @code{gauche.partcont} - Partial continuations
18245 @c NODE 部分継続, @code{gauche.partcont} - 部分継続
18246
18247 @deftp {Module} gauche.partcont
18248 @mdindex gauche.partcont
18249 @c EN
18250 Gauche internally supports partial continuations
18251 (a.k.a. delimited continuations) natively.
18252 This module exposes the feature for general use.
18253 @c JP
18254 Gaucheは内部的に、部分継続(限定継続と呼ばれることもあります)を
18255 ネイティブでサポートしています。このモジュールはその機能を
18256 一般的に使えるように公開するものです。
18257 @c COMMON
18258 @end deftp
18259
18260 @c EN
18261 Note:
18262 Partial continuations use two operators, @code{reset} and @code{shift}.
18263 Those names are introduced in the original papers, and stuck in the
18264 programming world. Unfortunately those names are too generic as
18265 library function names. We thought giving them more descriptive names,
18266 but decided to keep them after all; when you talk about partial
18267 continuations you can't get away from those names. If these names
18268 conflict to other names in your program, you can use @code{:prefix}
18269 import specifier (@pxref{Using modules}), for example as follows:
18270 @c JP
18271 註: 部分継続はふたつのオペレータ、@code{reset}と@code{shift}を使います。
18272 これらは元の論文で導入された名前ですが、既に用語として定着した感があります。
18273 ライブラリ関数名としては一般的に過ぎる名前なので、よりわかりやすい名前を
18274 つけようかとも考えたのですが、部分継続を話題にする際にはこれらの用語が
18275 使われるのが普通なので、最終的にこの名前をキープすることにしました。
18276 プログラム中で他の識別子とぶつかったり紛らわしい場合は、モジュールのimport
18277 時に@code{:prefix}インポート指示子(@ref{Using modules}参照)を
18278 次のように使うと良いでしょう。
18279 @c COMMON
18280
18281 @example
18282 ;; Add prefix pc: to the 'reset' and 'shift' operators.
18283 (use gauche.partcont :prefix pc:)
18284
18285 (pc:reset ... (pc:shift k ....) )
18286 @end example
18287
18288 @defmac reset expr @dots{}
18289 @c MOD gauche.partcont
18290 @c EN
18291 Saves the current continuation, and executes @var{expr} @dots{} with
18292 a @emph{null continuation} or @emph{empty continuation}.
18293 The @code{shift} operator captures the continuation from the @code{shift}
18294 expression to this null continuation.
18295 @c JP
18296 現在の継続を保存し、@var{expr} @dots{} を@emph{空の継続}を伴って実行します。
18297 空の継続は@code{shift}オペレータが捕捉する継続の終端になります。
18298 @c COMMON
18299
18300 @c EN
18301 Note on @emph{implicit delimited continuations}:
18302 There's an occasion Gauche effectively calls @code{reset} internally:
18303 When C routine calls back to Scheme in non-CPS manner.
18304 (If you know C API, it is @code{Scm_EvalRec()}, @code{Scm_ApplyRec*()},
18305 @code{Scm_Eval()} and @code{Scm_Apply()} family of functions.) The callers
18306 of such routines expect the result is returned at most once, which won't
18307 work well with Scheme's continuations that have unlimited extent.
18308 Such calls create delimited continuations implicitly.
18309
18310 For example, the @code{main} routine of @code{gosh} calls Scheme REPL by
18311 @code{Scm_Eval()}, which means the entire REPL is effectively surrounded
18312 by a @code{reset}. So, if you call @code{shift} without corresponding
18313 @code{reset}, the continuation of @code{shift} becomes the continuation
18314 of the entire REPL---which is to exit from @code{gosh}.
18315 This may be surprising if you don't know about the implicit delimited
18316 continuation.
18317
18318 Other places the implicit delimited continuations are created
18319 are the handlers virtual ports (@pxref{Virtual ports}),
18320 @code{object-apply} methods called from @code{write} and @code{display},
18321 and GUI callbacks such as the one registered by @code{glut-display-func}
18322 (See the document of Gauche-gl for the details), to name a few.
18323
18324 In general you don't need to worry about it too much, since most
18325 built-in and extension routines written in C calls back Scheme in CPS manner,
18326 and works with both full and delimited continuations.
18327 @c JP
18328 @emph{暗黙の限定継続}について:
18329 Gaucheは内部的に、@code{reset}相当の操作を行う場合があります。
18330 CルーチンがSchemeを継続渡し形式でない方法で呼び出す場合です。
18331 (C APIをご存知の方へ: @code{Scm_EvalRec()}, @code{Scm_Apply*Rec()},
18332 @code{Scm_Eval()}、および@code{Scm_Apply()}が相当する関数です。)
18333 これらの関数はCの呼び出し側へ、値をたかだか1度だけ返すことが期待されています。
18334 Schemeの継続は無限エクステントを持ち、一度返ったルーチンから再び返ることが
18335 あり得るため、こういったC関数とは相性が良くありません。
18336 これらの関数を呼び出す時に、Gaucheは限定継続を自動的に作成します。
18337
18338 例えば、@code{gosh}の@code{main}関数はSchemeのREPLを
18339 @code{Scm_Eval()}を通じて呼び出します。ということは、
18340 REPL全体が@code{reset}で囲まれているということです。
18341 従って@code{reset}の外側で@code{shift}を呼び出すと、その@code{shift}の
18342 継続はREPL全体の継続と同じになります。すなわち、@code{gosh}が終了するということです。
18343 暗黙の限定継続に気づかないと、この振る舞いにはびっくりするかもしれません。
18344
18345 他に暗黙の限定継続が作られる例をいくつかあげます。
18346 仮想ポートのハンドラ (@ref{Virtual ports}参照)、
18347 @code{write}や@code{display}から呼ばれる@code{object-apply}メソッド、
18348 @code{glut-display-func}により登録されたGUIコールバック
18349 (詳しくはGauche-glのマニュアル参照)などです。
18350
18351 そのような暗黙の限定継続を心配する必要は滅多にありません。Cで実装された
18352 組み込み関数や拡張関数のほとんどは継続渡し形式でSchemeを呼んでいるため、
18353 通常継続も限定継続も制限なく使うことができます。
18354 @c COMMON
18355 @end defmac
18356
18357 @defmac shift var expr @dots{}
18358 @c MOD gauche.partcont
18359 @c EN
18360 Packages the continuation of this expression until the current null
18361 continuation marked by the most recent @code{reset} into a procedure,
18362 binds the procedure to @var{var}, then executes @var{expr} @dots{}
18363 with the continuation saved by the most recent @code{reset}.
18364 @c JP
18365 この式からもっとも最近の@code{reset}により切り取られた空の継続までの継続を
18366 手続きに包み、それを@var{var}に束縛します。
18367 そしてもっとも近い@var{reset}式の継続を伴って@var{expr} @dots{}を実行します。
18368 @c COMMON
18369
18370 @c EN
18371 That is, after executing @var{expr} @dots{}, the value is passed
18372 to the expression waiting for the value of the most recent @code{reset}.
18373 When a partial continuation bound to @var{var} is executed, its
18374 argument is passed to the continuation waiting for the value
18375 of this @code{shift}. When the execution of the partial continuation
18376 reaches its end, it returns from the expression waiting
18377 for the value of invocation of @var{var}.
18378 @c JP
18379 すなわち、@var{expr} @dots{}を実行後、その結果の値はもっとも最近の@code{reset}
18380 の戻り値を待っている式に直ちに渡されます。
18381 @var{var}に束縛されている部分継続が実行されると、それに渡された値は
18382 @code{shift}の戻り値を待っている継続に直ちに渡されます。
18383 その部分継続の実行が終了すると、その結果の値は@var{var}を呼び出した式の
18384 戻り値となります。
18385 @c COMMON
18386 @end defmac
18387
18388 @defun call/pc proc
18389 @c MOD gauche.partcont
18390 @c EN
18391 This is a wrapper of @code{shift}. @code{(shift k expr @dots{})}
18392 is equivalent to @code{(call/pc (lambda (k) expr @dots{}))}.
18393 Sometimes this similarity of @code{call/cc} comes handy.
18394 @c JP
18395 これは@code{shift}のラッパーです。
18396 @code{(shift k expr @dots{})}は@code{(call/pc (lambda (k) expr @dots{}))}
18397 等価です。@code{call/cc}と似た形の呼び出し形式の方が便利な場合があるので
18398 用意しました。
18399 @c COMMON
18400 @end defun
18401
18402 @c EN
18403 Well, @dots{} I bet you feel like your brain is twisted hard
18404 unless you are one of those rare breed from the land of continuation.
18405 Let me break down what's happening here informally and intuitively.
18406 @c JP
18407 さてと… もしあなたが、継続の国の血を引く珍しい種族の一員でなければ、
18408 たぶんここまで読んできて、脳みそがこんがらがっていることでしょう。
18409 何が起きているか、厳密ではないが直感的な説明を試みてみます。
18410 @c COMMON
18411
18412 @c EN
18413 Suppose a procedure A calls an expression B. If A expects a return
18414 value from B and continue processing, we split the part after returning
18415 from B into a separate chunk A', then we can think of the whole
18416 control flow as this straight chain:
18417 @c JP
18418 手続きAが式Bを呼び出すとします。AがBの戻り値を受け取ってさらに計算を続ける場合、
18419 Bが戻ってからの残りの計算部分をA'として分離することにすれば、全体の制御の流れは
18420 次のように一本の鎖で表現できるでしょう。
18421 @c COMMON
18422
18423 @example
18424 A -> B -> A'
18425 @end example
18426
18427 @c EN
18428 @code{A -> B} is a procedure call and @code{B -> A'} is a return,
18429 but we all know procedure call and return is intrinsically the
18430 same thing, right?
18431 @c JP
18432 @code{A -> B}は手続き呼び出しで、@code{B -> A'}は手続きからのリターンですが、
18433 手続き呼び出しとリターンは本質的には同じものでしたね。
18434 @c COMMON
18435
18436 @c EN
18437 Procedure B may call another procedure C, and so on. So when
18438 you look at an execution of particular piece of code, you can
18439 think of a chain of control flow like this:
18440 @c JP
18441 Bはその中から別の手続きCをさらに呼び出しているかもしれません。
18442 コードのある部分に着目した場合、そこにある制御の鎖を
18443 次のようにイメージすることができるでしょう。
18444 @c COMMON
18445
18446 @example
18447 ... -> A -> B -> C -> .... -> C' -> B' -> A' -> ...
18448 @end example
18449
18450 @c EN
18451 The magic procedure @code{call/cc} picks the head of the chain
18452 following its execution (marked as @code{*} in the figure below),
18453 and passes it to the given procedure (denoted @code{k} in the figure
18454 below).
18455 So, whenever @code{k} is invoked, the control goes through the
18456 chain from @code{*}.
18457 @c JP
18458 魔法の手続き@code{call/cc}は、そのフォームの直後に来る鎖の先頭
18459 (下の図で@code{*}で示されている部分)を取り上げて、それを
18460 与えられた手続きに引数として渡すものです (下の図の@code{k})。
18461 従って、@code{k}が呼び出されると、制御は直ちに@code{*}へとジャンプします。
18462 @c COMMON
18463
18464 @example
18465 ... -> A -> B -> (call/cc -> (lambda (k) ... ) ) -> B' -> A' -> ...
18466 | ^
18467 \-----------> *
18468 @end example
18469
18470 @c EN
18471 One difficulty with @code{call/cc} is that the extracted chain
18472 is only one-ended---we don't know what is chained to the
18473 right. In fact, what will come after that depends
18474 on the whole program; it's outside of local control. This global
18475 attribute of @code{call/cc} makes it difficult to deal with.
18476 @c JP
18477 @code{call/cc}で難しいのは、制御の鎖の片方しか取り出せないことです。
18478 もう一方、鎖の右側がどこにつながっているのか、コードは知ることができません。
18479 そもそも、鎖の右側に何が来るかは、プログラム全体を知らないとわからないのです。
18480 この、グローバルな性質が、@code{call/cc}を扱い辛いものにしています。
18481 @c COMMON
18482
18483 @c EN
18484 The @code{reset} primitive @emph{cuts} this chain of
18485 continuation. The original chain of continuation (the @code{x}-end
18486 in the following figure) is saved somewhere, and the continuation
18487 of @code{reset} itself becomes open-ended (the @code{o}-end
18488 in the following figure).
18489 @c JP
18490 @code{reset}プリミティブはこの継続の鎖を@emph{切断}します。
18491 元の鎖 (下の図の@code{x}で示される端) は保存され、
18492 @code{reset}式の継続自体は宙ぶらりんになります (下の図の@code{o}で示される端)。
18493 @c COMMON
18494
18495 @example
18496 ... -> A -> B -> (reset ... ) -> o
18497
18498 x -> B ' -> A' -> ...
18499 @end example
18500
18501 @c EN
18502 A rule: If control reaches to the @code{o}-end, we pick the
18503 @code{x}-end @emph{most recently saved}.
18504 Because of this, @code{reset} alone doesn't show any
18505 difference in the program behavior.
18506 @c JP
18507 ここでひとつ規則を導入します。制御が@code{o}の端に達した場合、
18508 直近に保存された@code{x}の端から制御を再開するとします。
18509 従って、単に@code{reset}を挿入するだけでは、目に見える違いは生じません。
18510 @c COMMON
18511
18512 @c EN
18513 Now what happens if we insert @code{shift} inside @code{reset}?
18514 This is a superficial view of inserting @code{shift} into
18515 somewhere down the chain of reset:
18516 @c JP
18517 @code{reset}の中に@code{shift}を挿入したらどうなるでしょう。
18518 resetの内部の鎖に@code{shift}を形式的に挿入してみるとこうなります。
18519 @c COMMON
18520
18521 @example
18522 ... -> (reset -> X -> Y -> (shift k ... ) -> Y' -> X' ) -> o
18523 @end example
18524
18525 @c EN
18526 What actually happens is as follows.
18527 @c JP
18528 実際には次のような動作となります。
18529 @c COMMON
18530
18531 @enumerate
18532 @item
18533 @c EN
18534 @code{shift} packages @emph{the rest of the chain of work} until the
18535 end of @code{reset}, and bind it to the variable @var{k}.
18536 @c JP
18537 @code{shift}は、@code{reset}の終端までの@emph{仕事の残りの部分}を取り出し、
18538 それを変数@var{k}に束縛します。
18539 @c COMMON
18540 @item
18541 @c EN
18542 The continuation of @code{shift} becomes a null continuation as well,
18543 so after @code{shift} returns, the control skips the rest of
18544 operations until the corresponding @code{reset}.
18545 @c JP
18546 @code{shift}自身の継続は、空の継続となります。したがって@code{shift}から抜けると、
18547 @code{shift}以降対応する@code{reset}までの操作はスキップされます。
18548 @c COMMON
18549 @end enumerate
18550
18551 @example
18552 ... -> (reset -> X -> Y -> (shift k ... ) ---------> ) -> o
18553 |
18554 \-------> Y' -> X' ) -> o
18555 @end example
18556
18557 @c EN
18558 In other words, when you consider the @code{reset} form as
18559 one chunk of task, then @code{shift} in it
18560 @emph{stashes away} the rest of the task and immediately
18561 returns from the task.
18562 @c JP
18563 別の言い方をすれば、@code{reset}フォームをひとつの仕事の単位とすれば、
18564 その中の@code{shift}は、その仕事の残りの部分を@emph{一時保存}して
18565 仕事を中断して戻ってくるのです。
18566 @c COMMON
18567
18568 @c EN
18569 Let's see an example. The @var{walker} argument in
18570 the following example is a procedure that takes a procedure
18571 and some kind of collection,
18572 and applies the procedure to the each element in the collection.
18573 We ignore the return value of @var{walker}.
18574 @c JP
18575 例を見てみます。次に示す@var{walker}引数は、
18576 「手続きと何らかのコレクションを取り、手続きをコレクションの各要素に
18577 適用してゆく」という手続きとします。
18578 @var{walker}の戻り値は無視します。
18579 @c COMMON
18580
18581 @example
18582 (define (inv walker)
18583 (lambda (coll)
18584 (define (continue)
18585 (reset (walker (lambda (e) (shift k (set! continue k) e)) coll)
18586 (eof-object)))
18587 (lambda () (continue))))
18588 @end example
18589
18590 @c EN
18591 A typical example of @var{walker} is @code{for-each}, which takes
18592 a list and applies the procedure to each element of the list.
18593 If we pass @code{for-each} to @code{inv}, we get a procedure
18594 that is inverted @emph{inside-out}. What does that mean?
18595 See the following session:
18596 @c JP
18597 @var{walker}の典型的な例は@code{for-each}です。手続きとリストを取り、
18598 リストの各要素に手続きを適用するからです。
18599 @code{for-each}を上の@code{inv}に渡すと、@code{for-each}を
18600 @emph{裏返した}手続きが得られます。どういうことでしょう?
18601 下のやりとりを見てみましょう。
18602 @c COMMON
18603
18604 @example
18605 gosh> (define inv-for-each (inv for-each))
18606 inv-for-each
18607 gosh> (define iter (inv-for-each '(1 2 3)))
18608 iter
18609 gosh> (iter)
18610 1
18611 gosh> (iter)
18612 2
18613 gosh> (iter)
18614 3
18615 gosh> (iter)
18616 #<eof>
18617 @end example
18618
18619 @c EN
18620 When you pass a list to @code{inv-for-each}, you get an iterator
18621 that returns each element in the list for each call. That's because every
18622 time @code{iter} is called, @code{shift} in @code{inv}
18623 stashes away the task of @emph{walking the rest of the collection}
18624 and set it to @code{continue}, then returns the current element @var{e}.
18625 @c JP
18626 リストを@code{inv-for-each}に渡すと、呼ばれる度にリストの各要素を順に返す
18627 イテレータ手続きが得られます。というのも、@code{iter}が呼ばれる度に、
18628 @code{inv}の中で作られた@code{shift}は@emph{リストの残りの部分をたどって行く}
18629 という仕事の残りを@code{continue}に束縛して、現在の要素@var{e}を返すからです。
18630 @c COMMON
18631
18632 @c EN
18633 @var{walker} doesn't need to work just on list. The following
18634 function @code{for-each-leaf} traverses a tree and
18635 apply @var{f} on each non-pair element.
18636 @c JP
18637 @var{walker}はリストを取る必要はありません。次に示す@code{for-each-leaf}は
18638 木を取って、@var{f}をペアでない要素に適用してゆく手続きです。
18639 @c COMMON
18640
18641 @example
18642 (define (for-each-leaf f tree)
18643 (match tree
18644 [(x . y) (for-each-leaf f x) (for-each-leaf f y)]
18645 [x (f x)]))
18646 @end example
18647
18648 @c EN
18649 And you can inverse it just like @code{for-each}.
18650 @c JP
18651 これも@code{for-each}と同じように裏返すことができます。
18652 @c COMMON
18653
18654 @example
18655 gosh> (define iter2 ((inv for-each-leaf) '((1 . 2) . (3 . 4))))
18656 iter2
18657 gosh> (iter2)
18658 1
18659 gosh> (iter2)
18660 2
18661 gosh> (iter2)
18662 3
18663 gosh> (iter2)
18664 4
18665 gosh> (iter2)
18666 #<eof>
18667 @end example
18668
18669 @c EN
18670 The @code{util.combinations} module (@pxref{Combination library})
18671 provides a procedure that @emph{calls} a given procedure with
18672 every permutation of the given collection. If you pass
18673 it to @code{inv}, you get a procedure that @emph{returns}
18674 every permutation each time.
18675 @c JP
18676 @code{util.combinations}モジュール (@ref{Combination library}参照) には、
18677 コレクションの全ての並べ替えに対して与えられた手続きを@emph{呼び出す}手続きがあります。
18678 それを@code{inv}に渡せば、呼ばれる度に並べ替えを@emph{返す}手続きが得られます。
18679 @c COMMON
18680
18681 @example
18682 gosh> (define next ((inv permutations-for-each) '(a b c)))
18683 next
18684 gosh> (next)
18685 (a b c)
18686 gosh> (next)
18687 (a c b)
18688 gosh> (next)
18689 (b a c)
18690 gosh> (next)
18691 (b c a)
18692 gosh> (next)
18693 (c a b)
18694 gosh> (next)
18695 (c b a)
18696 gosh> (next)
18697 #<eof>
18698 @end example
18699
18700
18701
18702 @c ----------------------------------------------------------------------
18703 @node High-level process interface, Record types, Partial continuations, Library modules - Gauche extensions
18704 @section @code{gauche.process} - High-level process interface
18705 @c NODE 高レベルプロセスインタフェース, @code{gauche.process} - 高レベルプロセスインタフェース
18706
18707 @deftp {Module} gauche.process
18708 @mdindex gauche.process
18709 @c EN
18710 This module provides a higher-level API of process control,
18711 implemented on top of low-level system calls.
18712 This module also provides ``process ports'',
18713 a convenient way to send/receive information to/from subprocesses.
18714 @c JP
18715 このモジュールは、低レベルなシステムコールの上に実装された、
18716 プロセス制御の高レベル API を提供します。
18717 また、このモジュールは、サブプロセスに情報を送ったり、サブプロセスから
18718 情報を受け取ったりするのに便利な「プロセスポート」を提供します。
18719 @c COMMON
18720
18721 @c EN
18722 Note: This module used to provide
18723 @code{shell-escape-string} and @code{shell-tokenize-string}, but they're
18724 purely text manipulation and not really related to subprocesses, so
18725 we moved them to @code{text.sh}. @xref{Shell text utilities}, for the
18726 details. For the backward compatibility, we keep exporting those
18727 two procedures from @code{gauche.process}.
18728 @c JP
18729 註: このモジュールでは@code{shell-escape-string}と@code{shell-tokenize-string}
18730 というユーティリティ手続きを提供していましたが、これらはテキスト操作でありサブプロセスと
18731 直接の関係がないので、@code{text.sh}に移されました。
18732 詳しくは@ref{Shell text utilities}を参照してください。
18733 互換性のため、@code{gauche.process}からもこれらの手続きはエクスポートされます。
18734 @c COMMON
18735 @end deftp
18736
18737 @menu
18738 * Running subprocess::
18739 * Running process pipeline::
18740 * Process object::
18741 * Process ports::
18742 * Process connection::
18743 @end menu
18744
18745 @node Running subprocess, Running process pipeline, High-level process interface, High-level process interface
18746 @subsection Running subprocess
18747 @c NODE サブプロセスの実行
18748
18749 @defun do-process cmd/args :key redirects input output error @
18750 fork environment directory host sigmask on-abnormal-exit
18751 @defunx do-process! cmd/args :key redirects input output error @
18752 fork environment directory host sigmask
18753 @defunx run-process cmd/args :key redirects input output error @
18754 fork environment directory host sigmask wait
18755 @c MOD gauche.process
18756 @c EN
18757 Runs a command with arguments given to @var{cmd/args} in a subprocess.
18758 The @var{cmd/args} argument must be a list, whose car specifies
18759 the command name and whose cdr is the command-line arguments.
18760
18761 If the command name contains a slash, it is taken as the
18762 pathname of the executable. Otherwise the named command
18763 is searched from the directories in the @code{PATH} environment variable.
18764
18765 Each element in @var{cmd/args} are converted to a string
18766 by @code{x->string}, for the convenience.
18767 @c JP
18768 サブプロセスで、@var{cmd/args}に与えられたコマンドと引数を実行します。
18769 @var{cmd/args}引数はリストで、その@code{car}がコマンド名を、
18770 @code{cdr}がコマンドラインに渡す引数を指定します。
18771
18772 コマンド名がスラッシュを含んでいた場合、それは実行可能ファイルへの
18773 パス名と解釈されます。そうでなければ、コマンド名が@code{PATH}環境変数
18774 にあるディレクトリから探されます。
18775
18776 @var{cmd/args}の各要素は、@code{x->string}で文字列に変換されます。
18777 @c COMMON
18778
18779 @c EN
18780 @code{Do-process} always waits the subprocess to terminate, and
18781 returns @code{#t} if it exits successfully (i.e. with zero exit status).
18782 If the subprocess terminates abnormally, the behavior is controled
18783 by @var{on-abnormal-exit} keyword argument:
18784 @itemize @bullet
18785 @item
18786 If it is @code{#f} (default), @code{#f} is returned.
18787 Note that this default is different from @code{call-with-input-process} etc.,
18788 which raise an error by default. It is because @code{do-process} is
18789 intended to be used with conditionals
18790 like shell-script's @code{if} command; i.e.
18791 @code{(if (do-process command) then-expr else-expr)} works just
18792 like shell's @code{if command; then then-command; else else-command; fi}.
18793 @item
18794 If it is @code{:error}, a @code{<process-abnormal-exit>} error is thrown.
18795 @item
18796 If it is @code{:exit-code}, and the subprocess terminates with
18797 non-zero exit status, the integer exit code (the integer value passed
18798 to subprocess's @code{exit()}) is returned. Note that if the
18799 subprocess is terminated with a signal, a @code{<process-abnormal-exit>}
18800 is still thrown.
18801 @end itemize
18802 @c JP
18803 @code{do-process}は常にサブプロセスが終了するまで待ち、正常終了した場合(終了ステータスが
18804 0の場合)に@code{#t}を返します。サブプロセスが異常終了した場合の
18805 ふるまいはキーワード引数@var{on-abnormal-exit}によって次のように決定されます。
18806 @itemize @bullet
18807 @item
18808 引数が@code{#f}の場合(デフォルト)、単に@code{#f}が返されます。
18809 これは@code{call-with-input-process}などのデフォルト(エラーを投げる)とは
18810 異なっていることに注意してください。@code{do-process}は、条件分岐と組み合わせて
18811 シェルスクリプトの@code{if}コマンドのように使うことを想定しています。
18812 @code{(if (do-process command) then-expr else-expr)}は
18813 シェルの@code{if command; then then-command; else else-command; fi}
18814 のように動作します。
18815 @item
18816 引数が@code{:error}の場合、@code{<process-abnormal-exit>}エラーが投げられます。
18817 @item
18818 引数が@code{:exit-code}の場合、サブプロセスがゼロ以外の終了ステータスで終了したなら、
18819 その終了コード (サブプロセスの@code{exit()}に渡された整数値) を整数で返します。
18820 サブプロセスがシグナルにより終了した場合は
18821 @code{<process-abnormal-exit>}エラーが投げられることに注意してください。
18822 @end itemize
18823 @c COMMON
18824
18825 @c EN
18826 @code{Do-process!} is like @code{do-process} except that
18827 it raises @code{<process-abnormal-exit>} error when the process
18828 exists with non-zero status. It's the same behavior as
18829 giving @code{:error} to the @code{on-abnormal-exit} keyword argument
18830 of @code{do-process}. This is convenient if you want to let the script
18831 just fail when the command fails.
18832 @c JP
18833 @code{do-process!}は@code{do-process}とほぼ同じですが、
18834 プロセスが0以外の終了ステータスを返した場合に@code{<process-abnormal-exit>}エラーを
18835 投げます。@code{do-process}の@code{on-abnormal-exit}に@code{:error}を
18836 渡した場合の振る舞いと同じです。シェルスクリプト的な仕事で、
18837 コマンドが失敗したらそこで終わってよいといった場合に便利です。
18838 @c COMMON
18839
18840 @c EN
18841 @code{Run-process} can run the subprocess concurrently by default,
18842 that is, it returns immediately. The return value is a @code{<process>}
18843 object, which can be used to track the status of the subprocess
18844 (@pxref{Process object}).
18845 @c JP
18846 @code{run-process}はデフォルトでサブプロセスを並行して走らせます。
18847 つまり、直ちに返ってきます。返り値は@code{<process>}オブジェクトで、それを
18848 用いてサブプロセスの状態を追跡できます
18849 (@ref{Process object}参照)。
18850 @c COMMON
18851
18852 @c EN
18853 For example, the following expression runs @code{ls -al}.
18854 @c JP
18855 例えば、次の式は@code{ls -al}を実行します。
18856 @c COMMON
18857
18858 @example
18859 (do-process '(ls -al))
18860 @end example
18861
18862 @c EN
18863 You see the output of @code{ls -al}, then it returns @code{#t},
18864 unless the execution of @code{ls} command fails with some reason.
18865 @c JP
18866 @code{ls}コマンドが何らかの理由で失敗しない限り、
18867 @code{ls -al}の出力が表示されてから、@code{#t}が返されるでしょう。
18868 @c COMMON
18869
18870 @c EN
18871 Since @code{do-process} returns the success or failure of the command
18872 by a boolean value, you can use @code{and} and @code{or} to combine
18873 commands pretty much the same way as shell's @code{&&} and @code{||}
18874 operators.
18875 @c JP
18876 @code{do-process}はコマンドの成功失敗を真偽値で返すので、
18877 シェルの@code{&&}や@code{||}オペレータでコマンドを組み合わせるのと同じことが
18878 @code{and}や@code{or}でできます。
18879 @c COMMON
18880
18881 @example
18882 ;; shell: make && make -s check
18883 (and (do-process '(make))
18884 (do-process '(make -s check)))
18885
18886 ;; shell: mv x.tmp x.c || rm -f x.tmp
18887 (or (do-process '(mv x.tmp x.c))
18888 (do-process '(rm -f x.tmp)))
18889 @end example
18890
18891 @c EN
18892 If you use @code{run-process} instead, you'll get @code{<process>} object
18893 without waiting @code{ls -al} to finish. If you run the following expression
18894 on REPL, you'll likely to see the return value before output of @code{ls}.
18895 @c JP
18896 代わりに@code{run-process}を使った場合は、@code{ls -al}の終了を待たずに
18897 @code{<process>}オブジェクトが返されます。
18898 次の式をREPLで実行したなら、おそらく
18899 @code{ls}の出力の前に@code{<process>}オブジェクトが表示されるでしょう。
18900 @c COMMON
18901
18902 @example
18903 (run-process '(ls -al))
18904 @end example
18905
18906 @c EN
18907 You can keep the returned @code{<process>} object
18908 and call @code{process-wait} on it to wait for its termination.
18909 @xref{Process object}, for the details of @code{process-wait}.
18910 @c JP
18911 戻り値の@code{<process>}オブジェクトを保持しておいて、後で
18912 @code{process-wait}を呼ぶことによって子プロセスの終了を待つことができます。
18913 @code{process-wait}については@ref{Process object}で説明します。
18914 @c COMMON
18915
18916 @example
18917 (let1 p (run-process '(ls -al))
18918 ... do some other work ...
18919 (process-wait p))
18920 @end example
18921
18922 @c EN
18923 You can tell @code{run-process} to wait for the subprocess to exit; in
18924 that case, @code{run-process} calls @code{process-wait} internally.
18925 It is useful if you want to examine the exit status of the subprocess,
18926 rather than just caring its success/failure as @code{do-process} does.
18927 @c JP
18928 @code{run-process}に、プロセス終了を待つように指示することもできます。
18929 その場合、@code{run-process}は内部で@code{process-wait}を呼びます。
18930 @code{do-process}は成功/失敗しかわからないのに対し、
18931 プロセスの終了ステータスを後で調べたい場合に便利です。
18932 @c COMMON
18933
18934 @c EN
18935 Note that @code{-i} is read as an imaginary number,
18936 so be careful to pass @code{-i} as a command-line
18937 argument; you should use a string, or write @code{|-i|} to make it
18938 a symbol.
18939 @c JP
18940 ところで、@code{-i}は虚数として読まれることに注意してください。
18941 @code{-i}を引数として渡したい場合は文字列にするか、@code{|-i|}のように
18942 エスケープしてシンボルにする必要があります。
18943 @c COMMON
18944
18945 @example
18946 (run-process '(ls "-i"))
18947 @end example
18948
18949 @c EN
18950 Note: An alternative way to run external process is @code{sys-system},
18951 which takes a command line as a single string (@pxref{Process management}).
18952 The string is passed to the shell to be interpreted,
18953 so you can include redirections, or can pipe several commands.
18954 It would be handy for quick throwaway scripts.
18955
18956 On the other hand, with @code{sys-system},
18957 if you want to change command parameters
18958 at runtime, you need to worry about properly escape them
18959 (actually we have one to do the job:
18960 @code{shell-escape-string}, @pxref{Shell text utilities});
18961 you need to be aware that @code{/bin/sh}, used by
18962 @code{sys-system} via @code{system(3)} call, may differ among
18963 platforms and be careful not to rely on specific features on
18964 certain systems. As a rule of thumb, keep @code{sys-system} for
18965 really simple tasks with a constant command line,
18966 and use @code{run-process} and @code{do-process}
18967 for all other stuff.
18968 @c JP
18969 注:外部プロセスを走らせる方法にはもうひとつ、@code{sys-system}があります。
18970 こちらはコマンド行を単一の文字列で渡し、シェルを呼び出して解釈させます
18971 (@ref{Process management}参照)。
18972 したがって、入出力のリダイレクトや、パイプでつないだコマンド等もそのまま渡せます。
18973 書き捨てのスクリプトを素早く書くときはそちらの方が便利でしょう。
18974
18975 一方、@code{sys-system}を使う場合には、コマンドの引数を実行時に可変にしたい場合に
18976 きちんとエスケープされているかどうかを確認したり (実はそれをやってくれる
18977 @code{shell-escape-string}という手続きがあります。@ref{Shell text utilities}参照)、
18978 また@code{sys-system}が@code{system(3)}経由で
18979 呼び出す@code{/bin/sh}のプラットフォーム間の違いを気にしたりする必要があります。
18980 原則として、@code{sys-system}の使用は固定コマンドを呼び出す簡単な場合に
18981 止めておき、他の仕事には@code{run-process}や
18982 @code{do-process}を使うのが良いでしょう。
18983 @c COMMON
18984
18985 @c EN
18986 Note: Old version of this procedure took arguments differently,
18987 like @code{(run-process "ls" "-al" :wait #t)}, which was compatible
18988 to STk. This is still supported but deprecated.
18989 @c JP
18990 注:以前のバージョンのこの手続きは引数の取りかたが若干異なっており、
18991 例えば@code{(run-process "ls" "-al" :wait #t)}のように呼び出しました。
18992 これはSTkとの互換性によるものです。現在でもこの呼び出しはサポートされていますが、
18993 非推奨です。
18994 @c COMMON
18995
18996 @c EN
18997 Large number of keyword arguments can be passed to
18998 @code{do-process} and
18999 @code{run-process}
19000 to control execution of the child process. We describe them by
19001 categories.
19002 @c JP
19003 子プロセスの実行を細かく制御するために、@code{do-process}と
19004 @code{run-process}はたくさんの
19005 キーワード引数を取ります。以下でそれらをいくつかのカテゴリに分類して説明します。
19006 @c COMMON
19007 @end defun
19008
19009
19010 @c EN
19011 @subsubheading Synchronization
19012 @c JP
19013 @subsubheading 同期
19014 @c COMMON
19015
19016 @deftp {Subprocess argument} wait @var{flag}
19017 @c EN
19018 This can only be given to @code{run-process}.
19019 If @var{flag} is true, @code{run-process} waits until the
19020 subprocess terminates, by calling @code{process-wait} internally.
19021 Otherwise the subprocess runs asynchronously
19022 and @code{run-process} returns immediately, which is the default behavior.
19023
19024 Note that if the subprocess is running asynchronously, it is the
19025 caller's responsibility to call @code{process-wait} at a certain
19026 timing to collect its exit status.
19027 @c JP
19028 この引数は@code{run-process}のみに渡すことができます。
19029 @var{flag} が真の場合、@code{run-process} は内部で
19030 @code{process-wait}を呼びだし、サブプロセスが終了するまで待ちます。
19031 そうでなければ、サブプロセスは非同期に実行され、@code{run-process} は
19032 すぐに返ります。これがデフォルトの振る舞いになります。
19033
19034 サブプロセスが非同期に実行している場合、その終了ステータスを回収するために
19035 適切なタイミングで @code{process-wait} を呼ぶことは、呼び出し側の責任であることに
19036 注意してください。
19037 @c COMMON
19038
19039 @example
19040 ;; This returns after wget terminates.
19041 (define p (run-process '(wget http://practical-scheme.net/) :wait #t))
19042
19043 ;; Check the exit status
19044 (let1 st (process-exit-status p)
19045 (cond [(sys-wait-exited? st)
19046 (print "wget exited with status " (sys-wait-exit-status st))]
19047 [(sys-wait-signaled? st)
19048 (print "wget interrupted by signal " (sys-wait-termsig st))]
19049 [else
19050 (print "wget terminated with unknown status " st)]))
19051 @end example
19052 @end deftp
19053
19054 @deftp {Subprocess argument} on-abnormal-exit @var{how}
19055 @c EN
19056 This can only be given to @code{do-process}.
19057 If @var{how} is @code{#f}, which is the default,
19058 @code{do-process} returns @code{#f} when
19059 the subprocess exits abnormally (i.e. with nonzero exit status).
19060 If @var{how} is @code{:error}, it raises an error in such a case.
19061 @c JP
19062 この引数は@code{do-process}のみに渡すことができます。
19063 @var{how}が@code{#f}の場合(デフォルト)、
19064 サブプロセスが異常終了(ゼロ以外の終了ステータスを返)した場合は@code{#f}を返します。
19065 @var{how}が@code{:error}なら、その場合はエラーを投げます。
19066 @c COMMON
19067 @end deftp
19068
19069 @deftp {Subprocess argument} fork @var{flag}
19070 @c EN
19071 If @var{flag} is true, @code{do-process} and
19072 @code{run-process} forks to run
19073 the subprocess, which is the default behavior. If @var{flag} is
19074 false, @code{do-process} and
19075 @code{run-process} directly calls @code{sys-exec}, so
19076 it never returns.
19077 @c JP
19078 @var{flag} が真の場合、@code{do-process}と
19079 @code{run-process} はサブプロセスを実行するために
19080 フォークします。これはデフォルトの振る舞いです。@var{flag} が偽の場合、
19081 @code{do-process}と
19082 @code{run-process} は直接 @code{sys-exec} を呼ぶので、戻って来ません。
19083 @c COMMON
19084 @end deftp
19085
19086 @c EN
19087 @subsubheading I/O redirection
19088 @c JP
19089 @subsubheading I/Oリダイレクト
19090 @c COMMON
19091
19092 @deftp {Subprocess argument} redirects (@var{iospec} @dots{})
19093 @c EN
19094 Specifies how to redirect child process's I/Os.
19095 Each @var{iospec}
19096 can be one of the followings, where @var{fd}, @var{fd0}, and @var{fd1}
19097 are nonnegative integers referring to the file descriptor
19098 @emph{of the child process}.
19099 @c JP
19100 子プロセスのI/Oをどのようにリダイレクトするかを指定します。
19101 各@var{iospec}は次の形式のいずれかです。ここで@var{fd}, @var{fd0}および@var{fd1}は
19102 @emph{子プロセスにおける}ファイルディスクリプタを指定する非負の整数です。
19103 @c COMMON
19104
19105 @c EN
19106 (Note: If you just want to run a command and get its output as a string
19107 take a look at @code{process-output->string} (@pxref{Process ports}).
19108 If you want to pipe multiple commands together,
19109 @pxref{Running process pipeline}.)
19110 @c JP
19111 (註:簡単にコマンドを走らせて結果を文字列で得たい場合は、
19112 @code{process-output->string}が使えます(@ref{Process ports}参照)。
19113 また、複数のコマンドをパイプでつなぎたい場合は
19114 @ref{Running process pipeline}を見てください。)
19115 @c COMMON
19116
19117 @table @code
19118 @item (< @var{fd} @var{source})
19119 @c EN
19120 @var{source} can be a string, a symbol, a keyword @code{:null},
19121 an integer, or an input port.
19122
19123 If it is a string, it names a file opened for read
19124 and the child process can reads the content of the file from @var{fd}.
19125 An error is signaled if the file does not exist or cannot open for read.
19126
19127 If it is a symbol, an unidirectional pipe is created, whose reader end
19128 is connected to the child's @var{fd}, and whose writer end is
19129 available as an output port returned from
19130 @code{(process-input @var{process} @var{source})}.
19131
19132 If it is @code{:null}, the child's @var{fd} is connected to the
19133 null device.
19134
19135 If it is an integer, it should specify a parent's file descriptor
19136 opened for read. The child sees the duped file descriptor as @var{fd}.
19137
19138 If it is an input port, the underlying file descriptor is duped
19139 into child's @var{fd}. It is an error to pass an input port without
19140 associated file descriptor (See @code{port-file-number} in
19141 @ref{Common port operations}).
19142 @c JP
19143 @var{source}は文字列、シンボル、キーワード@code{:null}、整数、入力ポートのいずれかです。
19144
19145 文字列の場合、それはファイル名を指定します。そのファイルが読み込み用にオープンされ、
19146 子プロセスはfdからその内容を読み込みます。指定されたファイルが存在しないか
19147 読み込み用にオープンできなければエラーが報告されます。
19148
19149 シンボルの場合、一方向のパイプが作られ、その読み出し側の端が子プロセスのfdへと
19150 接続されます。書き込み側の端は
19151 @code{(process-input @var{process} @var{source})}
19152 を呼び出すことで入手できます。
19153
19154 @code{:null}の場合、@var{fd}はシステムのヌルデバイスからの
19155 読み込みになります。
19156
19157 整数の場合は、現プロセスの読み込み用ファイルディスクリプタを指定します。
19158 そのファイルディスクリプタの読み込み元が@code{dup}されて、子プロセスからは@var{fd}として
19159 見えます。
19160
19161 入力ポートの場合は、入力元のファイルディスクリプタが@code{dup}されて
19162 子プロセスの@var{fd}になります。ファイルディスクリプタを持たないポートを渡した
19163 場合はエラーになります(@ref{Common port operations}の@code{port-file-number}参照)。
19164 @c COMMON
19165
19166 @item (<< @var{fd} @var{value})
19167 @itemx (<<< @var{fd} @var{obj})
19168 @c EN
19169 Feeds @var{value} or @var{obj} to the input file
19170 descriptor @var{fd} of the child process.
19171
19172 With @code{<<}, @var{value} must be either a string or a uniform
19173 vector (@pxref{Uniform vectors}). It is sent to the child process as is.
19174 Using a uniform vector is good to pass binary content.
19175
19176 With @code{<<<}, @var{obj} can be any Scheme object, and
19177 the result of @code{(write-to-string obj)} is sent to the child process.
19178 @c JP
19179 @var{value}または@var{obj}を子プロセスの入力ファイルディスクリプタ@var{fd}への
19180 入力とします。
19181
19182 @code{<<}を使う場合、@var{value}は文字列かユニフォームベクタ
19183 (@pxref{Uniform vectors})でなければなりません。その内容がそのまま
19184 子プロセスの入力へと送られます。ユニフォームベクタはバイナリデータを渡すのに便利です。
19185
19186 @code{<<<}を使う場合、@var{obj}には任意のSchemeオブジェクトを渡せます。
19187 @code{(write-to-string obj)}の結果の文字列が子プロセスの入力へと送られます。
19188 @c COMMON
19189
19190 @item (<& @var{fd0} @var{fd1})
19191 @c EN
19192 Makes child process's file descriptor @var{fd0} refer to the same input
19193 as its file descriptor @var{fd1}. Note the difference from @code{<};
19194 @code{(< 3 0)} makes the parent's stdin (file descriptor 0) be read
19195 by the child's file descriptor 3, while @code{(<& 3 0)} makes
19196 the child's file descriptor 3 refer to the same input as child's stdin
19197 (which may be redirected to a file or something else by another @var{iospec}).
19198
19199 See the note below on the order of processing @code{<&}.
19200 @c JP
19201 子プロセスのファイルディスクリプタ@var{fd0}が、
19202 同じく子プロセスのファイルディスクリプタ@var{fd1}が指しているものと
19203 同じ入力を参照するようにします。
19204 @var{<}との違いに注意してください。@code{(< 3 0)}とすると、
19205 現プロセスのstdin (ファイルディスクリプタ0) が子プロセスからはファイルディスクリプタ3
19206 として見えるようになります。@code{(<& 3 0)}とすると、子プロセスのファイルディスクリプタ3
19207 は子プロセスのstdinと同じものを見るようになります (それは他の@var{iospec}によって
19208 ファイル等にリダイレクトされているかもしれません)。
19209
19210 @code{<&}の処理の順番について、下の方にある註も参照してください。
19211 @c COMMON
19212
19213 @item (> @var{fd} @var{sink})
19214 @itemx (>> @var{fd} @var{sink})
19215 @c EN
19216 @var{sink} must be either a string, a symbol, a keyword @code{:null},
19217 an integer or a file output port.
19218
19219 If it is a string, it names a file. The output of the child to
19220 the file descriptor @var{fd} is written to the file.
19221 If the named file already exists, @code{>} first truncates its
19222 content, while @code{>>} appends to the existing content.
19223
19224 For other arguments, @code{>} and @code{>>} works the same.
19225
19226 If @var{sink} is a symbol, an unidirectional pipe is created
19227 whose writer end is connected to the child's @var{fd}, and whose
19228 reader end is available as an input port returned by
19229 @code{(process-output @var{process} @var{sink})}.
19230
19231 If @var{sink} is @code{:null}, child's @var{fd} is connected
19232 to the system's null device.
19233
19234 If @var{sink} is an integer, it must specify a parent's file
19235 descriptor opened for output. The child sees the duped file descriptor
19236 as @var{fd}.
19237
19238 If @var{sink} is an output port, the underlying file descriptor is
19239 duped into @var{fd} in the child process.
19240 @c JP
19241 @var{sink}は文字列、シンボル、キーワード@code{:null}、整数、あるいは
19242 ファイル出力ポートでなければなりません。
19243
19244 文字列の場合、それはファイル名です。指定されたファイルが書き込み用にオープンされ、
19245 子プロセスのファイルディスクリプタ@var{fd}からそこに書き込むことができます。
19246 指定のファイルが既に存在している場合、@code{>}はファイルをまず空にするのに対し、
19247 @code{>>}はファイルの後に追加します。
19248 @code{>}と@code{>>}の違いが出るのは@var{sink}がファイルの場合のみです。
19249
19250 @var{sink}がシンボルなら、一方向のパイプが作られ、その入力端が
19251 子プロセスの@code{fd}へと繋がれます。パイプに送られた子プロセスの出力を
19252 読み出す入力ポートは、
19253 @code{(process-output @var{process} @var{sink})}で得ることができます。
19254
19255 @var{sink}が@code{:null}なら、@var{fd}はシステムのヌルデバイスへの
19256 書き出しになります。
19257
19258 整数の場合、それは現プロセスの書き込み用ファイルディスクリプタを
19259 指定します。それが@code{dup}されて子プロセスの@var{fd}となります。
19260
19261 出力ポートの場合は、出力先のファイルディスクリプタが@code{dup}されて
19262 子プロセスの@var{fd}になります。ファイルディスクリプタを持たないポートを渡した
19263 場合はエラーになります(@ref{Common port operations}の@code{port-file-number}参照)。
19264 @c COMMON
19265
19266 @item (>& @var{fd0} @var{fd1})
19267 @c EN
19268 Makes child process's file descriptor @var{fd0} refer to the same output
19269 as its file descriptor @var{fd1}. Note the difference from @code{>};
19270 @code{(> 2 1)} makes the child's stderr go to parent's stdout,
19271 while @code{(>& 2 1)} makes the child's stderr go to the same
19272 output as child's stdout (which may be redirected by another @var{iospec}).
19273 @c JP
19274 子プロセスのファイルディスクリプタ@var{fd0}が、子プロセスのファイルディスクリプタ@var{fd1}
19275 が参照するのと同じ出力先を参照するようにします。
19276 @var{>}との違いに注意: @code{(> 2 1)}は子プロセスのstderrが現プロセスのstdout
19277 と同じところに送られるようにするのに対し、@code{(>& 2 1)}は子プロセスのstderr
19278 が子プロセスのstdoutに送られます (それは別の@var{iospec}によってリダイレクト
19279 されているかもしれません)。
19280 @c COMMON
19281
19282 @example
19283 @c EN
19284 ;; Read both child's stdout and stderr
19285 @c JP
19286 ;; 子プロセスのstdoutとstderrを一緒にして読み込む
19287 @c COMMON
19288 (let1 p (run-process '(command arg)
19289 :redirects '((>& 2 1) (> 1 out)))
19290 (begin0 (port->string (process-output p 'out))
19291 (process-wait p)))
19292 @end example
19293
19294 @end table
19295
19296 @c EN
19297 Note: You can't use the same name (symbol) more than once for
19298 the pipe of source or sink. For example, the following code
19299 signals an error:
19300 @c JP
19301 註: 入力元や出力先にパイプを使う場合、同じ名前(シンボル)を複数の入出力に
19302 指定することはできません。例えば次のコードはエラーとなります。
19303 @c COMMON
19304 @example
19305 (run-process '(command) :redirects '((> 1 out) (> 2 out))) ; error!
19306 @end example
19307 @c EN
19308 You can use @code{>&} to ``merge'' the output to one sink,
19309 or @code{<&} to ``split'' the input from one source, instead:
19310 @c JP
19311 複数の出力を一つの出力先にマージするには@code{>&}を、
19312 一つの入力元を複数の入力で読み込みには@code{<&}を使ってください。
19313 @c COMMON
19314 @example
19315 (run-process '(command) :redirects '((> 1 out) (>& 2 1)))
19316 @end example
19317 @c EN
19318 It is allowed to give the same file name more than once,
19319 just like the Unix shell. However, note that the file is
19320 opened individually for each file descriptor, so simply
19321 writing to them may not produce desired result (for regular
19322 files, most likely that one output would overwrite another).
19323 @c JP
19324 同じファイル名を複数の入出力に指定することは、Unixのシェル同様、可能です。
19325 ただしその場合、ファイルはそれぞれの入出力ごとに別々にオープンされる
19326 ことに注意してください。例えば同じファイルを複数の出力からオープンして
19327 書き込んだ場合、求める結果が得られないかもしれません(通常のファイルであれば、
19328 一方の出力がもう一方の出力を上書きしてしまうでしょう)。
19329 @c COMMON
19330
19331 @c EN
19332 Note: I/O redirections are processed @emph{at once}, unlike the way
19333 unix shell does. For example, both of the following expression
19334 works the same way, that is, they redirect
19335 both stdout and stderr to a file @file{out}.
19336 @c JP
19337 註: I/Oリダイレクト指定は、unixのシェルと違って、
19338 全て@emph{同時に}処理されます。つまり、以下の式はどちらも同じように、
19339 stdoutとstderrをファイル@file{out}に書き出す処理となります。
19340 @c COMMON
19341
19342 @example
19343 (run-process '(command arg) :redirects '((>& 2 1) (> 1 "out")))
19344 (run-process '(command arg) :redirects '((> 1 "out") (>& 2 1)))
19345 @end example
19346
19347 @c EN
19348 Most unix shells process redirections @emph{in order}, so the following
19349 two command line works differently: The first one redirects child's
19350 stderr to the @emph{current} stdout, which is the same as the parent's
19351 stdout, then redirects child's stdout to a file @file{out}. So the
19352 error messages appear in the parent's stdout. The second one first
19353 redirects the child's stdout to a file @file{out}, so at the time
19354 of processing @code{2>&1}, the child's stderr also goes to the file.
19355 @c JP
19356 unixのシェルではリダイレクト指定は@emph{順に}処理されるので、
19357 次の二つのコマンドラインは異なる動作となります。最初の例では
19358 子プロセスのstderrが@emph{現時点での}stdout (それは現プロセスのstdoutでもある)
19359 へと向けられ、次に子プロセスのstdoutがファイル@file{out}に向けられます。
19360 従ってエラーメッセージは現プロセスのstdoutへと現れます。二番目の例では
19361 最初に子プロセスのstdoutがファイル@file{out}へ向けられるので、
19362 @code{2>&1}が処理される時にはstderrの行き先はやはり@file{out}となります。
19363 @c COMMON
19364
19365 @example
19366 $ command arg 2>&1 1>out
19367 $ command arg 1>out 2>&1
19368 @end example
19369
19370 @c EN
19371 You can say @code{do-process} and
19372 @code{run-process} always works like the latter,
19373 regardless of the order in @var{redirects} argument.
19374
19375 If you want to redirect child's stderr to parent's stdout,
19376 you can use @code{>} like the following:
19377 @c JP
19378 @code{do-process}と
19379 @code{run-process}は@var{redirects}引数の順番にかかわらず
19380 常に後者のように動作すると言ってもよいでしょう。
19381
19382 もし前者の例のように子プロセスのstderrだけを親プロセスのstdoutに
19383 向けたいのであれば、次のように@code{>}を使うことで実現できます。
19384 @c COMMON
19385
19386 @example
19387 (run-process '(command arg) :redirects '((> 2 1) (> 1 "out")))
19388 @end example
19389
19390 @end deftp
19391
19392
19393 @deftp {Subprocess argument} input @var{source}
19394 @deftpx {Subprocess argument} output @var{sink}
19395 @deftpx {Subprocess argument} error @var{sink}
19396 @c EN
19397 Redirects child's standard i/o.
19398 @var{source} and @var{sink} may be either a string, one
19399 of keywords @code{:null}, @code{:pipe}, or @code{merge},
19400 an integer file descriptor, or a symbol.
19401
19402 These are really shorthand notations of the @var{redirects} argument:
19403 @c JP
19404 サブプロセスの標準入出力を制御します。
19405 @var{source}及び@var{sink}は、文字列、キーワード @code{:pipe}、
19406 @code{:null}、@code{:merge}、整数のファイルディスクリプタ、もしくはシンボルです。
19407
19408 実のところ、これらは@var{redirects}引数の略記にすぎません。
19409 @c COMMON
19410
19411 @example
19412 :input x @equiv{} :redirects '((< 0 x))
19413 :output x @equiv{} :redirects '((> 1 x))
19414 :error x @equiv{} :redirects '((> 2 x))
19415 @end example
19416
19417 @c EN
19418 The keyword @code{:pipe} as @var{source} or @var{sink} is supported
19419 just for the backward compatibility. They work as if a symbol
19420 @code{stdin}, @code{stdout} or @code{stderr} is given, respectively:
19421 @c JP
19422 キーワード@code{:pipe}は互換性のためだけにサポートされています。
19423 それぞれ、シンボル@code{stdin}、@code{stdout}、@code{stderr}が
19424 指定されたかのように振る舞います。
19425 @c COMMON
19426
19427 @example
19428 :input :pipe @equiv{} :redirects '((< 0 stdin))
19429 :output :pipe @equiv{} :redirects '((> 1 stdout))
19430 :error :pipe @equiv{} :redirects '((> 2 stderr))
19431 @end example
19432
19433 @c EN
19434 That is, a pipe is created and its one end is connected to the
19435 child process's stdio, and the other end is available
19436 by calling @code{(process-input @var{process})},
19437 @code{(process-output @var{process})} or @code{(process-error @var{process})}.
19438 (That is because @code{process-input} and @code{process-output}
19439 uses @code{stdin} and @code{stdout} respectively when @var{name} argument
19440 is omitted, and @code{(process-error p)} is equivalent
19441 to @code{(process-output p 'stderr)}.)
19442 @c JP
19443 すなわち、パイプが作成され、その一方が子プロセスの標準入出力のいずれかに接続されます。
19444 もう一方の端は@code{(process-input @var{process})}、
19445 @code{(process-output @var{process})}および
19446 @code{(process-error @var{process})}によって得ることができます。
19447 (@code{process-input}, @code{process-output}は@var{name}引数が
19448 省略されるとそれぞれ@code{stdin}, @code{stdout}をデフォルトとし、
19449 また@code{(process-error p)}は@code{(process-output p 'stderr)}と
19450 等価だからです)
19451 @c COMMON
19452
19453 @c EN
19454 The keyword @code{:merge} can only be used for @code{:error} keyword
19455 argument, and it is a shorthand notation of
19456 @code{:redirects '((>& 2 1))}, that is, merge the child process's
19457 stderr into child process's stdout.
19458 @c JP
19459 キーワード@code{:merge}は@code{:error}キーワード引数のみに有効で、
19460 @code{:redirects '((>& 2 1))}の略記になります。
19461 すなわち、子プロセスのstderrを子プロセスのstdoutにマージします。
19462 @c COMMON
19463
19464 @c EN
19465 See the description of @var{redirects} above for the meanings
19466 of the argument values.
19467 @c JP
19468 引数の意味の詳しい説明については上の@var{redirects}の項を参照してください。
19469 @c COMMON
19470 @end deftp
19471
19472
19473 @c EN
19474 @subsubheading Execution environment
19475 @c JP
19476 @subsubheading 実行環境
19477 @c COMMON
19478
19479 @deftp {Subprocess argument} environment @var{env-list}
19480 @c EN
19481 The argument must be @code{#f} (default) or a list of strings,
19482 each of which has the form @code{@var{NAME}=@var{VALUE}}.
19483 If it is @code{#f}, the subprocess inherits the same environment
19484 variables as the current process. If it is a list of strings,
19485 it specifies the environment variables the subprocess sees.
19486 The form is the same as what @code{sys-environ} returns, so you
19487 can easily add to/remove from the current environment
19488 (@pxref{Environment inquiry}).
19489 @c JP
19490 引数は@code{#f}(デフォルト)もしくは文字列のリストでなければなりません。
19491 文字列のリストの場合、各文字列は@code{@var{NAME}=@var{VALUE}}という形式でなければなりません。
19492 これが@code{#f}の場合、子プロセスは現在のプロセスの環境変数を引き継ぎます。
19493 文字列のリストの場合であれば、それが子プロセスの環境変数を指定します。
19494 この形式は@code{sys-environ}が返すものと同じなので、
19495 容易に現在の環境変数に環境変数を加えたり取り除いたりすることができます
19496 (@ref{Environment inquiry}参照)。
19497 @c COMMON
19498 @end deftp
19499
19500 @deftp {Subprocess argument} directory @var{directory}
19501 @c EN
19502 If a string is given to @var{directory},
19503 the process starts with @var{directory} as its working directory.
19504 If @var{directory} is @code{#f}, this argument is ignored.
19505 An error is signaled if @var{directory} is other type of objects,
19506 or it is a string but is not a name of a existing directory.
19507
19508 When @var{host} keyword argument is also given, this argument
19509 specifies the working directory of the @emph{remote} process.
19510
19511 Note: @code{do-process} and
19512 @code{run-process} check the validity of @var{directory},
19513 but actual @code{chdir(2)} is done just before @code{exec(2)},
19514 and it is possible that @code{chdir} fails in spite of previous
19515 checks. At the moment when @code{chdir} fails, there's no
19516 reliable way to raise an exception to the caller,
19517 so it writes out an error message to standard error port and exits.
19518 A robust program may take this case into account.
19519 @c JP
19520 @var{directory}に文字列が与えられた場合、
19521 そのディレクトリが起動されるプロセスのワーキングディレクトリとなります。
19522 @code{#f}が与えられた場合はの引数は何もしません。
19523 文字列か@code{#f}以外が与えられた場合、もしくは文字列が存在するディレクトリの
19524 名前でない場合はエラーが報告されます。
19525
19526 @var{host}キーワード引数も与えられている場合、この引数は
19527 リモートプロセスのワーキングディレクトリを指定します。
19528
19529 註: @code{do-process}と
19530 @code{run-process}は@var{directory}が有効な値であることを事前に
19531 チェックしますが、実際の@code{chdir(2)}は@code{exec(2)}の直前に
19532 行われます。事前のチェックにもかかわらず@code{chdir}が失敗する可能性が
19533 あります。その時点では呼び出し元にエラーを伝える
19534 確実な方法が無いため、Gaucheは標準エラー出力にメッセージを印字して
19535 exitします。頑健なプログラムを書く場合、そのようなケースにも留意して下さい。
19536 @c COMMON
19537 @end deftp
19538
19539
19540 @deftp {Subprocess argument} sigmask @var{mask}
19541 @c EN
19542 @var{Mask} must be either an instance of @code{<sys-sigset>},
19543 a list of integers, or
19544 @code{#f}. If an instance of @code{<sys-sigset>} is given, the
19545 signal mask of executed process is set to it. A list of integers
19546 are treated as a list of signals to mask. It is important
19547 to set an appropriate mask if you call @code{run-process} from
19548 multithreaded application.
19549 See the description of @code{sys-exec} (@ref{Process management})
19550 for the details.
19551
19552 If the @var{host} keyword argument is specified, this argument
19553 merely sets the signal mask of the local process (@code{ssh}).
19554 @c JP
19555 @var{mask}は@code{<sys-sigset>}のインスタンス、整数のリスト、
19556 あるいは@code{#f}でなければなりません。
19557 @code{<sys-sigset>}のインスタンスである場合、それが実行する
19558 プロセスのシグナルマスクになります。整数のリストの場合は各整数が
19559 マスクすべきシグナル番号とみなされます。マルチスレッドアプリケーションで
19560 @code{run-process}を使う場合はシグナルマスクを適切に設定することが重要です。
19561 @code{sys-exec}の説明を参照して下さい (@ref{Process management})。
19562
19563 @var{host}キーワード引数が与えられている場合は、この引数は
19564 ローカル側のプロセス(@code{ssh})のみのシグナルマスクをセットします。
19565 @c COMMON
19566 @end deftp
19567
19568 @deftp {Subprocess argument} detached @var{flag}
19569 @c EN
19570 When a true value is given, the new process is detached from
19571 the parent's process group and belongs to its own group.
19572 It is useful when you run a daemon process.
19573 See @code{sys-fork-and-exec} (@pxref{Process management}), for
19574 the detailed description of @var{detached} argument.
19575 @c JP
19576 真の値が渡されると、作られるプロセスは親プロセスのプロセスグループから
19577 切り離され、独自のプロセスグループを作ります。
19578 デーモンプロセスを作る際に便利です。@var{detached}引数の詳しい動作については、
19579 @code{sys-fork-and-exec} を見てください (@ref{Process management}参照)。
19580 @c COMMON
19581 @end deftp
19582
19583
19584 @deftp {Subprocess argument} host @var{hostspec}
19585 @c EN
19586 This argument is used to execute @var{command} on the remote host.
19587 The full syntax of @var{hostspec} is @code{protocol:user@@hostname:port},
19588 where @var{protocol:}, @var{user@@}, or @var{:port} part can be
19589 omitted.
19590
19591 The @var{protocol} part specifies the protocol to communicate
19592 with the remote host; currently only @code{ssh} is supported, and
19593 it is also the default when @var{protocol} is omitted.
19594 The @var{user} part specifies the login name of the remote host.
19595 The @var{hostname} specifies the remote host name, and the
19596 @var{port} part specifies the alternative port number which
19597 @var{protocol} connects to.
19598
19599 The command line arguments are interpreted on the remote host.
19600 On the other hand, the I/O redirection is done on the local end.
19601 For example, the following code reads the file @file{/foo/bar} on
19602 the remote machine and copies its content into the local file
19603 @file{baz} in the current working directory.
19604 @c JP
19605 この引数は、@var{command}をリモートホストで実行させるのに使います。
19606 @var{hostspec}の完全な構文は@code{protocol:user@@hostname:port}で、
19607 @var{protocol:}、@code{user@@}、@code{:port}の部分は省略可能です。
19608
19609 @var{protocol}はリモートに接続するプロトコルを指定します。現在のところ
19610 @code{ssh}だけがサポートされており、また省略された場合も@code{ssh}が
19611 使われます。@var{user}はリモートでのユーザ名を、@var{hostname}は
19612 リモートホスト名を指定します。@var{port}は@var{protocol}のデフォルト
19613 以外のポートを使いたい場合に指定します。
19614
19615 コマンドライン引数はリモートホスト上で解釈されます。
19616 一方、I/Oリダイレクトはローカル側で処理されす。
19617 例えば、次のコードはリモートマシンの@file{/foo/bar}の内容を読み、
19618 それをローカルのワーキングディレクトリ内のファイル@file{baz}へとコピーします。
19619 @c COMMON
19620
19621 @example
19622 (do-process '(cat "bar")
19623 :host "remote-host.example.com"
19624 :directory "/foo"
19625 :output "baz")
19626 @end example
19627 @end deftp
19628
19629 @node Running process pipeline, Process object, Running subprocess, High-level process interface
19630 @subsection Running process pipeline
19631 @c NODE プロセスパイプラインの実行
19632
19633 @defun do-pipeline commands :key input output error directory sigmask on-abnormal-exit
19634 @defunx run-pipeline commands :key input output error wait directory sigmask
19635 @c MOD gauche.process
19636 @c EN
19637 Convenience routines to run pipeline of processes at once.
19638 Example:
19639 @c JP
19640 複数のプロセスでパイプラインを構成するための便利関数です。例:
19641 @c COMMON
19642
19643 @example
19644 (do-pipeline '((ls "src/")
19645 (grep "\\.c$")
19646 (wc -l)))
19647 @end example
19648
19649 @c EN
19650 This is equivalent to shell command pipeline
19651 @code{ls src/ | grep '\.c$' | wc -l}, i.e. shows the
19652 number of C source files in the @file{src} subdirectory.
19653 @c JP
19654 これはシェルのコマンドでのパイプライン@code{ls src/ | grep '\.c$' | wc -l}
19655 と同等で、@file{src}ディレクトリにあるCソースファイルの数を数えます。
19656 @c COMMON
19657
19658 @c EN
19659 The @var{commands} argument is a list of lists. Each list
19660 must be @code{cmd/args} argument @code{do-process}/@code{run-process} can accept.
19661 At least one command must be specified.
19662 @c JP
19663 @var{commands}引数はリストのリストです。
19664 それぞれの内側のリストは
19665 @code{do-process}/@code{run-process}が受け付ける@code{cmd/args}
19666 の形式でなければなりません。少なくともひとつのコマンドが指定される必要があります。
19667 @c COMMON
19668
19669 @c EN
19670 The specified commands will run concurrently, with the stdout of
19671 the first command is connected to the stdin of the second, and
19672 stdout of the second to the stdin of the third, and so on.
19673 The stdin of the first command is fed from the source specified
19674 by the @var{input} keyword argument, and the stdout of the last
19675 command is sent to the sink specified by the @var{output} keyword
19676 argument. The default values of these are the calling process's
19677 stdin and stdout, respectively. See @code{do-process}/@code{run-process},
19678 for the possible values of these arguments
19679 (@pxref{Running subprocess}).
19680 @c JP
19681 指定されたコマンドは、最初のコマンドのstdoutが次のコマンドのstdinに、
19682 そのコマンドのstdoutがさらに次のコマンドのstdinに、@dots{}という具合に
19683 接続されてから、全てが並行して実行されます。
19684 最初のコマンドのstdinは@var{input}キーワード引数で指定された入力から供給され、
19685 最後のコマンドのstdoutは@var{output}キーワード引数で指定された出力へと流れます。
19686 これらのキーワード引数の省略時の値は、呼び出すプロセスのstdinとstdoutです。
19687 これらキーワード引数に与えられる値については
19688 @code{do-process}/@code{run-process}の項を見てください
19689 (@ref{Running subprocess})。
19690 @c COMMON
19691
19692 @c EN
19693 The stderr of all the processes are sent to the sink specified
19694 by the @var{error} keyword argument, which is defaulted by the
19695 calling process's stderr.
19696 @c JP
19697 全てのプロセスのstderrは@var{stderr}キーワード引数で指定される出力へと流されます。
19698 省略時は呼び出すプロセスのstderrが使われます。
19699 @c COMMON
19700
19701 @c EN
19702 Like @code{do-process}, @code{do-pipeline} waits for completion of
19703 all the processes, and returns @code{#t} if the tail process
19704 succeeds (i.e. exits with zero status) or @code{#f} if the last process
19705 fails (i.e. exits with non-zero status). If you give
19706 @code{:error} to @code{on-abnormal-exit} keyword arguments, however,
19707 a failure of the tail process raises an error.
19708 Exit statuses of subprocesses other than the tail one are
19709 collected by @code{process-wait}, but won't affect the
19710 return value, and won't cause an error even
19711 @code{on-abnormal-exit} is @code{:error}.
19712 @c JP
19713 @code{do-process}と同じように、@code{do-pipeline}は全てのプロセスの終了を待ち、
19714 パイプライン末尾のプロセスが成功した(終了ステータスが0)場合に@code{#t}を、
19715 失敗した(終了ステータスが0以外)場合に@code{#f}を返します。
19716 ただし、@code{on-abnormal-exit}キーワード引数に@code{:error}を渡した場合は、
19717 末尾のプロセスが失敗した場合にエラーが投げられます。
19718 末尾以外のプロセスの終了ステータスは@code{process-wait}によって回収されますが、
19719 返り値には影響を与えず、
19720 失敗した場合に@code{on-abnormal-exit}引数が@code{:error}であってもエラーは投げられません。
19721 @c COMMON
19722
19723 @c EN
19724 On the other hand, @code{run-pipeline} returns a @code{<process>} object of
19725 the tail process. You can get other process objects in
19726 the pipeline by applying @code{process-upstreams} to the tail process.
19727 By default, @code{run-pipeline} runs all the subprocesses in background
19728 and returns immediately. Calling @code{process-wait} on the returned
19729 process object will waits for all the subprocesses.
19730 If you give a true value to @var{wait} keyword argument,
19731 @code{run-process} waits for all the subprocesses to finish
19732 before returning.
19733 @c JP
19734 一方、@code{run-pipeline}は末尾のプロセスの@code{<process>}オブジェクトを返します。
19735 パイプライン中の他のプロセスは末尾プロセスに@code{process-upstreams}
19736 を適用すれば得られます。
19737 デフォルトでは、@code{run-pipeline}は全てのサブプロセスをバックグラウンドで起動して
19738 直ちに戻ってきます。返り値の末尾プロセスに対して@code{process-wait}を呼ぶと、
19739 全てのサブプロセスが終了するまで待ちます。
19740 @var{wait}キーワード引数に真の値を渡した場合は、
19741 @code{run-process}は全てのサブプロセスの終了を待ってから戻ります。
19742 @c COMMON
19743
19744 @c EN
19745 The @var{directory} and @var{sigmask} keyword arguments are applied
19746 to all the processes;
19747 see @code{do-process}/@code{run-process} for the description
19748 of these arguments
19749 (@pxref{Running subprocess}).
19750 @c JP
19751 @var{directory}と@var{sigmask}キーワード引数は全てのプロセスに適用されます。
19752 これらの引数の説明は@code{do-process}/@code{run-process}の項を見てください
19753 (@ref{Running subprocess})。
19754 @c COMMON
19755
19756 @c EN
19757 Note: In Gauche 0.9.5, we introduced @code{run-process-pipeline}. It is similar
19758 to the current @code{run-pipeline} but returns a list of subprocess objects
19759 instead of a single one. We realized it's not very convenient, so we
19760 deprecated @code{run-process-pipeline} and replaced it with @code{run-pipeline}.
19761 We still support @code{run-process-pipeline}, but strongly recommend
19762 to move to @code{run-pipeline} as soon as possible.
19763 @c JP
19764 註: Gauche 0.9.5で、@code{run-process-pipeline}というAPIを導入しました。
19765 これは現在の@code{run-pipeline}に似ていますが、起動したプロセスのリストを返します。
19766 しかし使い勝手が悪いことがわかったので、@code{run-process-pipeline}は非推奨とし、
19767 @code{run-pipeline}で置き換えることにしました。
19768 @code{run-process-pipeline}もしばらくサポートされますが、
19769 できるだけ早く@code{run-pipeline}に移行してください。
19770 @c COMMON
19771 @end defun
19772
19773
19774 @node Process object, Process ports, Running process pipeline, High-level process interface
19775 @subsection Process object
19776
19777 @deftp {Class} <process>
19778 @clindex process
19779 @c MOD gauche.process
19780 @c EN
19781 An object to keep the status of a child process. You can create
19782 the process object by @code{run-process} procedure described below.
19783 The process ports explained in the next section also use process objects.
19784 @c JP
19785 子プロセスの状態を保持するためのオブジェクト。以下で説明される
19786 @code{run-process} 手続きにより、プロセスを作ることができます。
19787 次章で説明するプロセスポートもプロセスオブジェクトを用いています。
19788 @c COMMON
19789
19790 @c EN
19791 The @code{<process>} class keeps track of
19792 the child processes spawned by high-level APIs such
19793 as @code{run-process} or @code{open-input-process-port}.
19794 The exit status of such children must be collected by
19795 @code{process-wait} or @code{process-wait-any} calls,
19796 which also do some bookkeeping. Using
19797 the low-level process calls such as @code{sys-wait} or
19798 @code{sys-waitpid} directly will cause inconsistent state.
19799 @c JP
19800 @code{<process>}クラスは、@code{run-process}や@code{open-input-process-port}
19801 といった高レベルAPIで作られた子プロセスの状態を管理しています。
19802 それらの子プロセスの終了ステータスをとるには、
19803 @code{process-wait}や@code{process-wait-any}といった
19804 高レベルAPIを利用してください。これらの手続きはシステムコール以外の情報管理も
19805 行います。@code{sys-wait}や@code{sys-waitpid}といった低レベルAPIで
19806 直接子プロセスの終了ステータスを取ると、@code{<process>}クラスの
19807 内部状態に矛盾が生じます。
19808 @c COMMON
19809 @end deftp
19810
19811 @deftp {Class} <process-abnormal-exit>
19812 @clindex process-abnormal-exit
19813 @c MOD gauche.process
19814 @c EN
19815 A condition type mainly used by the process port utility procedures.
19816 Inherits @code{<error>}. This type of condition is thrown when
19817 the high-level process port utilities detect the child process exited
19818 with non-zero status code.
19819 @c JP
19820 主にプロセスポートユーティリティ関数で使われるコンディション型。
19821 @code{<error>}を継承。このコンディション型は高レベルプロセスポートユーティ
19822 リティが子プロセスが非ゼロのexitステータスで終了したことを検知したとき
19823 に投げられます。
19824 @c COMMON
19825
19826 @defivar {<process-abnormal-exit>} process
19827 @c EN
19828 A process object.
19829 @c JP
19830 プロセスオブジェクト。
19831 @c COMMON
19832 @end defivar
19833
19834 @c EN
19835 Note: In Unix terms, exiting a process by calling @code{exit(2)} or
19836 returning from @code{main()} is a normal exit, regardless of the
19837 exit status. Some commands do use non-zero exit status
19838 to tell one of the normal results of execution (such as @code{grep(1)}).
19839 However, large number of commands uses non-zero exit status to
19840 indicate that they couldn't carry out the required operation,
19841 so we treat them as exceptional situations.
19842 @c JP
19843 注: Unix用語では,exitステータスにかかわらず,プロセスがcalling
19844 @code{exit(2)}を呼ぶか,@code{main()}から帰った場合を「正常な終了」と
19845 しています。コマンドによっては非ゼロのexitステータスで何らかの正常な実行結果を
19846 示すものもあります(@code{grep(1)}など)。しかし,ほとんどのコマ
19847 ンドでは,非ゼロの exit ステータスは要求された操作が実行できなかったこ
19848 とを表わします。それゆえ上のような場合を例外的な場合として扱います。
19849 @c COMMON
19850 @end deftp
19851
19852
19853 @defun process? obj
19854 @c MOD gauche.process
19855 @equiv{} @code{(is-a? @var{obj} <process>)}
19856 @end defun
19857
19858 @deffn {Method} process-pid (process <process>)
19859 @c MOD gauche.process
19860 @c EN
19861 Returns the process ID of the subprocess @var{process}.
19862 @c JP
19863 サブプロセス @var{process} のプロセスIDを返します。
19864 @c COMMON
19865 @end deffn
19866
19867 @deffn {Method} process-command (process <process>)
19868 @c MOD gauche.process
19869 @c EN
19870 Returns the command invoked in the subprocess @var{process}.
19871 @c JP
19872 サブプロセス @var{process} 内で起動されたコマンドを返します。
19873 @c COMMON
19874 @end deffn
19875
19876 @deffn {Method} process-input (process <process>) :optional name
19877 @deffnx {Method} process-output (process <process>) :optional name
19878 @c MOD gauche.process
19879 @c EN
19880 Retrieves one end of a pipe, whose another end is connected
19881 to the process's input or output, respectively.
19882 @var{name} is a symbol given to the @var{redirects} argument
19883 of @code{run-process} to distinguish the pipe. See the following
19884 example:
19885 @c JP
19886 プロセスの入力もしくは出力に一方の端がつながれたパイプの、もう一方の端を取り出します。
19887 @var{name}は@code{run-process}の@var{redirects}引数に与えた
19888 識別用の名前です。次の例を見てください。
19889 @c COMMON
19890
19891 @example
19892 (let1 p (run-process '(command arg)
19893 :redirects '((< 3 aux-in)
19894 (> 4 aux-out)))
19895 (let ([auxin (process-input p 'aux-in)]
19896 [auxout (process-output p 'aux-out)])
19897 ;; feed something to the child's input
19898 (display 'something auxin)
19899 ;; read data from the child's output
19900 (read-line auxout)
19901 @dots{}
19902 )
19903 (process-wait p))
19904 @end example
19905
19906 @c EN
19907 The symbols @code{aux-in} and @code{aux-out} is used to
19908 identify the pipes. Note that @code{process-input} returns
19909 @emph{output} port, and @code{process-output} returns
19910 @emph{input} port.
19911 @c JP
19912 シンボル@code{aux-in}と@code{aux-out}がパイプを識別するのに
19913 使われています。@code{process-input}が返すのは@emph{出力}ポートであり、
19914 @code{process-output}が返すのは@emph{入力}ポートであることに注意してください。
19915 @c COMMON
19916
19917 @c EN
19918 When @var{name} is omitted, @code{stdin} is used for @code{process-input}
19919 and @code{stdout} is used for @code{process-output}. These are
19920 the names used if child's stdin and stdout are redirected by
19921 @code{:input :pipe} and @code{:output :pipe} arguments, respectively.
19922 @c JP
19923 @var{name}が省略された場合、@code{process-input}は@code{stdin}を、
19924 @code{process-output}は@code{stdout}を使います。これらは
19925 子プロセスの標準入力/出力をそれぞれ@code{:input :pipe}/@code{:output :pipe}で
19926 リダイレクトした場合に使われる名前です。
19927 @c COMMON
19928
19929 @c EN
19930 If there's no pipe with the given name, @code{#f} is returned.
19931 @c JP
19932 名前に対応するパイプが無い場合は@code{#f}が返ります。
19933 @c COMMON
19934
19935 @example
19936 (let* ((process (run-process '("date") :output :pipe))
19937 (line (read-line (process-output process))))
19938 (process-wait process)
19939 line)
19940 @result{} "Fri Jun 22 22:22:22 HST 2001"
19941 @end example
19942
19943 @c EN
19944 If @var{process} is a result of @code{run-pipeline},
19945 @code{(process-input process)} and @code{(process-input process 'stdin)}
19946 behave slightly differently---they return the pipe connected to the
19947 stdin of the @emph{head} process of the pipeline, not the
19948 process represented by @var{process} (which is the tail of the pipeline).
19949 This allows you to treat the whole pipeline as one entity.
19950 @c JP
19951 @var{process}が@code{run-pipeline}の結果であった場合、
19952 @code{(process-input process)}と@code{(process-input process 'stdin)}は
19953 少し違う振る舞いをします。
19954 @var{process}自体はプロセスパイプラインの末尾のプロセスを表していますが、
19955 上記二つの呼び出しに限り、
19956 プロセスパイプラインの先頭のプロセスのstdinにつながれたパイプを返します。
19957 これによって、パイプライン全体をひとまとめに扱うことができます。
19958 @c COMMON
19959
19960 @example
19961 (let1 p (run-pipeline `((cat)
19962 (grep "aba"))
19963 :input :pipe :output :pipe)
19964 (display "banana\nhabana\ntabata\ncabara\n"
19965 (process-input p)) ; head of the pipeline
19966 (close-port (process-input p))
19967 (process-wait p)
19968 (port->string (process-output p)))
19969 @result{} "habana\ntabata\ncabara\n"
19970 @end example
19971
19972 @c EN
19973 If you want to connect one process's output to another process's input
19974 without using @code{do-pipeline}/@code{run-pipeline}, you need to have
19975 coroutine or thread that actively reads from one process's output
19976 and feed it to another process's input. You can use a plumbing
19977 in @code{control.plumbing}
19978 (@pxref{Plumbing ports}) to do so easily. Plumbing also allows
19979 you to ``tap'' the pipe, i.e. to monitor the data that flows
19980 between processes.
19981 @c JP
19982 もし@code{do-pipeline}/@code{run-pipeline}を使わずに
19983 一つのプロセスの出力を別のプロセスの入力につなげたい場合、
19984 何らかのコルーチンかスレッドで一つのプロセスの出力をアクティブに読んで
19985 もう一つのプロセスの入力へと送ることが必要になります。
19986 @code{control.plumbing}を使えばそれは簡単にできます
19987 (@ref{Plumbing ports}参照)。また、流れるデータをモニタするといったことも可能です。
19988 @c COMMON
19989 @end deffn
19990
19991
19992 @deffn {Method} process-error (process <process>)
19993 @c MOD gauche.process
19994 @c EN
19995 This is equivalent to @code{(process-output @var{process} 'stderr)}.
19996 @c JP
19997 これは@code{(process-output @var{process} 'stderr)}と等価です。
19998 @c COMMON
19999 @end deffn
20000
20001 @defun process-alive? process
20002 @c MOD gauche.process
20003 @c EN
20004 Returns true if @var{process} is alive. Note that Gauche can't
20005 know the subprocess' status until it is explicitly checked by
20006 @code{process-wait}.
20007 @c JP
20008 @var{process} が生きている場合は真を返します。@code{process-wait} によって
20009 明示的にチェックされない限り、Gauche はサブプロセスのステータスを知ることが
20010 できないことに注意してください。
20011 @c COMMON
20012 @end defun
20013
20014 @defun process-upstreams process
20015 @c MOD gauche.process
20016 @c EN
20017 If @var{process} is the result of @code{run-pipeline}, this returns
20018 a list of processes that are upstream of @var{process} in the pipeline.
20019 If @var{process} is not the result of @code{run-pipeline}, this returns
20020 an empty list.
20021 @c JP
20022 @var{process}が@code{run-pipeline}の結果であった場合、
20023 パイプライン中で@var{process}の上流にあるプロセスのリストが返ります。
20024 @var{process}が@code{run-pipeline}の結果でなかった場合は空リストが返ります。
20025 @c COMMON
20026
20027 @example
20028 (define p (run-pipeline `((cat) (grep "ho") (wc)) :input :pipe))
20029
20030 p @result{} #<process 20658 "wc" active>
20031
20032 (process-upstreams p)
20033 @result{} (#<process 20656 "cat" active> #<process 20657 "grep" active>)
20034 @end example
20035 @end defun
20036
20037 @defun process-list
20038 @c MOD gauche.process
20039 @c EN
20040 Returns a list of active processes. The process remains active
20041 until its exit status is explicitly collected by @code{process-wait}.
20042 Once the process's exit status is collected and its state changed
20043 to inactive, it is removed from the list @code{process-list} returns.
20044 @c JP
20045 アクティブなプロセスのリストを返します。プロセスは、その終了ステータスが
20046 @code{process-wait} によって明示的に回収されない場合は、アクティブなまま
20047 残ります。
20048 ひとたび終了ステータスが回収され、プロセスの状態がインアクティブに
20049 変更されると、そのプロセスは@code{process-list}が返すリストからは除かれます。
20050 @c COMMON
20051 @end defun
20052
20053 @defun process-wait process :optional nohang error-on-nonzero-status
20054 @c MOD gauche.process
20055 @c EN
20056 Obtains the exit status of the subprocess @var{process}, and stores it
20057 to @var{process}'s status slot. The status can be obtained by
20058 @code{process-exit-status}.
20059
20060 This suspends execution until @var{process} exits by default.
20061 However, if a true value is given to the optional argument @var{nohang},
20062 it returns immediately if @var{process} hasn't exit.
20063
20064 If a true value is given to the optional argument
20065 @var{error-on-nonzero-status}, and the obtained status code is not zero,
20066 this procedure raises @code{<process-abnormal-exit>} error.
20067
20068 Returns @code{#t} if this call actually obtains the exit status,
20069 or @code{#f} otherwise.
20070 @c JP
20071 サブプロセス @var{process} の終了ステータスを取得し、@var{process}
20072 のstatusスロットに値を格納します。statusスロットの値は
20073 @code{process-exit-status}で得ることができます。
20074
20075 デフォルトでは、この手続きは@var{process} が終了するまで実行を一時停止します。
20076 しかし、@var{nohang}に真の値が与えられた場合は、@var{process}が終了して
20077 いない場合にも直ちに返ります。
20078
20079 オプショナル引数@var{error-on-nonzero-status}に真の値が与えられた場合、
20080 この手続きは得られた終了ステータスが0で無い場合に
20081 @code{<process-abnormal-exit>}エラーを投げます。
20082
20083 この呼び出しによって@var{process}の終了ステータスが実際に取得された場合は
20084 @code{#t}を、そうでなければ@code{#f}を返します。
20085 @c COMMON
20086
20087 @c EN
20088 If the process object is created by @code{run-pipeline}
20089 (@pxref{Running process pipeline}), @code{process-wait} waits
20090 @emph{all} of the subprocesses in the pipeline, not just the last one,
20091 unless true value is given to the @var{nohang} argument.
20092 However, @var{error-on-nonzero-status} only affects to the status
20093 of @var{process}, which represents the last process in the pipeline;
20094 if an other subprocess exits with nonzero status, it is stored in
20095 its respective process objects, but won't cause a fuss.
20096
20097 If you specify a true value to @var{nohang} for the pipelined
20098 process, @code{process-wait} still
20099 probes other subprocesses in the pipeline and updates exit statuses
20100 of terminated ones, but doesn't wait unterminated subprocesses.
20101 The unterminated subprocesses should be waited individually, or
20102 by @code{process-wait-any}, to collect their exit statuses.
20103 @c JP
20104 プロセスオブジェクトが@code{run-pipeline}によって作られたものである場合、
20105 @code{process-wait}は、@var{nohang}に真の値が与えられなければ、
20106 パイプラインに関わる全てのサブプロセスの終了を待ちます。
20107 但し、@var{error-on-nonzero-status}は@var{process}引数、すなわちパイプラインの
20108 最後のプロセスにしか効力を持ちません。その他のサブプロセスがステータス0以外で終了
20109 したとしても、その事実は各サブプロセスのプロセスオブジェクトに記録されるだけで、
20110 エラーは通知されません。
20111
20112 パイプラインのプロセスに対して@var{nohang}に真の値を指定した場合、
20113 @code{process-wait}はパイプラインの上流のプロセスに対しても終了のチェックを
20114 行い、終了していた場合は対応するプロセスオブジェクトの終了ステータスを更新しますが、
20115 終了していないサブプロセスについてはそのままにします。
20116 それらのサブプロセスの終了ステータスを回収するには、それぞれのプロセスオブジェクト
20117 について@code{process-wait}を発行するか、下の@code{process-wait-any}を使います。
20118 @c COMMON
20119 @end defun
20120
20121 @defun process-wait-any :optional nohang
20122 @c MOD gauche.process
20123 @c EN
20124 Obtains the exit status of any of the subprocesses created by
20125 @code{run-process}.
20126 Returns a process object whose exit status is collected.
20127
20128 If a true value is given to the optional argument @var{nohang}, this procedure
20129 returns @code{#f }immediately even if no child process has exit.
20130 If @var{nohang} is omitted or
20131 @code{#f}, this procedure waits for any of children exits.
20132
20133 If there's no child processes, this procedure immediately returns @code{#f}.
20134 @c JP
20135 @code{run-process}で作られたサブプロセスのどれかの終了ステータスを取得します。
20136 終了ステータスが取得できたプロセスのプロセスオブジェクトを返します。
20137
20138 真の値が@var{nohang}に与えられた場合は、どの子プロセスも終了していない場合は
20139 直ちに@code{#f}を返します。そうでなければ、この手続きはいずれかの子プロセスが
20140 終了するまで待ちます。
20141
20142 子プロセスが存在しない場合は、この手続きは直ちに@code{#f}を返します。
20143 @c COMMON
20144 @end defun
20145
20146 @defun process-wait/poll process :key interval max-wait continue-test raise-error?
20147 @c MOD gauche.process
20148 @c EN
20149 Polls wait status of @var{process} periodically, sleeping
20150 @var{interval} nanoseconds (default 2e6 ns, i.e. 2ms) between each poll.
20151 It returns as soon as it finds the process has exitted and its status is
20152 retrieved.
20153
20154 If @var{max-wait} is given and not @code{#f}, it species maximum duration
20155 in nanoseconds to keep polling. Once the duration expires, the procedure
20156 gives up and return. If it is not given or @code{#f},
20157 the procedure keeps polling until the process exits.
20158
20159 The @var{continue-test}, if given and not @code{#f}, must be a procedure
20160 that takes one argument, poll count. It is called after each unsuccessul
20161 polling (that is, the process hasn't been exitted), and the argument begins
20162 with 0 and incretemented for each callback. The procedure can return
20163 @code{#f} to give up polling. When it returns a true value, polling continues.
20164
20165 The @var{raise-error?} argument is the same as @code{process-wait}; an
20166 error is raised if @var{process}'s exit status isn't zero.
20167
20168 The procedure returns @code{#t} if the process exitted, and @code{#f} if
20169 it has given up. The process's exit status should be retrieved
20170 with @code{process-exit-status} from @var{process}.
20171 @c JP
20172 @var{process}の終了ステータスを、@var{interval}ナノ秒間隔でポーリングします
20173 (デフォルトは2e6ns=2msです)。@var{process}が終了していることを見つけたら
20174 終了ステータスを回収して直ちに戻ります。
20175
20176 @var{max-wait}が指定されて@code{#f}でなければ、それはポーリングを続ける期間の
20177 最大値をナノ秒単位で指定します。その期間が過ぎたら、この手続きは諦めて戻ります。
20178 指定されないか@code{#f}の場合は、プロセスが終了するまでポーリングしつづけます。
20179
20180 @var{continue-test}が与えられて@code{#f}でなければ、
20181 それは1引数の手続きでなければなりません。
20182 ポーリングでプロセスが終了してなかったら、その度にこの手続きが呼ばれます。
20183 引数はポーリングした回数で、0から始まりポーリングの度に1つづつ増えてゆきます。
20184 この手続きが@code{#f}を返したら、その時点でポーリングは打ちきられ
20185 @code{process-wait/poll}は直ちに戻ります。
20186 真の値を返したらポーリングは継続されます。
20187
20188 @var{raise-error?}は@code{process-wait}と同じで、
20189 @var{process}の終了ステータスが0でなければエラーを投げます。
20190
20191 戻り値は、プロセスが終了してステータスを回収できれば@code{#t}、
20192 途中で諦めた場合は@code{#f}となります。終了ステータス自体は
20193 @var{process}から@code{process-exit-status}で読み出してください。
20194 @c COMMON
20195 @end defun
20196
20197
20198 @defun process-exit-status process
20199 @c MOD gauche.process
20200 @c EN
20201 Returns exit status of @var{process} retrieved by @code{process-wait}.
20202 If this is called before @code{process-wait} is called on @var{process},
20203 the result is undefined.
20204
20205 The meaning of exit status depends on the platform. You need to
20206 use @code{sys-wait-exited?} or @code{sys-wait-signaled?} to
20207 see if it is terminated voluntarily or by a signal, and
20208 use @code{sys-wait-exit-status} or @code{sys-wait-termsig}
20209 to extract the exit code or the terminating signal
20210 (@pxref{Process management}).
20211 @c JP
20212 @code{process-wait}によって取得された@var{process}の終了ステータスを
20213 返します。@var{process}に対して@code{process-wait}を呼ぶ前にこの手続きを
20214 呼んだ場合の結果は未定義です。
20215
20216 終了ステータスの解釈はプラットフォームに依存します。プロセスが自発的に
20217 (@code{exit}を呼んで)終了したか、それともシグナルによって終了させられたかを
20218 確かめるには@code{sys-wait-exited?}か@code{sys-wait-signaled?}を
20219 使ってください。また、終了コードもしくは終了と原因となったシグナルを
20220 知るには@code{sys-wait-exit-status}を@code{sys-wait-termsig}
20221 使ってください (@ref{Process management}参照)。
20222 @c COMMON
20223 @end defun
20224
20225 @defun process-send-signal process signal
20226 @c MOD gauche.process
20227 @c EN
20228 Sends a signal @var{signal} to the subprocess @var{process}.
20229 @var{signal} must be an exact integer for signal number.
20230 @xref{Signal}, for predefined variables of signals.
20231 @c JP
20232 サブプロセス @var{process} にシグナル @var{signal} を送ります。
20233 @var{signal} は正確整数のシグナルナンバーでなければなりません。
20234 シグナルの定義済み変数については、@ref{Signal}を参照して下さい。
20235 @c COMMON
20236 @end defun
20237
20238 @defun process-kill process
20239 @defunx process-stop process
20240 @defunx process-continue process
20241 @c MOD gauche.process
20242 @c EN
20243 Sends SIGKILL, SIGSTOP and SIGCONT to @var{process}, respectively.
20244 @c JP
20245 それぞれ、@var{process} に、SIGKILL、SIGSTOP、SIGCONT を送ります。
20246 @c COMMON
20247 @end defun
20248
20249 @defun process-shutdown process :key ask ask-interval ask-retry signals signal-interval
20250 @c EN
20251 Tries to terminate @var{process} in the gradually escalating means.
20252 @c JP
20253 @var{process}を、徐々に強力な方法を使って終了させようとします。
20254 @c COMMON
20255
20256 @c EN
20257 The @var{ask} argument is, if not @code{#f}, a procedure taking one argument,
20258 the retry count. The @var{ask} procedure is responsible to interact with
20259 @var{process} in a proper protocol (e.g. send @code{exit} command via
20260 comminucation channel). After @var{ask} is executed (the return value
20261 is ignored), the process's status is monitored, and
20262 @code{process-shutdown} returns @code{#t} as soon as the
20263 process exits. If the process doesn't exit, the procedure repeats
20264 calling @var{ask} up to @var{retry} times, with @var{ask-interval} nanoseconds
20265 delay inbetween, incrementing the retry count
20266 argument. If @var{ask} argument is @code{#f}, this step is skipped.
20267 The default value of @var{ask} is @code{#f}, @var{ask-interval} is
20268 50e6 ns (50ms), and @var{ask-retry} is 1.
20269 @c JP
20270 @var{ask}引数は、@code{#f}でなければ、試行回数を引数にとる手続きでなければなりません。
20271 @var{ask}手続きは@var{process}に何らかの方法で作用して終了を試みるものです
20272 (例えば、通信チャネルから@code{exit}コマンドを送る等)。
20273 @var{ask}を呼び出し後(戻り値は捨てられます)、プロセスの状態が検査され、
20274 プロセスがexitしたら直ちに@code{process-shutdown}は@code{#t}を返します。
20275 プロセスがすぐにexitしなければ、@var{ask-interval}ナノ秒おきに@var{ask}手続きが
20276 最大@var{retry}回まで呼び出されます。@var{ask}に渡される引数は呼び出しの度に
20277 インクリメントされます。
20278 @var{ask}引数に@code{#f}が渡された場合、このステップは省かれます。
20279 省略時のデフォルト値は、@var{ask}が@code{#f}、@var{ask-interval}が50e6 ns (50ms)、
20280 @var{ask-retry}が1です。
20281 @c COMMON
20282
20283 @c EN
20284 If the first step fails, this procedure starts sending signals.
20285 The process's status is checked every time after a signal is sent.
20286 As soon as the process exists, @code{process-shutdown}
20287 returns @code{#t}.
20288 The sequence of signals is specified by @var{signals} argument,
20289 and the interval of sending signals is specified by @var{signal-interval}
20290 argument. The default value of @var{signals} is
20291 @code{(list SIGTERM SIGTERM SIGKILL)}, and @var{singal-interval} is
20292 50e6 ns (50ms).
20293 @c JP
20294 最初のステップでプロセスが止まらなければ、次にシグナルを送り始めます。
20295 シグナルが送られるたびにプロセスの状態が検査され、終了していれば直ちに
20296 @code{process-shutdown}は@code{#t}を返します。
20297 どのシグナルが送られるかは@var{signals}引数で決まり、
20298 またシグナルを送る間隔は@var{signal-interval}で指定されます。
20299 @var{signals}のデフォルト値は@code{(list SIGTERM SIGTERM SIGKILL)}、
20300 @var{signal-interval}のデフォルト値は50e6 ns (50ms)です。
20301 @c COMMON
20302
20303 @c EN
20304 If all the measures fail, @code{#f} is returned.
20305 @c JP
20306 全てを試みてもまだプロセスが終了していなければ、@code{#f}が返されます。
20307 @c COMMON
20308
20309 @c EN
20310 (Hint: If you wants to keep sending signals until the process really
20311 exits, you can pass a circular list to the @var{signals}.)
20312 @c JP
20313 (ヒント: プロセスが終了するまでシグナルを送りつづけたければ、
20314 @var{signals}に循環リストを渡すことで実現できます)
20315 @c COMMON
20316 @end defun
20317
20318 @node Process ports, Process connection, Process object, High-level process interface
20319 @subsection Process ports
20320
20321 @defun open-input-process-port command :key input error encoding conversion-buffer-size
20322 @c MOD gauche.process
20323 @c EN
20324 Runs @var{command} asynchronously in a subprocess. Returns
20325 two values, an input port which is connected to the stdout of the
20326 running subprocess, and a process object.
20327 @c JP
20328 @var{command} を子プロセスで非同期に実行します。
20329 走らせた子プロセスの標準出力につながれた入力ポートと、
20330 プロセスオブジェクトの二つの値を返します。
20331 @c COMMON
20332
20333 @c EN
20334 @var{Command} can be a string, a list of command name and arguments,
20335 or a list of lists of command name and arguments.
20336
20337 If it is a string, it is passed to @code{/bin/sh}.
20338 You can use shell metacharacters in this form, such as
20339 environment variable interpolation, globbing, and redirections.
20340 If you create the command line by concatenating strings,
20341 it's your responsibility to ensure escaping special characters
20342 if you don't want the shell to interpret them.
20343 The @code{shell-escape-string} function in @code{text.sh} might
20344 be a help (@pxref{Shell text utilities}).
20345 @c JP
20346 @var{command}は文字列か、コマンド名と引数のリストか、「コマンド名と引数のリスト」のリストです。
20347
20348 文字列の場合、それは@code{/bin/sh}に渡されます。
20349 環境変数の置換やグロブパターン、リダイレクトなどのシェルの機能が
20350 文字列中で使えます。
20351 文字列をつなぎ合わせてコマンドラインを作成する場合、
20352 特殊文字をシェルに解釈してほしくなければ、それを正しくエスケープするのは
20353 呼び出し元の責任です。@code{text.sh}の@code{shell-escape-string}は
20354 助けになるかもしれません(@ref{Shell text utilities}参照)。
20355 @c COMMON
20356
20357 @c EN
20358 If @var{command} is a list (but not a list of lists),
20359 each element is converted to a
20360 string by @code{x->string} and then passed directly to @code{sys-exec}
20361 (the @code{car} of the list is used as both the command path
20362 and the first element of argv, i.e. @code{argv[0]}).
20363 Use this form if you want to avoid the shell from interfering;
20364 i.e. you don't need to escape special characters.
20365 @c JP
20366 @var{command}がリスト(ただしリストのリストではない)の場合は、
20367 各要素が@code{x->string}で文字列に
20368 変換された後に、@code{sys-exec}を使って直接コマンドを起動します
20369 (リストの@code{car}がコマンドのパス名と@code{argv[0]}の両方に使われます)。
20370 シェルの介入を避けたい場合はこの形式を使うと良いでしょう。
20371 特殊文字をエスケープする必要はありません。
20372 @c COMMON
20373
20374 @c EN
20375 The subprocess's stdin is redirected from @code{/dev/null},
20376 and its stderr shares the calling process's stderr by default.
20377 You can change these by giving file pathnames to @var{input} and
20378 @var{error} keyword arguments, respectively.
20379 @c JP
20380 デフォルトでは、子プロセスの標準入力は@code{/dev/null}にリダイレクトされ、
20381 標準エラー出力は呼び出したプロセスと共有されます。
20382 @var{input}と@var{error}キーワード引数にパス名を与えることで、
20383 これらの出力をリダイレクトすることができます。
20384 @c COMMON
20385
20386 @c EN
20387 If @var{command} is a list of lists, it creates a command pipeline,
20388 as in @code{run-pipeline} (@pxref{Running process pipeline}).
20389 Each inner list should consists of a command path, followed by command-line
20390 arguments. They are applied on @code{x->string} before passed to
20391 @code{sys-exec}.
20392 The stdout of the last command is available from the returned input port,
20393 and the stdin of the first command is provided by @var{input} keyword
20394 arguments, or @code{/dev/null} by default. The stderr of all the commands
20395 goes to @var{error} keyword arguments if given, or shared with
20396 the caller process's stderr.
20397 @c JP
20398 @var{command}がリストのリストの場合は、コマンドパイプラインが作られます
20399 (@code{run-pipeline}, @ref{Running process pipeline}参照)。
20400 内側のリストは、コマンドパスとそのコマンドへの引数で、@code{x->string}で文字列に
20401 変換された後、@code{sys-exec}に渡されます。
20402 最後のコマンドの標準出力を、返されるポートから読み出すことができます。
20403 最初のコマンドの標準入力は、@var{input}キーワード引数にパス名が渡されれば
20404 そのファイルから、そうでなければ@code{/dev/null}から供給されます。
20405 各コマンドの標準エラー出力は、@var{error}キーワード引数にパス名が渡されればそのファイルに、
20406 そうでなければ呼び出したプロセスの標準エラー出力に流れます。
20407 @c COMMON
20408
20409 @c EN
20410 You can also give the @var{encoding} keyword argument
20411 to specify character encoding of the process output. If it is
20412 other than @code{utf-8},
20413 @code{open-input-process-port} inserts a character encoding
20414 conversion port.
20415 If @var{encoding} is given, the @var{conversion-buffer-size} keyword
20416 argument can control the conversion buffer size.
20417 See @ref{Character code conversion}, for
20418 the details of character encoding conversions.
20419 @c JP
20420 また、プロセスの出力の文字エンコーディングを指定するために
20421 @var{encoding}キーワード引数を与えることもできます。
20422 それが@code{utf-8}でなければ、
20423 @code{open-input-process-port}は文字コード変換ポートを挿入します。
20424 @var{encoding}が与えられた場合、@var{conversion-buffer-size}キーワード引数で
20425 変換バッファの大きさを指定することも可能です。文字コード変換の詳細については
20426 @ref{Character code conversion}を参照して下さい。
20427 @c COMMON
20428 @example
20429 (receive (port process) (open-input-process-port "ls -l Makefile")
20430 (begin0 (read-line port)
20431 (process-wait process)))
20432 @result{} "-rw-r--r-- 1 shiro users 1013 Jun 22 21:09 Makefile"
20433
20434 (receive (port process) (open-input-process-port '(ls -l "Makefile"))
20435 (begin0 (read-line port)
20436 (process-wait process)))
20437 @result{} "-rw-r--r-- 1 shiro users 1013 Jun 22 21:09 Makefile"
20438
20439 (open-input-process-port "command 2>&1")
20440 @result{} ;@r{the port reads both stdout and stderr}
20441
20442 (open-input-process-port "command 2>&1 1>/dev/null")
20443 @result{} ;@r{the port reads stderr}
20444 @end example
20445 @c EN
20446 The exit status of subprocess is not automatically collected.
20447 It is the caller's responsibility to issue @code{process-wait},
20448 or the subprocess remains in a zombie state. If it bothers you,
20449 you can use one of the following functions.
20450 @c JP
20451 サブプロセスの終了ステータスは自動的に回収されません。
20452 @code{process-wait} を呼ぶことは呼び出し側の責任であり、これを怠ると
20453 サブプロセスはゾンビプロセスになります。それが面倒であれば、以下の
20454 手続きを使うことができます。
20455 @c COMMON
20456 @end defun
20457
20458 @defun call-with-input-process command proc :key input error encoding conversion-buffer-size on-abnormal-exit
20459 @c MOD gauche.process
20460 @c EN
20461 Runs @var{command} in a subprocess and pipes its stdout
20462 to an input port, then call @var{proc} with the port as an argument.
20463 When @var{proc} returns, it collects its exit status,
20464 then returns the result @var{proc} returned.
20465 The cleanup is done even if @var{proc} raises an error.
20466
20467 The keyword argument @var{on-abnormal-exit} specifies what happens
20468 when the child process exits with non-zero status code.
20469 It can be either @code{:error} (default), @code{:ignore},
20470 @code{#f}, or a procedure that takes one argument. If it is @code{:error},
20471 a @code{<process-abnormal-exit>} error condition is thrown by
20472 non-zero exit status; the @code{process} slot of the condition
20473 holds the process object. If it is @code{:ignore}, nothing is done
20474 for non-zero exit status. If it is @code{#f}, the result of
20475 @var{proc} is discarded and @code{#f} is returned.
20476 If it is a procedure, it is called with
20477 a process object; when the procedure returns, @code{call-with-input-process}
20478 returns normally.
20479
20480 Note that @var{on-abnormal-exit} differs from @code{do-process}
20481 (@pxref{Running subprocess}). We want finer control over the situation
20482 than merely check if the subprocess is succeeded or failed.
20483
20484 The semantics of @var{command} and other keyword arguments are the same
20485 as @code{open-input-process-port} above.
20486 @c JP
20487 子プロセスで@var{command} を実行し、その標準出力と入力ポートを
20488 パイプで繋ぎ、そのポートを引数として @var{proc} を呼び出します。
20489 @var{proc} が返るとその終了ステータスを回収し、@var{proc} が返した
20490 結果を返します。@var{proc} がエラーを通知しても、クリーンアップは
20491 行われます。
20492
20493 キーワード引数@var{on-abnormal-exit}は子プロセスが0以外の終了ステータス
20494 を返した場合の振舞いを指定します。その値は@code{:error}(デフォルト)、
20495 @code{:ignore}、@code{#f}、もしくは一引数の手続きでなければなりません。
20496 値が@code{:error}の場合、0以外の終了ステータスは
20497 @code{<process-abnormal-exit>}エラーコンディションを発生させます。
20498 コンディションオブジェクトの@code{process}スロットには子プロセスオブジェクトが
20499 保持されます。値が@code{:ignore}の場合、0以外の終了ステータスに対して
20500 特別なアクションは取られません。値が@code{#f}の場合、プロセスの終了ステータスが
20501 0以外であれば、@var{proc}の結果は捨てられ、@code{#f}が返されます。
20502 値が手続きの場合、0以外の終了ステータスに対して
20503 子プロセスオブジェクトを引数にしてその手続きが呼ばれます。その手続きが
20504 戻れば、@code{call-with-input-process}は正常動作と同じように戻ります。
20505
20506 @var{on-abnormal-exit}の意味が@code{do-process}とは異なることに注意してください
20507 (@ref{Running subprocess}参照)。この手続きを使う場合は、
20508 単にサブプロセスの成功/失敗を知るだけでなく、より細かな制御を必要とする場合が多いからです。
20509
20510 @var{command}および他のキーワード引数の意味は@code{open-input-process-port}と
20511 同じです。
20512 @c COMMON
20513 @example
20514 (call-with-input-process "ls -l *"
20515 (lambda (p) (read-line p)))
20516 @end example
20517 @end defun
20518
20519 @defun with-input-from-process command thunk :key input error encoding conversion-buffer-size on-abnormal-exit
20520 @c MOD gauche.process
20521 @c EN
20522 Runs @var{command} in a subprocess, and calls @var{thunk}
20523 with its current input port connected to the command's stdout.
20524 The command is terminated and its exit status is collected,
20525 after @var{thunk} returns or raises an error.
20526
20527 The semantics of @var{command} and keyword arguments are the same
20528 as @code{call-with-input-process} above.
20529 @c JP
20530 子プロセスで @var{command} を実行し、コマンドの標準出力に
20531 接続された現在の入力ポートとともに @var{thunk} を呼び出します。
20532 @var{thunk}が終了するかエラーを投げた後に、コマンドの終了ステータスが
20533 回収されます。
20534
20535 @var{command}およびキーワード引数の意味は@code{call-with-input-process}と
20536 同じです。
20537 @c COMMON
20538 @example
20539 (with-input-from-process "ls -l *" read-line)
20540 @end example
20541 @end defun
20542
20543 @defun open-output-process-port command :key output error encoding conversion-buffer-size
20544 @c MOD gauche.process
20545 @c EN
20546 Runs @code{command} in a subprocess asynchronously. Returns two values,
20547 an output port which is connected to the stdin of the subprocess.
20548 and the process object.
20549
20550 The semantics of @var{command} is the same as
20551 @code{open-input-process-port}. The semantics of
20552 @var{encoding} and @var{conversion-buffer-size} are also the same.
20553
20554 The subprocess's stdout is redirected to @code{/dev/null} by default,
20555 and its stderr shares the calling process's stderr.
20556 You can change these by giving file pathnames to @var{output} and
20557 @var{error} keyword arguments, respectively.
20558
20559 The exit status of the subprocess is not automatically collected.
20560 The caller should call @code{process-wait} on the subprocess
20561 at appropriate time.
20562 @c JP
20563 子プロセスで @code{command} を非同期に実行します。
20564 子プロセスの標準入力に接続された出力ポートと、
20565 プロセスオブジェクトの二つの値を返します。
20566
20567 @var{command}引数、および@var{encoding}と@var{conversion-buffer-size}の
20568 意味は、@code{open-input-process-port}と同じです。
20569
20570 デフォルトでは、子プロセスの標準出力は@code{/dev/null}にリダイレクトされ、
20571 標準エラー出力は呼び出したプロセスと共有されます。
20572 @var{output}と@var{error}キーワード引数にパス名を与えることで、
20573 これらの出力をリダイレクトすることができます。
20574
20575 サブプロセスの終了ステータスは自動的には回収されません。
20576 適切なタイミングで、サブプロセスに対して @code{process-wait} を呼ぶ
20577 必要があります。
20578 @c COMMON
20579 @end defun
20580
20581 @defun call-with-output-process command proc :key output error encoding conversion-buffer-size on-abnormal-exit
20582 @c MOD gauche.process
20583 @c EN
20584 Runs @code{command} in a subprocess, and calls @var{proc}
20585 with an output port which is connected to the stdin of the command.
20586 The exit status of the command is collected after either @var{proc}
20587 returns or raises an error.
20588
20589 The semantics of keyword arguments are the same as
20590 @code{open-output-process-port}, except @var{on-abnormal-exit},
20591 which is the same as described in @code{call-with-input-process}.
20592 @c JP
20593 @code{command} を子プロセスで実行し、コマンドの標準入力に
20594 接続された出力ポートとともに @var{proc} を呼び出します。
20595 コマンドの終了ステータスは、@var{proc} が返るかエラーを通知した
20596 後に回収されます。
20597
20598 キーワード引数の意味は@var{open-output-process-port}と同じです。
20599 ただし@var{on-abnormal-exit}については@code{call-with-input-process}
20600 で説明したのと同じ意味です。
20601 @c COMMON
20602 @example
20603 (call-with-output-process "/usr/sbin/sendmail"
20604 (lambda (out) (display mail-body out)))
20605 @end example
20606 @end defun
20607
20608 @defun with-output-to-process command thunk :key output error encoding conversion-buffer-size on-abnormal-exit
20609 @c MOD gauche.process
20610 @c EN
20611 Same as @code{call-with-output-process}, except that the
20612 output port which is connected to the stdin of the command
20613 is set to the current output port while executing @var{thunk}.
20614 @c JP
20615 コマンドの標準入力に接続された出力ポートが、@var{thunk} の実行中は
20616 現在の出力ポートにセットされることを除いて、@code{call-with-output-process}
20617 と同じです。
20618 @c COMMON
20619 @end defun
20620
20621 @defun call-with-process-io command proc :key error encoding conversion-buffer-size on-abnormal-exit
20622 @c MOD gauche.process
20623 @c EN
20624 Runs @var{command} in a subprocess, and calls @var{proc}
20625 with two arguments; the first argument is an input port which
20626 is connected to the command's stdout, and the second is an output
20627 port connected to the command's stdin. The error output from
20628 the command is shared by the calling process's, unless
20629 an alternative pathname is given to the @var{error} keyword argument.
20630
20631 The exit status of the command is collected when @var{proc}
20632 returns or raises an error.
20633 @c JP
20634 @var{command} をサブプロセスで実行し、@var{proc} を2つの引数と
20635 ともに呼び出します。最初の引数は入力ポートで、コマンドの標準出力に
20636 接続されたものです。2番目の引数は出力ポートでコマンドの標準入力に
20637 接続されたものです。コマンドからのエラー出力は、@var{error}キーワード
20638 引数でパス名が指定されない限り、呼び出したプロセスのエラー出力が共有されます。
20639
20640 コマンドの終了ステータスは、@var{proc}が戻るかエラーを投げた場合に
20641 回収されます。
20642 @c COMMON
20643 @end defun
20644
20645 @defun process-output->string command :key error encoding conversion-buffer-size on-abnormal-exit
20646 @defunx process-output->string-list command :key error encoding conversion-buffer-size on-abnormal-exit
20647 @c MOD gauche.process
20648 @c EN
20649 Runs @var{command} and collects its output (to stdout) and returns them.
20650 @code{process-output->string} concatenates all the output from @var{command}
20651 to one string, replacing any sequence of whitespace characters to
20652 single space. The action is similar to ``command substitution''
20653 in shell scripts.
20654 @code{process-output->string-list} collects the output from
20655 @var{command} line-by-line and returns the list of them. Newline
20656 characters are stripped.
20657 @c JP
20658 @var{command} を実行し、その(標準出力への)出力を回収して返します。
20659 @code{process-output->string} は @var{command} からの全ての出力を連結し
20660 1つの文字列とします。その際、空白文字からなるシーケンスは1つの空白に
20661 置換されます。このアクションは、シェルスクリプトにおける「コマンド置換」
20662 に似たものです。
20663 @code{process-output->string-list} は @var{command} からの出力を行ごとに
20664 回収し、それらをリストにしたものを返します。改行文字は削除されます。
20665 @c COMMON
20666
20667 @c EN
20668 Internally, @var{command} is run by @code{call-with-input-process},
20669 to which keyword arguments are passed.
20670 @c JP
20671 内部的には、@var{command} は @code{call-with-input-process} により
20672 実行されます。キーワード引数は@code{call-with-input-process}に
20673 そのまま渡されます。
20674 @c COMMON
20675
20676 @c EN
20677 If you want to use this just like shell's command substituion,
20678 specifying @code{:on-abnormal-exit :ignore} is usually what you want.
20679 However, if you try another command when one fails,
20680 @code{:on-abnormal-exit #f} may be suitable, for @code{:ignore}
20681 returns empty string when the command fails without producing output.
20682 @c JP
20683 シェルのコマンド置換と同じように使いたい場合、
20684 通常は @code{:on-abnormal-exit :ignore} を指定するのが良いでしょう。
20685 ただし、ひとつコマンドを試してそれが失敗したら別のを試す、という場合は
20686 @code{:on-abnormal-exit #f} の方が有用です。@code{:ignore}だと
20687 コマンドが何も出力せず失敗した場合でも空文字列が返るからです。
20688 @c COMMON
20689
20690 @c EN
20691 (Tip: To receive stderr output of the child process in the result as well,
20692 pass @code{:merge} to @code{:error}. See @code{run-process} above
20693 for the details.)
20694 @c JP
20695 (ヒント: 子プロセスのstderr出力も一緒に結果として得たい場合は、
20696 @code{:error}引数に@code{:merge}を渡します。
20697 詳しくは上の@code{run-process}の項を見てください。)
20698 @c COMMON
20699 @example
20700 (process-output->string '(uname -smp))
20701 @result{} "Linux i686 unknown"
20702
20703 (process-output->string '(ls))
20704 @result{} "a.out foo.c foo.c~ foo.o"
20705
20706 (process-output->string-list '(ls))
20707 @result{} ("a.out" "foo.c" "foo.c~" "foo.o")
20708
20709 ;; Suppress error message when the-file doesn't exist:
20710 (process-output->string-list '(cat "the-file") :error :null)
20711
20712 ;; If the-file doesn't exit, want to try another-file:
20713 (any (^[flie] (process-output->string-list `(cat ,file)
20714 :error :null :on-abnormal-exit #f))
20715 '("the-file" "another-file"))
20716 @end example
20717 @end defun
20718
20719 @node Process connection, , Process ports, High-level process interface
20720 @subsection Process connection
20721
20722 @deftp {Class} <process-connection>
20723 @c EN
20724 A connection abstraction to communicate with an external processs.
20725 Inherits @code{<connection>}.
20726 @xref{Connection framework}, for the details of the connection interface.
20727 @c JP
20728 外部プロセスとの通信を@code{<connection>}として見せるクラスです。
20729 コネクションインタフェースについては@ref{Connection framework}を参照してください。
20730 @c COMMON
20731
20732 @c EN
20733 This is useful to give an external process to the code that expects
20734 connection. For example, instead of direct network connection, you can
20735 insert a filter process between remote server and your client code.
20736 @c JP
20737 これを使うとコネクションを期待しているコードに外部プロセスを渡せます。
20738 例えばネットワークと通信する部分を、直接の通信のかわりにリモートサーバの間に
20739 フィルタプロセスを入れる、といったことが簡単にできます。
20740 @c COMMON
20741 @end deftp
20742
20743 @defun make-process-connection process-or-spec
20744 @c EN
20745 Run an external process and returns a connection that's connected
20746 to standard I/O of the process.
20747 @c JP
20748 外部プロセスを起動し、その標準入出力とコネクションとして通信する
20749 コネクションオブジェクトを返します。
20750 @c COMMON
20751
20752 @c EN
20753 You can pass a list of command and its arguments, or
20754 a @code{<process>} object, to the @var{process-or-spec} argument.
20755 If you it's a @code{<process>} object, it's stdin and stdout
20756 must be connected to pipes. If it is a list, it is passed to @code{run-process}
20757 to run a new process.
20758 @c JP
20759 @var{process-or-spec}にはコマンドと引数からなるリストか、
20760 @code{<process>}オブジェクトを渡すことができます。
20761 @code{<process>}オブジェクトならそのプロセスの標準入力と標準出力はパイプに
20762 なっていなければなりません。
20763 リストの場合は、それが@code{run-process}に渡されて新たなプロセスが起動されます。
20764 @c COMMON
20765
20766 @c EN
20767 Shutting down both channels of the connection terminates the process.
20768 Most processes that reads from stdin would exits after it reads EOF
20769 from input, so we just poll the process exit status for a short period of time.
20770 If the process doesn't exit, we send signals (first SIGTERM, then SIGKILL)
20771 to ensure the termination of the process.
20772 @c JP
20773 コネクションの入出力チャネルを両方ともシャットダウンすれば、プロセスは終了します。
20774 多くのプロセスは、標準入力からEOFを読むと終了するので、
20775 まずは標準入力へのチャネルをシャットダウンしてから少し待ちます。
20776 もしそれでプロセスが終了する気配を見せなかった場合、シグナルSIGTERMを送り、
20777 それでも終了しなかったらSIGKILLを送ります。
20778 @c COMMON
20779
20780 @c EN
20781 Merely closing the connection doesn't terminate the process, so that
20782 the forked process can keep talking to the process.
20783 @c JP
20784 コネクションをクローズするだけではプロセスは終了しません。
20785 forkしたプロセスがまだ通信するかもしれないからです。
20786 @c COMMON
20787 @end defun
20788
20789
20790 @c ----------------------------------------------------------------------
20791 @node Record types, Reloading modules, High-level process interface, Library modules - Gauche extensions
20792 @section @code{gauche.record} - Record types
20793 @c NODE レコード型, @code{gauche.record} - レコード型
20794
20795 @deftp {Module} gauche.record
20796 @mdindex gauche.record
20797 @c EN
20798 This module provides a facility to define @emph{record types},
20799 user-defined aggregate types.
20800 The API is upper compatible to SRFI-9 (Defining Record Types) and
20801 SRFI-99 (ERR5RS Records).
20802 @c JP
20803 このモジュールは、@emph{レコード型}、すなわち、ユーザ定義の集合型を定義する機能を提供します。
20804 APIは、SRFI-9 (Defining Record Types) および SRFI-99 (ERR5RS Records)
20805 の上位互換です。
20806 @c COMMON
20807 @end deftp
20808
20809 @c EN
20810 Record types are implemented as Gauche's classes,
20811 but have different characteristics from the general classes.
20812 @xref{Record types introduction}, for when you want to
20813 use record types.
20814 @c JP
20815 レコード型は、Gaucheのクラスとして実装されていますが、
20816 一般的なクラスとは異なる特徴を持っています。
20817 どういった時にレコード型を使うと良いかについては
20818 @ref{Record types introduction}を参照してください。
20819 @c COMMON
20820
20821 @c EN
20822 The record API consists of three layers, following
20823 SRFI-99 and R6RS design.
20824 @c JP
20825 レコードAPIは、SRFI-99およびR6RSの設計に従い、3つの層から構成されています。
20826 @c COMMON
20827
20828 @c EN
20829 The syntactic layer is the @code{define-record-type} macro
20830 that conveniently defines a record type and related procedures
20831 (a constructor, a predicate, accessors and modifiers) all at once
20832 declaratively. Knowing this macro alone is sufficient for
20833 most common usage of records.
20834 @c JP
20835 構文層は、@code{define-record-type}マクロで、レコード型と関連する手続き
20836 (コンストラクタ、述語、アクセサ、モディファイア)を、
20837 一括して宣言的に定義します。このマクロを知っているだけで、
20838 ほとんどの一般的なレコードの使用方法においては十分です。
20839 @c COMMON
20840
20841 @c EN
20842 The inspection layer defines common procedures
20843 to query information to the records and record types.
20844 @c JP
20845 インスペクション層は、レコードおよびレコード型の情報を問い合わせるための
20846 共通の手続きを定義します。
20847 @c COMMON
20848
20849 @c EN
20850 The procedural layer is a low-level machinery to implement
20851 the syntactic layer; you don't usually need to use them
20852 in day-to-day programming, but they might be handy to
20853 create record types on-the-fly at runtime.
20854 @c JP
20855 手続き層は、構文層を実装するための低レベルの機構です。
20856 日常的なプログラミングにおいて使う必用はありませんが、
20857 実行時にその場でレコード型を作成するような場合には便利かもしれません。
20858 @c COMMON
20859
20860 @menu
20861 * Record types introduction::
20862 * Record types syntactic layer::
20863 * Record types inspection layer::
20864 * Record types procedural layer::
20865 * Pseudo record types::
20866 @end menu
20867
20868 @node Record types introduction, Record types syntactic layer, Record types, Record types
20869 @subsection Introduction
20870 @c NODE レコード型のイントロダクション, イントロダクション
20871
20872 @c EN
20873 Gauche provides a general way for users to define new types as new
20874 classes, using object system (@pxref{Object system}), and indeed
20875 record types are implemented as Gauche's classes.
20876 However, using record types instead of classes has several advantages.
20877 @c JP
20878 Gaucheは、オブジェクトシステム(@ref{Object system}参照)により、
20879 新しい型を新しいクラスとして定義する一般的な方法を提供しています。
20880 そして、実際にレコード型はGaucheのクラスとして実装されています。
20881 しかし、クラスではなくレコード型を使うことには、いくつかの利点があります。
20882 @c COMMON
20883
20884 @itemize
20885 @item
20886 @c EN
20887 It is portable. The API conforms two major record SRFIs,
20888 SRFI-9 and SRFI-99, so the code using record types can run on
20889 various Scheme systems.
20890 @c JP
20891 ポータブルであること。 APIは2つの有名なレコードSRFIであるSRFI-9とSRFI-99に適合しています。
20892 このため、レコード型を使用したコードは、様々なSchemeシステム上で動作します。
20893 @c COMMON
20894 @item
20895 @c EN
20896 It is efficient. Record types are less flexibile than classes,
20897 but that allows Gauche to optimize more. Hence creating records and
20898 accessing/modifying them are much faster than creating instances
20899 of general classes and accessing/modifying them. It makes record
20900 types preferable choice when you only need a mechanism to bundle
20901 several related values to carry around, and don't need fancier
20902 mechanisms such as class redefinitions.
20903 @c JP
20904 効率的であること。 レコード型はクラスほど柔軟ではありませんが、
20905 このためGaucheはより最適化を行えます。したがって、レコードを作成し、
20906 それらにアクセス/変更することは、一般的なクラスのインスタンスを作成して、
20907 それらにアクセス/変更することよりも高速に行えます。
20908 いくつかの関連する値をまとめて運用するメカニズムがほしいだけであり、
20909 クラスの再定義のような手の込んだメカニズムが不要な場合には、
20910 レコード型は良い選択肢になります。
20911 @c COMMON
20912 @item
20913 @c EN
20914 As Gauche's extension, you can define pseudo record types,
20915 which interprets ordinary aggregate types such as vectors and lists
20916 as records. (For Common Lisp users; it is like the @code{:type}
20917 option of @code{defstruct}).
20918 This helps flexibility of interface. For example, you can ask
20919 your library's users to pass a point in a vector of three numbers,
20920 instead of asking users to pack their point data into your
20921 custom point record type. Yet inside your library you can
20922 treat the passed data as if it is your point record type.
20923 See @ref{Pseudo record types}, for more details.
20924 @c JP
20925 Gaucheの拡張として、疑似レコード型を定義することができます。
20926 これは、ベクタやリストのような通常の集合型を、レコードとして扱うものです
20927 (Common Lisp ユーザにとっては、@code{defstruct}の@code{:type}が近いものです)。
20928 これは、インタフェースの柔軟性向上に役立ちます。
20929 例えば、あなたのライブラリのユーザに、
20930 独自の座標レコード型に座標データを格納するように依頼するのではなく、
20931 3個の数値を持つベクタを渡すように依頼することができます。
20932 そしてライブラリ内では、渡されたデータを座標レコード型として扱うことができるのです。
20933 詳しくは、@ref{Pseudo record types}を参照してください。
20934 @c COMMON
20935 @end itemize
20936
20937 @c EN
20938 The disadvantage of record types is that
20939 they don't obey Gauche's class redefinition
20940 protocol (@pxref{Class redefinition}).
20941 That is, if you redefine a record with the same name,
20942 it creates a new record type unrelated to the old one.
20943 The record instances created from the old definition
20944 won't be updated according to the new definition.
20945 @c JP
20946 レコード型の欠点は、Gaucheのクラス再定義プロトコル(@ref{Class redefinition}を参照)
20947 を利用できないことです。
20948 すなわち、同じ名前でレコードを再定義すると、
20949 古いものとは無関係の新しいレコード型が作成されます。
20950 古い定義で作成されたレコードのインスタンスは、
20951 新しい定義によって更新されることはありません。
20952 @c COMMON
20953
20954 @c EN
20955 More importantly, record constructors, accessors and modifiers
20956 are tend to be inlined where they are used, to achieve
20957 better performance. Since they are inlined, the code
20958 that uses those procedures are not affected when
20959 the record type is redefined.
20960 This means if you redefine a record type, you have to
20961 reload (recompile) the sources that uses any of
20962 record constructors, accessors or modifiers.
20963 @c JP
20964 さらに重要なこととして、
20965 レコードのコンストラクタ、アクセサ、および、モディファイアは、
20966 パフォーマンス向上のため、使用箇所でインライン展開される傾向があります。
20967 インライン展開により、これらの手続きを使用するコードは、
20968 レコード型が再定義されても影響を受けません。
20969 これは、レコード型を再定義した場合、レコードのコンストラクタ、アクセサ、
20970 または、モディファイアを使用するソースは、
20971 再ロード(再コンパイル)する必用があることを意味します。
20972 @c COMMON
20973
20974
20975 @node Record types syntactic layer, Record types inspection layer, Record types introduction, Record types
20976 @subsection Syntactic Layer
20977 @c NODE レコード型の構文層, 構文層
20978
20979
20980 @defmac define-record-type type-spec ctor-spec pred-spec field-spec @dots{}
20981 [R7RS base][SRFI-9][SRFI-99+]
20982 @c MOD gauche.record
20983 @c EN
20984 Defines a record type, and optionally defines
20985 a constructor, a predicate, and field accessors and modifiers.
20986 @c JP
20987 レコード型を定義し、オプションとしてコンストラクタ、述語、
20988 フィールドのアクセサ、および、モディファイアを定義します。
20989 @c COMMON
20990
20991 @c EN
20992 The @var{type-spec} argument names the record type,
20993 and optionally specifies the supertype (@var{parent}).
20994 @c JP
20995 @var{type-spec}引数は、レコード型に名前を付けます。
20996 また、オプションとしてスーパータイプ(@var{parent})を指定します。
20997 @c COMMON
20998
20999 @example
21000 @var{type-spec} : @var{type-name}
21001 | (@var{type-name} @var{parent} @var{option} @dots{})
21002
21003 @var{type-name} : @r{identifier}
21004 @var{parent} : @r{expression}
21005 @var{option} @dots{} : @r{keyword-value list}
21006 @end example
21007
21008 @c EN
21009 The @var{type-name} identifier will be bound to a
21010 @emph{record type descriptor}, or rtd,
21011 which can be used for introspection and reflection.
21012 See @ref{Record types inspection layer} and @ref{Record types procedural layer}
21013 for possible operations for record types.
21014 In Gauche, a record type descriptor is a @code{<class>} with a metaclass
21015 @code{<record-meta>}.
21016 @c JP
21017 @var{type-name}識別子は、
21018 レコード型記述子(@emph{record type descriptor})すなわちrtdに束縛され、
21019 イントロスペクションやリフレクションのために使用されます。
21020 レコード型に対して可能な操作については、@ref{Record types inspection layer}と
21021 @ref{Record types procedural layer}を参照してください。
21022 Gaucheでは、レコード型記述子は、メタクラス@code{<record-meta>}を持つ
21023 @code{<class>}です。
21024 @c COMMON
21025
21026 @c EN
21027 The @var{parent} expression should evaluate to a record type descriptor.
21028 If given, the defined record type inherits it; that is, all the
21029 slots defined in the parent type are available to the @var{type-name}
21030 as well, and the instance of @var{type-name} answers @code{#t} to the
21031 predicate of the parent type.
21032 @c JP
21033 @var{parent}式は、レコード型記述子に評価されなければなりません。
21034 これが与えられると、定義されるレコード型はそれを継承します。
21035 すなわち、親の型で定義されたすべてのスロットは、
21036 @var{type-name}でも利用可能です。そして、@var{type-name}のインスタンスは、
21037 親の型の述語に対しても@code{#t}を返します。
21038 @c COMMON
21039
21040 @c EN
21041 Since a record type is also a class, parent type is also a superclass
21042 of the defined record type. However, record types are limited to
21043 have single implementation inheritance. The parent type must be
21044 a subclass of @code{<record>}. (You can have abstract classes along
21045 the main inheritance, though. See @var{mixins} below.)
21046 @c JP
21047 レコード型もまたクラスであるため、親の型は定義されるレコード型の
21048 スーパークラスでもあります。
21049 しかし、レコード型には単一継承のみという制限があります。
21050 そして、親の型は@code{<record>}のサブクラスである必要があります。
21051 (ただし、メインの継承に加えて抽象クラスを持つことができます。
21052 下記の@var{mixins}を参照してください。)
21053 @c COMMON
21054
21055 @c EN
21056 You can give a pseudo record base type as @var{parent} to define a
21057 pseudo record type, which allows you to access ordinary aggregates
21058 like vectors as records. See @ref{Pseudo record types} for more details.
21059 @c JP
21060 疑似レコード型を定義するために、疑似レコード型のベースタイプを
21061 @var{parent}に指定することができます。これによって、
21062 ベクタのような通常の集合型を、レコードとしてアクセスできるようになります。
21063 詳しくは、@ref{Pseudo record types}を参照してください。
21064 @c COMMON
21065
21066 @c EN
21067 the @var{option} @dots{} part is Gauche's extension. It must be a
21068 keyword-value list. The following keywords are recognized:
21069 @c JP
21070 @var{option} @dots{} の部分は、Gaucheの拡張になります。それは、
21071 キーワードと値のリストである必要があります。次のキーワードが認識されます。
21072 @c COMMON
21073
21074 @table @asis
21075 @item @code{:mixins} (@var{class} @dots{})
21076 @c EN
21077 Specifies auxiliary superclasses. The classes must be abstract, that is,
21078 must not have slots. It is to implement protocols in the record type,
21079 e.g. @code{<sequence>} (@pxref{Sequence framework}).
21080 @c JP
21081 補助的なスーパークラスを指定します。そのクラスは抽象クラス、すなわち、
21082 スロットを持たないクラスである必要があります。
21083 これは、レコード型でプロトコルを実装するためのものです
21084 (例えば、@code{<sequence>} (@ref{Sequence framework}を参照) 等)。
21085 @c COMMON
21086 @item @code{:metaclass} @var{metaclass}
21087 @c EN
21088 Specifies alternative metaclass. By default, metaclass of record types
21089 is @code{<record-meta>}. If you specify an alternative metaclass,
21090 it must be a subclass of @code{<record-meta>}.
21091 @c JP
21092 メタクラスを変更する場合に指定します。
21093 デフォルトでは、レコード型のメタクラスは@code{<record-meta>}です。
21094 他のメタクラスを指定する場合、それは@code{<record-meta>}のサブクラスである
21095 必用があります。
21096 @c COMMON
21097 @end table
21098
21099 @c EN
21100 The @var{ctor-spec} defines the constructor of the record instance.
21101 @c JP
21102 @var{ctor-spec}は、レコードのインスタンスを作るコンストラクタを定義します。
21103 @c COMMON
21104
21105 @example
21106 @var{ctor-spec} : #f | #t | @var{ctor-name}
21107 | (@var{ctor-name} @var{field-name} @dots{})
21108
21109 @var{ctor-name} : @r{identifier}
21110 @var{field-name} : @r{identifier}
21111 @end example
21112
21113 @c EN
21114 If it is @code{#f}, no constructor is created.
21115 If it is @code{#t}, a default constructor is created with a name
21116 @code{make-@var{type-name}}. If it is a single identifier
21117 @var{ctor-name}, a default constructor is created with the name.
21118 The default constructor takes as many arguments as
21119 the number of fields of the record, including inherited ones if any.
21120 When called, it allocates an instance of the record, and initialize its
21121 fields with the given arguments in the order (inherited fields comes
21122 first), and returns the record.
21123 @c JP
21124 @code{#f}を指定すると、コンストラクタは生成されません。
21125 @code{#t}を指定すると、デフォルトのコンストラクタが@code{make-@var{type-name}}
21126 という名前で生成されます。
21127 単一の識別子@var{ctor-name}を指定すると、デフォルトのコンストラクタが、
21128 その名前で生成されます。
21129 デフォルトのコンストラクタは、レコードのフィールドの数と同じ数の引数を取ります。
21130 これには(もしあれば)継承されたものも含まれます。
21131 これが呼ばれると、レコードのインスタンスを割り当て、そのフィールドを
21132 与えられた引数で順番に(継承されたフィールドが先になります)初期化し、
21133 作成したレコードを返します。
21134 @c COMMON
21135
21136 @c EN
21137 The last variation of @var{ctor-spec} creates a custom
21138 constructor with the name @var{ctor-name}. The custom constructor
21139 takes as many arguments as the given @var{field-name}s, and initializes
21140 the named fields. If the inherited record type has a field of the same name
21141 as the ancestor record type, only the inherited ones are initialized.
21142 In Gauche, uninitialized fields remains unbound until some value is
21143 set to it.
21144 @c JP
21145 @var{ctor-spec}の最後のバリエーションは、
21146 @var{ctor-name}という名前のカスタムコンストラクタを生成します。
21147 カスタムコンストラクタは、指定した@var{field-name}の数と同じ数の引数を取り、
21148 その名前のフィールドを初期化します。
21149 継承されたレコード型が祖先のレコード型と同名のフィールドを持っていた場合には、
21150 継承されたレコード型のものだけが初期化されます。
21151 Gaucheでは、初期化されていないフィールドは、何らかの値がセットされるまでは、
21152 未束縛のままです。
21153 @c COMMON
21154
21155 @c EN
21156 The @var{pred-spec} defines the predicate of the record instance,
21157 which takes one argument and returns @code{#t} iff it is an instance
21158 of the defined record type or its descendants.
21159 @c JP
21160 @var{pred-spec}は、レコードのインスタンスの述語を定義します。
21161 それはひとつの引数を取り、定義されるレコード型、もしくは、その子孫の
21162 インスタンスであるときに@code{#t}を、そうでなければ@code{#f}を返します。
21163 @c COMMON
21164
21165 @example
21166 @var{pred-spec} : #f | #t | @var{pred-name}
21167
21168 @var{pred-name} : @r{identifier}
21169 @end example
21170
21171 @c EN
21172 If it is @code{#f}, no predicate is created.
21173 If it is @code{#t}, a predicate is created with a name
21174 @code{@var{type-name}?}. If it is a single identifier,
21175 a predicate is created with the given name.
21176 @c JP
21177 @code{#f}を指定すると、述語は生成されません。
21178 @code{#t}を指定すると、述語が@code{@var{type-name}?}という名前で生成されます。
21179 単一の識別子を指定すると、述語がその名前で生成されます。
21180 @c COMMON
21181
21182 @c EN
21183 The rest of the arguments specify fields (slots) of the record.
21184 @c JP
21185 残りの引数は、レコードのフィールド(スロット)を定めます。
21186 @c COMMON
21187
21188 @example
21189 @var{field-spec}
21190 : @var{field-name} ; @r{immutable, with default accessor}
21191 | (@var{field-name}) ; @r{mutable, with default accessor/modifier}
21192 | (@var{field-name} @var{accessor-name}); @r{immutable}
21193 | (@var{field-name} @var{accessor-name} @var{modifier-name}); @r{mutable}
21194
21195 @var{field-name} : @r{identifier}
21196 @var{accessor-name} : @r{identifier}
21197 @var{modifier-name} : @r{identifier}
21198 @end example
21199
21200 @c EN
21201 The first and the third forms define immutable fields, which can only
21202 be initialized by the constructor but cannot be modified afterwards
21203 (thus such fields don't have modifiers).
21204 The second and the fourth forms define mutable fields.
21205 @c JP
21206 1番目と3番目の形式は、変更不可のフィールドを定義します。
21207 それは、コンストラクタによる初期化のみが可能であり、
21208 後から変更することはできません
21209 (したがって、そのフィールドは、モディファイアを持ちません)。
21210 2番目と4番目の形式は、変更可能なフィールドを定義します。
21211 @c COMMON
21212
21213 @c EN
21214 The third and fourth forms explicitly name the accessor and modifier.
21215 With the first and second forms, on the other hand,
21216 the accessor is named as
21217 @code{@var{type-name}-@var{field-name}}, and the modifier is named
21218 as @code{@var{type-name}-@var{field-name}-set!}.
21219 @c JP
21220 3番目と4番目の形式は、アクセサとモディファイアの名前を明示的に指定します。
21221 一方、1番目と2番目の形式では、
21222 アクセサは@code{@var{type-name}-@var{field-name}}という名前になり、
21223 モディファイアは@code{@var{type-name}-@var{field-name}-set!}という
21224 名前になります。
21225 @c COMMON
21226 @end defmac
21227
21228 @c EN
21229 Let's see some examples. Here's a definition of a record
21230 type @code{point}.
21231 @c JP
21232 いくつかの例を見てみましょう。これは、レコード型@code{point}の定義です。
21233 @c COMMON
21234
21235 @example
21236 (define-record-type point #t #t
21237 x y z)
21238 @end example
21239
21240 @c EN
21241 The variable @code{point} is bound to a record type descriptor,
21242 which is just a class. But you can take its class and see it is
21243 indeed an instance of @code{<record-meta>} metaclass.
21244 @c JP
21245 変数@code{point}は、レコード型記述子に束縛されています。
21246 それは、単なるクラスです。しかし、さらにそのクラスを取得してみると、
21247 実はメタクラス@code{<record-meta>}のインスタンスでもあることが分かります。
21248 @c COMMON
21249
21250 @example
21251 point @result{} #<class point>
21252 (class-of point) @result{} #<class <record-meta>>
21253 @end example
21254
21255 @c EN
21256 You can create an instance of @code{point} by the default
21257 constructor @code{make-point}. The predicate is given the
21258 default name @code{point?}, and you can access the fields
21259 of the created record by @code{point-x} etc.
21260 @c JP
21261 デフォルトコンストラクタ@code{make-point}を使用して、
21262 @code{point}のインスタンスを生成できます。
21263 述語はデフォルトの名前である@code{point?}になります。
21264 そして、生成されたレコードのフィールドには、@code{point-x}等で
21265 アクセスできます。
21266 @c COMMON
21267
21268 @example
21269 (define p (make-point 1 2 3))
21270
21271 (point? p) @result{} #t
21272 (point-x p) @result{} 1
21273 (point-y p) @result{} 2
21274 (point-z p) @result{} 3
21275 @end example
21276
21277 @c EN
21278 Since we defined all fields immutable, we cannot modify
21279 the instance @code{p}.
21280 @c JP
21281 すべてのフィールドを変更不可として定義したため、
21282 インスタンス@code{p}を変更することはできません。
21283 @c COMMON
21284
21285 @c EN
21286 Here's a mutable version of point, @code{mpoint}.
21287 You can modify its fields by modifier procedures and
21288 generalized @code{set!}.
21289 @c JP
21290 以下は、pointの変更可能バージョンである@code{mpoint}です。
21291 そのフィールドは、モディファイア手続き、および、
21292 一般化された@code{set!}によって変更することができます。
21293 @c COMMON
21294
21295 @example
21296 (define-record-type mpoint #t #t
21297 (x) (y) (z))
21298
21299 (define p2 (make-mpoint 1 2 3)) ; @r{create an instance}
21300
21301 (mpoint-x p2) @result{} 1
21302
21303 (mpoint-x-set! p2 4) ; @r{default modifier}
21304 (mpoint-x p2) @result{} 4
21305
21306 (set! (mpoint-x p2) 6) ; @r{generalized @code{set!} also works}
21307 (mpoint-x p2) @result{} 6
21308 @end example
21309
21310 @c EN
21311 Next one is an example of inheritance.
21312 Note that the default constructor takes arguments for
21313 fields of the parent record as well.
21314 @c JP
21315 次は、継承の例です。
21316 デフォルトコンストラクタは、親のレコードのフィールドの分も
21317 引数に取ることに注意してください。
21318 @c COMMON
21319
21320 @example
21321 (define-record-type (qpoint mpoint) #t #t
21322 (w))
21323
21324 (define p3 (make-qpoint 1 2 3 4))
21325
21326 (qpoint? p3) @result{} #t ; @r{p3 is a qpoint}
21327 (mpoint? p3) @result{} #t ; @r{... and also an mpoint}
21328
21329 (mpoint-x p3) @result{} 1 ; @r{accessing inherited field}
21330 (mpoint-y p3) @result{} 2
21331 (mpoint-z p3) @result{} 3
21332 (qpoint-w p3) @result{} 4
21333 @end example
21334
21335 @c EN
21336 A small caveat: Accessors and modifiers for inherited fields
21337 (e.g. @code{qpoint-x} etc.) are not created.
21338 @c JP
21339 ちょっとした注意:継承されたフィールドのアクセサとモディファイア
21340 (例えば @code{qpoint-x} 等)は生成されません。
21341 @c COMMON
21342
21343 @c EN
21344 Gauche's convention is to enclose class name by @code{<>}.
21345 You can follow the convention and still explicitly gives
21346 simpler names (instead of @code{make-<point>} or @code{<point>-x}):
21347 @c JP
21348 Gaucheの慣例では、クラス名は@code{<>}で囲うようにしています。
21349 この慣例にしたがい、さらに各手続きについては
21350 (@code{make-<point>} や @code{<point>-x}) ではなく)
21351 シンプルな名前を使うようにするには、次のようにします。
21352 @c COMMON
21353
21354 @example
21355 (define-record-type <point> make-point point?
21356 (x point-x)
21357 (y point-y)
21358 (z point-z))
21359 @end example
21360
21361
21362 @node Record types inspection layer, Record types procedural layer, Record types syntactic layer, Record types
21363 @subsection Inspection layer
21364 @c NODE レコード型のインスペクション層, インスペクション層
21365
21366 @c EN
21367 This layer provides common procedures that operates on record type
21368 descriptors and record instances.
21369 @c JP
21370 この層は、レコード型記述子、および、レコードのインスタンスを操作する
21371 共通手続きを提供します。
21372 @c COMMON
21373
21374 @c EN
21375 Note that a record type descriptor is a class in Gauche, so
21376 you can also use operators on classes (e.g. @code{class-name},
21377 @code{class-slots} etc.) on record type descriptors as well.
21378 However, these procedures are more portable.
21379 @c JP
21380 Gaucheでは、レコード型記述子はクラスであるため、クラスに対する操作
21381 (例えば @code{class-name}や@code{class-slots} 等)を、
21382 レコード型記述子に対して使用することもできます。
21383 しかし、これらの手続きは、よりポータブルです。
21384 @c COMMON
21385
21386 @defun record? obj
21387 [SRFI-99][R6RS]
21388 @c MOD gauche.record
21389 @c EN
21390 Returns @code{#t} iff @var{obj} is an instance of record type,
21391 @code{#f} otherwise.
21392 @c JP
21393 @var{obj}がレコード型のインスタンスであれば@code{#t}を、
21394 そうでなければ@code{#f}を返します。
21395 @c COMMON
21396 @end defun
21397
21398 @defun record-rtd record
21399 [SRFI-99][R6RS]
21400 @c MOD gauche.record
21401 @c EN
21402 Returns the record type descriptor of the record instance.
21403 @c JP
21404 レコードインスタンスのレコード型記述子を返します。
21405 @c COMMON
21406 @end defun
21407
21408 @defun rtd-name rtd
21409 [SRFI-99]
21410 @c MOD gauche.record
21411 @c EN
21412 Returns the name of the record type descriptor @var{rtd}.
21413 @c JP
21414 レコード型記述子@var{rtd}の名前を返します。
21415 @c COMMON
21416 @end defun
21417
21418 @defun rtd-parent rtd
21419 [SRFI-99]
21420 @c MOD gauche.record
21421 @c EN
21422 Returns the parent type of the record type descriptor @var{rtd}.
21423 If @var{rtd} doesn't have a parent, @code{#f} is returned.
21424 @c JP
21425 レコード型記述子@var{rtd}の親の型を返します。
21426 @var{rtd}が親を持たなければ@code{#f}が返ります。
21427 @c COMMON
21428 @end defun
21429
21430 @defun rtd-field-names rtd
21431 [SRFI-99]
21432 @c MOD gauche.record
21433 @c EN
21434 Returns a vector of symbols, each of which is the names of the direct
21435 fields of the record represented by @var{rtd}. The result doesn't
21436 include inherited fields.
21437 @c JP
21438 シンボルのベクタを返します。各シンボルは
21439 @var{rtd}で示されるレコードの直属のフィールドの名前です。
21440 この結果には、継承されたフィールドは含まれません。
21441 @c COMMON
21442 @end defun
21443
21444 @defun rtd-all-field-names rtd
21445 [SRFI-99]
21446 @c MOD gauche.record
21447 @c EN
21448 Returns a vector of symbols, each of which is the names of the
21449 fields of the record represented by @var{rtd}. The result includes
21450 all inherited fields.
21451 @c JP
21452 シンボルのベクタを返します。各シンボルは
21453 @var{rtd}で示されるレコードのフィールドの名前です。
21454 この結果には、すべての継承されたフィールドが含まれます。
21455 @c COMMON
21456 @end defun
21457
21458 @defun rtd-field-mutable? rtd field-name
21459 [SRFI-99]
21460 @c MOD gauche.record
21461 @c EN
21462 Returns @code{#t} iff the field with the name @var{field-name}
21463 of a record represented by @var{rtd} is mutable.
21464 @c JP
21465 @var{rtd}で示されるレコードの@var{field-name}という名前を持つフィールドが、
21466 変更可能であれば@code{#t}を、そうでなければ@code{#f}を返します。
21467 @c COMMON
21468 @end defun
21469
21470
21471 @node Record types procedural layer, Pseudo record types, Record types inspection layer, Record types
21472 @subsection Procedural layer
21473 @c NODE レコード型の手続き層, 手続き層
21474
21475 @c EN
21476 These procedures are low-level machinery on top of which
21477 @code{define-record-type} is implemented. They can be used
21478 to create a new record type at runtime.
21479 @c JP
21480 これらの手続きは@code{define-record-type}を実装するための低レベルの機構です。
21481 それらは実行時に新しいレコード型を作成するために使用できます。
21482 @c COMMON
21483
21484 @defun make-rtd name field-specs :optional parent
21485 [SRFI-99]
21486 @c MOD gauche.record
21487 @c EN
21488 Creates and returns a new record type descriptor with name @var{name} and
21489 having fields specified by @var{field-specs}. If @var{parent}
21490 is given, it must be a record type descriptor or @code{#f}.
21491 If it is a record type descriptor, the created record type
21492 inherits from it.
21493 @c JP
21494 @var{name}という名前を持ち@var{field-specs}で示されるフィールドを持つ
21495 新しいレコード型記述子を作成して返します。
21496 @var{parent}を指定した場合、それはレコード型記述子もしくは@code{#f}でなければなりません。
21497 レコード型記述子であった場合、作成されるレコード型はそれを継承します。
21498 @c COMMON
21499
21500 @c EN
21501 The @var{field-specs} argument must be a vector, each
21502 element of which is a @emph{field specifier}. A field
21503 specifier can be a symbol, a list @code{(mutable @var{symbol})},
21504 or a list @code{(immutable @var{symbol})}. The @var{symbol} names
21505 the field. A single symbol or @code{(mutable @var{symbol})} format
21506 makes the field mutable, and @code{(immutable @var{symbol})} format
21507 makes the field immutable.
21508 @c JP
21509 @var{field-specs}引数は、@emph{field specifier}を各要素に持つベクタ
21510 でなければりません。@emph{field specifier}は、@var{symbol}、
21511 @code{(mutable @var{symbol})}というリスト、もしくは、
21512 @code{(immutable @var{symbol})}というリストのいずれかです。
21513 @var{symbol}はフィールド名になります。@var{symbol}ひとつ、もしくは、
21514 @code{(mutable @var{symbol})}形式の場合は、変更可能なフィールドを作ります。
21515 そして、@code{(immutable @var{symbol})}形式の場合は、
21516 変更不可のフィールドを作ります。
21517 @c COMMON
21518
21519 @c EN
21520 Note: Gauche does not implement the extension suggested in
21521 SRFI-99 yet, which is @code{sealed}, @code{opaque} and @code{uid}
21522 arguments.
21523 @c JP
21524 注意: Gaucheは、SRFI-99で提案されている拡張機能である
21525 @code{sealed}、@code{opaque}、および、@code{uid}引数を、まだ実装していません。
21526 @c COMMON
21527 @end defun
21528
21529 @defun rtd? obj
21530 [SRFI-99]
21531 @c MOD gauche.record
21532 @c EN
21533 Returns @code{#t} if @var{obj} is a record type descriptor,
21534 @code{#f} otherwise.
21535 @c JP
21536 @var{obj}がレコード型記述子であれば@code{#t}を、
21537 そうでなければ@code{#f}を返します。
21538 @c COMMON
21539 @end defun
21540
21541 @defun rtd-constructor rtd :optional field-specs
21542 [SRFI-99]
21543 @c MOD gauche.record
21544 @c EN
21545 Returns a procedure that creates an instance record of
21546 the record type represented by @var{rtd}.
21547 Without @var{field-specs}, it returns the default constructor,
21548 which takes as many arguments as the number of fields of
21549 the record to initialize them.
21550 @c JP
21551 @var{rtd}で示されるレコード型のインスタンスを作成する 手続きを返します。
21552 @var{field-specs}がなければ、デフォルトコンストラクタを返します。
21553 それは、初期化のためにレコードのフィールドの数と同じ数の引数を取ります。
21554 @c COMMON
21555
21556 @c EN
21557 You can give a vector of symbols as @var{field-specs}. The @var{n}-th
21558 symbol specifies which field of the instance should be initialized
21559 by the @var{n}-th argument. The @var{field-specs} vector cannot
21560 contain duplicate names. If the record type defines a field with
21561 the same name as the one in the parent record type, the custom constructor
21562 can only initialize the field of the derived type's instance.
21563 @c JP
21564 @var{field-specs}には、シンボルのベクタを指定できます。
21565 @var{n}番目のシンボルは、そのインスタンスのフィールドが、
21566 @var{n}番目の引数で初期化されることを示します。
21567 @var{field-specs}ベクタは重複する名前を持つことはできません。
21568 レコード型が親のレコード型と同じ名前のフィールドを定義した場合、
21569 カスタムコンストラクタは継承先のフィールドのみを初期化します。
21570 @c COMMON
21571 @end defun
21572
21573 @defun rtd-predicate rtd
21574 [SRFI-99]
21575 @c MOD gauche.record
21576 @c EN
21577 Returns a predicate to test an object is an instance of @var{rtd}.
21578 @c JP
21579 オブジェクトが@var{rtd}のインスタンスであるかをテストする 述語を返します。
21580 @c COMMON
21581
21582 @c EN
21583 If @var{rtd} is a pseudo record type, the predicate merely tests
21584 the given object is in an appropriate type and has enough size
21585 to hold the contents. See @ref{Pseudo record types} for the details.
21586 @c JP
21587 @var{rtd}が疑似レコード型であった場合、述語は、与えられたオブジェクトが、
21588 内容を保持するのに十分なサイズを持つ適合した型かどうかをテストします。
21589 詳しくは、@ref{Pseudo record types}を参照してください。
21590 @c COMMON
21591 @end defun
21592
21593 @defun rtd-accessor rtd field-name
21594 [SRFI-99]
21595 @c MOD gauche.record
21596 @c EN
21597 Returns a procedure that takes one argument, an instance of @var{rtd},
21598 and returns the value of the @var{field-name} of the instance.
21599 @c JP
21600 1個の引数として@var{rtd}のインスタンスを取り、
21601 そのインスタンスの@var{field-name}の値を返す 手続きを返します。
21602 @c COMMON
21603
21604 @c EN
21605 An error is signaled if the record type doesn't have the field
21606 of name @var{field-name}.
21607 @c JP
21608 レコード型が@var{field-name}の名前のフィールドを持たない場合には、
21609 エラーになります。
21610 @c COMMON
21611
21612 @c EN
21613 If @var{rtd} is inherits other record types, and it defines a field
21614 of the same name as inherited ones, then the accessor returned by
21615 this procedure retrieves the value of the field of the derived record.
21616 @c JP
21617 @var{rtd}が他のレコードを継承しており、
21618 継承元と同名のフィールドを定義していた場合、この手続きが返すアクセサは、
21619 継承先のレコードのフィールドの値を取得します。
21620 @c COMMON
21621 @end defun
21622
21623 @defun rtd-mutator rtd field-name
21624 [SRFI-99]
21625 @c MOD gauche.record
21626 @c EN
21627 Returns a procedure that takes two arguments, an instance of @var{rtd}
21628 and a value, and sets the latter as the value of the @var{field-name}
21629 of the instance.
21630 @c JP
21631 2個の引数として@var{rtd}のインスタンスと値を取り、
21632 そのインスタンスの@var{field-name}に値をセットする 手続きを返します。
21633 @c COMMON
21634
21635 @c EN
21636 An error is signaled if the record type doesn't have the field
21637 of name @var{field-name}, or the named field is immutable.
21638 @c JP
21639 レコード型が@var{field-name}の名前のフィールドを持たないか変更不可の場合には、
21640 エラーになります。
21641 @c COMMON
21642
21643 @c EN
21644 Like @code{rtd-accessor}, if the record has a field with the same
21645 name as inherited one, the modifier returned by this procedure
21646 only modifies the field of the derived record.
21647 @c JP
21648 @code{rtd-accessor}と同様に、
21649 レコードが継承元と同名のフィールドを定義していた場合、
21650 この手続きが返すモディファイアは、
21651 継承先のレコードのフィールドのみを変更します。
21652 @c COMMON
21653 @end defun
21654
21655
21656 @node Pseudo record types, , Record types procedural layer, Record types
21657 @subsection Pseudo record types
21658 @c NODE 疑似レコード型
21659
21660 @c EN
21661 A pseudo record type is a record type that does not create
21662 an instance of its own type.
21663 Instead it treats an object of other collection
21664 types, such as a vector, as if it had named fields. It's easier
21665 to understand by an example:
21666 @c JP
21667 疑似レコード型は、それ自身の型のインスタンスを作成しないレコード型です。
21668 その代わり、ベクタのような他の集合型のオブジェクトを、
21669 あたかもフィールド名を持っているかのように扱います。
21670 例で理解するのが良いでしょう:
21671 @c COMMON
21672
21673 @example
21674 (define-record-type (vpoint (pseudo-rtd <vector>)) #t #t
21675 (x) (y) (z))
21676
21677 (make-vpoint 1 2 3) @result{} #(1 2 3)
21678 (vpoint-x '#(1 2 3)) @result{} 1
21679
21680 (rlet1 v (make-vpoint 1 2 3)
21681 (set! (vpoint-y v) -1))
21682 @result{} #(1 -1 3)
21683 @end example
21684
21685 @c EN
21686 To create a pseudo record type, specify another pseudo
21687 record type as a parent. The procedure @code{pseudo-rtd}
21688 can be used to obtain a base pseudo record type of
21689 the suitable instance class.
21690 @c JP
21691 疑似レコード型を作るには、他の疑似レコード型を親に指定します。
21692 @code{pseudo-rtd}手続きは、適合するインスタンスクラスの
21693 ベース疑似レコード型を取得するために使用できます。
21694 @c COMMON
21695
21696 @defun pseudo-rtd instance-class
21697 @c MOD gauche.record
21698 @c EN
21699 Returns a pseudo rtd suitable to use @var{instance-class} as
21700 a pseudo record.
21701 @c JP
21702 @var{instance-class}を疑似レコードとして使うために
21703 適合する疑似rtdを返します。
21704 @c COMMON
21705
21706 @c EN
21707 Currently, @code{<list>}, @code{<vector>}, and uniform vector
21708 classes (@code{<u8vector>} etc.) are supported as @var{instance-class}.
21709 @c JP
21710 現在、@code{<list>}、@code{<vector>}、および、ユニフォームベクタ
21711 (例えば @code{<u8vector>} 等)が、
21712 @var{instance-class}としてサポートされています。
21713 @c COMMON
21714 @end defun
21715
21716 @c EN
21717 The predicates of a pseudo record return @code{#t} if the given
21718 object can be interpreted as the pseudo record. In the above
21719 example of @code{vpoint} record, the predicate @code{vpoint?}
21720 returns @code{#t} iff the given object is a vector with 3 or more
21721 elements:
21722 @c JP
21723 疑似レコード型の述語は、与えられたオブジェクトが
21724 疑似レコード型として解釈できるときに@code{#t}を返します。
21725 前述の@code{vpoint}レコードの例の場合、述語@code{vpoint?}は、
21726 3かそれ以上の要素を持つベクタのオブジェクトが与えられた場合に
21727 @code{#t}を返し、そうでなければ@code{#f}を返します。
21728 @c COMMON
21729
21730 @example
21731 (vpoint? '#(0 0 0)) @result{} #t
21732 (vpoint? '#(0 0)) @result{} #f
21733 (vpoint? '(0 0 0)) @result{} #f
21734 (vpoint? '#(0 0 0 0)) @result{} #t
21735 @end example
21736
21737 @c EN
21738 We allow more elements so that the pseudo record can be used
21739 to interpret the header part of the longer data.
21740 @c JP
21741 これは、より長いデータのヘッダ部分を解釈するために使えるように、
21742 より多くの要素を許すようにしています。
21743 @c COMMON
21744
21745 @c ----------------------------------------------------------------------
21746 @node Reloading modules, Simple dispatcher, Record types, Library modules - Gauche extensions
21747 @section @code{gauche.reload} - Reloading modules
21748 @c NODE モジュールの再ロード, @code{gauche.reload} - モジュールの再ロード
21749
21750 @deftp {Module} gauche.reload
21751 @mdindex gauche.reload
21752 @c EN
21753 In the development cycle, you often have to reload modules frequently.
21754 This module supports it.
21755
21756 Note that some part of semantics of the program depends on
21757 the order of loading modules, so reloading arbitrary modules
21758 may change the program behavior unexpectedly. This module
21759 is for developers who knows what they are doing.
21760 @c JP
21761 開発のサイクルのなかで、モジュールを再ロードしなければならないことは
21762 頻繁におこります。このモジュールはそれを支援するものです。
21763
21764 プログラムのいくつかの部分のセマンティクスはモジュールのロードの順に
21765 依存します。それで、任意のモジュールを再ロードすることはプログラムの
21766 ふるまいを予期せぬものに変えてしまう可能性があります。このモジュールは
21767 自分がなにをしようとしているか判っている開発者向けのものです。
21768 @c COMMON
21769
21770 @c EN
21771 @strong{Redefinition rules}: Reloading a module resets all
21772 the binding in the module by default.
21773 Sometimes it is not desirable, however. For example,
21774 you might want to keep an intermediate results in some variable.
21775 You can specify rules for the reloading procedure to determine
21776 which binding to keep.
21777
21778 The rule is described in the following syntax.
21779 @c JP
21780 @strong{再定義ルール}: モジュールを再ロードすると、デフォルトでは、その
21781 モジュール内のすべての束縛はリセットされます。
21782 しかしながら、場合によってこれは望ましいことではありません。たとえば、
21783 中間結果をある変数に残したままにしておきたい場合です。
21784 再ロード手続きにどの束縛を保存するかを決めるためのルールを指定することが
21785 できます。
21786
21787 このルールは以下の構文で記述します。
21788 @c COMMON
21789 @example
21790 <module-rules> : (<module-rule> @dots{})
21791 <module-rule> : (<module-pattern> <rule> @dots{})
21792 <module-pattern> : @r{a symbol module name, or a symbol containing glob pattern}
21793 <rule> : @r{procedure} | @r{symbol} | @r{regexp}
21794 | (and <rule> @dots{})
21795 | (or <rule> @dots{})
21796 | (not <rule>)
21797 @end example
21798
21799 @c EN
21800 @code{<module-rules>} is the global rule to determine per-module
21801 rules. @code{<module-pattern>} is either a symbol module name
21802 or a symbol that contains glob pattern (e.g. @code{mylib.*}).
21803 If @code{<rule>} is a procedure, it is used as a predicate
21804 and the bindings whose value satisfies the predicate are kept from
21805 redefinition. If @code{<rule>} is a symbol, the binding of
21806 the variable whose name is the symbol is kept. If @code{<rule>}
21807 is a regexp, the bindings of the variable whose name matches the
21808 regexp are kept.
21809
21810 Note that the mechanism to prevent redefinition is kind of ad-hoc
21811 hack and semantically unclean. Especially, the right-hand expressions
21812 of @code{define}s are still evaluated, so any side effects they have
21813 will be in effect (e.g. @code{define-class} would still redefine a class).
21814 It's just for your convenience.
21815 Take a look at the code if you want to know the exact behavior.
21816 @c JP
21817 @code{<module-rules>} はモジュールごとのルールをきめるグローバルルール
21818 です。@code{<module-pattern>} はモジュール名シンボルまたは(@code{mylib.*}
21819 のような)グロブパターンを含むシンボルのどちらかです。@code{<rule>} が
21820 手続きであれば、述語として使われ、この述語を満す値の束縛は再定義から
21821 保護されます。@code{<rule>} がシンボルであれば、それと同じ名前の
21822 変数の束縛は保護されます。@code{<rule>} が正規表現の場合、この正規表現に
21823 マッチする名前の変数は保護されます。
21824
21825 再定義からの保護機構は、場当たり的なもので、セマンティクスとしても
21826 不透明なものであることに注意してください。特に@code{define}の右辺式は
21827 評価されてしまうので、そこで起きる副作用は効果を持ちます (例えば
21828 @code{define-class}はクラスの再定義を行ってしまいます)。
21829 これは利便のためだけのものだと考えて下さい。
21830 正確な振舞いを知りたければ、コードを見てください。
21831 @c COMMON
21832 @end deftp
21833
21834 @defun reload module-name :optional rule @dots{}
21835 @c MOD gauche.reload
21836 @c EN
21837 Reloads the specified module. You can optionally specify
21838 redefinition rules by @var{rule} @dots{},
21839 where each @var{rule} is the term @code{<rule>} defined above.
21840 @c JP
21841 指定されたモジュールを再ロードします。オプションで
21842 @var{rule} @dots{} をつかって再定義ルールを指定することができます。
21843 ここで、それぞれの @var{rule} は上の @code{<rule>} で定義されたものです。
21844 @c COMMON
21845 @end defun
21846
21847 @defun reload-modified-modules :optional module-rules
21848 @c MOD gauche.reload
21849 @c EN
21850 Reloads module(s) that have been modified since they are loaded
21851 last time. If optional @var{module-rules} is given, it is
21852 used to determine the redefinition rules for reloaded modules.
21853 If @var{module-rules} is omitted, the current rules are used.
21854 The default of current rules is empty. You can set the current
21855 rules by @code{module-reload-rules}.
21856 @c JP
21857 前回ロードしたときより変更のあったモジュールを再ロードします。
21858 オプション引数 @var{module-rules} が与えられていれば、再ロードした
21859 モジュールに適用する再定義ルールを決定するために使います。
21860 @var{module-rules}が省略された場合、現在のルールが適用されます。
21861 デフォルトの現在のルールは空です。現在のルールは
21862 @code{module-reload-rules}をつかって設定できます。
21863
21864 @c COMMON
21865 @end defun
21866
21867 @defun module-reload-rules :optional module-rules
21868 @c MOD gauche.reload
21869 @c EN
21870 This is a parameter (@pxref{Parameters}) that keeps
21871 the default module rules for @code{reload-modified-modules}.
21872 If called without arguments, returns the current module rules.
21873 If called with @var{module-rules}, sets the argument to the
21874 current module rules.
21875 @c JP
21876 これは一種の「パラメータ」(@ref{Parameters}参照)で、
21877 @code{reload-modified-modules}に対応するデフォルトのモジュールルールを
21878 保持しています。引数なしで呼ばれたときには、現在のモジュールルールを
21879 返します。@var{module-rules}とともに呼ばれたきにはその引数を
21880 現在のモジュールルールにします。
21881 @c COMMON
21882 @end defun
21883
21884 @defun reload-verbose :optional flag
21885 @c MOD gauche.reload
21886 @c EN
21887 This is a parameter to control verbosity of the reloading procedures.
21888 If called without arguments, returns the current verbosity flag.
21889 If called with @var{flag}, it is set to the current verbosity flag.
21890 @c JP
21891 これは再ロード手続きのメッセージ出力レベルを制御するパラメータです。
21892 引数なしで呼ばれると現在の出力レベルフラグを返します。@var{flag}と
21893 ともに呼ばれると現在の出力レベルをこれに設定します。
21894 @c COMMON
21895 @end defun
21896
21897 @c ----------------------------------------------------------------------
21898 @node Simple dispatcher, Sequence framework, Reloading modules, Library modules - Gauche extensions
21899 @section @code{gauche.selector} - Simple dispatcher
21900 @c NODE 簡単なディスパッチャ, @code{gauche.selector} - 簡単なディスパッチャ
21901
21902 @deftp {Module} gauche.selector
21903 @mdindex gauche.selector
21904 @c EN
21905 This module provides a simple interface to dispatch I/O events to
21906 registered handlers, based on @code{sys-select} (@pxref{I/O multiplexing}).
21907 @c JP
21908 このモジュールは、@code{sys-select} (@ref{I/Oの多重化}参照)に基づき、
21909 登録されたハンドラにI/Oイベントをディスパッチするためのシンプルな
21910 インタフェースを提供します。
21911 @c COMMON
21912 @end deftp
21913
21914 @deftp {Class} <selector>
21915 @clindex selector
21916 @c MOD gauche.selector
21917 @c EN
21918 A dispatcher instance that keeps watching I/O ports with associated
21919 handlers. A new instance can be created by @code{make} method.
21920 @c JP
21921 ディスパッチャのインスタンスで、ハンドラを携えてI/Oポートを監視します。
21922 @code{make}メソッドで新しいインスタンスを作れます。
21923 @c COMMON
21924 @end deftp
21925
21926
21927 @deffn {Method} selector-add! (self <selector>) port-or-fd proc flags
21928 @c MOD gauche.selector
21929 @c EN
21930 Add a handler @var{proc} to the selector. @var{proc} is called
21931 when @var{port-or-fd}, which should be a port object or an integer
21932 that specifies a system file descriptor, meets a certain condition
21933 specified by @var{flags}.
21934 @var{flags} must be a list of one or more of the following symbols.
21935 @c JP
21936 セレクタにハンドラ@var{proc}を追加します。@var{proc}は、@var{port-or-fd}
21937 (ポートオブジェクトかシステムのファイルディスクリプタを表す整数)が
21938 @var{flags}で指定された条件に合致した場合に呼ばれます。
21939 @var{flags}は、以下のシンボルの1つ以上のリストでなければなりません。
21940 @c COMMON
21941 @c EN
21942 @table @code
21943 @item r
21944 Calls @var{proc} when data is available at @var{port-or-fd} to read.
21945 @item w
21946 Calls @var{proc} when @var{port-or-fd} is ready to be written.
21947 @item x
21948 Calls @var{proc} when an exceptional condition occurs on @var{port-or-fd}.
21949 @end table
21950 @c JP
21951 @table @code
21952 @item r
21953 @var{port-or-fd}が読み取り可能になった時点で@var{proc}が呼ばれます。
21954 @item w
21955 @var{port-or-fd}が書き込み可能になった時点で@var{proc}が呼ばれます。
21956 @item x
21957 @var{port-or-fd}で例外的な状況が発生した場合に@var{proc}が呼ばれます。
21958 @end table
21959 @c COMMON
21960
21961 @c EN
21962 @var{proc} is called with two arguments. The first one is @var{port-or-fd}
21963 itself, and the second one is a symbol @code{r}, @code{w} or @code{x},
21964 indicating the condition.
21965 @c JP
21966 @var{proc}は、2引数で呼ばれます。1つ目は@var{port-or-fd}そのもので、
21967 2つ目は条件を表すシンボル、@code{r}、@code{w}あるいは@code{x}です。
21968 @c COMMON
21969
21970 @c EN
21971 If a handler is already associated with @var{port-or-fd} under the
21972 same condition, the previous handler is replaced by @var{proc}.
21973 @c JP
21974 同じ条件の下ですでに@var{port-or-fd}にハンドラが関連付けられていた場合は、
21975 以前のハンドラが@var{proc}で置き換えられます。
21976 @c COMMON
21977 @end deffn
21978
21979 @deffn {Method} selector-delete! (self <selector>) port-or-fd proc flags
21980 @c MOD gauche.selector
21981 @c EN
21982 Deletes the handler entries that matches @var{port-or-fd}, @var{proc}
21983 and @var{flags}. One or more of the arguments may be @code{#f},
21984 meaning ``don't care''. For example,
21985 @c JP
21986 @var{port-or-fd}、@var{proc}、@var{flags}にマッチするハンドラエントリを
21987 削除します。引数のいずれかが@code{#f}である場合は、それが何でも良いことを
21988 意味します。例えば、
21989 @c COMMON
21990 @example
21991 (selector-delete! selector the-port #f #f)
21992 @end example
21993 @c EN
21994 deletes all the handlers associated to @var{the-port}, and
21995 @c JP
21996 @var{the-port}に関連付けられた全てのハンドラを削除します。
21997 @c COMMON
21998 @example
21999 (selector-delete! selector #f #f '(w))
22000 @end example
22001 @c EN
22002 deletes all the handlers waiting for writable condition.
22003 @c JP
22004 書き込み可能になるのを待っている全てのハンドラを削除します。
22005 @c COMMON
22006 @end deffn
22007
22008
22009 @deffn {Method} selector-select (self <selector>) :optional (timeout #f)
22010 @c MOD gauche.selector
22011 @c EN
22012 Dispatcher body. Waits for the conditions registered in @var{self},
22013 and when it occurs, calls the associated handler.
22014 @c JP
22015 ディスパッチャのボディです。@var{self}に登録された条件を待ち、条件が合致すると
22016 それに関連付けられたハンドラを呼びます。
22017 @c COMMON
22018 @c EN
22019 If the @var{timeout} argument is omitted or false, this method waits
22020 indefinitely. Alternatively you can give a timeout value, that can
22021 be a real number in microseconds, or a list of two integers that
22022 represents seconds and microseconds.
22023 @c JP
22024 @var{timeout}引数が省略されるか偽の場合、このメソッドは永久に待ちます。
22025 タイムアウトの値を与える場合は、マイクロ秒を表す実数か、秒とマイクロ秒を
22026 表す2つの整数のリストを与えます。
22027 @c COMMON
22028
22029 @c EN
22030 Returns the number of handlers called. Zero means the selector has been
22031 timed out.
22032 @c JP
22033 戻り値は、ハンドラが呼ばれた回数です。0(ゼロ)は、セレクタがタイムアウト
22034 したことを意味します。
22035 @c COMMON
22036
22037 @c EN
22038 It is safe to modify @var{self} inside handler. The change will be
22039 effective from the next call of @code{selector-select}
22040 @c JP
22041 ハンドラの中で@var{self}を変更することは安全です。その変更は、次回の
22042 @code{selector-select}の呼び出し以降に反映されます。
22043 @c COMMON
22044 @end deffn
22045
22046 @c EN
22047 This is a simple example of "echo" server:
22048 @c JP
22049 echoサーバのシンプルな例を示します。
22050 @c COMMON
22051
22052 @example
22053 (use gauche.net)
22054 (use gauche.selector)
22055 (use gauche.uvector)
22056
22057 (define (echo-server port)
22058 (let ((selector (make <selector>))
22059 (server (make-server-socket 'inet port :reuse-addr? #t)))
22060
22061 (define (accept-handler sock flag)
22062 (let* ((client (socket-accept server))
22063 (output (socket-output-port client)))
22064 (selector-add! selector
22065 (socket-input-port client :buffering #f)
22066 (lambda (input flag)
22067 (echo client input output))
22068 '(r))))
22069
22070 (define (echo client input output)
22071 (let ((str (read-uvector <u8vector> 4096 input)))
22072 (if (eof-object? str)
22073 (begin (selector-delete! selector input #f #f)
22074 (socket-close client))
22075 (begin (write-uvector str output)
22076 (flush output)))))
22077
22078 (selector-add! selector
22079 (socket-fd server)
22080 accept-handler
22081 '(r))
22082 (do () (#f) (selector-select selector))))
22083 @end example
22084
22085 @c ----------------------------------------------------------------------
22086 @node Sequence framework, Syslog, Simple dispatcher, Library modules - Gauche extensions
22087 @section @code{gauche.sequence} - Sequence framework
22088 @c NODE シーケンスフレームワーク, @code{gauche.sequence} - シーケンスフレームワーク
22089
22090 @deftp {Module} gauche.sequence
22091 @mdindex gauche.sequence
22092 @c EN
22093 Provides a generic operations on @emph{sequences}.
22094 A sequence is a collection with ordered elements.
22095 Besides all the operations applicable on collections,
22096 you can associate integer index to each element,
22097 and apply order-aware operations on the elements.
22098 @c JP
22099 @emph{シーケンス}に関するジェネリックな操作を提供するモジュールです。
22100 シーケンスとは、コレクションのうち要素の順序が規定されているものです。
22101 コレクションの操作全てに加え、シーケンスに対しては、
22102 各要素に整数のインデックスを関連づけること、
22103 それから要素の順序が影響する操作を適用することができます。
22104 @c COMMON
22105
22106 @c EN
22107 This module inherits @code{gauche.collection} (@pxref{Collection framework}).
22108 All the collection generic operations can be applied to a sequence as well.
22109 @c JP
22110 このモジュールは@code{gauche.collection}を継承しています
22111 (@ref{Collection framework}参照)。
22112 コレクションに使えるジェネリックな操作は全てシーケンスに対しても適用可能です。
22113 @c COMMON
22114
22115 @c EN
22116 Among Gauche builtin class, lists, vectors and strings are sequences
22117 and the specialized methods are defined for them. Other extension
22118 types, such as uniform vectors, have the methods as well.
22119 @c JP
22120 Gauche組み込みクラスのうち、リスト、ベクター、そして文字列は
22121 シーケンスであり、このモジュールでメソッドが定義されます。
22122 また@code{gauche.uvector}のユニフォームベクタ等、
22123 いくつかの拡張データタイプはシーケンスとなっています。
22124 @c COMMON
22125 @end deftp
22126
22127 @menu
22128 * Fundamental sequence accessors::
22129 * Slicing sequence::
22130 * Mapping over sequences::
22131 * Other operations over sequences::
22132 * Implementing sequences::
22133 @end menu
22134
22135 @node Fundamental sequence accessors, Slicing sequence, Sequence framework, Sequence framework
22136 @subsection Fundamental sequence accessors
22137 @c NODE 基本的なシーケンスのアクセサ
22138
22139 @deffn {Method} ref (seq <sequence>) index :optional fallback
22140 @c MOD gauche.sequence
22141 @c EN
22142 Returns @var{index}-th element of the sequence @var{seq}.
22143 This method enables uniform access for any sequence types.
22144
22145 When @var{index} is less than zero, or greater than or equal to the
22146 size of the sequence, @var{fallback} is returned if provided, or
22147 an error is signaled if not.
22148 @c JP
22149 シーケンス@var{seq}の@var{index}番目の要素を返します。
22150 このメソッドによって、全てのシーケンスが統一的にアクセスできます。
22151
22152 @var{index}が負値だったりシーケンスのサイズ以上だった場合は、
22153 @var{fallback}が与えられていればそれが返され、
22154 そうでなければエラーとなります。
22155 @c COMMON
22156
22157 @example
22158 (ref '(a b c) 1) @result{} b
22159 (ref '#(a b c) 1) @result{} b
22160 (ref "abc" 1) @result{} #\b
22161 @end example
22162 @end deffn
22163
22164 @deffn {Method} {(setter ref)} (seq <sequence>) index value
22165 @c MOD gauche.sequence
22166 @c EN
22167 Sets @var{value} to the @var{index}-th element of the sequence @var{seq}.
22168 This is the uniform sequence modifier.
22169
22170 Note: Some sequences may not support arbitrary modification by index.
22171 For example, if you have a sequence representing a set of sorted integers,
22172 you cannot modify @var{i}-th element with arbitrary value. Yet such
22173 sequence may provide other means of modification, such as inserting
22174 or deleting elements.
22175 @c JP
22176 統一的なシーケンスの変更メソッドです。
22177 シーケンス@var{seq}の@var{index}番目の要素に@var{value}をセットします。
22178
22179 註: シーケンスによってはインデックスによる変更をサポートしていない
22180 場合があります。例えば「ソートされた整数」を表すシーケンスがあった場合、
22181 @code{i}番目の要素を適当な整数で置き換えることはできないでしょう。
22182 そのようなシーケンスでも、要素の挿入や削除など、別の方法でシーケンスを
22183 変更する手段が与えられるかもしれません。
22184 @c COMMON
22185
22186 @example
22187 (let ((x (list 'a 'b 'c)))
22188 (set! (ref x 1) 'z)
22189 x) @result{} (a z c)
22190
22191 (let ((x (vector 'a 'b 'c)))
22192 (set! (ref x 1) 'z)
22193 x) @result{} #(a z c)
22194
22195 (let ((x (string #\a #\b #\c)))
22196 (set! (ref x 1) #\z)
22197 x) @result{} "azc"
22198 @end example
22199 @end deffn
22200
22201 @deffn {Method} referencer (seq <sequence>)
22202 @c MOD gauche.sequence
22203 @end deffn
22204
22205 @deffn {Method} modifier (seq <sequence>)
22206 @c MOD gauche.sequence
22207 @end deffn
22208
22209 @node Slicing sequence, Mapping over sequences, Fundamental sequence accessors, Sequence framework
22210 @subsection Slicing sequence
22211 @c NODE シーケンスのスライス
22212
22213 @deffn {Method} subseq (seq <sequence>) :optional start end
22214 @c MOD gauche.sequence
22215 @c EN
22216 Retrieve a subsequence of the sequence @var{seq}, from
22217 @var{start}-th element (inclusive) to @var{end}-th element (exclusive).
22218 If @var{end} is omitted, up to the end of sequence is taken.
22219 The type of the returned sequence is the same as @var{seq}.
22220 @c JP
22221 シーケンス@var{seq}の、@var{start}番目の要素から@var{end}番目の要素の直前
22222 までの部分シーケンスを返します。@var{end}が省略された場合はシーケンスの
22223 最後までが取られます。返されるシーケンスの型は@var{seq}と同じになります。
22224 @c COMMON
22225
22226 @example
22227 (subseq '(a b c d e) 1 4) @result{} (b c d)
22228 (subseq '#(a b c d e) 1 4) @result{} #(b c d)
22229 (subseq "abcde" 1 4) @result{} "bcd"
22230
22231 (subseq '(a b c d e) 3) @result{} (d e)
22232 @end example
22233 @end deffn
22234
22235 @deffn {Method} {(setter subseq)} (seq <sequence>) start end value-seq
22236 @deffnx {Method} {(setter subseq)} (seq <sequence>) start value-seq
22237 @c MOD gauche.sequence
22238 @c EN
22239 Sets the elements of @var{value-seq} from the @var{start}-th element
22240 (inclusive) to the @var{end}-th element (exclusive) of the sequence @var{seq}.
22241 @var{Value-seq} can be any sequence, but its size
22242 must be larger than (@var{end} - @var{start}).
22243
22244 In the second form, @var{end} is figured out by the length of @var{value-seq}.
22245 @c JP
22246 @var{value-seq}の各要素を、シーケンス@var{seq}の@var{start}番目から
22247 @var{end}番目の直前まで順にセットします。
22248 @var{value-seq}はどんなシーケンスでも構いませんが、
22249 (@var{end} - @var{start}) よりは長くなくてはなりません。
22250
22251 2番目の形式では、@var{end}が@var{value-seq}の長さから算出されます。
22252 @c COMMON
22253
22254 @example
22255 (define s (vector 'a 'b 'c 'd 'e))
22256 (set! (subseq s 1 4) '(4 5 6))
22257 s @result{} #(a 4 5 6 e)
22258 (set! (subseq s 0) "ab")
22259 s @result{} #(#\a #\b 5 6 e)
22260 @end example
22261 @end deffn
22262
22263 @node Mapping over sequences, Other operations over sequences, Slicing sequence, Sequence framework
22264 @subsection Mapping over sequences
22265 @c NODE シーケンス上のマップ
22266
22267 @c EN
22268 You can use extended @code{fold}, @code{map}, @code{for-each} and other
22269 generic functions on sequences, since a sequence is also a collection.
22270 However, sometimes you want to have index as well as the element itself
22271 during iteration. There are several generic functions for it.
22272 @c JP
22273 シーケンスはまたコレクションでもあるので、シーケンスについて
22274 @code{fold}、@code{map}、@code{for-each}や他のジェネリック関数を
22275 拡張することができます。しかし、時にはイテレーション中に要素そのものと
22276 そのインデックスを知りたいことでしょう。そのためのジェネリック関数が
22277 いくつかあります。
22278 @c COMMON
22279
22280 @deffn {Method} fold-with-index kons knil (seq <sequence>) @dots{}
22281 @c MOD gauche.sequence
22282 @c EN
22283 Like generic @code{fold}, except @var{kons} is given
22284 the index within @var{seq}, as the first argument,
22285 as well as each element from @var{seq}s and the accrued value.
22286 @c JP
22287 ジェネリックな@code{fold}と似ていますが、@var{kons}には@var{seq}の
22288 インデックス内から、第1引数として@var{seq}の要素と増加する値が渡る
22289 点が異なります。
22290 @c COMMON
22291
22292 @example
22293 (fold-with-index acons '() '(a b c))
22294 @result{} ((2 . c) (1 . b) (0 . a))
22295 @end example
22296 @end deffn
22297
22298 @deffn {Method} map-with-index proc (seq <sequence>) @dots{}
22299 @deffnx {Method} map-to-with-index class proc (seq <sequence>) @dots{}
22300 @deffnx {Method} for-each-with-index proc (seq <sequence>) @dots{}
22301 @c MOD gauche.sequence
22302 @c EN
22303 Like @code{map}, @code{map-to} and @code{for-each}, except @var{proc}
22304 receives the index as the first argument.
22305 @c JP
22306 @code{map}、@code{map-to}、@code{for-each}と似ていますが、@var{proc}が
22307 第1引数としてインデックスを受け取る点が違います。
22308 @c COMMON
22309
22310 @example
22311 (map-with-index list '(a b c d) '(e f g h))
22312 @result{} ((0 a e) (1 b f) (2 c g) (3 d h))
22313
22314 (map-to-with-index <vector> cons '(a b c d))
22315 @result{} #((0 . a) (1 . b) (2 . c) (3 . d))
22316 @end example
22317 @end deffn
22318
22319 @deffn {Method} find-with-index pred (seq <sequence>)
22320 @c MOD gauche.sequence
22321 @c EN
22322 Finds the first element in @var{seq} that satisfies @var{pred}
22323 like @code{find}, but returns two values, the index of the element
22324 and the element itself. If no element satisfies @var{pred},
22325 two @code{#f}'s are returned.
22326 @c JP
22327 @code{find}のように、@var{seq}の中で@var{pred}を満足する最初の要素を
22328 探しますが、2つの値、要素のインデックスと要素自身を返します。
22329 @var{pred}を満足する要素がなかったら、2つの@code{#f}が返ります。
22330 @c COMMON
22331
22332 @example
22333 (find-with-index char-upper-case? "abraCadabra")
22334 @result{} 4 and #\C
22335
22336 (find-with-index char-numeric? "abraCadabra")
22337 @result{} #f and #f
22338 @end example
22339 @end deffn
22340
22341 @deffn {Method} find-index pred (seq <sequence>)
22342 @c MOD gauche.sequence
22343 @c EN
22344 Like @code{find}, but returns the index of the first element
22345 that satisfies @var{pred} in @var{seq}, instead of the element itself.
22346 If no element in @var{seq} satisfies @var{pred}, @code{#f} is returned.
22347 @c JP
22348 @code{find}に似ていますが、@var{seq}の中で@var{pred}を満足する最初の、
22349 要素自身ではなくインデックスを返す点が異なります。
22350 @var{seq}の中に@var{pred}を満足する要素がなかったら、@code{#f}が返ります。
22351 @c COMMON
22352
22353 @example
22354 (find-index char-upper-case? "abraCadabra")
22355 @result{} 4
22356
22357 (find-index char-numeric? "abraCadabra")
22358 @result{} #f
22359 @end example
22360
22361 @c EN
22362 See also @code{list-index} in @code{scheme.list}
22363 (@pxref{R7RS lists}).
22364 @c JP
22365 @code{scheme.list} (@ref{R7RS lists}参照)の@code{list-index}も見て下さい。
22366 @c COMMON
22367 @end deffn
22368
22369 @deffn {Method} fold-right kons knil (seq <sequence>) @dots{}
22370 @c MOD gauche.sequence
22371 @c EN
22372 Generalization of @code{fold-right} on lists.
22373 Like @code{fold}, this method applies a higher-order function
22374 @var{kons} over given sequence(s), passing the "seed" value
22375 whose default is @var{knil}. The difference between @code{fold}
22376 and @code{fold-right} is the associative order of elements on
22377 which @var{kons} is applied.
22378
22379 When we have one sequence, @code{[E0, E1, ..., En]}, @code{fold}
22380 and @code{fold-right} work as follows, respectively.
22381 @c JP
22382 リストに対する@code{fold-right}の総称関数版です。
22383 @code{fold}と同じように、このメソッドは種となる値 (初期値は@var{knil})
22384 を受渡しながら、高階関数@var{kons}を与えられたシーケンスの各要素に
22385 適用してゆきます。@code{fold}と@code{fold-right}の違いは
22386 要素間の結合の順序にあります。
22387
22388 ひとつだけのシーケンス@code{[E0, E1, ..., En]}に適用する場合、
22389 @code{fold}と@code{fold-right}はそれぞれ以下のように動作します。
22390 @c COMMON
22391
22392 @example
22393 fold:
22394 (kons En (kons En-1 (kons ... (kons E1 (kons E1 knil)) ...)))
22395
22396 fold-right
22397 (kons E0 (kons E1 (kons ... (kons En-1 (kons En knil)) ...)))
22398 @end example
22399
22400 @c EN
22401 This method isn't defined on @code{<collection>}, since
22402 collections don't care the order of elements.
22403 @c JP
22404 このメソッドは@code{<collection>}に対しては提供されていません。
22405 コレクションは要素の順序を規定しないからです。
22406 @c COMMON
22407 @end deffn
22408
22409
22410 @node Other operations over sequences, Implementing sequences, Mapping over sequences, Sequence framework
22411 @subsection Other operations over sequences
22412 @c NODE その他のシーケンス上の操作
22413
22414 @c EN
22415 @subsubheading Selection and searching
22416 @c JP
22417 @subsubheading 選択と検索
22418 @c COMMON
22419
22420 @deffn {Generic function} sequence-contains haystack needle :key test
22421 @c MOD gauche.sequence
22422 @c EN
22423 Both @var{needle} and @var{haystack} must be sequences.
22424 Searches @var{needle} from @var{haystack} from the beginning of @var{haystack}.
22425 If @var{needle} is found, the index in @var{haystack} where it begins is
22426 returned. Otherwise @code{#f} is returned. The keyword argument
22427 @var{test} is used to compare elements; its default is @code{eqv?}.
22428 @c JP
22429 @var{needle}と@var{haystack}はシーケンスです。
22430 @var{haystack}の中で、@var{needle}に一致するシーケンスを左から探します。
22431 もし見つかれば、@var{haystack}中の@var{needle}が始まる場所のインデックスを、
22432 見つからなければ@code{#f}を返します。キーワード引数@var{test}は
22433 要素を比較するのに使われます。デフォルトは@code{eqv?}です。
22434 @c COMMON
22435
22436 @example
22437 (sequence-contains '#(a b r a c a d a b r a) '#(b r a))
22438 @result{} 1
22439
22440 (sequence-contains '#(a b r a c a d a b r a) '#(c r a))
22441 @result{} #f
22442 @end example
22443
22444 @c EN
22445 This can be regarded as generalization of @code{string-contains} in SRFI-13
22446 (@pxref{SRFI-13 String searching}).
22447 @c JP
22448 これは、SRFI-13の@code{string-contains}を一般化したものとみることもできます
22449 (@ref{SRFI-13 String searching}参照)。
22450 @c COMMON
22451 @end deffn
22452
22453 @defun break-list-by-sequence list needle :key test
22454 @defunx break-list-by-sequence! list needle :key test
22455 @c MOD gauche.sequence
22456 @c EN
22457 Searches a sequence @var{needle} from @var{list},
22458 and if found, breaks @var{list}
22459 to two parts---the prefix of @var{list} up to right before @var{needle}
22460 begins, and the rest---and returns them.
22461 @var{List} must be a list, but @var{needle} can be any sequence.
22462 Elements are compared by @var{test}, defaulted to @code{eqv?}.
22463 @c JP
22464 シーケンス@var{needle}を@var{list}から探し、見つかれば@var{list}を
22465 @var{needle}の直前までとそれ以降に分割して二つの値として返します。
22466 @var{list}はリストでなければなりませんが、
22467 @var{needle}には任意のシーケンスを渡せます。
22468 各要素は@var{test}手続きで比較されます。デフォルトは@code{eqv?}です。
22469 @c COMMON
22470
22471 @example
22472 (break-list-by-sequence '(a b r a c a d a b r a) '(c a d))
22473 @result{} (a b r a) @r{and} (c a d a b r a)
22474 @end example
22475
22476 @c EN
22477 If @var{needle} isn't found in @var{list}, it returns @var{list} itself
22478 and @code{()}. This behavior is aligned to @code{span} and @code{break}
22479 (@pxref{R7RS lists}), which split a list by predicate but
22480 returns the whole list if split condition isn't met.
22481 @c JP
22482 @var{needle}が@var{list}中に見つからなかった場合は、
22483 @var{list}そのものと@code{()}が返されます。
22484 これは@code{span}や@code{break}の動作に合わせてあります
22485 (@ref{R7RS lists}参照)。
22486 これらの手続きは要素に対する述語でもってリストを分割しますが、
22487 分割条件が満たされなかった場合はリスト全体を返します。
22488 @c COMMON
22489
22490 @example
22491 (break-list-by-sequence '(a b r a c a d a b r c a) '(c a z))
22492 @result{} (a b r a c a d a b r c a) @r{and} ()
22493 @end example
22494
22495 @c EN
22496 The linear update version @code{break-list-by-sequence!}
22497 modifies @var{list} to create the return value if necessary,
22498 so @var{list} must be mutable. The caller must use the return
22499 value instead of relying on side-effects, though,
22500 for @var{list} may not be modified.
22501 @c JP
22502 @code{break-list-by-sequence!}はその場で更新するバージョンで、
22503 必要なら@var{list}を破壊的に変更して返り値を生成します。渡すリストは変更可能で
22504 なければなりません。@var{list}が変更されない場合もあるので、
22505 呼出側は副作用に頼らず常に返り値を利用する必要があります。
22506 @c COMMON
22507 @end defun
22508
22509 @defun sequence->kmp-stepper needle :key test
22510 @c MOD gauche.sequence
22511 @c EN
22512 This is an internal routine to search subsequence (@var{needle}) inside
22513 larger sequence, using Knuth-Morris-Pratt (KMP) algorithm.
22514 It is used in @code{sequence-contains},
22515 @code{break-list-by-sequence} and @code{break-list-by-sequence!}.
22516 @c JP
22517 これは、KMPアルゴリズムを使って大きなシーケンス中から
22518 部分シーケンス@var{needle}を探すための内部ルーチンです。
22519 @code{sequence-contains}、
22520 @code{break-list-by-sequence}、
22521 @code{break-list-by-sequence!}の中で使われています。
22522 @c COMMON
22523
22524 @c EN
22525 Returns a procedure that performs one step of KMP search.
22526 The procedure takes two arguments, an element @var{elt}
22527 and an index @var{k}. It compares @var{elt} with
22528 @code{(~ needle k)}, and returns two values---the next index and
22529 a flag indicating the match is completed. When the match is
22530 completed, the next index is equal to the length of @var{needle}.
22531 @c JP
22532 KMPアルゴリズムの1ステップを行う手続きを返します。
22533 返される手続きは二つの引数、要素@var{elt}とインデックス@var{k}を取り、
22534 @var{elt}と@code{(~ needle k)}を比較します。二つの値を返します:
22535 次に比較すべきインデックスと、マッチが終了したかどうかのフラグです。
22536 マッチが終了した場合、次のインデックスとして返される値は@var{needle}の
22537 長さと等しいです。
22538 @c COMMON
22539
22540 @c EN
22541 As an edge case, if @var{needle} is an empty sequence,
22542 @code{sequence->kmp-stepper} returns @code{#f}.
22543 @c JP
22544 エッジケースとして、@var{needle}が空のシーケンスの場合、
22545 @code{sequence->kmp-stepper}は@code{#f}を返します。
22546 @c COMMON
22547
22548 @c EN
22549 Elements are compared using @var{test}, which is defaulted to @code{eqv?}.
22550 @c JP
22551 要素は@var{test}で比較されます。デフォルトは@code{eqv?}です。
22552 @c COMMON
22553
22554 @c EN
22555 The following is a skeleton of searcher using
22556 @code{sequence->kmp-stepper}. Here we assume @var{haystack}
22557 is a list, and we just return whether the needle is
22558 found or not, or needle is empty; you might want to carry
22559 around other info in the loop (e.g. @code{sequence-contains}
22560 tracks the current index of @var{haystack} in order to
22561 return the found index.)
22562 @c JP
22563 以下に、@code{sequence->kmp-stepper}を使った探索コードの骨格を示します。
22564 この例では@var{haystack}はリストで、単に@var{needle}が見つかったかどうか
22565 (あるいは@var{needle}が空か)だけを返しています。
22566 実際の応用では、他の情報をループで持ち回ることになるでしょう
22567 (例えば@code{sequence-contains}では@var{haystack}中の
22568 インデックスをトラックして、見つかった場所を返しています。)
22569 @c COMMON
22570
22571 @example
22572 (if-let1 stepper (sequence->kmp-stepper needle)
22573 (let loop ([haystack haystack]
22574 [k 0])
22575 (if (null? haystack)
22576 'not-found
22577 (receive (k found) (stepper (car haystack) k) ; KMP step
22578 (if found
22579 'found
22580 (loop (cdr haystack) k)))))
22581 'needle-is-empty)
22582 @end example
22583 @end defun
22584
22585 @c EN
22586 Note that selection and searching methods for collections
22587 can also be applied to sequences.
22588 See @ref{Selection and searching in collection}.
22589 @c JP
22590 コレクションに対する選択と探索はシーケンスにも使えます。
22591 @ref{Selection and searching in collection}を参照して下さい。
22592 @c COMMON
22593
22594 @c EN
22595 @subsubheading Grouping
22596 @c JP
22597 @subsubheading グループ化
22598 @c COMMON
22599
22600 @deffn {Generic function} group-sequence seq :key key test
22601 @c MOD gauche.sequence
22602 @c EN
22603 Groups consecutive elements in a sequence @var{seq} which
22604 have the common key value. A key value of an element is
22605 obtained by applying the procedure @var{key} to the element;
22606 the default procedure is @code{identity}.
22607 For each element in @var{seq}, @var{key} is applied exactly once.
22608 The equal-ness of keys are compared by @var{test} procedure,
22609 whose default is @code{eqv?}.
22610 @c JP
22611 シーケンス@var{seq}の連続する要素で、同じキー値を持つもの同士を
22612 グループ化します。
22613 キーの値は要素に手続き@var{key}を適用することで得られます。@var{key}の
22614 デフォルト値は@code{identity}です。@var{sedq}の各要素に対して、
22615 @var{key}は正確に一回だけ呼ばれます。
22616 キーの等価性判定には手続き@var{test}が使われます。デフォルト値は@code{eqv?}です。
22617 @c COMMON
22618
22619 @example
22620 (group-sequence '(1 1 1 2 3 4 4 2 2 3 1 1 3))
22621 @result{} ((1 1 1) (2) (3) (4 4) (2 2) (3) (1 1) (3))
22622
22623 (group-sequence '(1 1 1 2 3 4 4 2 2 3 1 1 3)
22624 :key (cut modulo <> 2)))
22625 @result{} ((1 1 1) (2) (3) (4 4 2 2) (3 1 1 3))
22626
22627 (group-sequence '#("a" "a" "b" "b" "c" "d" "d")
22628 :test string=?)
22629 @result{} (("a" "a") ("b" "b") ("c") ("d" "d"))
22630
22631 (group-sequence "aabbcdd"
22632 :test char=?)
22633 @result{} ((#\a #\a) (#\b #\b) (#\c) (#\d #\d))
22634 @end example
22635
22636 @c EN
22637 This method is similar to Haskell's @code{group}.
22638 If you want to group elements that are not adjacent,
22639 use @code{group-collection}
22640 (@pxref{Selection and searching in collection}).
22641 @c JP
22642 このメソッドはHaskellの@code{group}と似ています。
22643 隣り合っていない要素もグループ化したい場合は、
22644 @code{group-collection}
22645 (@ref{Selection and searching in collection}参照)を使って下さい。
22646 @c COMMON
22647
22648 @c EN
22649 If you simply need to reduce each group for one instance,
22650 that is, removing adjacent duplicated elements,
22651 you can use @code{delete-neighbor-dups} below.
22652 @c JP
22653 もし、単にそれぞれのグループあたり一つづとつの要素だけを残したい、
22654 つまり、隣り合う重複する要素を除きたい場合は、
22655 下の@code{delete-neighbor-dups}が使えます。
22656 @c COMMON
22657 @end deffn
22658
22659 @deffn {Generic function} group-contiguous-sequence seq :key key next test squeeze
22660 @c MOD gauche.sequence
22661 @c EN
22662 Group contiguous elements in @var{seq}.
22663 @c JP
22664 @var{seq}中の連続する要素をまとめます。
22665 @c COMMON
22666
22667 @example
22668 (group-contiguous-sequence '(1 2 3 4 7 8 9 11 13 14 16))
22669 @result{} ((1 2 3 4) (7 8 9) (11) (13 14) (16))
22670 @end example
22671
22672 @c EN
22673 If the keyword argument @var{squeeze} is true, each subsequence is
22674 represented with its first and last elements, except when the subsequence
22675 has only one element.
22676 @c JP
22677 キーワード引数@var{squeeze}に真の値が与えられた場合は、
22678 まとめた後の部分列を、その最初と最後の要素のみに置き換えます。部分列が要素ひとつだけの
22679 場合はそのままです。
22680 @c COMMON
22681
22682 @example
22683 (group-contiguous-sequence '(1 2 3 4 7 8 9 11 13 14 16) :squeeze #t)
22684 @result{} ((1 4) (7 9) (11) (13 14) (16))
22685 @end example
22686
22687 @c EN
22688 The keyword argument @var{key} must be a procedure taking one argument,
22689 and it is applied to every element in the sequence once, to construct
22690 the result. Its default is @code{identity}.
22691
22692 The keyword argument @var{next} must be a procedure
22693 taking one argument, which is the key value (whatever @var{key} procedure
22694 returns) and must return the ``next'' key value.
22695 Its default is @code{(^n (+ n 1))}.
22696
22697 The @var{test} argument must be a procedure taking two argument
22698 and used to compare two key values. Its default is @code{eqv?}.
22699 @c JP
22700 キーワード引数@var{key}はひとつの引数を取る手続きでなければならず、
22701 シーケンスの各要素に一回だけ適用され、その戻り値が結果を作るのに使われます。
22702 デフォルトは@code{identity}です。
22703
22704 キーワード引数@var{next}はひとつの引数を取る手続きでなければならず、
22705 キーの値(@var{key}手続きが返すもの)を受け取って、その「次」にあたるキーの値を返します。
22706 デフォルトは@code{(^n (+ n 1))}です。
22707
22708 キーワード引数@var{test}はふたつの引数を取る手続きでなければならず、
22709 ふたつのキー値が等しいかどうかを判定します。デフォルトは@code{eqv?}です。
22710 @c COMMON
22711
22712 @example
22713 (group-contiguous-sequence "AbCdFgH"
22714 :key char-upcase :next (^c (integer->char (+ 1 (char->integer c)))))
22715 @result{} ((#\A #\B #\C #\D) (#\F #\G #\H))
22716 @end example
22717 @end deffn
22718
22719 @deffn {Generic function} delete-neighbor-dups seq :key key test start end
22720 @c MOD gauche.sequence
22721 @c EN
22722 Returns a sequence of the same type as @var{seq}, in which
22723 elements in @var{seq} are included in the original order, except
22724 duplicate adjacent elements.
22725 The type of @var{seq} must has a builder.
22726 @c JP
22727 @var{seq}中で、隣り合う重複する要素を取り除いたものを
22728 @var{seq}と同じ型のシーケンスとして返します。
22729 @var{seq}の型はビルダーを持っていなければなりません。
22730 @c COMMON
22731
22732 @example
22733 (delete-neighbor-dups '(1 1 1 2 3 4 4 2 2 3 1 1 3))
22734 @result{} (1 2 3 4 2 3 1 3)
22735
22736 (delete-neighbor-dups '#(1 1 1 2 3 4 4 2 2 3 1 1 3))
22737 @result{} #(1 2 3 4 2 3 1 3)
22738
22739 (delete-neighbor-dups "1112344223113")
22740 @result{} "12342313"
22741 @end example
22742
22743 @c EN
22744 Elements are compared with @code{eqv?} by default. You can pass
22745 alternative procedure to @var{test} keyword argument; it is always
22746 called as @code{(@var{test} @var{x} @var{y})},
22747 where @var{x} and @var{y} are the contiguous elements in @var{seq}.
22748 If elements are compared equal, the first one is kept:
22749 @c JP
22750 要素同士はデフォルトでは@code{eqv?}で比較されます。
22751 @var{test}キーワード引数に代わりの比較手続きを渡すこともできます。
22752 @var{seq}中に要素@var{x}と@var{y}がこの順で隣り合っているとすると、
22753 比較手続きは常に@code{(@var{test} @var{x} @var{y})}として呼ばれます。
22754 要素が等しかった場合、最初に出現する要素が残ります。
22755 @c COMMON
22756
22757 @example
22758 (delete-neighbor-dups "AaaAbBBbCCcc" :test char-ci=?)
22759 @result{} "AbC"
22760 @end example
22761
22762 @c EN
22763 If @var{key} is provided, it must be a procedure that takes one arguments.
22764 It is applied to each element of @var{seq} at most once, and each resulting
22765 value is used for the comparison instead of elements themselves.
22766 @c JP
22767 @var{key}キーワード引数が与えられた場合、それは1引数の手続きでなければなりません。
22768 @var{seq}の各要素に対してその手続きは1回だけ適用され、結果が比較に使われます。
22769 @c COMMON
22770
22771 @example
22772 (delete-neighbor-dups
22773 '((1 . "a") (1 . "b") (2 . "c") (2 . "d"))
22774 :key car)
22775 @result{} ((1 . "a") (2 . "c"))
22776 @end example
22777
22778 @c EN
22779 The @var{start} and @var{end} arguments specify indexes in the @var{seq}
22780 to limit the range to look at. Where @var{start} is inclusive, @var{end}
22781 is exclusive.
22782 @c JP
22783 @var{start}と@var{end}引数は@var{seq}へのインデックスで、
22784 調べる範囲を限定します。@var{start}番目の要素から、
22785 @var{end}番目の要素の一つ手前までが対象となります。
22786 @c COMMON
22787
22788 @example
22789 (delete-neighbor-dups "1112344223113" :start 3 :end 9)
22790 @result{} "2342"
22791 @end example
22792 @end deffn
22793
22794 @deffn {Generic function} delete-neighbor-dups! seq :key key test start end
22795 @c MOD gauche.sequence
22796 @c EN
22797 Scan @var{seq} from left to right, dropping consecutive duplicated
22798 elements. The result is stored into @var{seq}, packed to left.
22799 Note @var{seq} must be modifiable by index, i.e. @code{modifier} method
22800 must be defined. The rest of @var{seq} will be untouched.
22801 Returns the next index after the last modified entry.
22802 @c JP
22803 @var{seq}を左から右にスキャンし、重複する要素を除いた結果を左に詰めて@var{seq}に
22804 格納してゆきます。@var{seq}はインデックス指定で変更可能でなければなりません。
22805 つまり、@var{modifier}メソッドが定義されてなければなりません。
22806 詰め終わった残りの部分は変更せずに残されます。
22807 最後に変更された場所の次のインデックスを返します。
22808 @c COMMON
22809
22810 @example
22811 (let1 v (vector 1 1 2 2 3 3 2 2 4 4)
22812 (list (delete-neighbor-dups! v)
22813 v))
22814 @result{} (5 #(1 2 3 2 4 3 2 2 4 4))
22815 @end example
22816
22817 @c EN
22818 The semantics of keyword arguments @var{key}, @var{test},
22819 @var{start} and @var{end} are the same as
22820 @code{delete-neighbor-dups}.
22821 @c JP
22822 キーワード引数@var{key}、@var{test}、@var{start}、@var{end}の意味は
22823 @code{delete-neighbor-dups}と同じです。
22824 @c COMMON
22825
22826 @example
22827 (let1 v (vector 1 1 2 2 3 3 2 2 4 4)
22828 (list (delete-neighbor-dups! v :start 2)
22829 v))
22830 @result{} (6 #(1 1 2 3 2 4 2 2 4 4))
22831 @end example
22832
22833 @c EN
22834 Note: This method works on any sequence with @code{modifier}
22835 method, but it's not necessarily more efficient than
22836 @code{delete-neighbor-dups}, which creates a new sequence.
22837 If @var{seq} is a list or a string, each modification by index takes O(n)
22838 time (for a string even it costs O(n) extra storage), so the
22839 total cost is O(n^2), whereas @code{delete-neighbor-dups}
22840 needs O(n) time and storage.
22841 This works best for vectors and alike,
22842 with which it doesn't cost extra allocation and runs in O(n) time.
22843 @c JP
22844 註: このメソッドは@code{modifier}が定義されているシーケンスなら何でも
22845 使えますが、新たなシーケンスをアロケートする@code{delete-neighbor-dups}より
22846 効率的であるとは限りません。@var{seq}がリストや文字列であれば、
22847 一ヶ所の変更にO(n)の時間がかかります(文字列の場合はさらにO(n)のメモリも使います)から
22848 トータルのコストはO(n^2)になります。@code{delete-neighbor-dups}なら
22849 時間空間ともにO(n)です。
22850 このメソッドはベクタとその仲間で最も効率よく動作します。
22851 余分なメモリを必要とせず、O(n)時間で済みます。
22852 @c COMMON
22853 @end deffn
22854
22855 @deffn {Generic function} delete-neighbor-dups-squeeze! seq :key key test start end
22856 @c MOD gauche.sequence
22857 @c EN
22858 Operates like @code{delete-neighbor-dups} but reuses storage of @var{seq},
22859 which will be resized by dropping duplicated elements.
22860 Returns the sequence after dupes are removed.
22861 @c JP
22862 @code{delete-neighbor-dups}と同じように動作しますが、
22863 @var{seq}の格納領域を再利用します。
22864 @var{seq}内の重複する要素は消去され、全体の長さが短くなります。
22865 変更後の@var{seq}を返します。
22866 @c COMMON
22867
22868 @c EN
22869 Not all sequences are resizable, so this method won't be defined
22870 for such sequences. The @code{gauche.sequence} module only
22871 provides this method for @code{<list>}, in which dropping the
22872 middle of the sequence is very efficient as it is just a
22873 single @code{set-cdr!}.
22874 @c JP
22875 シーケンスは長さを変更できるとは限らないので、
22876 このメソッドはそういったシーケンスに対しては定義されません。
22877 @code{gauche.sequence}モジュールでは、
22878 @code{<list>}に対してのメソッドだけが提供されます。
22879 リストは@code{set-cdr!}を用いることで効率よく中間の要素を削除できます。
22880 @c COMMON
22881
22882 @example
22883 (delete-neighbor-dups-squeeze! (list 1 1 1 2 2 2 3 3 3))
22884 @result{} (1 2 3)
22885
22886 (delete-neighbor-dups-squeeze! (list 1 1 1 2 2 2 3 3 3 4 4)
22887 :start 3 :end 9)
22888 @result{} (2 3)
22889 @end example
22890
22891 @c EN
22892 The semantics of keyword arguments @var{key}, @var{test},
22893 @var{start} and @var{end} are the same as
22894 @code{delete-neighbor-dups}.
22895 @c JP
22896 キーワード引数@var{key}、@var{test}、@var{start}、@var{end}の意味は
22897 @code{delete-neighbor-dups}と同じです。
22898 @c COMMON
22899 @end deffn
22900
22901 @c EN
22902 @subsubheading Prefix
22903 @c JP
22904 @subsubheading プレフィクス
22905 @c COMMON
22906
22907 @deffn {Generic function} common-prefix (a <sequence>) (b <sequence>) :key key test
22908 @c MOD gauche.sequence
22909 @c EN
22910 Returns a new sequence of the same type of @var{a} which contains
22911 the common prefix of sequences @var{a} and @var{b}. The types of
22912 @var{a} and @var{b} doesn't need to match.
22913 The type of @var{a} must have a builder.
22914
22915 For each corresponding element in @var{a} and @var{b}, the @var{key}
22916 procedure is applied (default @code{identity}), then compared with
22917 @var{test} procedure (default @code{eqv?}).
22918 @c JP
22919 シーケンス@var{a}と@var{b}に共通するプレフィクスを、@var{a}と同じ型の
22920 新たなシーケンスで返します。@var{a}と@var{b}の型は異なっていても構いません。
22921 @var{a}の型はビルダーを持っている必要があります。
22922
22923 @var{a}と@var{b}のそれぞれ対応する要素について、まず@var{key}手続きが
22924 呼ばれ、その結果が@var{test}手続きで比較されます。省略時にはそれぞれ
22925 @code{identity}および@code{eqv?}が使われます。
22926 @c COMMON
22927
22928 @example
22929 (common-prefix '(a b c d e) '(a b c e f))
22930 @result{} (a b c)
22931
22932 (common-prefix "abcef" '#(#\a #\b #\c #\d #\e))
22933 @result{} "abc"
22934 @end example
22935
22936 @c EN
22937 For strings, SRFI-13 has a specific function with
22938 related feature: @code{string-prefix-length}
22939 (@pxref{SRFI-13 String prefixes & suffixes}).
22940 @c JP
22941 文字列については、SRFI-13に似た機能を持つ手続き
22942 @code{string-prefix-length}があります。
22943 (@ref{SRFI-13 String prefixes & suffixes}参照)。
22944 @c COMMON
22945 @end deffn
22946
22947 @deffn {Generic function} common-prefix-to (class <class>) (a <sequence>) (b <sequence>) :key key test
22948 @c MOD gauche.sequence
22949 @c EN
22950 Returns a new sequence of the type @var{class} which contains
22951 the common prefix of sequences @var{a} and @var{b}. The types of
22952 @var{a} and @var{b} doesn't need to match, and neither
22953 needs to have a builder. The @var{class} must be a sequence class
22954 with a builder.
22955
22956 The meanings of keyword arguments are the same as @code{common-prefix}.
22957 @c JP
22958 シーケンス@var{a}と@var{b}に共通するプレフィクスを、@var{class}の
22959 インスタンスとして返します。@var{a}と@var{b}の型は異なっていても構わず、
22960 ビルダーを持っていなくても構いません。@var{class}はビルダーを備えた
22961 シーケンスのクラスである必要があります。
22962
22963 キーワード引数については@code{common-prefix}と同じです。
22964 @c COMMON
22965
22966 @example
22967 (common-prefix-to <list> "abcde" "ABCEF" :test char-ci=?)
22968 @result{} '(#\a #\b #\c)
22969 @end example
22970 @end deffn
22971
22972 @c EN
22973 @subsubheading Permutation and shuffling
22974 @c JP
22975 @subsubheading 置換とシャッフル
22976 @c COMMON
22977
22978 @deffn {Generic function} permute (src <sequence>) (permuter <sequence>) :optional fallback
22979 @c MOD gauche.sequence
22980 @c EN
22981 Returns a newly created sequence of the same type as @var{src}, in which
22982 the elements are permuted from @var{src} according to @var{permuter}.
22983
22984 @var{Permuter} is a sequence of exact integers. When the @var{k}-th element
22985 of @var{permuter} is @var{i}, the @var{k}-th element of the result
22986 is @code{(ref @var{src} @var{i})}. Therefore, the size of the result
22987 sequence is the same as the size of @var{permuter}. @var{Permuter}
22988 can be any kind of sequence, unrelated to the type of @var{src}.
22989
22990 It is allowed that the same index @var{i} can appear more than once
22991 in @var{permuter}.
22992 @c JP
22993 シーケンス@var{src}の要素を@var{permuter}に従って並べ替えた、新たなシーケンスを
22994 作って返します。返されるシーケンスは@var{src}と同じ型です。
22995
22996 @var{permuter}は正確な整数のシーケンスです。@var{pertmuter}の@var{k}番目の
22997 要素が@var{i}であれば、結果の@var{k}番目の要素が@code{(ref @var{src} @var{i})}
22998 になります。従って結果のシーケンスの長さは@var{permuter}と長さと同じになります。
22999 @var{permuter}の型は@var{src}の型と違っていて構いません。
23000
23001 同じインデックス@var{i}が複数回@var{permuter}に現れても構いません。
23002 @c COMMON
23003
23004 @example
23005 (permute '(a b c d) '(3 2 0 1)) @result{} (d c a b)
23006 (permute '(a b c d) '(0 2)) @result{} (a c)
23007 (permute '(a b c d) '(0 0 1 1 2 2)) @result{} (a a b b c c)
23008 @end example
23009
23010 @c EN
23011 If an integer in @var{permuter} is out of the valid range as the index
23012 of @var{src}, then an error is signaled unless @var{fallback} is given.
23013 If @var{fallback} is given, what value is used depends on the result of
23014 @code{(ref @var{src} @var{i} @var{fallback})}---which usually returns
23015 @var{fallback} for the out-of-range index @var{i}.
23016 @c JP
23017 @var{permuter}の要素の整数が@var{src}の有効なインデックスの範囲外であった場合、
23018 デフォルトではエラーが通知されます。しかし@var{fallback}が与えられた場合は、
23019 @var{src}の要素の読み出しが@code{(ref @var{src} @var{i} @var{fallback})}
23020 として行われます。これは通常、@var{i}が範囲外であった場合に@var{fallback}を
23021 返します。
23022 @c COMMON
23023
23024 @example
23025 (permute '#(a b c) '(3 2 1 0) 'foo) @result{} #(foo c b a)
23026
23027 (permute "!,HWdelor" #(2 5 6 6 7 1 -1 3 7 8 6 4 0) #\space)
23028 @result{} "Hello, World!"
23029 @end example
23030 @end deffn
23031
23032 @deffn {Generic function} permute-to (class <class>) (src <sequence>) (permuter <sequence>) :optional fallback
23033 @c MOD gauche.sequence
23034 @c EN
23035 Like @code{permute}, but the result will be an instance of the given @var{class}
23036 instead of the class of @var{src}.
23037 @c JP
23038 結果のシーケンスが@var{src}の型でなく@var{class}になること以外は、
23039 @code{permute}と同じです。
23040 @c COMMON
23041
23042 @example
23043 (permute-to <string> '(#\a #\b #\c #\d #\r)
23044 '(0 1 4 0 2 0 3 0 1 4 0))
23045 @result{} "abracadabra"
23046 @end example
23047 @end deffn
23048
23049 @deffn {Generic function} permute! (src <sequence>) (permuter <sequence>) :optional fallback
23050 @c MOD gauche.sequence
23051 @c EN
23052 Also like @code{permute}, but the result is stored back to @var{src}.
23053 @var{Src} must be a mutable sequence, and the length of @var{src} and
23054 @var{permuter} must be the same.
23055 @c JP
23056 これも@code{permute}と似ていますが、結果は新たに作られるシーケンスではなく
23057 @var{src}を破壊的変更して格納されます。@var{src}は変更可能でなければならず、
23058 また@var{src}と@var{permuter}は同じ長さでなければなりません。
23059 @c COMMON
23060 @end deffn
23061
23062 @deffn {Generic function} shuffle (src <sequence>) :optional random-source
23063 @c MOD gauche.sequence
23064 @c EN
23065 Returns a new sequence of the same type and size as @var{src},
23066 in which elements are randomly permuted.
23067 @c JP
23068 @var{src}と同じ型、長さのシーケンスで、@var{src}の要素の順序がランダムに
23069 置き換えられたものを返します。
23070 @c COMMON
23071
23072 @example
23073 (shuffle '(a b c d e)) @result{} (e b d c a)
23074 (shuffle "abcde") @result{} "bacde"
23075 @end example
23076
23077 @c EN
23078 This generic function uses SRFI-27 (@pxref{Sources of random bits}).
23079 By default it uses @code{default-random-source}, but you can pass
23080 an alternative random source by the optional argument.
23081 @c JP
23082 このジェネリックファンクションはSRFI-27 (@ref{Sources of random bits}参照)
23083 を使っています。デフォルトでは乱数源として@code{default-random-source}が
23084 使われますが、省略可能引数に乱数源を渡すこともできます。
23085 @c COMMON
23086 @end deffn
23087
23088 @deffn {Generic function} shuffle-to (class <class>) (src <sequence>) :optional random-source
23089 @c MOD gauche.sequence
23090 @c EN
23091 Like @code{shuffle}, except that the result will be an instance of
23092 @var{class} instead of the class of @var{src}.
23093 @c JP
23094 結果を@var{src}の型ではなく@var{class}のインスタンスとして返す@code{shuffle}です。
23095 @c COMMON
23096 @end deffn
23097
23098 @deffn {Generic function} shuffle! (src <sequence>) :optional random-source
23099 @c MOD gauche.sequence
23100 @c EN
23101 Like @code{shuffle}, but the result is stored back to @var{src}.
23102 @var{Src} must be a mutable sequence.
23103 @c JP
23104 結果を@var{src}を破壊的変更して格納する@code{shuffle}です。
23105 @var{src}は変更可能でなければなりません。
23106 @c COMMON
23107 @end deffn
23108
23109
23110 @node Implementing sequences, , Other operations over sequences, Sequence framework
23111 @subsection Implementing sequences
23112 @c NODE シーケンスを実装する
23113
23114 @c EN
23115 When you define your own aggregate class that holds ordered objects,
23116 you can follow the sequence protocol below to make it sequence.
23117 @c JP
23118 複数のオブジェクトを順序づけて保持するクラスを定義した場合、
23119 次のシーケンスプロトコルを実装することで、それをシーケンスにすることができます。
23120 @c COMMON
23121
23122 @c EN
23123 @strong{Inherit @code{<sequence>}}: You need to derive your class
23124 from @code{<sequence>}, so that sequence-related methods can be uniformly
23125 used. Note that @code{<sequence>} inherits @code{<collection>}, so your
23126 class will also be a collection.
23127 @c JP
23128 @strong{@code{<sequence>}を継承する}:
23129 ユーザ定義クラスが@code{<sequence>}を継承することにより、
23130 シーケンス関連のメソッドが一様に使えるようになります。なお、@code{<sequence>}は
23131 @code{<collection>}を継承しているので、そのクラスはコレクションにもなります。
23132 @c COMMON
23133
23134 @c EN
23135 @strong{Implement collection protocol}: A sequence is also a collection,
23136 and you need to implement a collection protocol
23137 (@pxref{Implementing collections}).
23138 For the very least, you need to have @code{call-with-iterator} method.
23139 If you want your sequence to be buildable,
23140 you also need to have @code{call-with-builder} method.
23141 All other collection generic functions have
23142 default method on top of these two, so they'll work; though
23143 you can specialize other collection generic functions if it's
23144 more efficient. We strongly recommend to specialize @code{size-of},
23145 for its default method walks over the entire sequence to find its size,
23146 which can be very ineffient (O(N) time).
23147 @c JP
23148 @strong{コレクションプロトコルを実装する}: シーケンスはコレクションでもあるので、
23149 コレクションプロトコルを実装しなければなりません
23150 (@ref{Implementing collections})。
23151 少なくとも@code{call-with-iterator}メソッドが必要で、ビルダブルにしたいなら
23152 @code{call-with-builder}も必要です。
23153 それ以外のコレクションジェネリックファンクションは、
23154 デフォルトメソッドがこれら二つのプリミティブの上に作られているので、
23155 他のメソッドを定義しなくてもコレクションAPIが使えます。
23156 ただ、他のジェネリックファンクションも特定化することで、
23157 ショートカットして性能が見込めるならそうするのが良いでしょう。
23158 特に@code{size-of}は、デフォルトメソッドは
23159 @code{call-with-iterator}で全要素を数え上げるO(N)時間を要するので、
23160 可能なら専用メソッドを定義することを強くおすすめします。
23161 @c COMMON
23162
23163 @c EN
23164 @strong{Implement sequence protocol}: You need to define @code{referencer},
23165 @code{modifier}, at least.
23166 If your sequence is immutable, you can leave @code{modifier} undefined
23167 (the default method raises an error). Again, you may want to
23168 specialize other generic functions if it's more efficient.
23169 It is recommended to define @code{call-with-reverse-iterator} as well,
23170 which is used for operations that walks the sequence in the reverse order
23171 (e.g. @code{fold-right)}. If @code{call-with-reverse-iterator} is not
23172 specialized, the default method uses @code{call-with-iterator}
23173 and keeps all the elements temporarily during execution, which
23174 takes O(N) space.
23175 @c JP
23176 @strong{シーケンスプロトコルを実装する}: 少なくとも@code{referencer}と
23177 @code{modifier}を実装する必要があります。
23178 シーケンスが変更不可なら@code{modifier}は未定義のままにすることもできます。
23179 デフォルトメソッドはエラーを投げます。
23180 ここでも、性能向上が見込めるなら他のシーケンスAPIを特定化するのが良いでしょう。
23181 可能なら、@code{call-with-reverse-iterator}も定義することをおすすめします。
23182 シーケンスを逆順にたどるAPI (例: @code{fold-right}) は、このメソッドが定義されていれば
23183 それを使います。定義されていなければ、@code{call-with-iterator}で一旦全要素を
23184 取り出す必要があるのでO(N)空間を消費します。
23185 @c COMMON
23186
23187 @c ----------------------------------------------------------------------
23188 @c @node Serializer, Terminal control, Simple dispatcher, Library modules
23189 @c @section @code{gauche.serializer} - Serializer
23190
23191 @c @deftp {Module} gauche.serializer
23192 @c @mdindex gauche.serializer
23193 @c @end deftp
23194
23195 @c ----------------------------------------------------------------------
23196 @node Syslog, Terminal control, Sequence framework, Library modules - Gauche extensions
23197 @section @code{gauche.syslog} - Syslog
23198 @c NODE Syslog, @code{gauche.syslog} - Syslog
23199
23200 @deftp {Module} gauche.syslog
23201 @mdindex gauche.syslog
23202 @c EN
23203 This module provides syslog(3) system logger interface.
23204
23205 For the common applications, you might find @code{gauche.logger} module
23206 easier to use (@pxref{User-level logging}). For the portable code,
23207 you might want to look at SRFI-215 (@pxref{Central log exchange}).
23208 This module is for those who need direct access to the syslog API.
23209
23210 The procedures are only defined if the underlying system supports them.
23211 @c JP
23212 このモジュールは syslog(3) のシステムロガーのインタフェースを提供します。
23213
23214 一般的なアプリケーションについては、@code{gauche.logger} モジュールの
23215 ほうが使いやすいでしょう(@ref{User-level logging}参照)。
23216 また、ポータブルなコードを書く場合は、SRFI-215が使えます
23217 (@ref{Central log exchange}参照)。
23218 このモジュールは syslog の API に直接アクセスする必要のある人向きです。
23219
23220 手続き群は基盤になっているシステムで syslog がサポートされている場合に
23221 のみ定義されます。
23222 @c COMMON
23223 @end deftp
23224
23225 @defun sys-openlog ident option facility
23226 [POSIX]
23227 @c MOD gauche.syslog
23228 @c EN
23229 Opens a connection to the system logger. A string argument
23230 @var{ident} is used for the prefix of the log, and usually is
23231 the program name. @var{Option} is an integer flag to control
23232 the behavior of logging, and @var{facility} is an integer
23233 that specify the type of the program.
23234
23235 The flag for @var{option} can be composed by @code{logior}-ing
23236 one or more of the following integer constants:
23237 @code{LOG_CONS}, @code{LOG_NDELAY}, @code{LOG_NOWAIT},
23238 @code{LOG_ODELAY}, @code{LOG_PERROR} and @code{LOG_PID}.
23239 (Some of the constants may not be defined if the underlying system
23240 doesn't support them).
23241
23242 The @var{facility} argument can be one of the following integer
23243 constants: @code{LOG_AUTH}, @code{LOG_AUTHPRIV}, @code{LOG_CRON},
23244 @code{LOG_DAEMON}, @code{LOG_FTP}, @code{LOG_KERN}, @code{LOG_LOCAL0}
23245 through @code{LOG_LOCAL7}, @code{LOG_LPR}, @code{LOG_MAIL}, @code{LOG_NEWS},
23246 @code{LOG_SYSLOG}, @code{LOG_USER} and @code{LOG_UUCP}.
23247 (Some of the constants may not be defined if the underlying system
23248 doesn't support them).
23249
23250 See your system's manpage of openlog(3) for detail description about
23251 these constants.
23252 @c JP
23253 システムロガーへのコネクションをオープンします。文字列の引数 @var{ident}
23254 はログの接頭辞に使われます。通常はプログラムを名前にします。@var{option}
23255 は整数のフラグで、ログの振舞いを制御します。@var{facility} はプログラムの
23256 タイプを指定する整数です。
23257
23258 @var{option}のフラグは以下の整数定数の1つまたは複数を @code{logior} で
23259 合成することができます:
23260 @code{LOG_CONS}、@code{LOG_NDELAY}、@code{LOG_NOWAIT}、
23261 @code{LOG_ODELAY}、@code{LOG_PERROR} および @code{LOG_PID} です
23262 (これらの定数のいくつかは基盤となるシステムがサポートしていなければ
23263 定義されません)。
23264
23265 @var{facility} 引数は以下の整数定数のどれかひとつです。
23266 @code{LOG_AUTH}、@code{LOG_AUTHPRIV}、@code{LOG_CRON},
23267 @code{LOG_DAEMON}、@code{LOG_FTP}、@code{LOG_KERN}、@code{LOG_LOCAL0}、
23268 から @code{LOG_LOCAL7}、@code{LOG_LPR}、@code{LOG_MAIL}、@code{LOG_NEWS},
23269 @code{LOG_SYSLOG}、@code{LOG_USER}、@code{LOG_UUCP} までです。
23270 (これらの定数のいくつかは基盤となるシステムがサポートしていなければ
23271 定義されません)。
23272
23273 これらの定数の詳しい説明については、システムの openlog(3) の
23274 マニュアル・ページを見てください。
23275 @c COMMON
23276 @end defun
23277
23278 @defun sys-syslog priority message
23279 [POSIX]
23280 @c MOD gauche.syslog
23281 @c EN
23282 Log the string @var{message}. Unlike syslog(3), this procedure doesn't
23283 do formatting---you can use @code{format} (@pxref{Output}) to create
23284 a formatted message, or use higher-level routine @code{log-format}
23285 (@pxref{User-level logging}).
23286
23287 An integer argument @var{priority} can be composed by @code{logior}-ing
23288 one of the @var{facility} constants described above and
23289 the @var{level} constants: @code{LOG_EMERG}, @code{LOG_ALERT},
23290 @code{LOG_CRIT}, @code{LOG_ERR}, @code{LOG_WARNING}, @code{LOG_NOTICE},
23291 @code{LOG_INFO}, @code{LOG_DEBUG}.
23292 @c JP
23293 文字列 @var{message} をログに記録します。syslog(3) とは違って、この手続きは
23294 フォーマットを行いません。フォーマットされた文字列を生成するなら
23295 @code{format} (@ref{Output}参照)が使えます。あるいは、より高水準の
23296 ルーチン @code{log-format} (@ref{User-level logging}参照)
23297 を使うこともできます。
23298
23299 整数の引数 @var{priority} は上述の @var{facility} 定数のどれかひとつ
23300 と、以下の@var{level}定数と@code{logior}して、合成することができます:
23301 @code{LOG_EMERG}、@code{LOG_ALERT}、@code{LOG_CRIT}、@code{LOG_ERR}、
23302 @code{LOG_WARNING}、@code{LOG_NOTICE}、@code{LOG_INFO}、@code{LOG_DEBUG}
23303 @c COMMON
23304
23305 @end defun
23306
23307 @defun sys-closelog
23308 [POSIX]
23309 @c MOD gauche.syslog
23310 @c EN
23311 Closes the connection to the logging system.
23312 @c JP
23313 ロギングシステムとのコネクションをクローズします。
23314 @c COMMON
23315 @end defun
23316
23317 @defun sys-setlogmask mask
23318 [POSIX]
23319 @c MOD gauche.syslog
23320 @c EN
23321 Sets the process's log priority mask that determines which calls to
23322 @code{sys-syslog} may be logged.
23323 An priority @var{mask} can be composed by @code{logior}-ing
23324 bitmasks corresponding to the @var{level} argument of @code{sys-syslog}.
23325 You can use @code{sys-logmask} below to obtain a bitmask
23326 from the level.
23327 @c JP
23328 どの @code{sys-syslog}への呼び出しを記録できるかを決める、プロセスのログ
23329 優先度マスクを設定します。
23330 優先度マスク@var{mask}は@code{sys-syslog}の@var{level}引数に
23331 対応するビットマスクを@code{logior}することで作成できます。
23332 レベルに対応するビットマスクは下の@code{sys-logmask}から
23333 取得することができます。
23334 @c COMMON
23335 @end defun
23336
23337 @defun sys-logmask level
23338 [POSIX]
23339 @c MOD gauche.syslog
23340 @c EN
23341 Returns an integer bitmask for @code{sys-setlogmask} from
23342 the log level @var{level}.
23343 @c JP
23344 ログレベル @var{level} から @code{sys-setlogmask} に対する
23345 ビットマスク整数を返します。
23346 @c COMMON
23347 @end defun
23348
23349 @c ----------------------------------------------------------------------
23350 @node Terminal control, Unit testing, Syslog, Library modules - Gauche extensions
23351 @section @code{gauche.termios} - Terminal control
23352 @c NODE 端末の制御, @code{gauche.termios} - 端末の制御
23353
23354 @deftp {Module} gauche.termios
23355 @mdindex gauche.termios
23356 @c EN
23357 This module provides procedures to control terminals.
23358 On Unix platforms, the low-level API provides POSIX termios interface
23359 as the module name suggests. This module also provides
23360 pseudo tty interface, if the system supports it.
23361 @c JP
23362 このモジュールは端末の制御のための手続きを提供します。
23363 Unix環境では、低レベルAPIはモジュール名からわかるように
23364 POSIX termiosへのインタフェースを提供しています。
23365 さらに、このモジュールでは、システムがサポートしている場合には
23366 擬似 tty のインタフェースも提供しています。
23367 @c COMMON
23368
23369 @c EN
23370 On Windows native platforms, POSIX termios interface is not
23371 available. It is too different from Windows console API to
23372 provide a meaningful emulation. The low-level Windows console
23373 API is available in the @code{os.windows} module
23374 (@pxref{Windows support}). You can still use high-level
23375 terminal control procedures in this module.
23376 @c JP
23377 Windowsネイティブ環境ではPOSIX termiosインタフェースは使えません。
23378 Windows console APIは大きく違っているので、意味のあるエミュレーションを
23379 提供するのが難しいためです。低レベルのWindows console APIは
23380 @code{os.windows}モジュールで使うことができます(@ref{Windows support}参照)。
23381 ただし、このモジュールの高レベル端末制御手続きは、
23382 Windowsネイティブ環境でも使うことができます。
23383 @c COMMON
23384 @end deftp
23385
23386 @menu
23387 * Posix termios interface::
23388 * Common high-level terminal control::
23389 @end menu
23390
23391 @node Posix termios interface, Common high-level terminal control, Terminal control, Terminal control
23392 @subsection Posix termios interface
23393 @c NODE POSIX termiosインタフェース
23394
23395 @c EN
23396 These procedures are available when the feature identifier
23397 @code{gauche.os.windows} is @emph{not} defined. See @code{cond-expand}
23398 in @ref{Feature conditional} for how to switch code using
23399 feature identifiers.
23400 @c JP
23401 ここに挙げる手続きは、機能シンボル@code{gauche.os.windows}が定義されて@emph{いない}
23402 場合にのみ利用可能です。機能シンボルによってコードを切り替える方法は
23403 @ref{Feature conditional}の@code{cond-expand}を参照してください。
23404 @c COMMON
23405
23406 @deftp {Builtin Class} <sys-termios>
23407 @clindex sys-termios
23408 @c MOD gauche.termios
23409 @c EN
23410 POSIX termios(7) structure.
23411 @c JP
23412 POSIX termios(7) の構造体です。
23413 @c COMMON
23414
23415 @defivar {<sys-termios>} iflag
23416 @end defivar
23417 @defivar {<sys-termios>} oflag
23418 @end defivar
23419 @defivar {<sys-termios>} cflag
23420 @end defivar
23421 @defivar {<sys-termios>} lflag
23422 @end defivar
23423 @defivar {<sys-termios>} cc
23424 @end defivar
23425
23426 @c EN
23427 The slots @code{iflag}, @code{oflag}, @code{cflag} and @code{lflag}
23428 contains non-negative integers representing bitmasks.
23429
23430 The slot @code{cc} contains a @emph{copy} of @code{c_cc} array
23431 of @code{struct termios}, as an u8vector (see @ref{Uniform vectors}
23432 for the details about u8vector).
23433 Since @code{cc} slot is a copy of the internal structure, you have
23434 to @code{set!} an u8vector to the slot explicitly to make
23435 changes to the @code{c_cc} array.
23436 @c JP
23437 @code{iflag}、@code{oflag}、@code{cflag}、@code{lflag}の各スロットは、
23438 対応するビットマスクを非負の整数で表現した値を保持しています。
23439
23440 また、@code{cc}スロットは@code{struct termios}の@code{c_cc}配列の
23441 @emph{コピー}を返します。
23442 @code{c_cc}配列の値を変えたい場合は、変更したu8vectorを明示的に
23443 @code{cc}スロットに@code{set!}して下さい。
23444 @c COMMON
23445
23446 @end deftp
23447
23448 @c EN
23449 Throughout this section, argument @var{port-or-fd} refers to
23450 either a port object or a small integer representing system's file
23451 descriptor. If @var{port} is not associated
23452 to the system terminal, an error is signaled. (You can check if @var{port}
23453 has an associated terminal by @code{sys-isatty?}.
23454 @pxref{Other file operations}).
23455 @c JP
23456 このセクションを通じて、引数 @var{port-or-fd} はポートオブジェクトか
23457 システムのファイルディスクリプタを表現する小さい整数かのどちらかです。
23458 @var{port}がシステム端末に結びついていないければ、エラーになります。
23459 (@code{sys-isatty?}を使えば@var{port}が端末と結びついているか
23460 どうかチェックできます。 @ref{Other file operations}参照)
23461 @c COMMON
23462
23463 @defun sys-tcgetattr port-or-fd
23464 @c MOD gauche.termios
23465 @c EN
23466 Returns terminal parameters in a @code{<sys-termios>} object,
23467 associated to @var{port-or-fd}.
23468 @c JP
23469 @var{port-or-fd} と結びついている @code{<sys-termios>}オブジェクトの
23470 端末パラメータを返します。
23471 @c COMMON
23472 @end defun
23473
23474 @defun sys-tcsetattr port-or-fd when termios
23475 @c MOD gauche.termios
23476 @c EN
23477 Sets terminal parameters associated to @var{port-or-fd} by @var{termios},
23478 which must be an instance of @code{<sys-termios>}.
23479
23480 An integer argument @var{when} specifies when the changes take effect.
23481 Three variables are pre-defined for the argument:
23482 @c JP
23483 @var{port-or-fd}と結びついている端末のパラメータを @var{termios} に設定します。
23484 @var{termios} は @code{<sys-termios>} のインスタンスでなければなりません。
23485
23486 整数の引数@var{when}はいつ変更を有効にするかを指定します。
23487 この引数用に3つの変数があらかじめ定義されています。
23488 @c COMMON
23489 @table @code
23490 @item TCSANOW
23491 @vindex TCSANOW
23492 @c EN
23493 The change is reflected immediately.
23494 @c JP
23495 変更を直ちに反映します。
23496 @c COMMON
23497 @item TCSADRAIN
23498 @vindex TCSADRAIN
23499 @c EN
23500 The change is reflected after all pending output is flushed.
23501 @c JP
23502 変更を、すべてのペンディングになっている出力がフラッシュされた後に反映します。
23503 @c COMMON
23504 @item TCSAFLUSH
23505 @vindex TCSAFLUSH
23506 @c EN
23507 The change is reflected after all pending output is flushed,
23508 and all pending input is discarded.
23509 @c JP
23510 変更を、すべてのペンディングになっている出力がフラッシュされ、かつ、
23511 すべてのペンディングになっている入力が破棄されたあとに反映します。
23512 @c COMMON
23513 @end table
23514 @end defun
23515
23516 @defun sys-tcsendbreak port-or-fd duration
23517 @c MOD gauche.termios
23518 @c EN
23519 Transmits a zero stream for the specified duration
23520 to the terminal associated to @var{port-or-fd}.
23521 The unit of duration depends on the system; see man tcsendbreak(3) of
23522 your system for details.
23523 @c JP
23524 ゼロストリームを指定した時間、@var{port-or-fd}と結びついている端末に
23525 送出します。時間の単位はシステム依存です。詳しくは、お使いの
23526 システムのマニュアルページ tcsendbreak(3)を参照してください。
23527 @c COMMON
23528 @end defun
23529
23530 @defun sys-tcdrain port-or-fd
23531 @c MOD gauche.termios
23532 @c EN
23533 Waits until all output written to @var{port-or-fd} is transmitted.
23534 @c JP
23535 @var{port-or-fd}へのすべての出力が送出されるまで待ちます。
23536 @c COMMON
23537 @end defun
23538
23539 @defun sys-tcflush port-or-fd queue
23540 @c MOD gauche.termios
23541 @c EN
23542 Discards data in the buffer of @var{port-or-fd}, specified by
23543 @var{queue}, which may be one of the following values.
23544 @c JP
23545 @var{port-or-fd}のバッファ内のデータを破棄します。@var{queue}には以下の値の
23546 どれかを指定します。
23547 @c COMMON
23548 @table @code
23549 @item TCIFLUSH
23550 @vindex TCIFLUSH
23551 @c EN
23552 Discards data received but not read.
23553 @c JP
23554 受信データしたが読み込んではいないデータを破棄します。
23555 @c COMMON
23556 @item TCOFLUSH
23557 @vindex TCOFLUSH
23558 @c EN
23559 Discards data written but not transmitted.
23560 @c JP
23561 書き出したが送出していないデータを破棄します。
23562 @c COMMON
23563 @item TCIOFLUSH
23564 @vindex TCIOFLUSH
23565 @c EN
23566 Do both @code{TCIFLUSH} and @code{TCOFLUSH} action.
23567 @c JP
23568 @code{TCIFLUSH} と @code{TCOFLUSH} の両方の動作をします。
23569 @c COMMON
23570 @end table
23571 @end defun
23572
23573 @defun sys-tcflow port-or-fd action
23574 @c MOD gauche.termios
23575 @c EN
23576 Controls data flow of @var{port-or-fd} by @var{action}, which may be
23577 one of the following values:
23578 @c JP
23579 @var{port-or-fd}のデータフローを@var{action}で制御します。@var{action}は
23580 以下の値のうちどれかです。
23581 @c COMMON
23582 @table @code
23583 @item TCOOFF
23584 @vindex TCOOFF
23585 @c EN
23586 Suspends output transmission.
23587 @c JP
23588 出力の送出をサスペンドします。
23589 @c COMMON
23590 @item TCOON
23591 @vindex TCOON
23592 @c EN
23593 Restarts output transmission.
23594 @c JP
23595 出力の送出を再開します。
23596 @c COMMON
23597 @item TCIOFF
23598 @vindex TCIOFF
23599 @c EN
23600 Transmits a STOP character to make the terminal device stop transmitting
23601 data to the system.
23602 @c JP
23603 端末デバイスがシステムへの送出を止めるよう STOP 文字を送出する。
23604 @c COMMON
23605 @item TCION
23606 @vindex TCION
23607 @c EN
23608 Transmits a START character to make the terminal device resume transmitting
23609 data to the system.
23610 @c JP
23611 端末デバイスがシステムへの送出を再開するよう START 文字を送出する。
23612 @c COMMON
23613 @end table
23614 @end defun
23615
23616 @defun sys-tcgetpgrp port-or-fd
23617 @c MOD gauche.termios
23618 @c EN
23619 Returns process group ID of the terminal associated to @var{port-or-fd}.
23620 @c JP
23621 @var{port-or-fd}の結びついている端末のプロセスのグループIDを返します。
23622 @c COMMON
23623 @end defun
23624
23625 @defun sys-tcsetpgrp port-or-fd pgrp
23626 @c MOD gauche.termios
23627 @c EN
23628 Sets process group ID of the terminal associated to @var{port-or-fd}
23629 to @var{pgrp}.
23630 @c JP
23631 @var{port-or-fd}の結びついている端末のプロセスのグループIDを@var{pgrp}に
23632 設定します。
23633 @c COMMON
23634 @end defun
23635
23636 @defun sys-cfgetispeed termios
23637 @defunx sys-cfsetispeed termios speed
23638 @defunx sys-cfgetospeed termios
23639 @defunx sys-cfsetospeed termios speed
23640 @c MOD gauche.termios
23641 @c EN
23642 Gets/sets input/output speed (baud rate) parameter stored in @var{termios}
23643 object. Speed is represented by the following predefined numbers:
23644 @code{B0}, @code{B50}, @code{B75}, @code{B110}, @code{B134},
23645 @code{B150}, @code{B200}, @code{B300}, @code{B600}, @code{B1200},
23646 @code{B1800}, @code{B2400}, @code{B4800}, @code{B9600},
23647 @code{B19200}, @code{B38400}.
23648 @c JP
23649 @var{termios}内の入出力スピード(ボーレート)を取得/設定します。スピードは
23650 以下の定義ずみの数値で表現されてます:
23651 @code{B0}、@code{B50}、@code{B75}、@code{B110}、@code{B134}、
23652 @code{B150}、@code{B200}、@code{B300}、@code{B600}、@code{B1200}、
23653 @code{B1800}、@code{B2400}、@code{B4800}、@code{B9600}、
23654 @code{B19200}、@code{B38400}。
23655 @c COMMON
23656
23657 @c EN
23658 Some system may support higher baud rate, such as @code{B57600},
23659 @code{B115200} or @code{B230400}. You can use @code{symbol-bound?}
23660 to check these options are defined. @code{B0} is used to
23661 terminate the connection.
23662 @c JP
23663 もっと速いボーレート、たとえば、@code{B57600}、
23664 @code{B115200} あるいは @code{B230400} をサポートしている
23665 システムもあります。@code{symbol-bound?}をつかえば、これらの
23666 オプションが定義されているかどうかをチェックできます。@code{B0}
23667 はコネクションを終了するのに使われます。
23668 @c COMMON
23669 @end defun
23670
23671 @defun sys-openpty :optional term
23672 @c MOD gauche.termios
23673 @c EN
23674 Opens a pair of pseudo ttys, one for master and the other for slave,
23675 then returns two integers which are their file descriptors.
23676 An optional argument @var{term} must be, if passed, a @code{<sys-termios>}
23677 object; it sets the slave pty's parameters.
23678
23679 You can use @code{open-input-fd-port} and/or @code{open-output-fd-port}
23680 to create a port around the returned file descriptor (@pxref{File ports}).
23681 To obtain pseudo tty's name, use @code{sys-ttyname}
23682 (@pxref{Other file operations}).
23683
23684 This function is available only if the system supports @code{openpty(3)}.
23685 @c JP
23686 擬似 tty のペア、マスターとスレーブをオープンし、2つの
23687 ファイルディスクリプタの整数を返します。オプション引数 @var{term}
23688 が渡される場合は、@code{<sys-termios>}オブジェクトでなければなりません。
23689 これは、pty パラメータを設定します。
23690
23691 @code{open-input-fd-port}と@code{open-output-fd-port}の両方またはどちらか
23692 を返されたファイルディスクリプタに対するポートを生成するために使うことが
23693 できます(@ref{File ports}参照)。擬似端末の名前を得るには @code{sys-ttyname}
23694 を使います(@ref{Other file operations}参照)。
23695
23696 この関数はシステムが @code{openpty(3)} をサポートしている場合にのみ利用
23697 可能です。
23698 @c COMMON
23699 @end defun
23700
23701 @defun sys-forkpty :optional term
23702 @c MOD gauche.termios
23703 @c EN
23704 Opens a pair of pseudo ttys, one for master and the other for slave,
23705 sets the slave pty suitable for login terminal, then fork(2).
23706
23707 Returns two integers; the first value is a child pid for the parent process,
23708 and 0 for the child process. The second value is a file descriptor
23709 of the master pty.
23710
23711 An optional argument @var{term} must be, if passed, a @code{<sys-termios>}
23712 object; it sets the slave pty's parameters.
23713
23714 This function is available only if the system supports @code{forkpty(3)}.
23715 @c JP
23716 擬似 ttyのペア、マスターとスレーブをオープンし、スレーブ sty を
23717 ログイン端末になるよう設定し、fork(2) します。
23718
23719 二つの整数、最初の値は親プロセスに対しては子の pid の値で、0ならば
23720 子プロセスです。ふたつ目の値はマスター pty のファイルディスクリプタの
23721 値です。
23722
23723 オプション引数 @var{term}が渡される場合は、それは@code{<sys-termios>}オブジェクト
23724 でなければなりません。これはスレーブ pty のパラメータを設定します。
23725
23726 この関数はシステムが @code{forkpty(3)} をサポートしている場合にのみ利用
23727 可能です。
23728 @c COMMON
23729
23730 @c EN
23731 Note: @code{sys-forkpty} has the same MT hazard as @code{sys-fork}
23732 (see @ref{Process management}, for details). If you're
23733 running multiple threads, use @code{sys-forkpty-and-exec} below.
23734 @c JP
23735 注意: @code{sys-forkpty}には@code{sys-fork}と同様のマルチスレッドハザー
23736 ドの危険性があります。(詳細については@ref{Process management}参照
23737 してください)。マルチスレッドプログラムでは後述の
23738 @code{sys-forkpty-and-exec}を利用してください。
23739 @c COMMON
23740 @end defun
23741
23742 @defun sys-forkpty-and-exec command args :key iomap term sigmask
23743 @c MOD gauche.termios
23744 @c EN
23745 Does @code{sys-forkpty}, and lets the child process
23746 immediately @code{exec}s the specified @var{command}
23747 with arguments @var{args}. This function doesn't have
23748 the hazard in multi-thread environment.
23749 @c JP
23750 @code{sys-forkpty}して、ただちに指定した@var{command}を引数
23751 @var{args}で子プロセスで@code{exec}します。この関数にはマルチスレッド
23752 環境でもハザードを起こしません。
23753 @c COMMON
23754
23755 @c EN
23756 The meanings of arguments @var{command}, @var{args}, @var{iomap} and
23757 @var{sigmask}
23758 are the same as @code{sys-exec} (see @ref{Process management}).
23759 If the keyword argument @var{term} is given, it is used to initialize
23760 the slave pty.
23761 @c JP
23762 引数@var{command}、@var{args}、@var{iomap}、@var{sigmask}の意味は
23763 @code{sys-exec}のものと同じです。(@ref{Process management}を見て
23764 ください)。キーワード引数@var{term}が与えられれば、スレーブptyの初期化
23765 に使われます。
23766 @c COMMON
23767 @end defun
23768
23769 @node Common high-level terminal control, , Posix termios interface, Terminal control
23770 @subsection Common high-level terminal control
23771 @c NODE 共通の高レベル端末制御
23772
23773 @defun without-echoing iport proc
23774 @c MOD gauche.termios
23775 @c EN
23776 If @var{iport} is an input port connected to a terminal,
23777 sets the terminal mode non-echoing and call @var{proc} with
23778 @var{iport} as an argument. Before returning from
23779 @code{without-echoing}, or throwing an error,
23780 the terminal mode is reset to the original state when this
23781 procedure is called. The procedure returns whatever value(s)
23782 @var{proc} returns.
23783 @c JP
23784 @var{iport}が端末につながった入力ポートである場合、
23785 端末をエコーしないモードにして@var{proc}を呼びます。@var{proc}には
23786 @var{iport}が引数として渡されます。
23787 @var{proc}から戻るか、@var{proc}がエラーを投げた場合に、
23788 端末は元のモードに戻されます。@var{proc}からの戻り値が@code{without-echoing}の
23789 戻り値となります。
23790 @c COMMON
23791
23792 @c EN
23793 You can also pass @code{#f} to @var{iport}. In that case,
23794 this procedure tries to open a console (@code{/dev/tty} on Unix,
23795 @code{CON} on Windows) and set the console mode, then calls
23796 @var{proc} with the opened input port. An error is thrown
23797 if the procedure can not open a console.
23798 @c JP
23799 @var{port}に@code{#f}を渡すこともできます。その場合、
23800 この手続きは標準の端末 (Unixでは@code{/dev/tty}、Windowsでは@code{CON})を
23801 オープンし、そにこつながった入力ポートを引数に@var{proc}を呼び出します。
23802 標準の端末がオープンできない場合はエラーが投げられます。
23803 @c COMMON
23804
23805 @c EN
23806 If @var{iport} is other than above, this procedure
23807 simply calls @var{proc} with @var{iport}. This allows
23808 the caller to read password from redirected input,
23809 for example.
23810 @c JP
23811 @var{iport}が上記のいずれにも該当しない場合は、単に@var{proc}を@var{iport}を引数にして
23812 呼び出し結果を返します。
23813 例えば、端末からエコーなしでパスワードを読むのと、
23814 リダイレクトでパスワードが流し込まれるのとを、区別せずに処理できます。
23815 @c COMMON
23816
23817 @c EN
23818 Note: Because of an implementation issue, on Windows native
23819 platforms this procedure always changes console mode
23820 of the standard input handle when @code{iport} is either
23821 @code{#f} or a terminal input port.
23822 @c JP
23823 註: 実装上の問題から、Windowsでは、@var{iport}が@code{#f}もしくは
23824 端末につながっている場合、常に標準入力ハンドルのモードが変更されます。
23825 @c COMMON
23826 @end defun
23827
23828 @defun has-windows-console?
23829 @c MOD gauche.termios
23830 @c EN
23831 Returns @code{#t} iff the running Gauche is Windows-native and
23832 the process has attached console. On Unix platforms this
23833 procedure always returns @code{#f}.
23834 @c JP
23835 走っているGaucheがWindowsネイティブで、プロセスが端末を持っている場合に@code{#t}を
23836 返します。Unixプラットフォームでは常に@code{#f}が返されます。
23837 @c COMMON
23838
23839 @c EN
23840 The reason that @code{cond-expand} isn't enough is that on Windows
23841 the program may start without console, but you can attach console
23842 afterwards. @xref{Windows console API}, for the details.
23843 @c JP
23844 この用途に@code{cond-expand}は不適です。というのも、Windowsプログラムは
23845 端末なしで起動した後に端末をアタッチする、といったことができるからです。
23846 詳しくは@ref{Windows console API}参照。
23847 @c COMMON
23848 @end defun
23849
23850
23851 @c ----------------------------------------------------------------------
23852 @node Unit testing, Threads, Terminal control, Library modules - Gauche extensions
23853 @section @code{gauche.test} - Unit Testing
23854 @c NODE 単体テスト, @code{gauche.test} - 単体テスト
23855
23856 @deftp {Module} gauche.test
23857 @mdindex gauche.test
23858 @c EN
23859 Defines a set of functions to write test scripts.
23860 A test script will look like this:
23861 @c JP
23862 テストスクリプトを書くための手続きを提供します。
23863 テストスクリプトは次のような形になります。
23864 @c COMMON
23865
23866 @lisp
23867 (use gauche.test)
23868 (test-start "my feature")
23869 @c EN
23870 (load "my-feature") ; @r{load your program}
23871 (import my-feature) ; @r{if your program defines a module.}
23872
23873 (test-module 'my-feature) ; @r{tests consistency in your module.}
23874 @c JP
23875 (load "my-feature") ; @r{テストすべきプログラムをロード}
23876 (import my-feature) ; @r{モジュールを定義している場合はインポート}
23877
23878 (test-module 'my-feature) ; @r{モジュールの一貫性チェック}
23879 @c COMMON
23880
23881 (test-section "feature group 1")
23882 (test "feature 1-1" EXPECT (lambda () TEST-BODY))
23883 (test "feature 1-2" EXPECT (lambda () TEST-BODY))
23884 @dots{}
23885
23886 (test-section "feature group 2")
23887 (define test-data ...)
23888 (test "feature 2-1" EXPECT (lambda () TEST-BODY))
23889 (test "feature 2-2" (test-error) (lambda () TEST-THAT-SIGNALS-ERROR))
23890 @dots{}
23891
23892 (test-end :exit-on-failure #t)
23893 @end lisp
23894
23895 @c EN
23896 With this convention, you can run test both interactively or
23897 in batch. To run a test interactively, just load the file
23898 and it reports a result of each test, as well as the summary
23899 of failed test at the end. To run a test in batch, it is
23900 convenient to redirect the stdout to some file
23901 If stdout is redirected to other than tty, all the verbose logs will go
23902 there, and only a small amount of messages go to stderr.
23903 @c JP
23904 このテストスクリプトは、バッチ処理でもインタラクティブセッションからでも
23905 実行できます。インタラクティブセッションの場合はこのテストスクリプトを
23906 ただロードすれば、各テストの結果とサマリーが報告されます。
23907 バッチテストの場合は、標準出力を別のファイルにリダイレクトしておくと良いでしょう。
23908 標準出力が端末でない場合、テスト手続きは詳しい結果をstdoutに出力し、簡単な
23909 メッセージを標準エラー出力に書き出します。
23910 @c COMMON
23911
23912 @c EN
23913 It is recommended to have a "check" target always in Makefile
23914 of your module/program, so that the user of your program can run a
23915 test easily. The rule may look like this:
23916 @c JP
23917 モジュールやプログラムを書いたら、Makefileに"check"ターゲットを作ることを
23918 お薦めします。ルールはこんな感じになるでしょう:
23919 @c COMMON
23920
23921 @example
23922 check :
23923 gosh my-feature-test.scm > test.log
23924 @end example
23925
23926 @c EN
23927 For the portable programs, there are a couple of srfis that provide testing
23928 frameworks (@pxref{Lightweight testing},
23929 and @pxref{A Scheme API for test suites}).
23930 In Gauche, when you can use these srfis with @code{gauche.test},
23931 srfi's tests work as a part of Gauche's tests.
23932 @c JP
23933 ポータブルなコードでは、テストフレームワークを定めたsrfiがあります
23934 (@ref{Lightweight testing}、および@ref{A Scheme API for test suites}参照)。
23935 Gaucheでは、これらのsrfiを@code{gauche.test}と一緒に使うと、
23936 srfiのテストがGaucheのテストとして走るようになっています。
23937 @c COMMON
23938 @end deftp
23939
23940
23941 @menu
23942 * Structuring a test file::
23943 * Individual test::
23944 * Incorporating external tests::
23945 * Better test failure reporting::
23946 * Quasi-static checks::
23947 @end menu
23948
23949 @node Structuring a test file, Individual test, Unit testing, Unit testing
23950 @subsection Structuring a test file
23951 @c NODE テストファイルの構造
23952
23953 @defun test-start module-name
23954 @c MOD gauche.test
23955 @c EN
23956 Initializes internal state and prints a log header.
23957 This should be called before any tests.
23958 @var{Module-name} is used only for logging purpose.
23959 @c JP
23960 テストの状態を初期化して、ヘッダをログに書き出します。テストを呼ぶ前に呼んで下さい。
23961 @var{module-name}はログのために使われる文字列です。
23962 @c COMMON
23963
23964 @c EN
23965 If a test is already running, this procedure just emits a log message
23966 and update internal test nesting level. It allows a test script
23967 to include another test script with @code{test-start}/@code{test-end}
23968 pair.
23969
23970 With this feature, you can split a lengthy test script into several
23971 sub test scripts, each of which is a stand-alone test script, and include
23972 them into the main test script. By doing so, you can run a single
23973 sub test script while developing, and run the main test script for
23974 full tests.
23975 @c JP
23976 テストが既に走っている場合は、
23977 この手続きはログメッセージを出して内部のテストネストレベルを更新するだけです。
23978 これにより、@code{test-start}/@code{test-end}のペアを持つスクリプトを
23979 別のテストスクリプトからincludeすることができます。
23980
23981 この機能は、例えば長大なテストスクリプトをいくつかのサブテストスクリプトに
23982 分割するのに役立ちます。各サブテストスクリプトはそれぞれ独立に走れるように
23983 しておいて、元のテストスクリプトはそれらをincludeします。
23984 これによって、開発中は必要なサブテストスクリプトだけを走らせ、フルテストでは
23985 全てのテストを走らせる、といった運用ができます。
23986 @c COMMON
23987 @end defun
23988
23989 @defun test-end :key exit-on-failure
23990 @c MOD gauche.test
23991 @c EN
23992 Prints out list of failed tests. If @var{exit-on-failure} is @code{#f} or
23993 omitted, this procedure returns the number of failed tests.
23994
23995 Otherwise, this function terminates the @code{gosh}
23996 process by @code{exit}. If a fixnum is given to @code{exit-on-failure}
23997 it becomes the process's exit status; if other true value is given,
23998 the exit status will be 1.
23999 @c JP
24000 失敗したテストのリストを報告します。@var{exit-on-failure}が@code{#f}か
24001 省略された場合は、この手続きは失敗したテストの数を返します。
24002
24003 そうでなければ、この手続きは@code{exit}を呼んで@code{gosh}を
24004 終了させます。@code{exit-on-failure}にfixnumが渡された場合は、
24005 それがプロセスの終了ステータスとして使われます。@code{exit-on-failure}が
24006 他の真となる値であった場合は、終了ステータスは1となります。
24007 @c COMMON
24008
24009 @c EN
24010 If test is nested, that is, this @code{test-end} corresponds
24011 to inner @code{test-start} while outer test is ongoing, this procedure
24012 only emits a log message and adjust internal test nesting level.
24013 @c JP
24014 テストがネストしている場合、つまりこの@code{test-end}と対応する@code{test-start}
24015 が、既にテストが走っている状況で実行されていた場合は、この手続きは単にログメッセージを
24016 出力して内部のテストネストレベルを調整します。
24017 @c COMMON
24018 @end defun
24019
24020 @defun test-running?
24021 @c MOD gauche.test
24022 @c EN
24023 Returns @code{#t} if test is running, that is, you're between outermost
24024 @code{test-start} and @code{test-end}. Returns @code{#f} otherwise.
24025 @c JP
24026 テストが実行中、つまり、一番外側の@code{test-start}と@code{test-end}の間に
24027 いるならば@code{#t}を、そうでなければ@code{#f}を返します。
24028 @c COMMON
24029 @end defun
24030
24031
24032 @defun test-section section-name
24033 @c MOD gauche.test
24034 @c EN
24035 Marks beginning of the group of tests. This is just for logging.
24036 @c JP
24037 一群のテストの開始をマークします。単にログに使われるだけです。
24038 @c COMMON
24039 @end defun
24040
24041 @defun test-log fmtstr args @dots{}
24042 @c MOD gauche.test
24043 @c EN
24044 This is also just for logging. Creates a formatted string
24045 with @var{fmrstr} and @var{args} just like @code{format},
24046 then write it to the current output port, with prefix @code{;; }
24047 and newline at the end.
24048
24049 With the typical Makefile settings, where you redirect
24050 stdout of test scripts to a log file, the message only goes to
24051 the log file.
24052
24053 Using this, you can dump information that can't be automatically
24054 tested but may be useful for troubleshooting. For example,
24055 you get a mysterious test failure reports you can't reproduce
24056 on your machine, and suspect
24057 some aspects of the running systems may unpredictably
24058 affect the test result.
24059 You can put @code{test-log} in the test code to dump such parameters,
24060 and ask the reporter to run the test again and analyze the log.
24061 @c JP
24062 この手続きも単なるログのためのものです。
24063 @code{format}と同じように@var{fmtstr}と@var{args}からフォーマット済み文字列を
24064 作り、@code{;; }を前に、改行文字を後につけて現在の出力ポートへと出力します。
24065
24066 典型的なMakefileでのテスト起動では、テストスクリプトの標準出力をログに流すので、
24067 このメッセージもログにのみ記録されることになります。
24068
24069 この手続きは、自動化テストで検査することは出来ないけれどトラブルシューティングに
24070 役に立つかもしれない情報をダンプしておくのに使えます。
24071 例えば、謎のテスト失敗報告が来て、でも手元ではどうしても再現できず、
24072 実行システムに固有のある側面が影響しているのではないかと推測できたとしましょう。
24073 その場合、@code{test-log}でそういった情報をダンプするコードをテストスクリプトに
24074 仕込んでおいて、もう一度報告者のマシンでテストを走らせてもらい、そのログを解析する
24075 ことができるでしょう。
24076 @c COMMON
24077 @end defun
24078
24079 @defun test-record-file file
24080 @c MOD gauche.test
24081 @c EN
24082 Suppose you have several test scripts. Normally you run them
24083 as a group and what you want to know is a concise summary of
24084 the whole results, instead of each result of individual test files.
24085
24086 A @emph{test record file} is an auxiliary file used to
24087 gather summary of the result. It holds a one-line summary
24088 of tests like this:
24089 @c JP
24090 テストスクリプトがいくつかある場合を考えます。通常は、それらのテストスクリプト
24091 をひとつづつ走らせて結果を確かめるのではなく、全部を一気に走らせて
24092 簡単な結果のまとめだけを知りたいと思うでしょう。
24093
24094 @emph{test record file}はテスト結果を集積するための補助ファイルです。
24095 その内容は次のような一行のサマリになっています。
24096 @c COMMON
24097
24098 @example
24099 Total: 9939 tests, 9939 passed, 0 failed, 0 aborted.
24100 @end example
24101
24102 @c EN
24103 When a test record file exists,
24104 @code{test-start} reads and parses it, and remembers the numbers.
24105 Then @code{test-end} adds the count of the results and
24106 writes them back to the same test record file.
24107 @c JP
24108 test record fileが既に存在していると、@code{test-start}は
24109 それを読みこんで数字を覚えておきます。そして@code{test-end}が
24110 そのスクリプト中のテスト結果の数字を加算して、同じtest record fileに書き戻します。
24111 @c COMMON
24112
24113 @c EN
24114 If you writes the @code{check} target in your makefile as follows,
24115 you will get the final one-line summary every time you run
24116 @code{make check}, assuming that @file{test1.scm}, @file{test2.scm},
24117 and @file{test3.scm} all has @code{(test-record-file "test.record")}
24118 before a call to @code{test-start}.
24119 @c JP
24120 makefileの@code{check}ターゲットを次のように書いておけば、
24121 @code{make check}を実行するたびにテスト結果の一行サマリを
24122 得ることができます。
24123 ただし、@file{test1.scm}、@file{test2.scm}、@file{test3.scm}はいずれも
24124 @code{test-start}呼び出し前に@code{(test-record-file "test.record")}を
24125 評価しているものとします。
24126 @c COMMON
24127
24128 @example
24129 check:
24130 @@rm -f test.record test.log
24131 gosh test1.scm >> test.log
24132 gosh test2.scm >> test.log
24133 gosh test3.scm >> test.log
24134 @@cat test.record
24135 @end example
24136
24137 @c EN
24138 Note that to make @code{test-record-file} work, it must be placed
24139 before the call to @code{test-start}.
24140
24141 Alternatively, you can use the environment variable
24142 @code{GAUCHE_TEST_RECORD_FILE} to specify the test record file.
24143 @c JP
24144 @code{test-record-file}手続きがうまく動作するためには、それが
24145 @code{test-start}より前に呼ばれなければならないことに注意してください。
24146
24147 この手続きのかわりに、環境変数@code{GAUCHE_TEST_RECORD_FILE}を使って
24148 test record fileを指定することもできます。
24149 @c COMMON
24150 @end defun
24151
24152 @deftp {Environment Variable} GAUCHE_TEST_RECORD_FILE
24153 @c EN
24154 If this environment variable is set when the test script is run,
24155 its value is used as the name of the test record file.
24156
24157 If the test script calls @code{test-record-file}, it takes precedence
24158 and this environment variable is ignored.
24159 @c JP
24160 テストスクリプトが走る時にこの環境変数が指定されていれば、
24161 その値がtest record fileの名前として使われます。
24162
24163 ただしテストスクリプト中に@code{test-record-file}の呼び出しがあると
24164 そちらが優先され、この環境変数は無視されます。
24165 @c COMMON
24166 @end deftp
24167
24168 @defun test-summary-check
24169 @c MOD gauche.test
24170 @c EN
24171 If the test record file is set (either by @code{test-record-file} or
24172 the environment variable @code{GAUCHE_TEST_RECORD_FILE}), read it,
24173 and then exit with status 1 if the record has nonzero failure
24174 count and/or nonzero abort count. If the test record file isn't
24175 set, this procedure does nothing.
24176 @c JP
24177 テストレコードファイルが(@code{test-record-file}もしくは環境変数
24178 @code{GAUCHE_TEST_RECORD_FILE}によって)設定されていた場合、
24179 それを読み込んで、失敗カウントとアボートカウントがともに0でなければ
24180 終了ステータス1でexitします。テストレコードファイルが設定されていなければ
24181 何もしません。
24182 @c COMMON
24183
24184 @c EN
24185 This is useful when you have multiple test scripts and you want
24186 to let @code{make} fail if any of tests fails, but not before all
24187 test script is run. If you make every test script use
24188 @code{:exit-on-failure} of @code{test-end}, then @code{make}
24189 stops immediately after the script that fails. Instead, you
24190 avoid using @code{:exit-on-failure}, but use the test record file
24191 and for the last thing you can call this function:
24192 @c JP
24193 これは、複数のテストスクリプトを持っていて、どれかが失敗したら@code{make}に
24194 それを伝えたいけれども、テストスクリプト自体はすべて走らせたい、という場合に便利です。
24195 各テストスクリプトで@code{test-end}に@code{:exit-on-failure}を
24196 使ってしまうと、@code{make}は失敗したテストスクリプトのところで処理を打ち切って
24197 しまいます。そこで@code{:exit-on-failure}を使うのを避け、
24198 テストレコードファイルを使い、ビルドの最後にこの関数を呼ぶようにします:
24199 @c COMMON
24200
24201 @example
24202 check:
24203 rm -f $GAUCHE_TEST_RECORD_FILE test.log
24204 gosh test1.scm >> test.log
24205 gosh test2.scm >> test.log
24206 cat $GAUCHE_TEST_RECORD_FILE /dev/null
24207 gosh -ugauche.test -Etest-summary-check -Eexit
24208 @end example
24209
24210 @c EN
24211 By this, @code{make} will run all the test script no matter how
24212 many of them fails (since @code{gosh} exits with status 0), but
24213 detect an error since the last line of @code{gosh} call exits
24214 with status 1 if there has been any failure.
24215 @c JP
24216 こうしておくと@code{make}は失敗があろうともすべてのテストスクリプトを
24217 実行し (@code{gosh}は常に終了ステータス0で終了するので)、
24218 最後の行でテストレコードファイルを参照して、失敗があった場合に
24219 @code{make}にそれを伝えることができます。
24220 @c COMMON
24221 @end defun
24222
24223 @node Individual test, Incorporating external tests, Structuring a test file, Unit testing
24224 @subsection Individual test
24225 @c NODE 個々のテスト
24226
24227 @c EN
24228 Most test frameworks have various test procedures such as @code{test-assert},
24229 @code{test-equal}, etc., depending on what you want to test.
24230 We have only one, @code{test}, and its thin wrapper
24231 @code{test*}. It takes a thunk (or an expression) to run, the expected
24232 result, and an optional check predicate to compare the expected result against
24233 the actual result. Various conditions, such as testing the actual
24234 result is a true value,
24235 or testing the expression raising a specific error, can be handled
24236 by the check predicate. The default check predicate handles typical cases:
24237 @c JP
24238 多くのテストフレームワークでは、何をテストするかによって@code{test-assert}や
24239 @code{test-equal}などの様々なテスト手続きを提供しています。
24240 Gaucheではテスト手続きは@code{test} (およびそのラッパーである@code{test*}) だけです。
24241 @code{test}はテストする式(のサンク)、期待される結果、そして省略可能な検査述語を取り、
24242 式の実際の結果と期待される結果を検査述語で比較します。
24243 単純に値を比較する、エラーが投げられることを確認する、など様々なテストは
24244 検査述語によって処理されます。デフォルトの検査述語でも、
24245 以下のような色々なテストに対応できます。
24246 @c COMMON
24247
24248 @itemize @bullet
24249 @item
24250 @c EN
24251 Compare the expected result with the actual result.
24252 @c JP
24253 期待される結果と実際の結果を比較する。
24254 @c COMMON
24255 @example
24256 (test* "one plus one equals two"
24257 2
24258 (+ 1 1))
24259 @end example
24260 @item
24261 @c EN
24262 Assert the expression returns true value (i.e. not @code{#f}).
24263 @c JP
24264 式が真となる値(@code{#f}でない値)を返すことを確認する。
24265 @c COMMON
24266 @example
24267 (test* "'any' returns non-false value"
24268 (test-truthy)
24269 (any integer? '(1.2 3/4 5)))
24270 @end example
24271 @item
24272 @c EN
24273 Check if the actual result is one of possible values.
24274 @c JP
24275 実際の結果が可能ないくつかの結果のうちのひとつであることを確認する。
24276 @c COMMON
24277 @example
24278 (test* "get random ineteger between 0 and 5"
24279 (test-one-of 0 1 2 3 4 5)
24280 (random-integer 6))
24281 @end example
24282
24283 @item
24284 @c EN
24285 Check if the expression raises an expected error.
24286 @c JP
24287 式が期待するエラーを投げることを確認する。
24288 @c COMMON
24289 @example
24290 (test* "expects read error"
24291 (test-error <read-error>)
24292 (read-from-string "(a .)"))
24293 @end example
24294 @end itemize
24295
24296 @c EN
24297 With this way, it is easier to parameterize tests, e.g.
24298 loop over a list of expected result and test thunks.
24299 @c JP
24300 このようにしておくと、例えば期待される結果とテストサンクのリストを用意して
24301 ループするような、テストのパラメタライズが容易にできます。
24302 @c COMMON
24303
24304
24305 @defmac test* name expected expr :optional check report hook
24306 @c MOD gauche.test
24307 @c EN
24308 A convenience macro that wraps @var{expr} by lambda.
24309 @c JP
24310 @var{expr}をlambdaでくるんでくれる便利なマクロです。
24311 @c COMMON
24312
24313 @example
24314 (test* name expected expr opt ...)
24315 @equiv{} (test name expected (lambda () expr) opt ...)
24316 @end example
24317 @end defmac
24318
24319 @defun test name expected thunk :optional check report hook
24320 @c MOD gauche.test
24321 @c EN
24322 Calls @var{thunk}, and checks its result fits @var{expected}
24323 using a procedure @var{check}, which
24324 is called as follows:
24325 @example
24326 (@var{check} @var{expected} @var{result-of-thunk})
24327 @end example
24328 It should return @code{#t} if the given result agrees with the
24329 expected value, or @code{#f} otherwise.
24330 The default check procedure is @code{test-check}, explained
24331 below. It compares @var{expected} and @var{result-of-thunk}
24332 with @code{equal?}, except when @var{expected} is some
24333 of special case test objects. (See ``testing ambiguous results''
24334 and ``testing abnormal cases''
24335 paragraphs below for this special treatment.)
24336
24337 One typical usage of the custom check
24338 procedure is to compare inexact numbers tolerating small error.
24339 @c JP
24340 @var{thunk}を呼び、その結果が@var{expected}に沿っているかを
24341 @var{check}を次のとおり呼び出すことで確認します。
24342 @example
24343 (@var{check} @var{expected} @var{result-of-thunk})
24344 @end example
24345 この手続きは、渡された結果が期待する値と合致する場合に@code{#t}を、
24346 そうでなければ@code{#f}を返さなければなりません。
24347 デフォルトの@var{check}手続きは下で述べる@code{test-check}です。
24348 これは、@var{expected}がいくつかの特殊なテストオブジェクトである場合をのぞき、
24349 @var{expected}と@var{result-of-thunk}が@code{equal?}
24350 である場合に@code{#t}を返します。すなわち、通常はテスト式の結果が
24351 期待するものと@code{equal?}であればテストは成功である、ということです。
24352 (特別な場合については下の ``曖昧な結果をテストする'' および
24353 ``異常系をテストする'' の項を見てください)。
24354
24355 特別な比較手続きのひとつの用法は、非正確な数値を、多少の誤差を許して
24356 比較するような場合です。
24357 @c COMMON
24358
24359 @example
24360 (test "test 1" (/ 3.141592653589 4)
24361 (lambda () (atan 1))
24362 (lambda (expected result)
24363 (< (abs (- expected result)) 1.0e-10)))
24364 @end example
24365
24366 @c EN
24367 @var{Name} is a name of the test, for the logging purpose.
24368 @c JP
24369 @var{name}はログに残すためのテストの名前です。
24370 @c COMMON
24371
24372 @c EN
24373 When @var{thunk} signals an uncaptured error, it is caught and
24374 yields a special error object @code{<test-error>}.
24375 You can check it with another error object created by
24376 @code{test-error} function to see if it is an expected type
24377 of error. See the entry of @code{test-error} below for the details.
24378 @c JP
24379 @var{thunk}内で捕捉されないエラーが発生した場合、それは捕捉され、
24380 特別なエラーオブジェクト@code{<test-error>}に置き換えられます。
24381 その結果を、下で説明する@code{test-error}手続きで作った@code{<test-error>}
24382 オブジェクトと比較することにより、エラーが期待されたものであるか、
24383 また適切な例外が上がっているかをテストすることができます。
24384 @c COMMON
24385
24386 @c EN
24387 The @var{report} optional argument must be an @code{#f} or a
24388 procedure that takes three arguments. If it is a procedure, it is called
24389 after @var{check} returns false (but before @var{hook} is called).
24390 The first argument is @var{name},
24391 the seond argument is @var{expected}, and the third argument
24392 is either the result of @var{thunk}, or a @code{<test-error>} object
24393 when @var{thunk} raises an error.
24394 The default is @code{test-report-failure} procedure, which simply
24395 uses @code{write} to display the result of @var{thunk}
24396 or a @code{<test-error>} object.
24397 By passing your own procedure, you can customize
24398 the message to be printed when the test is failed.
24399 @c JP
24400 省略可能引数@var{report}は@code{#f}か、引数を3つ取る手続きです。
24401 @var{check}が偽を返した場合に呼ばれます (ただし、@var{hook}が呼ばれる前です)。
24402 最初の引数は@var{name}、次の引数は@var{expeced}、最後の引数は@var{thunk}が
24403 返した値か、@var{thunk}がエラーを投げた場合は@code{<test-error>}オブジェクトです。
24404 デフォルトは@code{test-report-failure}手続きで、これは単に@code{write}を使って
24405 最後の引数(実際の結果、あるいは@code{<test-error>}オブジェクト)を出力するだけです。
24406 別の手続きを与えることにより、テスト失敗時の出力をカスタマイズできます。
24407 @c COMMON
24408
24409 @c EN
24410 Finally, the @var{hook} optional argument must be an @code{#f} or a procedure
24411 that takes four arguments. If it is a procedure, it is called after
24412 the @code{test} procedure finishes the test. The first argument
24413 is a symbol either @code{pass} or @code{fail}, the second argument
24414 is @var{name}, the third argument is @var{expected}, and the fourth argument
24415 is either the result of @var{thunk}, or a @code{<test-error>} object
24416 when @var{thunk} raises an error. The return value of @var{hook} is
24417 ignored.
24418
24419 It is mainly for libraries that wrap @code{gauche.test} and wants to
24420 do its own bookkeeping.
24421 @c JP
24422 最後に、省略可能引数@var{hook}は、@code{#f}か4引数の手続きでなければなりません。
24423 それが手続きの場合、@code{test}がテストを終えた後で次の引数で呼び出されます:
24424 第1引数はシンボル@code{pass}か@code{fail}、第2引数は@var{name}、
24425 第3引数は@var{expected}、そして第4引数は、@var{thunk}の返り値か、
24426 @var{thunk}がエラーを投げた場合は@code{<test-error>}オブジェクト。
24427 @var{hook}の戻り値は無視されます。
24428
24429 これは、@code{gauche.test}をラップしたライブラリが独自にテスト結果を記録したい
24430 場合に便利です。
24431 @c COMMON
24432
24433 @c EN
24434 Note: In 0.9.10, we didn't have @var{report} argument. Instead of
24435 adding @var{report} to the last optional argument, we made it the second
24436 and shifted @var{hook}, for @var{hook} arugment will rarely be used.
24437 To keep the backward compatibility, we recognize if
24438 4-argument procedure is passed to a @var{report} argument we treat it
24439 as @var{hook}, with warning. This compatibility feature will be removed
24440 in future releases.
24441 @c JP
24442 註: 0.9.10では@var{report}引数がありませんでした。@var{report}引数を追加するに
24443 当たって、それを最後の省略可能引数ではなく、2番目の省略可能引数として
24444 @var{hook}引数をずらすことにしました。
24445 @var{hook}引数は滅多に使われないだろうという判断です。
24446 互換性のため、@var{report}引数に4引数の手続きが渡された場合は
24447 警告を出したうえでそれを@var{hook}として扱うコードが今は入っています。
24448 将来のリリースではこの互換性コードは取り除かれます。
24449 @c COMMON
24450 @end defun
24451
24452 @defun test-check expected actual :optional equal
24453 @c MOD gauche.test
24454 @c EN
24455 The default procedure @code{test} and @code{test*} use
24456 to check the result of the test expression conforms the
24457 expected value. By default, @code{test-check} just compares
24458 @var{expected} and @var{actual} with a procedure @var{equal},
24459 which is defaulted to @code{equal?}. @code{test-check} behaves
24460 differently if @var{expected} is one of special test objects
24461 described below.
24462 @c JP
24463 テスト式の結果が期待された値に合致していることをチェックするために
24464 @code{test}と@code{test*}が使うデフォルトの手続きです。
24465 基本的に、@code{test-check}は@var{expected}と@var{actual}を
24466 @var{equal}に渡された手続きで比較するだけです。@var{equal}の
24467 デフォルト値は@code{equal?}です。
24468 ただし、以下に述べるとおり、@var{expected}が特殊なテストオブジェクト
24469 だった場合には特別な振る舞いをします。
24470 @c COMMON
24471 @end defun
24472
24473 @defun test-report-failure name expected actual
24474 @c MOD gauche.test
24475 @c EN
24476 The default procedure to report test failure. It just
24477 writes @var{actual} with @code{write}.
24478 You can customize the failure report by passing your reporting procedure
24479 to @var{report} argument to @code{test} and @var{test*}.
24480 See @code{test-report-failure-diff} below, for example.
24481 @c JP
24482 テスト失敗をレポートする手続きのデフォルトです。これは単に
24483 @var{actual-result}を@code{write}で書き出すだけです。
24484 @code{test}や@code{test*}の@var{report}引数に独自の手続きを渡すことにより、
24485 テスト失敗時の表示をカスタマイズできます。
24486 例えば下の@code{test-report-failure-diff}を参照してください。
24487 @c COMMON
24488 @end defun
24489
24490 @c EN
24491 @subsubheading Testing ambiguous results
24492 @c JP
24493 @subsubheading 曖昧な結果をテストする
24494 @c COMMON
24495
24496 @defun test-one-of choice @dots{}
24497 @c MOD gauche.test
24498 @c EN
24499 Sometimes the result of test expression depends on various
24500 external environment, and you cannot put an exact expected value.
24501 This procedure supports to write such tests conveniently.
24502 @c JP
24503 時々、テスト式@var{expr}の結果が外部の環境に左右されるため、
24504 ひとつの確定した値を期待値@code{expected}として書いておけない場合があります。
24505 この手続きはそのようなテストを簡単に書けるようにします。
24506 @c COMMON
24507
24508 @c EN
24509 Returns a special object representing @emph{either one of the choices}.
24510 The default check procedure, @code{test-check}, recognizes the object
24511 when it is passed in the @var{expected} argument, and returns true
24512 if any one of @var{choice} @dots{} passes the check against the result.
24513
24514 For example, the following test passes if @code{proc} returns either
24515 1 or 2.
24516 @c JP
24517 @emph{@var{choice} @dots{} のいずれか} を表現する特別なオブジェクトを返します。
24518 デフォルトの検査手続きである@code{test-check}は、@var{expected}引数に
24519 そのオブジェクトが渡ってきた場合には、テスト結果と@var{choice} @dots{}を
24520 ひとつづつ照合し、どれかがマッチすれば真を返します。
24521
24522 例えば次のテストは、@code{proc}が1か2を返せば成功となります。
24523 @c COMMON
24524
24525 @example
24526 (test* "proc returns either 1 or 2" (test-one-of 1 2) (proc))
24527 @end example
24528
24529 @c EN
24530 Note that @code{test-check} compares the actual result against each of
24531 @var{choice}s by @code{test-check} itself, that is:
24532 @c JP
24533 @code{test-check}は各@var{choice}に対して@code{test-check}を再帰的に
24534 呼びます。すなわち:
24535 @c COMMON
24536
24537 @example
24538 (test-check (test-one-of choice @dots{}) result equal)
24539 @equiv{} (or (test-check choice result equal) @dots{})
24540 @end example
24541
24542 @c EN
24543 This, if you want to compare each choice
24544 with customized equivalence procedure, pass @code{test-check}
24545 with a specialized equivalence procedure as the check procedure.
24546 The following example compares each @var{choice} and the result
24547 case-insensitively:
24548 @c JP
24549 従って、各選択肢を比較する手続きをカスタマイズしたい場合は、
24550 それを与えた@code{test-check}手続きをチェック手続きとして渡してください。
24551 例えば次の例は、各選択肢と結果を@code{string-ci=?}で比較します:
24552 @c COMMON
24553
24554 @example
24555 (test* "Using one-of with case insensitive comparison"
24556 (test-one-of "abc" "def")
24557 "Abc"
24558 (cut test-check <> <> string-ci=?))
24559 @end example
24560 @end defun
24561
24562
24563 @defun test-none-of choice @dots{}
24564 @c MOD gauche.test
24565 @c EN
24566 Similar to @code{test-one-of}, but creates a special object
24567 representing @emph{none of the choices}.
24568 The test suceeds if the test expression evaluates to a value that
24569 don't match any of @var{choice}s.
24570 @c JP
24571 @emph{@var{choice} @dots{} のいずれでもない} を表現する特別なオブジェクトを返します。
24572 テストは、テスト結果が@var{choice}のどれにもマッチしなかった時に成功となります。
24573 @c COMMON
24574 @end defun
24575
24576 @c EN
24577 Note: If you want to compare inexact numeric result,
24578 you can use @code{approx=?} (@pxref{Numerical comparison}).
24579 @c JP
24580 註: 非正確な数値の結果を比較したい場合は、
24581 @code{approx=?}が使えます (@ref{Numerical comparison}参照)。
24582 @c COMMON
24583
24584
24585 @defun test-truthy
24586 @c MOD gauche.test
24587 @c EN
24588 Returns a special object that expects a true value, i.e. anything
24589 but @code{#f}. Use it to assert the test expression returns a true value
24590 but not necessarily @code{#t}.
24591 @c JP
24592 真の値、つまり@code{#f}以外のあらゆる値を期待するオブジェクトを返します。
24593 テストする式が真の値を返す(が、@code{#t}とは限らない)場合に便利です。
24594 @c COMMON
24595 @end defun
24596
24597
24598 @c EN
24599 @subsubheading Testing abnormal cases
24600 @c JP
24601 @subsubheading 異常系をテストする
24602 @c COMMON
24603
24604 @defun test-error :optional (condition-type <error>) (message #f)
24605 @c MOD gauche.test
24606 @c EN
24607 Returns a new @code{<test-error>} object that matches with
24608 other @code{<test-error>} object with the given @var{condition-type}.
24609 @c JP
24610 与えられた@var{condition-type}と適合する@code{<test-error>}オブジェクト
24611 とマッチするような、新たな@code{<test-error>}オブジェクトを作成して返します。
24612 @c COMMON
24613
24614 @c EN
24615 The @code{test-check} procedure treats @code{<test-error>} objects
24616 specially. When @code{err-expected} and @code{err-actual}
24617 are @code{<test-error>} objects,
24618 @code{(test-check err-expected err-actual)} returns @code{#t}
24619 if @code{err-expected}'s
24620 condition type is the same as or supertype of @code{err-actual}'s.
24621 @c JP
24622 テスト結果をチェックする@code{test-check}手続きは@code{<test-error>}オブジェクトを
24623 特別に扱います。@code{err-expected}と@code{err-actual}が
24624 ともに@code{<test-error>}のインスタンスであるとき、
24625 @code{(test-check err-expected err-actual)}は
24626 @code{err-expected}の持つcondition typeが@code{err-actual}の
24627 それと同じであるか、スーパータイプである場合に@code{#t}を返します。
24628 @c COMMON
24629
24630 @c EN
24631 For example, if you want to test a call to @code{foo} raises
24632 an @code{<io-error>} (or its condition subtype), you can write
24633 as the following example:
24634 @c JP
24635 例えば@code{foo}の呼び出しが@code{<io-error>} (もしくはそのサブタイプ) の
24636 コンディションを投げるかどうかをテストしたければ、次のように書くことができます。
24637 @c COMMON
24638
24639 @example
24640 (test "see if foo raises <io-error>" (test-error <io-error>) (foo))
24641 @end example
24642
24643 @c EN
24644 Another optional argument @var{message} can be used to check if
24645 the raised error has a message of expected pattern. The argument
24646 may be a string, a regexp, or @code{#f} (default).
24647 If it is a string, @code{test-check}
24648 checks if the message of the raised error exactly match the
24649 string. If it is a regexp, @code{test-check} checks
24650 the message of the raised error matches that regexp.
24651 If it is @code{#f}, the message is not checked.
24652 @c JP
24653 もう一つの省略可能引数@var{message}は、テスト中に投げられたエラーの
24654 メッセージが期待するパターンを満たしているかどうかをチェックするのに使います。
24655 この引数は文字列、正規表現、@code{#f}のいずれかでなければなりません。
24656 この引数が文字列の場合、@code{test-check}は投げられたエラーのメッセージが
24657 その文字列と完全に一致するかどうかをチェックします。
24658 この引数が正規表現の場合、@code{test-check}は投げられたエラーのメッセージが
24659 その正規表現にマッチするかをチェックします。
24660 デフォルトは@code{#f}で、その場合はメッセージのチェックは行われません。
24661 @c COMMON
24662 @end defun
24663
24664 @defvar *test-error*
24665 @c MOD gauche.test
24666 @c DEPRECATED
24667 @c EN
24668 Bounded to an instance of @code{<test-error>} with
24669 condition type @code{<error>}. This is only provided for the
24670 backward compatibility; new code should use @code{test-error}
24671 procedure above.
24672 @c JP
24673 condition typeとして@code{<error>}を持つ@code{<test-error>}
24674 オブジェクトに束縛されています。この変数は互換性のためにのみ残されています。
24675 新しいコードは上に述べた@code{test-error}手続きを使ってください。
24676 @c COMMON
24677 @end defvar
24678
24679 @defvar *test-report-error*
24680 @c MOD gauche.test
24681 @c EN
24682 If this variable is true, the @code{test} routine prints stack trace
24683 to the current error port when it captures an error. It is useful
24684 when you got an unexpected test-error object and want to check out
24685 where the error is occurring.
24686
24687 This variable is initialized by the environment variable
24688 @code{GAUCHE_TEST_REPORT_ERROR} when the @code{gauche.test} module
24689 is loaded. For example, you can use the environment variable to check out
24690 an unexpected error from your test script as follows (the value
24691 of the environment variable doesn't matter).
24692 @c JP
24693 この変数が真であれば、@code{test}ルーチンはエラーを捕捉した際に
24694 スタックトレースをカレントエラーポートに出力します。
24695 期待しない状況でtest-errorオブジェクトが返された際に、そのエラーが
24696 どこで起こったかを知るのに役立つでしょう。
24697
24698 この変数は@code{gauche.test}モジュールが読み込まれた時点で
24699 環境変数@code{GAUCHE_TEST_REPORT_ERROR}の値により初期化されます。
24700 例えば、テストスクリプト中の予期せぬエラーを調べるのに、
24701 次のようにすることができるでしょう (環境変数がセットされていれば、値は関係ありません)。
24702 @c COMMON
24703
24704 @example
24705 env GAUCHE_TEST_REPORT_ERROR=1 gosh mytest.scm
24706 @end example
24707 @end defvar
24708
24709 @node Incorporating external tests, Better test failure reporting, Individual test, Unit testing
24710 @subsection Incorporating external tests
24711 @c NODE 外部のテストの取り込み
24712
24713 @c EN
24714 Sometimes you implment an existing specification that comes with tests.
24715 If tests are written in R7RS Scheme, you can run it by itself;
24716 however, you might want to run it as a part of larger test suite
24717 managed by @code{gauche.test}. By doing so, you can get consolidated
24718 test result reports, for Gauche integrates SRFI test frameworks
24719 such as @code{srfi.64} and @code{srfi.78}.
24720 @c JP
24721 しばしば、既存の仕様を実装していて、テストコードがその仕様に付属していることがあります。
24722 テストがR7RSで書かれていればそれ自体をGaucheで実行することはできますが、
24723 @code{gauche.test}で管理されるより大きなテストスイートの一部として
24724 与えられたテストを実行したい場合もあるでしょう。
24725 Gaucheではテスト用SRFIである@code{srfi.64}や@code{srfi.78}が@code{gauche.test}
24726 と連携するようになっているので、テスト結果がまとめて報告されます。
24727 @c COMMON
24728
24729 @c EN
24730 If the test file is written in R7RS format, however, you may
24731 not be able to simply @code{include} the test file into Gauche's
24732 test suite. As R7RS @code{import} differs from Gauche's, we have
24733 some black magic to switch R7RS/Gauche namespace based on
24734 whether the first form in the file is R7RS @code{import} form
24735 or not (@pxref{Three forms of import}). If you include R7RS program into
24736 Gauche's program, the @code{import} in the R7RS code is interpreted
24737 as Gauche's and doesn't work. The macro @code{test-include-r7} can
24738 be used instead.
24739 @c JP
24740 ただ、テストがR7RS形式で書かれている場合、それをGaucheのテストスイートに
24741 単純に@code{include}するだけではうまくいかないことがあります。
24742 Gaucheにもともとあった@code{import}とR7RSの@code{import}は異なっているので、
24743 Gaucheは実行時に、
24744 プログラム中で最初に出会う@code{import}でどちらかを切り替える黒魔術を使っています
24745 (@ref{Three forms of import}参照)。
24746 Gaucheプログラム中にR7RSプログラムをインクルードした場合、R7RSプログラム中の
24747 @code{import}がGaucheの@code{import}と解釈されてしまうのでうまくありません。
24748 かわりに、下のマクロ@code{test-include-r7}が使えます。
24749 @c COMMON
24750
24751 @c EN
24752 NB: If the external test is written for Chibi Scheme,
24753 you can use @code{chibi-test} instead (@pxref{Running Chibi-scheme test suite}).
24754 @c JP
24755 註: 外部テストがChibi Scheme向けに書かれている場合、
24756 @code{chibi-test}が使えます(@ref{Running Chibi-scheme test suite}参照)。
24757 @c COMMON
24758
24759 @defmac test-include-r7 path [exclude-clause]
24760 @c MOD gauche.test
24761 @c EN
24762 Like @code{include} form (@pxref{Inclusions}), expands the content of
24763 the file specified by @var{path} in place of this form.
24764 If @var{path} is relative, it is relative from the includer.
24765 @c JP
24766 @code{include}フォーム (@ref{Inclusions}参照) と同じように、
24767 @var{path}で指定されるファイルの内容をこのマクロの位置に挿入します。
24768 @var{path}が相対パスの場合は、インクルードしているファイルからの相対になります。
24769 @c COMMON
24770
24771 @c EN
24772 The code is included in the environment where @code{import} is bound
24773 to R7RS's, so that a test script written for R7RS can be included as is.
24774 @c JP
24775 ファイル中のコードは、@code{import}がR7RSの@code{import}に束縛された
24776 環境で挿入されます。したがってR7RSで書かれたテストスクリプトがそのまま実行できます。
24777 @c COMMON
24778
24779 @c EN
24780 A recommended usage is to create a submodule in Gauche's test script:
24781 @c JP
24782 推奨される使い方は、Gaucheのテストスクリプト中に別のモジュールを作ってその中で
24783 インクルードする方法です。
24784 @c COMMON
24785
24786 @example
24787 (use gauche.test)
24788 (test-start ...)
24789 :
24790 (test-section "xxx-tests")
24791 (define-module xxx-tests
24792 (use gauche.test)
24793 (test-include-r7 "xxx-tests"))
24794 @end example
24795
24796 @c EN
24797 Sometimes the external script refers to a library that's not
24798 corresponds to what Gauche provides (e.g.
24799 @file{tests/include/srfi-222-tests.scm}
24800 imports @code{(compounds)} library, but Gauche provides it as @code{srfi.222}.)
24801 You can list such libraries to @code{exclude clause} so that import won't
24802 load it:
24803 @c JP
24804 しばしば、与えられたテストスクリプトが、Gaucheにない名前でライブラリを参照
24805 していることがあります (例えば@file{tests/include/srfi-222-tests.scm}
24806 は@code{(compounds)}というライブラリをインポートしていますが、
24807 Gaucheではそのライブラリは@code{srfi.222}という名前で提供されています)
24808 その場合、Gaucheに無いモジュールを@var{exclude-clause}に列挙することで、
24809 @code{import}がそのモジュールを無視するようにできます:
24810 @c COMMON
24811
24812 @example
24813 (define-module srfi-222-tests
24814 (use gauche.test)
24815 (use srfi.222)
24816 (test-include-r7 "include/srfi-222-tests" (exclude (compounds))))
24817 @end example
24818
24819 @c EN
24820 The format of @var{exclude-clause} is as follows:
24821 @c JP
24822 @var{exclude-clause}は次の形式を取ります:
24823 @c COMMON
24824
24825 @example
24826 <exclude-clause> : (exclude @var{r7rs-library-name} @dots{})
24827 @end example
24828 @end defmac
24829
24830 @node Better test failure reporting, Quasi-static checks, Incorporating external tests, Unit testing
24831 @subsection Better test failure reporting
24832 @c NODE 見やすいテスト失敗の報告
24833 @c COMMON
24834
24835 @c EN
24836 As described in @code{test} entry above, you can customize
24837 how the failure is reported by passing the optional @var{report} argument
24838 to @code{test} and @code{test*}. One of useful customizations is
24839 to show the difference between multi-line text. It's such a useful tool
24840 so we provide a report procedure.
24841 @c JP
24842 上記@code{test}の項で説明したように、@code{test}手続きや@code{test*}マクロの
24843 @var{report}引数に手続きを渡すことで、失敗の報告をカスタマイズできます。
24844 便利なカスタマイズのひとつは、複数行に渡るテキストの差分を示すことです。
24845 これはとても便利なので、それ用の手続きを用意しました。
24846 @c COMMON
24847
24848 @c EN
24849 Here's a contrived example. We pass @code{test-report-failure-diff}
24850 as a report procedure (and @code{test-check-diff} for check procedure,
24851 which we'll explain later). Expected text is given as a list of lines,
24852 while the actual result is a single string;
24853 Both @code{test-report-failure-diff} and @code{test-check-diff}
24854 procedures canonicalize expected
24855 and actual result into a single multi-line string, so you can give
24856 them in whichever ways that's convenient for you.
24857 @c JP
24858 これはちょっとわざとらしいテストです。
24859 @code{test-report-failure-diff}を@var{report}引数に渡しています
24860 (それと、@var{check}引数に@code{test-check-diff}を渡しています。後で説明します。)
24861 期待される結果は行のリストで、実際の結果は単一の文字列になっています。
24862 @code{test-report-failure-diff}と@code{test-check-diff}手続きは、
24863 @var{expected}と@var{actual}に渡されるものを単一の文字列へと正規化するので、
24864 渡しやすいような形式で引数を渡すことができます。
24865 @c COMMON
24866
24867 @example
24868 (test* "Beatrice"
24869 ;; expected
24870 '("What fire is in mine ears? Can this be true?"
24871 "Stand I condemned for pride and scorn so much?"
24872 "Contempt, farewell, and maiden pride, adieu!"
24873 "No glory lives behind the back of such.")
24874 ;; actual
24875 "What fire is in mine ears? Can this be true?\n\
24876 Stand I condemn'd for pride and scorn so much?\n\
24877 Contempt, farewell! and maiden pride, adieu!\n\
24878 No glory lives behind the back of such.\n"
24879 test-check-diff ; check
24880 test-report-failure-diff) ; report
24881
24882 @result{} @r{Reports:}
24883 ERROR: GOT diffs:
24884 --- expected
24885 +++ actual
24886 @@@@ -1,4 +1,4 @@@@
24887 What fire is in mine ears? Can this be true?
24888 -Stand I condemned for pride and scorn so much?
24889 -Contempt, farewell, and maiden pride, adieu!
24890 +Stand I condemn'd for pride and scorn so much?
24891 +Contempt, farewell! and maiden pride, adieu!
24892 No glory lives behind the back of such.
24893 @end example
24894
24895 @c EN
24896 As you see, the result is reported in a unified diff format
24897 (@pxref{Calculate difference of text streams}) so that you can
24898 spot the difference easily.
24899 @c JP
24900 このとおり、結果がunified diffフォーマットで報告されるので、どこが違っているのか
24901 見つけやすくなります
24902 (unified diffフォーマットについては@ref{Calculate difference of text streams}参照)。
24903 @c COMMON
24904
24905 @defun test-check-diff expected actual :optional equal
24906 @c MOD gauche.test
24907 @c EN
24908 An alternative check procedure you can pass into @var{check} argument
24909 of @code{test} procedure / @code{test*} macro.
24910 @c JP
24911 @code{test}手続き/@code{test*}マクロの@var{check}引数に渡せる
24912 チェック手続きです。
24913 @c COMMON
24914
24915 @c EN
24916 Before comparing @var{expected} and @var{actual}, it performs the
24917 following operations on each of @var{expected} and @var{actual}:
24918 @c JP
24919 まず、@var{expected}と@var{actual}を次の規則によって正規化します。
24920 @c COMMON
24921 @itemize @bullet
24922 @item
24923 @c EN
24924 If it is a list of strings, join them with @code{\n} (with @code{suffix}
24925 syntax, so the last line is also appended with @code{\n}).
24926 @c JP
24927 文字列のリストであれば、@code{\n}を糊としてひとつの文字列へとjoinします
24928 (@code{suffix}シンタックスを使います。つまり、最後の行の末尾にも@code{\n}は付きます)。
24929 @c COMMON
24930 @item
24931 @c EN
24932 If it is a form @code{(content-of <string>)}, then @code{<string>}
24933 is taken as a filename and the content of the file is used as
24934 a string. If the filename is relative, it is relative to the
24935 current loading file. If named file doesn't exist, an empty string
24936 is used.
24937 @c JP
24938 @code{(content-of <string>)}という形であれば、
24939 @code{<string>}をファイル名と解釈し、そのファイルを読み込んだ文字列を使います。
24940 ファイル名が相対パスの場合、現在ロードしているファイルからの相対と解釈されます。
24941 ファイルが無ければ空文字列になります。
24942 @c COMMON
24943 @item
24944 @c EN
24945 If it is a string or other object, it is used as is.
24946 @c JP
24947 文字列や他のオブジェクトの場合は、それがそのまま使われます。
24948 @c COMMON
24949 @end itemize
24950
24951 @c EN
24952 Then the two arguments are compared using @var{equal}, which is defaulted
24953 to @code{equal?}.
24954 @c JP
24955 正規化後、二つの引数が@var{equal}手続きによって比較されます。デフォルトは@code{equal?}です。
24956 @c COMMON
24957 @end defun
24958
24959 @defun test-report-failure-diff msg expected actual
24960 @c MOD gauche.test
24961 @c EN
24962 An alternative failure report procedure you can pass into @var{report}
24963 argument of @code{test} procedure / @code{test*} macro.
24964 @c JP
24965 @code{test}手続き/@code{test*}マクロの@var{report}引数に渡せる
24966 チェック手続きです。
24967 @c COMMON
24968
24969 @c EN
24970 The @var{expected} and @var{actual} arguments are converted in the same
24971 way as @code{test-check-diff}; that is, if it is a list of strings (lines)
24972 or a form @code{(content-of <filename>)}, it is converted to
24973 a single string.
24974 @c JP
24975 まず@var{expected}と@var{actual}引数が@code{test-check-diff}と同様に
24976 正規化されます。つまり、文字列のリストか@code{(content-of <filename>)}ならば
24977 単一の文字列に変換されます。
24978 @c COMMON
24979
24980 @c EN
24981 Then the difference of the two is reported in a unified diff format
24982 (using @code{diff-report/unified}. @xref{Calculate difference of text streams}).
24983 @c JP
24984 それから、両者の差異をunified diff形式で表示します
24985 (@code{diff-report/unified}が使われます。
24986 @ref{Calculate difference of text streams}参照)。
24987 @c COMMON
24988
24989 @c EN
24990 If either @var{expected} or @var{actual} is not convertable to a single
24991 string, the result is reported in the same way as the standard
24992 @code{test-report-failure}.
24993 @c JP
24994 @var{expected}と@var{actual}の少なくとも一方が文字列に変換されなかった場合は、
24995 標準の@code{test-report-failure}と同じ表示になります。
24996 @c COMMON
24997
24998 @c EN
24999 Note: This procedure is called twice, once when the test is failed,
25000 and again from @code{test-end} to report the summary of discrepancy.
25001 If you pass @code{(content-of <filename>)} form, you have to make sure
25002 the named file exists until @code{test-end} returns. This is tricky
25003 if you generate text into a temporary file during a single test.
25004 In general, @code{(content-of <filename>)} form is useful in the
25005 @var{expected} argument, where you can specify the prepared file.
25006 @c JP
25007 註: この手続きは、テストが失敗した時だけでなく、@code{test-end}がテスト結果の
25008 まとめを表示する時にも呼ばれます。
25009 従って、@code{(content-of <filename>)}の形式を使う場合は、
25010 @code{test-end}が戻るまで@code{<filename>}が存在するようにしてください。
25011 例えばテスト内で一時ファイルを作って結果をそこに出し、そのテスト後にクリアする、
25012 という場合はこの形式は使い辛いでしょう。
25013 一般的に、@code{(content-of <filename>)}形式は、@var{expected}に
25014 あらかじめ用意してあるファイルを指定するのに使うのが良いでしょう。
25015 @c COMMON
25016 @end defun
25017
25018 @defmac test*/diff name expected expr
25019 @c MOD gauche.test
25020 @c EN
25021 This is a convenience version of @code{test*}, using
25022 @code{test-check-diff} and @code{test-report-failure-diff} as
25023 check and report procedures, respectively.
25024 @c JP
25025 @code{test*}マクロで@code{test-check-diff}と@code{test-report-failure-diff}を
25026 @var{check}と@var{report}引数に指定したもので、簡便のために用意されています。
25027 @c COMMON
25028
25029 @example
25030 (test*/diff name expected expr)
25031 @equiv{}
25032 (test* name expected expr test-check-diff test-report-failure-diff)
25033 @end example
25034 @end defmac
25035
25036 @node Quasi-static checks, , Better test failure reporting, Unit testing
25037 @subsection Quasi-static checks
25038 @c NODE 準静的検査
25039
25040 @c EN
25041 Scheme is dynamically typed, which is convenient for incremental
25042 and experimental development on REPL, but it tends to delay error detection
25043 until the code is actually run. It is very annoying that you run your
25044 program for a while only to see it barfs on simple typo of variable name.
25045 @c JP
25046 Schemeは動的型付けで、これはREPLでインクリメンタルあるいは実験的な開発を
25047 するには便利なのですが、コードが実際に走るまでエラーに気づかないということになりがちです。
25048 しばらく走らせた後で変数名のタイポで止まってしまうと腹立ちますよね。
25049 @c COMMON
25050
25051 @c EN
25052 Gauche addresses this issue by checking certain types of errors
25053 at the test phase. It isn't purely a static check (we need to load
25054 a module or a script, which evaluates toplevel expressions), nor
25055 exhaustive (we can't catch inconsistencies that span over multiple
25056 modules or about information that can be added at runtime). Nevertheless
25057 it can often catch some common mistakes, such as incorrect variable names
25058 or calling procedures with wrong number of arguments.
25059 @c JP
25060 Gaucheでは、こういった種類のエラーをテスト時に検査する方法を用意しています。
25061 これは完全に静的な検査ではありません(対象のモジュールやスクリプトをロードするので、
25062 トップレベル式は実行されてしまいます)し、網羅的でもありません
25063 (複数のモジュールを見たり、実行時に追加される情報に依存するものは検査できません)。
25064 それでも、変数名の間違いや引数の個数の誤りなどよくあるミスはこの検査で大抵見つけることが
25065 できます。
25066 @c COMMON
25067
25068 @c EN
25069 The two procedures, @code{test-module} and @code{test-script},
25070 load the named module and the script files respectively (which compiles
25071 the Scheme code to VM instructions), then scan the compiled VM code
25072 to perform the following tests:
25073 @c JP
25074 @code{test-module}と@code{test-script}手続きはそれぞれ、
25075 指定されたモジュールもしくはスクリプトをロードし (その過程でSchemeコードは
25076 VM命令列へとコンパイルされます)、次にコンパイルされたVMコードを走査して
25077 以下のテストを行います。
25078 @c COMMON
25079
25080 @enumerate
25081 @item
25082 @c EN
25083 See if the global variables referenced within functions are all defined
25084 (either in the module, or in one of imported modules).
25085 @c JP
25086 関数内から参照されているグローバル変数は(該当モジュール内、もしくはインポートしたモジュールで)
25087 全て定義されているか
25088 @c COMMON
25089
25090 @item
25091 @c EN
25092 If a global variable is used as a function, see if the number of arguments
25093 given to it is consistent to the actual function.
25094 @c JP
25095 グローバル変数が関数として使われているなら、その引数の数が
25096 関数の定義と合致しているか。
25097 @c COMMON
25098
25099 @item
25100 @c EN
25101 See if the symbols set as autoload in the code can be resolved.
25102 @c JP
25103 autoloadに設定されている変数が実際にロードできるか。
25104 @c COMMON
25105
25106 @item
25107 @c EN
25108 While testing module, see if the symbols declared in the export list
25109 are actually defined.
25110 @c JP
25111 モジュールをテストしている場合、exportされているシンボルが
25112 定義されているか。
25113 @c COMMON
25114 @end enumerate
25115
25116 @c EN
25117 The check is somewhat heuristic and we may miss some errors and/or
25118 can have false positives. For false positives, you can enumerate
25119 symbols to be excluded from the test.
25120 @c JP
25121 今のところ検査はヒューリスティックで、エラーを見逃すこともあれば、
25122 エラーでないものをエラーと報告してしまう可能性もあります。後者については、
25123 偽陽性となるシンボルを列挙して検査から外すようにできます。
25124 @c COMMON
25125
25126 @defun test-module module :key allow-undefined bypass-arity-check
25127 @c MOD gauche.test
25128 @c EN
25129 Loads the module and runs the quasi-static consistency check.
25130 @var{Module} must be a symbol module name or a module.
25131 @c JP
25132 モジュールをロードし、準静的な一貫性チェックを行います。
25133 @var{Module}はモジュール名のシンボルかモジュールでなければなりません。
25134 @c COMMON
25135
25136 @c EN
25137 Sometimes you have a global variable that may not be
25138 defined depending on compiler options or platforms, and
25139 you check its existence at runtime before using it.
25140 The undefined variable reference check by @code{test-module}
25141 doesn't follow such logic, and reports an error whenever
25142 it finds your code referring to undefined variable. In such case,
25143 you can give a list of symbols to the @var{allow-undefined}
25144 keyword argument; the test will excludes them from the check.
25145 @c JP
25146 しばしば、プラットフォームやコンパイルオプションによって
25147 グローバル変数が定義されるかどうかが異なる場合があります。
25148 コード中では実行時にその変数の存在を確認してから使うように
25149 コーディングしてあったとしても、@code{test-module}は
25150 そのようなロジックを追わないため、未定義変数の参照を報告して
25151 しまいます。そのような場合は、チェックから外す変数名のリストを
25152 @var{allow-undefined}キーワード引数に渡して下さい。
25153 @c COMMON
25154
25155 @c EN
25156 The arity check may also raise false positives, if the module
25157 count on a behavior of global procedures that will be modified
25158 after the module is loaded (e.g. a method with different number
25159 of arguments can be added to a generic function after the module
25160 is loaded, which would make the code valid.) If you know
25161 you're doing right thing and need to suppress the false positives,
25162 pass a list of names of the functions to @code{bypass-arity-check}
25163 keyword arguments.
25164 @c JP
25165 引数の個数のチェックも、偽陽性のエラーをあげる可能性があります。
25166 モジュールがロードされた後のグローバルな関数の変更を当てにしている場合などです
25167 (例えば、コード中であるジェネリックファンクションに渡されている引数の個数が、
25168 モジュールのロード時点では不正なものだったとしても、そのコードが実行される
25169 までに該当引数のメソッドが追加されれば、正しいコードとなるわけです)。
25170 自分のコードは確かに正しく、チェックが誤りであるような場合は、
25171 該当関数の名前のリストを@code{bypass-arity-check}キーワード引数に
25172 渡してください。
25173 @c COMMON
25174 @end defun
25175
25176 @defun test-script filename :key allow-undefined bypass-arity-check compile-only
25177 @c MOD gauche.test
25178 @c EN
25179 Loads the script named by @var{filename}
25180 into a fresh anonymous module and runs the quasi-static
25181 consistency check.
25182 @var{Filename} must be a string that names the script file.
25183 @c JP
25184 @var{filename}で指定されるスクリプトを新しい無名モジュールにロードし、
25185 準静的な一貫性チェックを行います。
25186 @var{filename}はスクリプトファイル名を指定する文字列でなければなりません。
25187 @c COMMON
25188
25189 @c EN
25190 The meaning of keyword arguments is the same as @code{test-module}.
25191 @c JP
25192 キーワード引数の意味は@code{test-module}と同じです。
25193 @c COMMON
25194
25195 @c EN
25196 Note that the toplevel forms in @var{filename} are evaluated, so scripts that
25197 relies on the actions of toplevel forms could cause unwanted side-effects.
25198 This check works best for the scripts written in SRFI-22 convention,
25199 that is, calling actions from @code{main} procedure instead of toplevel
25200 forms. R7RS scripts relies on actions in toplevel forms and can't be
25201 tested with this procedure.
25202 @c JP
25203 @var{filename}中のトップレベルフォームは評価されるので、
25204 トップレベルフォームのアクションに依存したスクリプトは望ましくない副作用を生じるでしょう。
25205 この検査は、スクリプトがSRFI-22形式、
25206 つまりアクションを@code{main}手続きから呼ぶようになっているとうまくいきます。
25207 R7RSスクリプトはトップレベルフォームのアクションに頼らざるを得ないので
25208 この手続きではうまく検査できません。
25209 @c COMMON
25210
25211 @c EN
25212 Scripts that relies on being loaded into @code{user} module also
25213 won't work well with this check, which loads the forms into anonymous
25214 module.
25215 @c JP
25216 スクリプトが@code{user}モジュールにロードされることに依存して書かれている場合も、
25217 この手続きではうまくいきません。
25218 @c COMMON
25219
25220 @c EN
25221 If you need to test a script with toplevel side-effecting forms and
25222 you can't change it, you may want to pass
25223 true value to the @code{compile-only} keyword argument. Then
25224 @code{test-script} just compiles each toplevel form before running
25225 static checking,
25226 instead of @code{load}ing (which not only compiles but executes each
25227 of toplevel forms).
25228 @c JP
25229 もしスクリプトに副作用があるトップレベルフォームが書かれていて、それを
25230 変更することができないなら、@code{compile-only}キーワード引数に
25231 真の値を渡してみてください。すると、@code{test-script}は
25232 スクリプトのトップレベルフォームをコンパイルだけしてから静的検査を行います。
25233 (デフォルトの@code{load}はコンパイルだけではなく実行も行います)。
25234 @c COMMON
25235 @end defun
25236
25237 @c ----------------------------------------------------------------------
25238 @node Threads, Measure timings, Unit testing, Library modules - Gauche extensions
25239 @section @code{gauche.threads} - Threads
25240 @c NODE スレッド, @code{gauche.threads} - スレッド
25241
25242 @c EN
25243 Gauche can use threads
25244 built on top of either POSIX threads (pthreads) or Windows threads,
25245 depending on the platform.
25246 @c JP
25247 Gaucheでは、POSIXスレッド(pthreads)か
25248 Windowsスレッド上に構築されるスレッドを使うことができます
25249 (どちらを使うかはプラットフォームによります)。
25250 @c COMMON
25251
25252 @deftp {Module} gauche.threads
25253 @mdindex gauche.threads
25254 @c EN
25255 Provides thread API. The thread support is built-in, and this
25256 module merely provides a separate namespace.
25257 @c JP
25258 スレッドを扱うAPIを提供します。スレッドサポートは組み込みで、
25259 このモジュールは名前空間を提供しているだけです。
25260 @c COMMON
25261 @end deftp
25262
25263 @c EN
25264 Although you hardly need to distinguish
25265 the underlying thread subsystem (either pthreads or Windows threads)
25266 in Scheme level, you may want to detect the difference if your code
25267 depends on a particular subsystem-specific semantics.
25268 There are feature identifiers @code{gauche.sys.pthreads}
25269 or @code{gauche.sys.wthreads}, for pthreads platform and Windows thread
25270 platform, respectively. You can use @code{cond-expand}
25271 to switch the platform-dependent code
25272 (@pxref{Feature conditional}).
25273 @c JP
25274 Schemeレベルでは、スレッドサブシステムの違い(pthreadsかWindowsスレッドか)を
25275 意識する必要はほどんど無いでしょう。ただ、特定のサブシステムのセマンティクスに
25276 依存したコードを書きたい場合は、
25277 pthreadプラットフォームとWindowsスレッドプラットフォームで
25278 それぞれ、@code{gauche.sys.pthreads}と@code{gauche.sys.wthreads}
25279 という機能識別子が用意されています。
25280 @code{cond-expand}でプラットフォーム依存のコードを切り替えられます
25281 (@ref{Feature conditional}参照)。
25282 @c COMMON
25283
25284 @c EN
25285 To check if threads are available at runtime,
25286 instead of compile time, use the following procedure.
25287 @c JP
25288 コンパイル時ではなく実行時にスレッドが有効かどうかをチェックするためには、
25289 次の手続きを使います。
25290 @c COMMON
25291
25292 @defun gauche-thread-type
25293 @c MOD gauche.threads
25294 @c EN
25295 Returns a symbol that indicates the supported thread type.
25296 It returns @code{pthread} for POSIX pthreads,
25297 and @code{wthread} for Windows threads.
25298 @c JP
25299 サポートされているスレッドのタイプを表すシンボルを返します。
25300 POSIX pthreadsなら@code{pthread}、
25301 Windowsスレッドなら@code{wthread}が返されます。
25302 @c COMMON
25303
25304 @c EN
25305 (Note: On pthreads platforms, it should return @code{pthreads} instead
25306 of @code{pthread}; then the returned symbol would correspond to the
25307 value given to @code{--enable-threads} option at configuration time.
25308 It's a historical overlook, stuck for the backward compatibility.)
25309 @c JP
25310 (註:pthreadプラットフォームではシンボル@code{pthread}ではなく
25311 @code{pthreads}を返すべきでした。そうすれば、
25312 @code{gauche-thread-type}の返り値はコンフィグレーション時に
25313 @code{--enable-threads}に与えた値と対応するものになっていたでしょう。
25314 互換性のために、残念ながらこの見過ごしは修正されないでしょう。
25315 @c COMMON
25316 @end defun
25317
25318 @c EN
25319 Scheme-level thread API conforms SRFI-18, "Multithreading support",
25320 wrapped around Gauche's object interface.
25321 @c JP
25322 SchemeレベルのスレッドAPIはSRFI-18、``マルチスレッドサポート''を満たし、
25323 Gaucheのオブジェクトのインターフェースでラップされます。
25324 @c COMMON
25325
25326 @menu
25327 * Thread programming tips::
25328 * Thread procedures::
25329 * Thread local storage::
25330 * Synchronization primitives::
25331 * Thread exceptions::
25332 @end menu
25333
25334 @node Thread programming tips, Thread procedures, Threads, Threads
25335 @subsection Thread programming tips
25336 @c NODE スレッドプログラミングTips
25337
25338 @c EN
25339 @subsubheading What's Gauche threads for
25340 @c JP
25341 @subsubheading Gaucheのスレッドをどう使うか
25342 @c COMMON
25343
25344 @c EN
25345 Although the surface API of threads looks simple and portable,
25346 you need to know how the threads are implemented in order to utilize
25347 the feature's potential. Some languages support threads as
25348 language's built-in construct and encourage programmers
25349 to express the calculation in terms of threads.
25350 However, it should be noted that in many cases there are
25351 alternative ways than threads to implement the desired
25352 algorithm, and you need to compare advantages and
25353 disadvantages of using threads depending on how the threads
25354 are realized in the underlying system.
25355 @c JP
25356 スレッドのAPIは外見上シンプルでポータブルに見えますが、
25357 その機能の潜在的な力を活用するためには、スレッドがどのように
25358 実装されているかを知る必要があります。
25359 いくつかの言語では言語組み込みの機能としてスレッドをサポートし、
25360 プログラマによるスレッドの利用を推奨しています。
25361 しかし、多くの場合、実現したいアルゴリズムをスレッドを使わずに
25362 実装する方法があります。
25363 スレッドを使うことの利点と欠点を、そのスレッドがシステムによってどのように
25364 実現されているかを考慮した上で比較する必要があります。
25365 @c COMMON
25366
25367 @c EN
25368 In Gauche, the primary purpose of threads is to write programs
25369 that @emph{require} preemptive scheduling, therefore are
25370 difficult to express in other ways. Preemptive threads may
25371 be required, for example, when you have to call a module that
25372 does blocking I/O which you can't intercept, or may spend
25373 nondeterministic amount of calculation time that you want
25374 to interrupt.
25375 @c JP
25376 Gaucheでは、スレッドを使う一番の目的は、他の方法で表現することが
25377 難しい、プリエンプティブなスケジューリングを@emph{必要}とする
25378 プログラムを書くことです。プリエンプティブなスレッドは、
25379 例えば、中断できないブロッキングI/Oを行うモジュールを
25380 使わなければならないときや、実行時間の分からない計算に
25381 割り込みを行いたいときなどに必要となります。
25382 @c COMMON
25383
25384 @c EN
25385 For each Gauche's thread, an individual VM is allocated
25386 and it is run by the dedicated POSIX thread. Thus the
25387 cost of context switch is the same as the native
25388 thread, but the creation of threads costs much higher than,
25389 say, lightweight threads built on top of call/cc.
25390 So Gauche's preemptive threads are @emph{not} designed for
25391 applications that want to create thousands of threads
25392 for fine-grained calculation.
25393 @c JP
25394 それぞれのGaucheのスレッドには、個別の仮想マシンが割り当てられ、
25395 専用のPOSIXスレッドにより実行されます。したがって、コンテキスト
25396 スイッチのオーバヘッドは、ネイティブスレッドと同等です。
25397 しかし、スレッドの生成は、例えばcall/ccによる軽量スレッドよりは
25398 ずっとコストのかかる処理です。
25399 このように、Gaucheのプリエンプティブなスレッドは、
25400 きめ細かい計算のために幾千ものスレッドを生成したいアプリケーション
25401 向けでは@emph{ありません}。
25402 @c COMMON
25403
25404 @c EN
25405 The recommended usage is the technique so called "thread pool",
25406 that you create a set of threads and keep them around for
25407 long time and dispatch jobs to them as needed. Gauche provides
25408 a thread pool implementation in @code{control.thread-pool} module
25409 (@pxref{Thread pools}).
25410 @c JP
25411 推奨される使用方法は、いわゆる``スレッドプール''と呼ばれる
25412 テクニックです。つまり、スレッドの集合を作って長時間それを
25413 保持し、必要になったときにジョブをそこへディスパッチする
25414 というものです。Gaucheは@code{control.thread-pool}モジュール
25415 (@ref{Thread pools}参照) でスレッドプールの実装を提供しています。
25416 @c COMMON
25417
25418 @c EN
25419 Preemptive threads have other difficulties,
25420 and sometimes the alternatives may be a better fit
25421 than the native preemptive threads
25422 (e.g. see @uref{https://www-sop.inria.fr/mimosa/rp/FairThreads/html/FairThreads.html}).
25423 @c JP
25424 プリエンプティブなスレッドには他にも難しい点があり、
25425 しばしばネイティブなプリエンプティブスレッドよりも
25426 より良くフィットする代替策があります
25427 (例えば@uref{https://www-sop.inria.fr/mimosa/rp/FairThreads/html/FairThreads.html}参照)。
25428 @c COMMON
25429
25430 @itemize @bullet
25431 @item
25432 @c EN
25433 If what you need is just a concurrent calculation, you
25434 might be able to use cooperative thread technique built
25435 on top of @code{call/cc}. Creating call/cc-based threads
25436 is much faster than creating native threads.
25437 @c JP
25438 単に並行実行が必要なだけなら、@code{call/cc}による協調スレッド
25439 テクニックが使えるでしょう。call/ccベースのスレッドの生成は、
25440 ネイティブスレッドを生成するよりも高速です。
25441 @c COMMON
25442
25443 @item
25444 @c EN
25445 If what you need is to deal with blocking I/O, and you have
25446 all your code at hand, it is sometimes easier to use good old
25447 @code{select}-based dispatching (@xref{Simple dispatcher},
25448 for example).
25449 @c JP
25450 ブロッキングI/Oを扱う必要があり、全てのコードが手元にある場合は、
25451 古き良き@code{select}ベースのディスパッチ(@ref{Simple dispatcher}に
25452 例があります)を使うほうが簡単なことがあります。
25453 @c COMMON
25454
25455 @item
25456 @c EN
25457 If what you need is to control the resource consumption in the
25458 subsystem, and the subsystem works fairly independently from
25459 the main system, you may be able to use Unix processes instead of threads.
25460 It may sound to go backward, but Unix process does provide
25461 higher "shield" between the subsystem and the main system
25462 (e.g. the main system can keep running even if subsystem segfaults).
25463 @c JP
25464 サブシステムにおけるリソースの消費をコントロールする必要がある場合で、
25465 サブシステムがメインシステムとほとんど独立に動作する場合は、
25466 スレッドの代わりにUnixプロセスが使えることでしょう。
25467 時代に逆行するように聞こえますが、Unixプロセスはサブシステムと
25468 メインシステムの間に高度な``防御壁''を提供します。
25469 (例えば、サブシステムがセグメンテーション違反を起こしても、
25470 メインシステムは実行しつづけられます。)
25471 @c COMMON
25472
25473 @end itemize
25474
25475 @c EN
25476 Of course, these technique are not mutually exclusive with
25477 native threads. You can use dispatcher with "thread pool" technique,
25478 for example. Just keep it in your mind that the native threads
25479 are not only but one of the ways to realize those features.
25480 @c JP
25481 もちろん、これらのテクニックはネイティブスレッドとは相互排他ではありません。
25482 例えば、``スレッドプール''テクニックと一緒にディスパッチャを使うこともできます。
25483 それらの機能を実現するために、ネイティブスレッドが唯一の方法ではないということを
25484 心に留め置いて下さい。
25485 @c COMMON
25486
25487 @c EN
25488 @subsubheading Uncaught errors in a thread body
25489 @c JP
25490 @subsubheading スレッドボディ内で捕捉されないエラー
25491 @c COMMON
25492
25493 @c EN
25494 When you run a single-thread program that raises an unexpected (unhandled)
25495 error, Gauche prints an error message and a stack trace by default.
25496 So sometimes it perplexes programmers when a thread doesn't print
25497 anything when it dies because of an unhandled error.
25498 @c JP
25499 シングルスレッドのプログラムが予期せぬ(捕捉されない)エラーを起こした場合、
25500 デフォルトではGaucheはエラーメッセージとスタックトレースを表示します。
25501 ところが、スレッドで捕捉されないエラーが生じスレッドが終了しても、
25502 何も表示されません。
25503 @c COMMON
25504
25505 @c EN
25506 What's happening is this: An unhandled error in a thread body would
25507 cause the thread to terminate, and the error itself will propagate
25508 to the thread who's expecting the result of the terminated thread.
25509 So, you get the error (wrapped by @code{<uncaught-exception>})
25510 when you call @code{thread-join!} on a thread which is terminated
25511 because of an unhandled error. The behavior is defined in SRFI-18.
25512 @c JP
25513 それはこういうわけです。スレッド本体でエラーが起き、それがスレッド中で処理されなければ、
25514 スレッドは終了し、エラー自体はそのスレッドの終了を待つスレッドへと伝達される仕組みだからです。
25515 エラーで終了したスレッドに対して@code{thread-join!}を呼んだ時点で、
25516 元のエラーを@code{<uncaught-exception>}でラップしたエラーが投げられます。
25517 この動作はSRFI-18で規定されています。
25518 @c COMMON
25519
25520 @c EN
25521 If you fire a thread for one-shot calculation, expecting to receive
25522 the result by @code{thread-join!}, then this is reasonable---you can
25523 handle the error situation in the ``parent'' thread. However,
25524 if you run a thread to loop indefinitely to process something and
25525 not expect to retrieve its result via @code{thread-join!}, this becomes
25526 a pitfall; the thread may die unexpectedly but you wouldn't know it.
25527 (If such a thread is garbage-collected, a warning is printed.
25528 However you wouldn't know when that happens so you can't count on it.)
25529 @c JP
25530 新たなスレッドを一時的な計算のために走らせて、その結果を@code{thread-join!}で
25531 受け取るという使い方なら、この動作は便利です。「親スレッド」でまとめてエラーを
25532 捕捉できるからです。けれどもスレッドをずっとループさせてジョブを次々と処理する、といった
25533 用法では@code{thread-join!}は呼ばれるとは限らず、この仕様は落とし穴になり得ます。
25534 スレッドがエラーで死んだのに気づかないかもしれないからです。
25535 (エラーで終了したスレッドが@code{thread-join!}されることなくGC対象になった場合は
25536 警告が出力されます。しかし、GCがどのタイミングで起きるかはわかりません。)
25537 @c COMMON
25538
25539 @c EN
25540 For such threads, you should always wrap the body of such thread
25541 with @code{guard}, and handles the error explicitly. You can call
25542 @code{report-error} to display the default error message and a stack
25543 trace.
25544 @c JP
25545 そういう使い方をするスレッドについては、本体を常に@code{guard}で包んで
25546 エラーを明示的に処理すべきです。例えばエラーメッセージとスタックトレースを出したければ
25547 @code{report-error}を呼びます。
25548 @c COMMON
25549
25550 @example
25551 (thread-start!
25552 (make-thread (^[] (guard (e [else (report-error e) #f])
25553 ... thread body ...))))
25554 @end example
25555
25556 @c EN
25557 @xref{Thread exceptions}, for the details of thread exception handling.
25558 @c JP
25559 スレッドでの例外の処理について詳しくは@ref{Thread exceptions}を参照してください。
25560 @c COMMON
25561
25562 @c EN
25563 Note: As of 0.9.5, Gauche has a known bug that the tail call of
25564 error handling clauses of @code{guard} doesn't become a proper
25565 tail call. So, the following code, which should run safely
25566 in Scheme, could eat up a stack:
25567 @c JP
25568 註: 0.9.5の時点では、@code{guard}のエラーハンドラ節が
25569 末尾コンテクストで呼ばれないというバグがあります。
25570 例えば次のコードはSchemeでは本来スタックを消費せずにループするはずですが、
25571 現在のGaucheではスタックを徐々に食いつぶしてしまいます。
25572 @c COMMON
25573
25574 @example
25575 (thread-start!
25576 (make-thread (^[] (let loop ()
25577 (guard (e [else (report-error e) (loop)])
25578 ... thread body ...)))))
25579 @end example
25580
25581 @c EN
25582 For the time being, you can lift the call to loop outside of
25583 @code{guard} as workaround.
25584 @c JP
25585 当面は回避策として、@code{loop}の呼び出しを@code{guard}の外側に出してください。
25586 @c COMMON
25587
25588 @example
25589 (thread-start!
25590 (make-thread (^[] (let loop ()
25591 (guard (e [else (report-error e)])
25592 ... thread body ...)
25593 (loop)))))
25594 @end example
25595
25596
25597 @node Thread procedures, Thread local storage, Thread programming tips, Threads
25598 @subsection Thread procedures
25599 @c NODE スレッド手続き
25600
25601 @deftp {Builtin Class} <thread>
25602 @clindex thread
25603 @c EN
25604 A thread. Each thread has an associated thunk which is evaluated by
25605 a POSIX thread. When thunk returns normally, the result is stored
25606 in the internal 'result' slot, and can be retrieved by @code{thread-join!}.
25607 When thunk terminates abnormally, either by raising an exception or
25608 terminated by @code{thread-terminate!}, the exception condition is
25609 stored in their internal 'result exception' slot, and will be passed
25610 to the thread calling @code{thread-join!} on the terminated thread.
25611 @c JP
25612 スレッドを表すクラスです。それぞれのスレッドは、POSIXスレッドにより
25613 評価される関連付けられた手続きを持ちます。手続きが正常に戻ると、
25614 その結果は内部的な``結果''スロットに格納され、@code{thread-join!}により
25615 取得することができます。例外が投げられるか
25616 @code{thread-terminate!}により終了されるかで、手続きが異常終了すると、
25617 例外条件が内部的な``結果としての例外''スロットに格納され、
25618 その例外条件は終了したスレッドに対して@code{thread-join!}を
25619 呼ぶスレッドへと渡されます。
25620 @c COMMON
25621
25622 @c EN
25623 Each thread has its own dynamic environment and dynamic handler stack.
25624 When a thread is created, its dynamic environment is initialized by
25625 the creator's dynamic environment. The thread's dynamic handler
25626 stack is initially empty.
25627 @c JP
25628 それぞれのスレッドは独自の動的環境と動的なハンドラスタックを持っています。
25629 あるスレッドが生成されると、その動的な環境は生成者の動的な環境によって
25630 初期化されます。そのスレッドの動的なハンドラスタックは初期においては空です。
25631 @c COMMON
25632
25633 @c EN
25634 A thread is in one of the following four states at a time.
25635 You can query the thread state by the @code{thread-state} procedure.
25636 @c JP
25637 スレッドは以下の4つの状態のうちのひとつを取ります。@code{thread-state}手続きで
25638 スレッドの状態を調べることができます。
25639 @c COMMON
25640
25641 @table @code
25642 @item new
25643 @c EN
25644 A thread hasn't started yet. A thread returned from @code{make-thread}
25645 is in this state.
25646 Once a thread is started it will never be in this state again.
25647 At this point, no POSIX thread has been created; @code{thread-start!}
25648 creates a POSIX thread to run the Gauche thread.
25649 @c JP
25650 まだ作られたばかりで起動されてない状態です。@code{make-thread}が返すスレッドは
25651 この状態です。スレッドがひとたび起動されると、そのスレッドがこの状態に戻ることは
25652 決してありません。
25653 この時点ではPOSIXスレッドはまだ作られません。@code{thread-start!}によって
25654 POSIXスレッドが作られ、Gaucheのスレッドを実行します。
25655 @c COMMON
25656 @item runnable
25657 @c EN
25658 When a thread is started by @code{thread-start!}, it becomes to this
25659 state. Note that a thread blocked by a system call is still in
25660 @code{runnable} state.
25661 @c JP
25662 @code{thread-start!}によって起動されたスレッドはこの状態になります。
25663 スレッドがシステムコールによるブロックされている時もその状態は@code{runnable}
25664 であることに注意してください。
25665 @c COMMON
25666 @item stopped
25667 @c EN
25668 A thread becomes in this state when it is stopped by @code{thread-stop!}.
25669 A thread in this state can go back to @code{runnable} state by
25670 @code{thread-cont!}, resuming execution from the point when
25671 it is stopped.
25672 @c JP
25673 スレッドが@code{thread-stop!}によって止められるとこの状態になります。
25674 この状態のスレッドは@code{thread-cont!}によって再び@code{runnable}になり、
25675 止められた時点から実行を再開することができます。
25676 @c COMMON
25677 @item terminated
25678 @c EN
25679 When the thread finished executing associated code, or
25680 is terminated by @code{thread-terminate!}, it becomes in this state.
25681 Once a thread is in this state, the state can no longer be changed.
25682 @c JP
25683 割り当てられたコードの実行が終了したり、@code{thread-terminate!}によって
25684 強制的に終了させられた時に、スレッドはこの状態になります。
25685 一度この状態になると他の状態に遷移することはありません。
25686 @c COMMON
25687 @end table
25688
25689 @c EN
25690 Access to the resources shared by multiple threads must be protected
25691 explicitly by synchronization primitives.
25692 @xref{Synchronization primitives}.
25693 @c JP
25694 複数のスレッドで共有されるリソースへのアクセスは、同期化プリミティブにより
25695 明示的に保護されなければなりません。@ref{Synchronization primitives}参照。
25696 @c COMMON
25697
25698 @c EN
25699 Access to ports are serialized by Gauche. If multiple threads attempt
25700 to write to a port, their output may be interleaved but no output
25701 will be lost, and the state of the port is kept consistent.
25702 If multiple threads attempt to read from a port, a single read
25703 primitive (e.g. @code{read}, @code{read-char} or @code{read-line})
25704 works atomically.
25705 @c JP
25706 ポートへのアクセスはGaucheによりシリアライズされます。
25707 複数のスレッドが1つのポートへの書き込みを試みた場合、それらの出力は
25708 混じることもありますが、失われる出力はなく、そのポートのステータスは
25709 一貫性が保たれます。複数のスレッドが1つのポートからの読み込みを試みた
25710 場合、1つの読み込みプリミティブ(例えば、@code{read}や@code{read-char}、
25711 @code{read-line}など)がアトミックに実行されます。
25712 @c COMMON
25713
25714 @c EN
25715 Signal handlers are shared by all threads, but each thread has
25716 its own signal mask. @xref{Signals and threads}, for details.
25717 @c JP
25718 シグナルハンドラは全てのスレッドで共有されますが、それぞれのスレッドは
25719 独自のシグナルマスクを持ちます。詳細は、@ref{Signals and threads}を参照。
25720 @c COMMON
25721
25722 @c EN
25723 A thread object has the following external slots.
25724 @c JP
25725 スレッドオブジェクトは以下の外部スロットを持ちます。
25726 @c COMMON
25727
25728 @defivar <thread> name
25729 @c EN
25730 A name can be associated to a thread.
25731 This is just for the convenience of the application.
25732 The primordial thread has the name "@code{root}".
25733 @c JP
25734 スレッドに関連付けられる名前。
25735 これは単にアプリケーションにとっての便宜を図るためのものです。
25736 原始となるスレッドは``@code{root}''という名前を持ちます。
25737 @c COMMON
25738 @end defivar
25739
25740 @defivar <thread> specific
25741 @c EN
25742 A thread-local slot for use of the application.
25743 @c JP
25744 アプリケーションが使うスレッドローカルなスロット。
25745 @c COMMON
25746 @end defivar
25747 @end deftp
25748
25749 @defun current-thread
25750 [SRFI-18], [SRFI-21]
25751 @c MOD gauche.threads
25752 @c EN
25753 Returns the current thread.
25754 @c JP
25755 現在のスレッドを返します。
25756 @c COMMON
25757 @end defun
25758
25759 @defun thread? obj
25760 [SRFI-18], [SRFI-21]
25761 @c MOD gauche.threads
25762 @c EN
25763 Returns @code{#t} if @var{obj} is a thread, @code{#f} otherwise.
25764 @c JP
25765 @var{obj}がスレッドなら@code{#t}、そうでなければ@code{#f}を返します。
25766 @c COMMON
25767 @end defun
25768
25769 @defun make-thread thunk :optional name
25770 [SRFI-18], [SRFI-21]
25771 @c MOD gauche.threads
25772 @c EN
25773 Creates and returns a new thread to execute @var{thunk}.
25774 To run the thread, you need to call @code{thread-start!}.
25775 The result of @var{thunk} may be retrieved by calling @var{thread-join!}.
25776 @c JP
25777 @var{thunk}を実行するための新しいスレッドを生成して返します。
25778 そのスレッドの実行を開始するには、@code{thread-start!}を呼ぶ必要があります。
25779 @var{thunk}の実行結果は、@var{thread-join!}を呼ぶことで回収できます。
25780 @c COMMON
25781
25782 @c EN
25783 You can provide the name of the thread by the optional argument @var{name}.
25784 @c JP
25785 オプション引数@var{name}を与えることで、そのスレッドに名前を与えることができます。
25786 @c COMMON
25787
25788 @c EN
25789 The created thread inherits the signal mask of the calling thread
25790 (@pxref{Signals and threads}), and has a copy of
25791 parameters of the calling thread at the time of creation
25792 (@pxref{Parameters}).
25793 @c JP
25794 作成されたスレッドは、呼び出したスレッドのシグナルマスクを継承し
25795 (@ref{Signals and threads}参照)、また呼び出したスレッドの持つ
25796 その時点でのパラメータのコピーを受けとります。
25797 @c COMMON
25798
25799 @c EN
25800 Other than those initial setups, there will be no relationship between
25801 the new thread and the calling thread; there's no parent-child
25802 relationship like Unix process. Any thread can call @code{thread-join!}
25803 on any other thread to receive the result. If nobody issues
25804 @code{thread-join!} and nobody holds a
25805 reference to the created thread, it will be garbage collected
25806 after the execution of the thread terminates.
25807 @c JP
25808 これらの初期化操作以外に、作られるスレッドと呼び出したスレッド間の関係は
25809 ありません。Unixのプロセスのような親子関係があるわけではないのです。
25810 どのスレッドも、他のスレッドに対して@code{thread-join!}を発行
25811 して結果を受け取ることができます。
25812 もし誰も@code{thread-join!}を発行せず、また作られたスレッドに対する
25813 参照を保持していなかった場合、スレッドは実行が終了した後にガベージコレクトされます。
25814 @c COMMON
25815
25816 @c EN
25817 If a thread execution is terminated because of uncaught exception,
25818 and its result is never retrieved by @code{thread-join!}, a warning
25819 will be printed to the standard error port notifying
25820 ``thread dies a lonely death'': It usually indicates some coding
25821 error. If you don't collect the result of threads, you have to
25822 make sure that all the exceptions are captured and handled within @var{thunk}.
25823 @c JP
25824 もしスレッドが捕捉されない例外のために実行を終了し、その結果が@code{thread-join!}で
25825 回収されなかった場合、標準エラーポートに``thread dies a lonely death'' という
25826 警告メッセージが出力されます。そのようなケースは通常何らかのコーディングエラーで
25827 あるからです。スレッドの結果を回収しない場合は、
25828 @var{thunk}中ですべての例外を捕捉し処理しなければなりません。
25829 @c COMMON
25830
25831 @c EN
25832 Internally, this procedure just allocates and initializes a Scheme
25833 thread object; the POSIX thread is not created until @code{thread-start!}
25834 is called.
25835 @c JP
25836 内部的に、この手続きは単にSchemeスレッドオブジェクトを割り当て初期化している
25837 だけです。POSIXスレッドは@code{thread-start!}が呼ばれるまで生成されません。
25838 @c COMMON
25839 @end defun
25840
25841 @defun thread-state thread
25842 @c MOD gauche.threads
25843 @c EN
25844 Returns one of symbols @code{new}, @code{runnable}, @code{stopped}
25845 or @code{terminated}, indicating the state of @var{thread}.
25846 @c JP
25847 @var{thread}の状態を示す、@code{new}、@code{runnable}、@code{stopped}、
25848 @code{terminated}のいずれかのシンボルを返します。
25849 @c COMMON
25850 @end defun
25851
25852 @defun thread-name thread
25853 [SRFI-18], [SRFI-21]
25854 @c MOD gauche.threads
25855 @c EN
25856 Returns the value of @var{name} slot of @var{thread}.
25857 @c JP
25858 @var{thread}のスロット@var{name}の値を返します。
25859 @c COMMON
25860 @end defun
25861
25862 @defun thread-specific thread
25863 @defunx thread-specific-set! thread value
25864 [SRFI-18], [SRFI-21]
25865 @c MOD gauche.threads
25866 @c EN
25867 Gets/sets the value of the @var{thread}'s specific slot.
25868 @c JP
25869 @var{thread}の指定したスレッドの値を取得/設定します。
25870 @c COMMON
25871 @end defun
25872
25873 @defun thread-start! thread
25874 [SRFI-18], [SRFI-21]
25875 @c MOD gauche.threads
25876 @c EN
25877 Starts the @var{thread}. An error is thrown if @var{thread} is not in
25878 ``new'' state.
25879 Returns @var{thread}.
25880 @c JP
25881 @var{thread}を開始します。@var{thread}が ``new'' 状態でなければエラーが投げられます。
25882 @var{thread}を返します。
25883 @c COMMON
25884 @end defun
25885
25886 @defun thread-try-start! thread
25887 @c MOD gauche.threads
25888 @c EN
25889 Starts and returns the @var{thread} if it is in ``new'' state.
25890 Otherwise, returns @code{#f}.
25891 @c JP
25892 @var{thread}が ``new'' 状態であればそれを開始し、@var{thread}自身を返します。
25893 そうでなければ@code{#f}を返します。
25894 @c COMMON
25895
25896 @c EN
25897 Note that a thread can become a ``terminated'' state even if it is never
25898 started, if another thread calls @code{thread-terminate!} on it.
25899 If that's the possibility, this procedure comes handy,
25900 for @code{thread-start!} may raise an error if the thread is
25901 termianted before started.
25902 @c JP
25903 スレッドは開始する前に ``terminated'' 状態になる場合があります。他のスレッドが
25904 そのスレッドに対して@code{thread-terminate!}を呼んだ場合です。
25905 開始する前に終了してしまったスレッドに対して@code{thread-start!}を呼ぶとエラーが
25906 投げられますが、この手続きではエラーになりません。
25907 @c COMMON
25908 @end defun
25909
25910 @defun thread-join! thread :optional timeout timeout-val
25911 [SRFI-18], [SRFI-21]
25912 @c MOD gauche.threads
25913 @c EN
25914 Waits termination of @var{thread}, or until the timeout is reached
25915 if @var{timeout} is given.
25916 @c JP
25917 @var{thread}の終了、あるいは@var{timeout}が与えられていればtimeoutが
25918 それに達するのを待ちます。
25919 @c COMMON
25920
25921 @c EN
25922 @var{Timeout} must be either a @code{<time>} object (@pxref{Time})
25923 that specifies absolute point of time, or a real number that specifies
25924 relative point of time from the time this procedure is called
25925 in number of seconds, or @code{#f} that indicates no timeout (default).
25926 @c JP
25927 @var{Timeout}は絶対的な時間を表す@code{<time>}オブジェクト(@ref{Time}参照)か、
25928 この手続きが呼ばれた時刻からの相対的な時間を秒数で表した実数でなければなりません。
25929 タイムアウトが指定されていない(デフォルト)は@code{#f}です。
25930 @c COMMON
25931
25932 @c EN
25933 If @var{thread} terminates normally, @code{thread-join!} returns
25934 a value which is stored in the result field of @var{thread}.
25935 If @var{thread} terminates abnormally, @code{thread-join!} raises
25936 an exception which is stored in the result exception field of @var{thread}.
25937 It can be either a @code{<terminated-thread-exception>} or
25938 @code{<uncaught-exception>}.
25939 @c JP
25940 @var{thread}が正常に終了したら、@code{thread-join!}は@var{thread}の
25941 結果フィールドに格納されている値を返します。
25942 @var{thread}が異常終了したら、@code{thread-join!}は@var{thread}の結果例外
25943 フィールドに格納されている例外を投げます。それは
25944 @code{<terminated-thread-exception>}か
25945 @code{<uncaught-exception>}のどちらかです。
25946 @c COMMON
25947
25948 @c EN
25949 If the timeout is reached, @var{thread-join!} returns @var{timeout-val}
25950 if given, or raises @code{<join-timeout-exception>}.
25951 @c JP
25952 タイムアウトに達すると、@var{timeout-val}が与えられていれば@var{timeout-val}を返し、
25953 与えられていなければ@code{<join-timeout-exception>}を投げます。
25954 @c COMMON
25955
25956 @c EN
25957 @xref{Thread exceptions}, for the details of these exceptions.
25958 @c JP
25959 これらの例外の詳細については@ref{Thread exceptions}を参照してください。
25960 @c COMMON
25961 @end defun
25962
25963 @defun thread-yield!
25964 [SRFI-18], [SRFI-21]
25965 @c MOD gauche.threads
25966 @c EN
25967 Suspends the execution of the calling thread and yields CPU to other
25968 waiting runnable threads, if any.
25969 @c JP
25970 呼び出しているスレッドの実行を中断し、他に待機中の実行可能なスレッドがあれば、
25971 CPUにそれを処理させます。
25972 @c COMMON
25973 @end defun
25974
25975 @defun thread-sleep! timeout
25976 [SRFI-18], [SRFI-21]
25977 @c MOD gauche.threads
25978 @c EN
25979 Suspends the calling thread for the period specified by @var{timeout},
25980 which must be either a @code{<time>} object (@pxref{Time}) that
25981 specifies absolute point of time, or a real number that specifies
25982 relative point of time from the time this procedure is called
25983 in number of seconds.
25984 @c JP
25985 呼び出しているスレッドを@var{timeout}に指定した時間だけ中断します。
25986 @var{timeout}は絶対的な時間を表す@code{<time>}オブジェクト(@ref{Time}参照)か、
25987 この手続きが呼ばれた時刻からの相対的な秒数を表す実数でなければなりません。
25988 @c COMMON
25989
25990 @c EN
25991 After the specified time passes, @code{thread-sleep!} returns with
25992 unspecified value.
25993 @c JP
25994 指定された時間が経過すると、@code{thread-sleep!}は未定義値を返します。
25995 @c COMMON
25996
25997 @c EN
25998 If @var{timeout} points a past time, @code{thread-sleep!} returns
25999 immediately.
26000 @c JP
26001 @var{timeout}が過去の時間を指していたら、@code{thread-sleep!}はすぐに戻ります。
26002 @c COMMON
26003 @end defun
26004
26005 @defun thread-stop! thread :optional timeout timeout-val
26006 @c MOD gauche.threads
26007 @c EN
26008 Stops execution of the target @var{thread} temporarily.
26009 You can resume the execution of the @var{thread} by @code{thread-cont!}.
26010 @c JP
26011 対象となるスレッド@var{thread}の実行を一時的に停止します。
26012 停止されたスレッドは@code{thread-cont!}により実行を再開させられます。
26013 @c COMMON
26014
26015 @c EN
26016 The stop request is handled synchronously; that is,
26017 Gauche VM only checks the request at the ``safe'' point
26018 of the VM and stops itself. It means if the @var{thread} is
26019 blocked by a system call, it won't become @code{stopped} state
26020 until the system call returns.
26021 @c JP
26022 停止リクエストは同期的に処理されます。すなわち、GaucheのVMは実行ループ中の
26023 「安全な」場所で停止リクエストをチェックし、それがあれば自分自身を停止するように
26024 なっています。このことは、@var{thread}がシステムコールによりブロックされている場合、
26025 それが戻ってくるまでスレッドが@code{stopped}状態にならないことを意味します。
26026 @c COMMON
26027
26028 @c EN
26029 By default, @code{thread-stop!} returns after the target
26030 thread stops. Since it may take indefinitely, you can give optional
26031 @var{timeout} argument to specify timeout. The @var{timeout}
26032 argument can be @code{#f}, which means no timeout, or
26033 a @code{<time>} object that specifies an absolute point of time,
26034 or a real number specifying the number of seconds to wait.
26035 @c JP
26036 デフォルトでは、@code{thread-stop!}は対象スレッドが停止状態になってから
26037 戻ってきます。しかしそうなるまでにどれだけ時間がかかるかわからないので、
26038 省略可能引数@var{timeout}を与えて、タイムアウトすることができます。
26039 @var{timeout}引数には@code{#f}(タイムアウトせず停止するまで待ち続ける)、
26040 @code{<time>}オブジェクト(絶対的な時刻を指定)、もしくは
26041 実数(現在からの秒数を指定)を与えられます。
26042 @c COMMON
26043
26044 @c EN
26045 The return value of @code{thread-stop!} is @var{thread} if
26046 it could successfully stop the target, or @var{timeout-val}
26047 if timeout reached. When @var{timeout-val} is omitted, @code{#f}
26048 is assumed.
26049 @c JP
26050 @code{thread-stop!}の戻り値は、対象スレッドを停止させられたなら
26051 その@var{thread}オブジェクト、タイムアウトしたなら@var{timeout-val}です。
26052 @var{timeout-val}が省略された場合は@code{#f}とみなされます。
26053 @c COMMON
26054
26055 @c EN
26056 If the target @var{thread} has already been stopped by the caller
26057 thread, this procedure returns @var{thread} immediately.
26058 @c JP
26059 対象スレッドが既に呼び出しスレッドの要求によって停止していた場合は、
26060 直ちに@var{thread}が返されます。
26061 @c COMMON
26062
26063 @c EN
26064 When @var{thread-stop!} is timed out, the request remains
26065 effective even after @code{thread-stop!} returns.
26066 That is, the target thread may stop at some point in future.
26067 The caller thread is expected to call @code{thread-stop!}
26068 again to complete the stop operation.
26069 @c JP
26070 @var{thread-stop!}がタイムアウトして@code{thread-stop!}から帰ってきた
26071 場合でも、リクエストは有効なままになっており、未来のいつか@var{thread}を
26072 停止させます。呼び出し側は、いずれ@code{thread-stop!}を再び呼び出して
26073 停止を確認する必要があります。
26074 @c COMMON
26075
26076 @c EN
26077 An error is signaled if the target thread has already been
26078 stopped by another thread (including the ``pending'' stop
26079 request issued by other threads), or the target thread
26080 is in neither @code{runnable} nor @code{stopped} state.
26081 @c JP
26082 対象スレッドが既に別のスレッドによって停止させられていた場合
26083 (別のスレッドによって停止要求が出されて停止待ちに
26084 なっている状態も含みます)や、
26085 対象スレッドが@code{runnable}でも@code{stopped}でもない状態の場合は
26086 エラーが報告されます。
26087 @c COMMON
26088 @end defun
26089
26090 @defun thread-cont! thread
26091 @c MOD gauche.threads
26092 @c EN
26093 Resumes execution of @var{thread} which has been stopped by
26094 @code{thread-stop!}. An error is raised if @var{thread}
26095 is not in stopped state, or it is stopped by another thread.
26096 @c JP
26097 @code{thread-stop!}で停止した@var{thread}の実行を再開します。
26098 @var{thread}が停止状態でなかったり、@code{thread-cont!}を呼び出したのとは
26099 別のスレッドによって停止させられていた場合はエラーが報告されます。
26100 @c COMMON
26101
26102 @c EN
26103 If the caller thread has already requested to stop the target
26104 thread but timed out, calling @code{thread-cont!} cancels
26105 the request.
26106 @c JP
26107 停止要求を既に出していて、タイムアウトしていた場合、@code{thread-cont!}は
26108 その停止要求をキャンセルする役割を持ちます。
26109 @c COMMON
26110 @end defun
26111
26112 @defun thread-terminate! thread :key force
26113 [SRFI-18+], [SRFI-21+]
26114 @c MOD gauche.threads
26115 @c EN
26116 Terminates the specified thread @var{thread}.
26117 The @var{thread} is terminated and an instance of
26118 @code{<terminated-thread-exception>} is stored in the result exception
26119 field of @var{thread}.
26120 @c JP
26121 指定されたスレッド@var{thread}を終了します。
26122 @var{thread}は終了され、@code{<terminated-thread-exception>}のインスタンスが
26123 @var{thread}の結果例外のフィールドに格納されます。
26124 @c COMMON
26125
26126 @c EN
26127 If @var{thread} is the same as the calling thread, this procedure
26128 won't return. Otherwise, this procedure returns unspecified value.
26129 @c JP
26130 @var{thread}が呼び出しているスレッドと同じ場合、この手続きは戻りません。
26131 そうでなければ、この手続きは未定義値を返します。
26132 @c COMMON
26133
26134 @c EN
26135 If @var{thread} is already terminated, this procedure does nothing.
26136 @c JP
26137 @var{thread}が既に終了していた場合は、この手続きは何もしません。
26138 @c COMMON
26139
26140 @c EN
26141 By default, this procedure tries to termiante the thread in ``safe''
26142 point, so that the thread can keep the process in consistent state.
26143 The locked mutexes, however, may remain locked; they become
26144 ``abandoned'' state and when other thread tries to touch the mutex
26145 it will raise @code{<abandoned-mutex-exception>}.
26146 @c JP
26147 デフォルトでは、この手続きは指定スレッドを「安全な」箇所で終了させます。
26148 これは、プロセスの状態に最低限の一貫性を保証します。
26149 ただし、指定スレッドがロックしていたmutexはロックされたまま「放棄された」状態になります。
26150 他のスレッドがそのmutexに触ろうとすると@code{<abandoned-mutex-exception>}例外が
26151 投げられます。
26152 @c COMMON
26153
26154 @c EN
26155 This strategy may, however, leave the system's thread unterminated,
26156 if the thread is blocking in certain system calls, even in Scheme level
26157 the thread is marked terminated. The system thread will terminate itself
26158 as soon as it resumes and return the control to Gauche runtime.
26159 @c JP
26160 この戦略では、スレッドがある種のシステムコールでブロックしていた場合、
26161 Schemeレベルのスレッドが「terminated」とマークされた後でもシステムスレッドが
26162 生きたまま残る可能性があります。このシステムスレッドが再開されてGaucheのランタイムに
26163 制御が戻れば、その時点でシステムスレッドは自己終了します。
26164 @c COMMON
26165
26166 @c EN
26167 If, for some reason, you need to guarantee to terminate the system thread,
26168 you can pass a true value to @code{force} keyword argument. If you do so,
26169 @code{thread-terminate!} will forcibly terminate the system thread
26170 after the usual graceful termination fails. It calls
26171 @code{pthread_cancel} or @code{TerminateThread} as the last resort,
26172 which can leave the process state inconsistent, so this mode should be
26173 used in an absolute emergency.
26174 @c JP
26175 もし何らかの理由でシステムスレッドも確実に終了させたい場合は、
26176 @code{force}キーワードに真の値を渡してください。その場合、
26177 @code{thread-terminate!}は通常の穏やかな終了を試みて失敗したら、
26178 強制的にシステムスレッドを終了させます。
26179 これは最終的に@code{pthread_cancel}や@code{TerminateThread}コールによって
26180 行われ、スレッドに後始末の余地を与えないため、プロセスの状態に一貫性が無くなる
26181 可能性があります。緊急事態の時のみ用いてください。
26182 @c COMMON
26183 @end defun
26184
26185 @defun thread-schedule-terminate! thread
26186 [SRFI-226]
26187 @c MOD gauche.threads
26188 @c EN
26189 Triggers termination of a thread @var{thread}, but returns immediately
26190 without confirming the termination.
26191
26192 This procedure does not attempt ``forcible'' termination as the @var{force}
26193 argument of @code{thread-terminate!} does. It just initiate the first
26194 stage of termination, which just send an internal request to @var{thread}.
26195 The thread will eventually terminate but there's no guarantee when it happens.
26196
26197 You can wait for @var{thread} to terminate later, using @code{thread-join!}.
26198 @c JP
26199 @var{thread}を終了させる仕組みを起動します。手続き自体はスレッドの終了を見届けることなく
26200 直ちに返ります。
26201
26202 この手続きは@code{thread-terminate!}の@var{force}引数が行うような「強制的」な
26203 終了も試みません。スレッド終了の最初のステージである、@var{thread}に内部的な
26204 リクエストを送るところまでをやります。
26205 @var{thread}はいずれ終了しますが、それがいつ起きるかについては何も保証はありません。
26206
26207 後で@code{thread-join!}を使って@var{thread}が終了するのを待つことはできます。
26208 @c COMMON
26209 @end defun
26210
26211 @node Thread local storage, Synchronization primitives, Thread procedures, Threads
26212 @subsection Thread local storage
26213 @c NODE スレッドローカル領域
26214
26215 @c EN
26216 A thread local is an object that can hold per-thread value.
26217 It is defined in SRFI-226.
26218 @c JP
26219 スレッドローカルはスレッドごとの値を格納できるオブジェクトです。
26220 SRFI-226で規定されています。
26221 @c COMMON
26222
26223 @c EN
26224 Note: Parameters used to be the way to keep per-thread value, but
26225 we've decided to split thread local storage from dyncamic binding
26226 to conform SRFI-226.
26227 Parameters should be used for dynamic binding, and thread locals should
26228 be used for per-thread value.
26229 If your existing code uses parameters for the per-thread value,
26230 update it to use thread locals.
26231 @xref{Transition to SRFI-226 parameters}, for the necessary changes.
26232 @c JP
26233 註: これまで、パラメータがスレッド毎の値を格納するためにも使われてきましたが、
26234 SRFI-226に準拠するために、
26235 動的束縛とスレッドローカル領域を切り離すことにしました。
26236 パラメータは動的束縛のためだけに使われるべきで、スレッド毎の値を保持するには
26237 スレッドローカルを使うようにしてください。
26238 既存のコードで、スレッド毎の値を保持するためにパラメータを使っている場合は、
26239 スレッドローカルを使うようにアップデートしてください。
26240 必要な変更については@ref{Transition to SRFI-226 parameters}を参照してください。
26241 @c COMMON
26242
26243
26244 @defun make-thread-local init-value :optional inheritable? name
26245 [SRFI-226]
26246 @c MOD gauche.threads
26247 @c EN
26248 Returns a new thread local, with @var{init-value} as an initial value.
26249 The optional @var{name} argument specifies thread local's name;
26250 it is only used for debugging purpose.
26251 @c JP
26252 @var{init-value}を初期値とするあらたなスレッドローカルを作って返します。
26253 省略可能な@var{name}引数は、スレッドローカルに名前を与えます。デバッグ時にのみ使われます。
26254 @c COMMON
26255
26256 @c EN
26257 A thread local is a handle to thread specific storage that can contain
26258 single Scheme value. You can retrieve its value with @code{tlref}
26259 and set a new value with @code{tlset!}.
26260 Once a thread local is created, it can be used from all existing
26261 and future threads.
26262 @c JP
26263 スレッドローカルは一つのScheme値を格納できるスレッド毎の固有領域へのハンドルです。
26264 @code{tlref}でその値を読み出し、@code{tlset!}で新たな値をセットできます。
26265 一度スレッドローカルが作られると、それはその時点で存在する、あるいはこれから作られる
26266 全てのスレッドで利用可能になります。
26267 @c COMMON
26268
26269 @c EN
26270 If @code{#f} is specified in @var{inheritable?} (default),
26271 when a thread local is @code{tlref}-ed
26272 first time in a thread, it returns @code{init-value}.
26273 If a true value is specified in @var{inheritable?},
26274 on the other hand, the initial value of the thread local
26275 inherits the value of the creator thread at the moment
26276 the thread is created.
26277 @c JP
26278 @var{inheritable?}引数が@code{#f}の場合(デフォルト)、
26279 スレッドローカルが最初に@code{tlref}されると、@code{init-value}が返ります。
26280 一方、@var{inheritable?}に真の値を指定すると、
26281 スレッドが作られた時点で、それを作ったスレッドのスレッドローカルの値が初期値として使われます。
26282 @c COMMON
26283 @end defun
26284
26285 @defun thread-local? obj
26286 [SRFI-226]
26287 @c MOD gauche.threads
26288 @c EN
26289 Returns @code{#t} if @var{obj} is a thread local, @code{#f} otherwise.
26290 @c JP
26291 @var{obj}がスレッドローカルなら@code{#t}を、そうでなければ@code{#f}を返します。
26292 @c COMMON
26293 @end defun
26294
26295 @defun tlref tl
26296 [SRFI-226]
26297 @c MOD gauche.threads
26298 @c EN
26299 Returns the value of a thread local @var{tl}.
26300 @c JP
26301 スレッドローカル@var{tl}の呼び出しスレッドでの値を返します。
26302 @c COMMON
26303 @end defun
26304
26305 @defun tlset! tl val
26306 [SRFI-226]
26307 @c MOD gauche.threads
26308 @c EN
26309 Modifies the value of a thread local @var{tl} with @var{val}.
26310 @c JP
26311 スレッドローカル@var{tl}の呼び出しスレッドでの値を@var{val}に設定します。
26312 @c COMMON
26313
26314 @c EN
26315 As Gauche's extension, you can also use @code{set!} with @code{tlref}:
26316 @c JP
26317 Gaucheの拡張として、@code{tlref}と@code{set!}を使うこともできます:
26318 @c COMMON
26319
26320 @example
26321 (set! (tlref tl) obj) @equiv{} (tlset! tl obj)
26322 @end example
26323 @end defun
26324
26325
26326 @node Synchronization primitives, Thread exceptions, Thread local storage, Threads
26327 @subsection Synchronization primitives
26328 @c NODE 同期プリミティブ
26329
26330 @c EN
26331 Mutexes and condition variables are the low-level synchronization devices.
26332 Defined in SRFI-18 and SRFI-21, they are portable across Scheme implementations
26333 that supports one of those srfis.
26334 (@xref{Mutex}, and @pxref{Condition variable}, for the details.)
26335
26336 However, in most cases you want to
26337 use following higher-level synchronization utilities:
26338 @c JP
26339 mutexと条件変数が低レベルの同期デバイスとして提供されます。
26340 これらはSRFI-18とSRFI-21で定義されているので、サポートしているScheme実装間では
26341 ポータブルです。
26342 (@ref{Mutex}、@ref{Condition variable}参照)。
26343
26344 しかし多くの場合、次のような高レベルの同期ユーティリティを使った方が良いです。
26345 @c COMMON
26346
26347 @table @asis
26348 @c EN
26349 @item Atoms
26350 An atom is a wrapper of arbitrary Scheme object, and allows synchronized
26351 access to it somewhat like Java's @code{synchronized} blocks.
26352 @c JP
26353 @item アトム
26354 アトムは任意のSchemeオブジェクトをラップして、Javaの@code{synchronized}ブロックに
26355 似た形で同期アクセスを提供します。
26356 @c COMMON
26357 @c EN
26358 @item Semaphores
26359 A traditional synchronization primitive to share fixed number of resources.
26360 @c JP
26361 @item セマフォ
26362 決まった数のリソースの利用を振り分けるのに使う、定番の同期プリミティブです。
26363 @c COMMON
26364 @c EN
26365 @item Latch
26366 Holds thread(s) until a set of operations is completed by
26367 other thread(s).
26368 @c JP
26369 @item ラッチ
26370 いくつかの操作が完了するまで、他のスレッドを待たせる同期プリミティブです。
26371 @c COMMON
26372 @c EN
26373 @item Barrier
26374 Wait until the preset number of thread reaches at the point.
26375 @c JP
26376 @item バリア
26377 指定した個数のスレッドが指定ポイントに到達するまで全員で待ち合わせる同期プリミティブです。
26378 @c COMMON
26379 @c EN
26380 @item MT-Queues
26381 Thread-safe queues (@code{<mtqueue>}) are provided in @code{data.queue} module
26382 (@pxref{Queue}), which works as a synchronized channel and
26383 suitable to implement producer-consumer pattern.
26384 @c JP
26385 @item MT-Queue
26386 スレッドセーフなキュー(@code{<mtqueue>})が@code{data.queue}モジュールで
26387 提供されます(@ref{Queue}参照)。これは同期チャネルとして動作し、
26388 生産者-消費者パターンを実装するのに適しています。
26389 @c COMMON
26390 @end table
26391
26392 @menu
26393 * Mutex::
26394 * Condition variable::
26395 * Atom::
26396 * Semaphore::
26397 * Latch::
26398 * Barrier::
26399 @end menu
26400
26401 @node Mutex, Condition variable, Synchronization primitives, Synchronization primitives
26402 @subsubsection Mutex
26403 @c NODE Mutex
26404
26405 @deftp {Builtin Class} <mutex>
26406 @clindex mutex
26407 @c MOD gauche.threads
26408 @c EN
26409 A primitive synchronization device. It can take one of four states:
26410 locked/owned, locked/not-owned, unlocked/abandoned and unlocked/not-abandoned.
26411 A mutex can be locked (by @code{mutex-lock!}) only if it is in unlocked state.
26412 An 'owned' mutex keeps a thread that owns it.
26413 Typically an owner thread is the one that locked the mutex,
26414 but you can make a thread other than the locking thread own a mutex.
26415 A mutex becomes unlocked either by @code{mutex-unlock!} or the owner
26416 thread terminates. In the former case, a mutex becomes unlocked/not-abandoned
26417 state. In the latter case, a mutex becomes unlocked/abandoned state.
26418 @c JP
26419 同期のためのプリミティブなデバイスです。次の4つの状態のいずれかを持ちます:
26420 locked/owned、locked/not-owned、unlocked/abandoned、unlocked/not-abandoned。
26421 Mutexは、それがunlocked(ロックされていない状態)であるときのみ、
26422 (@code{mutex-lock!}により)ロックされます。
26423 所有されている(owned) mutexは、そのmutexを所有しているスレッドを記憶しています。
26424 通常、所有者となるスレッドはmutexをロックしたスレッドですが、
26425 ロックしたのとは別のスレッドがmutexを所有するようにすることもできます。
26426 ロックは@code{mutex-unlock!}によるか、所有するスレッドが終了すると解放されます。
26427 前者の場合、mutexはunlocked/not-abandoned(ロックされておらず、放棄されていない状態)
26428 になります。
26429 後者の場合、mutexはunlocked/abandoned(ロックされておらず、放棄された状態)になります。
26430 @c COMMON
26431
26432 @c EN
26433 A mutex has the following external slots.
26434 @c JP
26435 Mutexは、以下の外部スロットを持ちます。
26436 @c COMMON
26437
26438 @defivar <mutex> name
26439 @c EN
26440 The name of the mutex.
26441 @c JP
26442 Mutexの名前。
26443 @c COMMON
26444 @end defivar
26445
26446 @defivar <mutex> state
26447 @c EN
26448 The state of the mutex. This is a read-only slot.
26449 See the description of @code{mutex-state} below.
26450 @c JP
26451 Mutexの状態。これは読み取りのみ可能なスロットです。
26452 下記の@code{mutex-state}の説明を参照して下さい。
26453 @c COMMON
26454 @end defivar
26455
26456 @defivar <mutex> specific
26457 @c EN
26458 A slot an application can keep arbitrary data. For example, an application
26459 can implement a 'recursive' mutex using the specific field.
26460 @c JP
26461 アプリケーションが任意のデータを保持することのできるスロットです。
26462 例えば、アプリケーションはこの固有フィールドで'再帰的な' mutexを
26463 実装することができます。
26464 @c COMMON
26465 @end defivar
26466 @end deftp
26467
26468 @defun mutex? obj
26469 [SRFI-18], [SRFI-21]
26470 @c MOD gauche.threads
26471 @c EN
26472 Returns @code{#t} if @var{obj} is a mutex, @code{#f} otherwise.
26473 @c JP
26474 @var{obj}がmutexであれば@code{#t}、そうでなければ@code{#f}を返します。
26475 @c COMMON
26476 @end defun
26477
26478 @defun make-mutex :optional name
26479 [SRFI-18], [SRFI-21]
26480 @c MOD gauche.threads
26481 @c EN
26482 Creates and returns a new mutex object.
26483 When created, the mutex is in unlocked/not-abandoned state.
26484 Optionally, you can give a name to the mutex.
26485 @c JP
26486 新しいmutexオブジェクトを生成して返します。
26487 生成時には、mutexの状態は、unlocked/not-abandoned(ロックされておらず、
26488 放棄されていない状態)です。オプションで、このmutexに名前を付けることができます。
26489 @c COMMON
26490 @end defun
26491
26492 @defun mutex-name mutex
26493 [SRFI-18], [SRFI-21]
26494 @c MOD gauche.threads
26495 @c EN
26496 Returns the name of the mutex.
26497 @c JP
26498 Mutexの名前を返します。
26499 @c COMMON
26500 @end defun
26501
26502 @defun mutex-specific mutex
26503 @defunx mutex-specific-set! mutex value
26504 [SRFI-18], [SRFI-21]
26505 @c MOD gauche.threads
26506 @c EN
26507 Gets/sets the specific value of the mutex.
26508 @c JP
26509 Mutexの固有の値を取得/セットできます。
26510 @c COMMON
26511 @end defun
26512
26513 @defun mutex-state mutex
26514 [SRFI-18], [SRFI-21]
26515 @c MOD gauche.threads
26516 @c EN
26517 Returns the state of @var{mutex}, which may be one of the followings:
26518 @c JP
26519 @var{mutex}の状態を返します。状態は以下のうちの1つです。
26520 @c COMMON
26521
26522 @table @asis
26523 @c EN
26524 @item a thread
26525 The mutex is locked/owned, and the owner is the returned thread.
26526 @item symbol @code{not-owned}
26527 The mutex is locked/not-owned.
26528 @item symbol @code{abandoned}
26529 The mutex is unlocked/abandoned.
26530 @item symbol @code{not-abandoned}
26531 The mutex is unlocked/not-abandoned.
26532 @c JP
26533 @item あるスレッド
26534 Mutexはlocked/owned(ロックされ所有されている)で、所有者は返されたスレッド。
26535 @item シンボル @code{not-owned}
26536 Mutexはlocked/not-owned(ロックされているが所有されていない)。
26537 @item シンボル @code{abandoned}
26538 Mutexはunlocked/abandoned(ロックされておらず、放棄されている)。
26539 @item シンボル @code{not-abandoned}
26540 Mutexはunlocked/not-abandoned(ロックされておらず、放棄されていない)。
26541 @c COMMON
26542 @end table
26543 @end defun
26544
26545 @defun mutex-lock! mutex :optional timeout thread
26546 [SRFI-18], [SRFI-21]
26547 @c MOD gauche.threads
26548 @c EN
26549 Locks @var{mutex}. If @var{mutex} is in unlocked/not-abandoned
26550 state, this procedure changes its state to locked state exclusively.
26551 By default, @var{mutex} becomes locked/owned state, owned by the
26552 calling thread. You can give other owner thread as @var{thread} argument.
26553 If @var{thread} argument is given and @code{#f}, the mutex becomes
26554 locked/not-owned state.
26555 @c JP
26556 @var{mutex}をロックします。@var{mutex}がunlocked/not-abandoned(
26557 ロックされておらず放棄されていない状態)なら、
26558 この手続きはその状態を排他的なlocked(ロックされた状態)に変更します。
26559 デフォルトでは、@var{mutex}はlocked/owned(ロックされ、所有された状態)になり、
26560 所有者は呼び出したスレッドです。
26561 他の所有しているスレッドを、引数@var{thread}を与えることもできます。
26562 引数@var{thread}に@code{#f}が与えられると、mutexはlocked/not-owned
26563 (ロックされ所有されていない状態)になります。
26564 @c COMMON
26565
26566 @c EN
26567 If @var{mutex} is in unlocked/abandoned state, that is, some other
26568 thread has been terminated without unlocking it, this procedure
26569 signals 'abandoned mutex exception' (@pxref{Thread exceptions})
26570 after changing the state of @var{mutex}.
26571 @c JP
26572 @var{mutex}がunlocked/abandoned(ロックされておらず放棄された状態)ならば、それはつまり、
26573 他の何らかのスレッドがそのロックを解放せずに終了した場合、
26574 この手続きは@var{mutex}の状態を変更した後に、'abandoned mutex exception'
26575 (@ref{Thread exceptions}参照)を通知します。
26576 @c COMMON
26577
26578 @c EN
26579 If @var{mutex} is in locked state and
26580 @var{timeout} is omitted or @code{#f}, this procedure blocks until
26581 @var{mutex} becomes unlocked. If @var{timeout} is specified,
26582 @code{mutex-lock!} returns when the specified time reaches in
26583 case it couldn't obtain a lock. You can give @var{timeout}
26584 an absolute point of time (by @code{<time>} object, @pxref{Time}),
26585 or a relative time (by a real number).
26586 @c JP
26587 @var{mutex}がlocked(ロックされた状態)で、@var{timeout}が省略されるか@code{#f}ならば、
26588 この手続きは@var{mutex}のロックが解放されるまでブロックします。
26589 @var{timeout}が指定されている場合は、ロックが獲得できなかったケースでは
26590 指定された時間に達した時に@code{mutex-lock!}は戻ります。
26591 @var{timeout}には、絶対的な時間(@code{<time>}オブジェクト、@ref{Time}参照)か、
26592 相対的な時間を(実数で)指定できます。
26593 @c COMMON
26594
26595 @c EN
26596 @code{Mutex-lock!} returns @code{#t} if @var{mutex} is successfully
26597 locked, or @code{#f} if timeout reached.
26598 @c JP
26599 @var{mutex}のロックが成功すると@code{mutex-lock!}は@code{#t}を返し、
26600 タイムアウトに達すると@code{#f}が返ります。
26601 @c COMMON
26602
26603 @c EN
26604 Note that @var{mutex} itself doesn't implements a 'recursive lock'
26605 feature; that is, if a thread that has locked @var{mutex} tries to lock
26606 @var{mutex} again, the thread blocks. It is not difficult, however,
26607 to implement a recursive lock semantics on top of this mutex.
26608 The following example is taken from SRFI-18 document:
26609 @c JP
26610 @var{mutex}それ自身は'再帰的なロック'の機能は実装していません。
26611 つまり、@var{mutex}をロックしたスレッドが再度@var{mutex}をロックしようと
26612 すると、そのスレッドはブロックします。しかし、このmutexに
26613 基づいて再帰的なロックのセマンティクスを実装することは難しくありません。
26614 次の例は、SRFI-18のドキュメントから引用したものです。
26615 @c COMMON
26616
26617 @example
26618 (define (mutex-lock-recursively! mutex)
26619 (if (eq? (mutex-state mutex) (current-thread))
26620 (let ((n (mutex-specific mutex)))
26621 (mutex-specific-set! mutex (+ n 1)))
26622 (begin
26623 (mutex-lock! mutex)
26624 (mutex-specific-set! mutex 0))))
26625
26626 (define (mutex-unlock-recursively! mutex)
26627 (let ((n (mutex-specific mutex)))
26628 (if (= n 0)
26629 (mutex-unlock! mutex)
26630 (mutex-specific-set! mutex (- n 1)))))
26631 @end example
26632 @end defun
26633
26634 @defun mutex-unlock! mutex :optional condition-variable timeout
26635 [SRFI-18], [SRFI-21]
26636 @c MOD gauche.threads
26637 @c EN
26638 Unlocks @var{mutex}. The state of @var{mutex} becomes unlocked/not-abandoned.
26639 It is allowed to unlock a mutex that is not owned by the calling thread.
26640 @c JP
26641 @var{mutex}をアンロックします。@var{mutex}の状態は、unlocked/not-abandoned
26642 (ロックされておらず、放棄されていない状態)となります。
26643 呼び出しているスレッドにより所有されていないmutexをアンロックすることは
26644 許されています。
26645 @c COMMON
26646
26647 @c EN
26648 If optional @var{condition-variable} is given, @code{mutex-unlock!}
26649 serves the "condition variable wait" operation (e.g. @code{pthread_cond_wait}
26650 in POSIX threads). The current thread atomically wait on
26651 @var{condition-variable} and unlocks @var{mutex}.
26652 The thread will be unblocked when other thread signals on
26653 @var{condition-variable} (see @code{condition-variable-signal!}
26654 and @code{condition-variable-broadcast!} below), or @var{timeout}
26655 reaches if it is supplied. The @var{timeout} argument can be either
26656 a @code{<time>} object to represent an absolute time point (@pxref{Time}),
26657 a real number to represent a relative time in seconds, or @code{#f} which
26658 means never. The calling thread may be unblocked prematurely,
26659 so it should reacquire the lock of @var{mutex} and checks the
26660 condition, as in the following example (it is taken from SRFI-18 document):
26661 @c JP
26662 オプショナル引数の@var{conditional-variable}が与えられている場合、
26663 @code{mutex-unlock!}は``条件変数待機''の動作も行います(例えば、POSIXスレッドの
26664 @code{pthread_cond_wait})。
26665 現在のスレッドは@var{mutex}をアンロックし、
26666 @var{condition-variable}の待ち状態に入る動作をアトミックに行います。
26667 スレッドは、他のスレッドが@var{condition-variable}にシグナルを通知するか
26668 (下記の@code{condition-variable-signal!}と@code{condition-variable-broadcast!}を
26669 見て下さい)、
26670 @var{timeout}が与えられていてそれに達すると、ブロックが解除されます。
26671 引数@var{timeout}は、絶対的な時間を表す@code{<time>}オブジェクト(@ref{Time}参照)、
26672 相対的な時間を秒数で表す実数、タイムアウトしないことを表す@code{#f}のいずれかです。
26673 ブロックが解除された時に、必ずしも条件が満たされているとは限らないので、
26674 次に挙げる例(SRFI-18のドキュメントより引用)のように、
26675 呼び出したスレッドは@var{mutex}のロックを再獲得して条件を検査するべきです。
26676 @c COMMON
26677
26678 @example
26679 (let loop ()
26680 (mutex-lock! m)
26681 (if (condition-is-true?)
26682 (begin
26683 (do-something-when-condition-is-true)
26684 (mutex-unlock! m))
26685 (begin
26686 (mutex-unlock! m cv)
26687 (loop))))
26688 @end example
26689
26690 @c EN
26691 The return value of @code{mutex-unlock!} is @code{#f} when it returns
26692 because of timeout, and @code{#t} otherwise.
26693 @c JP
26694 @code{mutex-unlock!}の戻り値は、タイムアウトした場合に@code{#f}、
26695 それ以外の場合は@code{#t}となります。
26696 @c COMMON
26697 @end defun
26698
26699 @defun mutex-locker mutex
26700 @defunx mutex-unlocker mutex
26701 @c MOD gauche.threads
26702 @c EN
26703 Returns @code{(lambda () (mutex-lock! mutex))} and
26704 @code{(lambda () (mutex-unlock! mutex))}, respectively.
26705 Each closure is created at most once per @var{mutex},
26706 thus it is lighter than using literal lambda forms in a tight loop.
26707 @c JP
26708 それぞれ@code{(lambda () (mutex-lock! mutex))} と
26709 @code{(lambda () (mutex-unlock! mutex))} を返します。
26710 これらのクロージャは、各@var{mutex}につきひとつづつしか作られないため、
26711 タイトなループの中ではこれらの形のリテラルなラムダ式を使うよりも軽量です。
26712 @c COMMON
26713 @end defun
26714
26715
26716 @defun with-locking-mutex mutex thunk
26717 @c MOD gauche.threads
26718 @c EN
26719 Calls @var{thunk} with locking a mutex @var{mutex}. This is defined as
26720 follows.
26721 @c JP
26722 @var{mutex}をロックして@var{thunk}を呼びます。次のように実装されています。
26723 @c COMMON
26724 @example
26725 (define (with-locking-mutex mutex thunk)
26726 (dynamic-wind
26727 (mutex-locker mutex)
26728 thunk
26729 (mutex-unlocker mutex)))
26730 @end example
26731 @end defun
26732
26733 @defmac run-once expr @dots{}
26734 @c MOD gauche.threads
26735 @c EN
26736 When this form is first evaluated, it evaluates @var{expr} @dots{}
26737 returns the result(s) of the lat expression.
26738 The results are memoized, so the subsequent
26739 evaluation of the form returns the same results without
26740 evaluating @var{expr}s.
26741 @c JP
26742 最初にこのフォームが評価された時、@var{expr} @dots{}が順に評価され、
26743 最後の式の結果(複数であることもあります)が変えされます。
26744 結果は記憶され、以降のこのフォームの評価は@var{expr} @dots{}を評価することなく
26745 以前の結果が直ちに返されます。
26746 @c COMMON
26747
26748 @c EN
26749 It may sound somewhat similar to @code{force} a promise,
26750 but @code{run-once} guarantees
26751 that only one thread ever evaluates @var{expr}s. If more than one thread
26752 tries to evaluate the same @code{run-once} form, the one that aquire the
26753 lock first evaluates it, making other threads wait. Note that @code{force}
26754 does not prevent more than one thread to start evaluating the promise's
26755 body simultaneously; it
26756 only guarantees that the first delivered result becomes the value
26757 of the promise.
26758 @c JP
26759 プロミスを@code{force}するのに似ていると思うかもしれません。
26760 ただ、@code{run-once}は一つのスレッドだけが@var{exprs}を評価することを保証します。
26761 複数のスレッドが同じ@code{ron-once}フォームを同時に評価しようとした場合、
26762 ロックを獲得したスレッドのみが@var{expr} @dots{}の評価を行い、
26763 他のスレッドはその結果が出るまで待たされます。
26764 これは@code{force}と異なることに注意してください。
26765 @code{force}は複数のスレッドが同時にプロミスの本体を評価し始めることは禁じておらず、
26766 ただ、最初に確定した結果がプロミスの結果となることのみ保証してまいす。
26767 @c COMMON
26768
26769 @c EN
26770 If the control goes out from this form before completing evaluation,
26771 e.g. by an error, it is unlocked and another thread may start
26772 evaluating @var{expr}s. If you have operations that should never
26773 be evaluated more than once no matter what, you should use @code{guard}
26774 or @code{unwind-protect} to make sure evaluation completes.
26775 @c JP
26776 制御が式の評価を全て完了する前に、エラーなどでフォームから制御が外にに移った場合、
26777 ロックは外され、他のスレッドが@var{expr}を評価できるようになります。
26778 何があっても二度評価してはいけない操作がある場合は、@code{guard}や
26779 @code{unwind-protect}で適切に保護してください。
26780 @c COMMON
26781 @end defmac
26782
26783
26784 @node Condition variable, Atom, Mutex, Synchronization primitives
26785 @subsubsection Condition variable
26786 @c NODE 条件変数
26787
26788 @deftp {Builtin Class} <condition-variable>
26789 @clindex condition-variable
26790 @c MOD gauche.threads
26791 @c EN
26792 A condition variable keeps a set of threads that are waiting for
26793 a certain condition to be true. When a thread modifies the state
26794 of the concerned condition, it can call @code{condition-variable-signal!}
26795 or @code{condition-variable-broadcast!}, which unblock one or more
26796 waiting threads so that they can check if the condition is satisfied.
26797 @c JP
26798 条件変数は、ある条件が真になるのを待っているスレッドの集合を保持します。
26799 あるスレッドがその条件を変更する時、@code{condition-variable-signal!}あるいは
26800 @code{condition-variable-broadcast!}が呼ばれ、それは1つ以上の待機中の
26801 スレッドのブロックを解除するため、それらのスレッドは条件が満足するかどうか
26802 検査できます。
26803 @c COMMON
26804
26805 @c EN
26806 A condition variable object has the following slots.
26807 @c JP
26808 条件変数オブジェクトは以下のスロットを持ちます。
26809 @c COMMON
26810
26811 @defivar <condition-variable> name
26812 @c EN
26813 The name of the condition variable.
26814 @c JP
26815 条件変数の名前。
26816 @c COMMON
26817 @end defivar
26818
26819 @defivar <condition-variable> specific
26820 @c EN
26821 A slot an application can keep arbitrary data.
26822 @c JP
26823 アプリケーションが任意のデータを保持できるスロット。
26824 @c COMMON
26825 @end defivar
26826
26827 @c EN
26828 Note that SRFI-18 doesn't have a routine equivalent to pthreads'
26829 @code{pthread_cont_wait}. If you want to wait on condition variable,
26830 you can pass a condition variable to @code{mutex-unlock!} as an
26831 optional argument (see above), then acquire mutex again by
26832 @code{mutex-lock!}. This design is for flexibility; see
26833 SRFI-18 document for the details.
26834 @c JP
26835 SRFI-18は、pthreadの@code{pthread_cond_wait}に相当する手続きを
26836 持たないことに注意してください。条件変数を待つのは、
26837 @code{mutex-unlock!}の省略可能引数に条件変数を渡し、
26838 その後mutexを再び@code{mutex-lock!}で得ることで行います。
26839 この設計は柔軟性のためです。詳しくはSRFI-18を参照して下さい。
26840 @c COMMON
26841
26842 @c EN
26843 This is the common usage of pthreads' condition variable:
26844 @c JP
26845 このような、pthreadで条件変数を使う定石は:
26846 @c COMMON
26847 @example
26848 while (some_condition != TRUE) @{
26849 pthread_cond_wait(condition_variable, mutex);
26850 @}
26851 @end example
26852 @c EN
26853 And it can be translated to SRFI-18 as follows:
26854 @c JP
26855 SRFI-18では次のようなコードになります。
26856 @c COMMON
26857 @example
26858 (let loop ()
26859 (unless some-condition
26860 (mutex-unlock! mutex condition-variable)
26861 (mutex-lock! mutex)
26862 (loop)))
26863 @end example
26864 @end deftp
26865
26866 @defun condition-variable? obj
26867 [SRFI-18], [SRFI-21]
26868 @c MOD gauche.threads
26869 @c EN
26870 Returns @code{#t} if @var{obj} is a condition variable,
26871 @code{#f} otherwise.
26872 @c JP
26873 @var{obj}が条件変数なら@code{#t}、そうでなければ@code{#f}を返します。
26874 @c COMMON
26875 @end defun
26876
26877 @defun make-condition-variable :optional name
26878 [SRFI-18], [SRFI-21]
26879 @c MOD gauche.threads
26880 @c EN
26881 Returns a new condition variable. You can give its name by
26882 optional @var{name} argument.
26883 @c JP
26884 新しい条件変数を返します。オプショナル引数@var{name}で
26885 その名前を与えることができます。
26886 @c COMMON
26887 @end defun
26888
26889 @defun condition-variable-name cv
26890 [SRFI-18], [SRFI-21]
26891 @c MOD gauche.threads
26892 @c EN
26893 Returns the name of the condition variable.
26894 @c JP
26895 条件変数の名前を返します。
26896 @c COMMON
26897 @end defun
26898
26899 @defun condition-variable-specific cv
26900 @defunx condition-variable-specific-set! cv value
26901 [SRFI-18]、[SRFI-21]
26902 @c MOD gauche.threads
26903 @c EN
26904 Gets/sets the specific value of the condition variable.
26905 @c JP
26906 条件変数の固有の値を取得/セットします。
26907 @c COMMON
26908 @end defun
26909
26910 @defun condition-variable-signal! cv
26911 [SRFI-18]、[SRFI-21]
26912 @c MOD gauche.threads
26913 @c EN
26914 If there are threads waiting on @var{cv}, causes the scheduler to select
26915 one of them and to make it runnable.
26916 @c JP
26917 @var{cv}で待機しているスレッドがある場合は、それらのうちの1つがスケジューラに
26918 より選択され、実行可能にされます。
26919 @c COMMON
26920 @end defun
26921
26922 @defun condition-variable-broadcast! cv
26923 [SRFI-18]、[SRFI-21]
26924 @c MOD gauche.threads
26925 @c EN
26926 Unblocks all the threads waiting on @var{cv}.
26927 @c JP
26928 @var{cv}で待機している全てのスレッドのブロックを解除します。
26929 @c COMMON
26930 @end defun
26931
26932 @node Atom, Semaphore, Condition variable, Synchronization primitives
26933 @subsubsection Atom
26934 @c NODE アトム
26935
26936 @c EN
26937 An atom is a convenient wrapper to make operations on a
26938 given set of objects thread-safe. Instead of defining
26939 thread-safe counterparts of every structure, you can easily
26940 wrap an existing data structures to make it thread-safe.
26941 @c JP
26942 アトムはオブジェクトの集まりをスレッドセーフに簡単に扱うことができるラッパーです。
26943 それぞれの構造に対応するスレッドセーフ版を作るかわりに、
26944 既にあるいくつかのデータをまとめて包んでスレッドセーフにできます。
26945 @c COMMON
26946
26947 @defun atom val @dots{}
26948 @c MOD gauche.threads
26949 @c EN
26950 Creates and returns an atom object with @var{val} @dots{} as the
26951 initial values.
26952 @c JP
26953 @var{val} @dots{}を初期値に持つアトムオブジェクトを作って返します。
26954 @c COMMON
26955 @end defun
26956
26957 @defun atom? obj
26958 @c MOD gauche.threads
26959 @c EN
26960 Returns @code{#t} iff @var{obj} is an atom.
26961 @c JP
26962 @var{obj}がアトムなら@code{#t}を、そうでなければ@code{#f}を返します。
26963 @c COMMON
26964 @end defun
26965
26966 @c EN
26967 The following procedures can be used to @emph{atomically}
26968 access and update the content of an atom. They commonly
26969 take optional @var{timeout} and @var{timeout-val} arguments,
26970 both are defaulted to @code{#f}. In some cases, the procedure
26971 takes more than one @var{timeout-val} arguments.
26972 With the default value @code{#f} as @var{timeout} argument,
26973 those procedures blocks until they acquire a lock.
26974 @c JP
26975 以下の手続きは、アトムの中身に@emph{アトミック}にアクセスしたり、
26976 それをアップデートするのに使えます。共通する省略可能引数として、
26977 @var{timeout}と@var{timeout-val}を取ります。
26978 これらのデフォルト値は@code{#f}です。手続きによっては一つ以上の@var{timeout-val}
26979 を取ることがあります。
26980 @var{timeout}引数がデフォルト値@code{#f}であれば、
26981 以下の手続きはロックが得られるまでブロックします。
26982 @c COMMON
26983
26984 @c EN
26985 The timeout arguments can be used to modify the behavior when
26986 the lock cannot be acquired in timely manner.
26987 @var{timeout} may be a @code{<time>} object (@pxref{Time})
26988 to specify an absolute point of time, or a real number
26989 to specify the relative time in seconds. If timeout is
26990 expired, those procedures give up acquiring the lock,
26991 and the value given to @var{timeout-val} is returned.
26992 In @code{atomic} and @code{atomic-update!}, you can make them return
26993 multiple timeout values, by giving
26994 more than one @var{timeout-val} arguments.
26995 @c JP
26996 @var{timeout}引数はすぐにロックが得られなかった場合の動作を変更します。
26997 @var{timeout}引数には、絶対的な時刻を指定する@code{<time>}オブジェクト
26998 (@ref{Time}参照)か、相対的な時刻を秒数で指定する実数を渡すことができます。
26999 指定された時刻が過ぎたら、以下の手続きはロックを獲得するのを諦めて、
27000 @var{timeout-val}に指定された値を返します。
27001 @code{atomic}と@code{atomic-update!}は一つ以上の値を返し得るので、
27002 一つ以上の@var{timeout-val}を渡せます。
27003 @c COMMON
27004
27005 @defun atom-ref atom :optional index timeout timeout-val
27006 @c MOD gauche.threads
27007 @c EN
27008 Returns @var{index}-th value of @var{atom}.
27009 See above for @var{timeout} and @var{timeout-val} arguments.
27010 @c JP
27011 アトム@var{atom}の@var{index}番目の値を返します。
27012 @var{timeout}と@var{timeout-val}については上記参照。
27013 @c COMMON
27014
27015 @example
27016 (define a (atom 'a 'b))
27017
27018 (atom-ref a 0) @result{} a
27019 (atom-ref a 1) @result{} b
27020 @end example
27021 @end defun
27022
27023 @defun atomic atom proc :optional timeout timeout-val timeout-val2 @dots{}
27024 @c MOD gauche.threads
27025 @c EN
27026 Calls @var{proc} with the current values in @var{atom},
27027 while locking @var{atom}. @var{proc} must take
27028 as many arguments as the number of values @var{atom} has.
27029 @c JP
27030 @var{atom}をロックして、@var{proc}を現在の@var{atom}の値に適用します。
27031 @var{proc}は@var{atom}の値の数だけの引数を取ることができなければなりません。
27032 @c COMMON
27033
27034 @c EN
27035 The returned value(s) of @var{proc} is the result of
27036 @code{atomic}, unless timeout occurs.
27037 See above for @var{timeout} and @var{timeout-val} arguments.
27038 @c JP
27039 タイムアウトが起こらない限り、@var{proc}が返した値が@code{atomic}の返り値となります。
27040 @var{timeout}と@var{timeout-val}については上記参照。
27041 @c COMMON
27042
27043 @c EN
27044 For example, the @code{ref/count} procedure
27045 in the following example counts the number of times
27046 the hashtable is referenced in thread-safe way.
27047 @c JP
27048 例えば次の@code{ref/count}は、
27049 ハッシュテーブルが参照された回数を数えるスレッドセーフな手続きです。
27050 @c COMMON
27051
27052 @example
27053 (define a (atom (make-hash-table 'eq?) (list 0)))
27054
27055 (define (ref/count a key)
27056 (atomic a
27057 (lambda (ht count-cell)
27058 (inc! (car count-cell))
27059 (hash-table-get h key))))
27060 @end example
27061 @end defun
27062
27063 @defun atomic-update! atom proc :optional timeout timeout-val timeout-val2 @dots{}
27064 @c MOD gauche.threads
27065 @c EN
27066 Calls @var{proc} with the current values in @var{atom}
27067 while locking @var{atom}, and updates the values in @var{atom}
27068 by the returned values from @var{proc}.
27069 @var{proc} must take as many arguments as the number of
27070 values @var{atom} has, and must return the at least the same number of
27071 values. If @var{proc} returns more than the number of values @var{atom}
27072 holds, the extra values are not used to update the @var{atom}, but
27073 is included in the return values of @code{atomic-update!}.
27074 @c JP
27075 @var{atom}をロックして、その値を引数として@var{proc}を呼び、
27076 @var{proc}の戻り値を@var{atom}の新たな値とします。
27077 @var{proc}は@var{atom}の値の数だけ引数を取らねばならず、
27078 また@var{atom}の値の数以上の戻り値を返さねばなりません。
27079 @var{proc}が@var{atom}の値の数以上の値を返した場合、
27080 余分な値は@var{atom}を更新するのには使われませんが、
27081 @code{atomic-update!}の結果には含まれます。
27082 @c COMMON
27083
27084 @c EN
27085 The returned value(s) of @code{atomic-update!} is what
27086 @var{proc} returns, unless timeout occurs.
27087 See above for @var{timeout} and @var{timeout-val} arguments.
27088 @c JP
27089 @code{atomic-update!}の戻り値は、タイムアウトが起こらなければ@var{proc}の戻り値です。
27090 @var{timeout}と@var{timeout-val}については上記参照。
27091 @c COMMON
27092
27093 @c EN
27094 The following example shows a thread-safe counter.
27095 @c JP
27096 下はスレッドセーフなカウンタです。
27097 @c COMMON
27098
27099 @example
27100 (define a (atom 0))
27101
27102 (atomic-update! a (cut + 1 <>))
27103 @end example
27104 @end defun
27105
27106 @c EN
27107 Note: The term @emph{atom} in historical Lisps
27108 meant an object that is not a cons cell (pair). Back then
27109 cons cells were the only aggregate datatype and there were
27110 few other datatypes (numbers and symbols), so having a
27111 complementary term to cells made sense.
27112 @c JP
27113 @emph{atom}は古のLispでは「コンスセル(ペア)でないもの」を指していました。
27114 当時、コンスセルは唯一の複合型であり、他の型もごくわずか(数値とシンボル)だったので、
27115 セルでないものを指すことには意味がありました。
27116 @c COMMON
27117
27118 @c EN
27119 Although it still appears in introductory Lisp tutorials,
27120 modern Lisps, including Scheme, has so many datatypes and it makes
27121 little sense to have a specific term for non-pair types.
27122 @c JP
27123 今でもatomはLispのチュートリアルで目にすることがありますが、
27124 Schemeをはじめ現代のLispではたくさんのデータ型があり、
27125 コンスセル以外をひとまとめにする用語を使う意味がほとんどありません。
27126 @c COMMON
27127
27128 @c EN
27129 Clojure adopted the term @emph{atom} for thread-safe (atomic)
27130 primitive data, and we followed it.
27131 @c JP
27132 Clojureはatomをスレッドセーフ(アトミック)な基本データに使ったので、
27133 Gaucheもそれに倣うことにしました。
27134 @c COMMON
27135
27136 @c EN
27137 Note: The constructor of atom is not @code{make-atom}
27138 but @code{atom}, following the convention of @code{list}/@code{make-list},
27139 @code{vector}/@code{make-vector}, and @code{string}/@code{make-string};
27140 that is, the name without @code{make-} takes its elements as
27141 variable number of arguments.
27142 @c JP
27143 註: コンストラクタが@code{make-atom}ではなく@code{atom}なのは、
27144 @code{list}/@code{make-list}、@code{vector}/@code{make-vector}、
27145 @code{string}/@code{make-string}などの慣習に従っています。
27146 つまり、@code{make-}のない手続きは、各要素を可変長引数の形で取ります。
27147 @c COMMON
27148
27149 @node Semaphore, Latch, Atom, Synchronization primitives
27150 @subsubsection Semaphore
27151 @c NODE セマフォ
27152
27153 @deftp {Builtin Class} <semaphore>
27154 @clindex semaphore
27155 @c MOD gauche.threads
27156 @c EN
27157 A semaphore manages ``tokens'' for a fixed number of resources.
27158 A thread that wants to use one of the resources requests a token
27159 by @code{semaphore-acquire!}, and returns the token to the pool
27160 by @code{semaphore-release!}. When the thread requests a token
27161 but none is available, it waits until a token becomes available
27162 by some other thread returning one.
27163 @c JP
27164 セマフォは、決まった数のリソースを使うための「トークン」を管理します。
27165 リソースを使いたいスレッドは@code{semaphore-acquire!}を呼びトークンを獲得します。
27166 リソースを使い終わったら@code{semaphore-release!}でトークンを返します。
27167 スレッドがトークンを要求した時点でトークンが余っていなければ、他のスレッドがトークンを返す
27168 まで待ちます。
27169 @c COMMON
27170 @end deftp
27171
27172 @defun make-semaphore :optional init-value name
27173 @c MOD gauche.threads
27174 @c EN
27175 Creates and returns a new semaphore, with @var{init-value} tokens
27176 available initially. If @var{init-value} is omitted, 0 is assumed.
27177 Another optional argument @var{name} is an arbitrary Scheme object
27178 and only used for a debugging purpose only; it is displayed
27179 when a semaphore is printed.
27180 @c JP
27181 新たなセマフォを作って返します。@var{init-value}は初期段階で使えるトークンの数を
27182 指定します。省略された場合は0になります。
27183 もう一つの省略可能引数@var{name}は任意のSchemeオブジェクトで、
27184 セマフォの表示にのみ使われます。
27185 @c COMMON
27186 @end defun
27187
27188 @defun semaphore? obj
27189 @c MOD gauche.threads
27190 @c EN
27191 Returns @code{#t} iff @var{obj} is a semaphore.
27192 @c JP
27193 @var{obj}がセマフォなら@code{#t}を、そうでなければ@code{#f}を返します。
27194 @c COMMON
27195 @end defun
27196
27197 @defun semaphore-acquire! sem :optional timeout timeout-val
27198 @c MOD gauche.threads
27199 @c EN
27200 Obtain a token from a semaphore @var{sem}.
27201 If a token is available, this returns @code{#t} immediately,
27202 decrementing the available token count of @var{sem} atomically.
27203 If no token is available, this waits until a token becomes
27204 avaialble, or @var{timeout} reaches if it is given. If timeout
27205 occurs, it returns @var{timeout-val}, defaulted to @code{#f}.
27206 @c JP
27207 セマフォ@var{sem}からトークンを獲得します。トークンがあれば、
27208 トークンの残り数をデクリメントして、直ちに@code{#t}を返します。
27209 もしトークンが余ってなければ、新たなトークンが返却されるか、
27210 @var{timeout}が指定するタイムアウトまで待ちます。
27211 タイムアウトした場合は@var{timeout-val}が返されます。@var{timeout-val}の
27212 デフォルトは@code{#f}です。
27213 @c COMMON
27214
27215 @c EN
27216 The value of @var{timeout} is the same as @code{mutex}; it can be
27217 @code{#f} (no timeout, default), a @code{<time>} object to specify an absolute
27218 point of time, or a real number to specify the minimum number of seconds
27219 to wait.
27220 @c JP
27221 @var{timeout}に渡せる値は@var{mutex}と同じで、
27222 @code{#f} (タイムアウトなし。デフォルト値)、
27223 絶対的な時刻を指定する@code{<time>}オブジェクト、
27224 あるいは現在からの秒数を相対的に指定する実数です。
27225 @c COMMON
27226 @end defun
27227
27228 @defun semaphore-release! sem :optional count
27229 @c MOD gauche.threads
27230 @c EN
27231 Return a token to a semaphore @var{sem}, by incrementing its token count,
27232 and running one of the threads waiting with @code{semaphore-acquire!} atomically.
27233 @c JP
27234 トークンをセマフォ@var{sem}に返却します。@var{sem}のトークン数をインクリメントするのと
27235 同時に、@var{semaphore-acquire!}で待っているスレッドのひとつを走らせます。
27236 @c COMMON
27237
27238 @c EN
27239 The @var{count} argument specifies number of tokens to return, defaulted to 1.
27240 @c JP
27241 @var{count}引数で返却するトークンの数を指定できます。デフォルトは1です。
27242 @c COMMON
27243
27244 @c EN
27245 Actually, the ``token'' model is to make it easier to understand the
27246 idea of semaphore, but internally it's just a counter, so you can
27247 call @code{semaphore-release!} even you haven't called @code{semaphore-acuqire!}.
27248 @c JP
27249 実のところ、「トークン」と読んでいるのはセマフォのモデルを理解しやすくするためで、
27250 内部的には単なるカウンタにすぎません。なので
27251 @code{semaphore-acuqire!}を呼んでいなくても@code{semaphore-release!}でトークンを追加
27252 することができます。
27253 @c COMMON
27254 @end defun
27255
27256
27257 @node Latch, Barrier, Semaphore, Synchronization primitives
27258 @subsubsection Latch
27259 @c NODE ラッチ
27260
27261 @deftp {Builtin Class} <latch>
27262 @clindex latch
27263 @c MOD gauche.threads
27264 @c EN
27265 A latch is a synchornization device with a counter.
27266 Any number of threads can wait until the counter becomes zero.
27267 Once the counter reaches zero, all threads go.
27268 (As opposed to semaphores, whose internal counter affects
27269 number of waiting threads as well.)
27270 @c JP
27271 ラッチはカウンタを内部に持つ同期デバイスです。
27272 カウンタが0になるまで、スレッドはいくつでも待ちます。
27273 カウンタが0になった途端、全てのスレッドが走ります。
27274 (セマフォでは、内部のカウンタは待つスレッドの数にも影響しますが、
27275 ラッチではカウンタと待つスレッドの数は無関係です)。
27276 @c COMMON
27277
27278 @c EN
27279 One simple usage is to start with initial count 1; it is sometimes
27280 called a ``gate''. You can let threads wait before the gate, and
27281 decrement the counter, then boom! All threads proceeds.
27282 @c JP
27283 最も単純な用途では、初期カウントを1から始めます。これはしばしば「ゲート」と呼ばれます。
27284 待つスレッドはゲートに達したらそこで停止し、ひとたびカウンタをデクリメントしたら、
27285 全てのスレッドがそこから走り始めます。
27286 @c COMMON
27287 @end deftp
27288
27289 @defun make-latch initial-count :optional name
27290 @c MOD gauche.threads
27291 @c EN
27292 Creates and returns a new latch with the counter value @var{initial-count},
27293 which must be an exact positive integer.
27294 @c JP
27295 カウンタの初期値として@var{initial-count}を持つラッチを作って返します。
27296 @var{initial-count}は正確な正整数でなければなりません。
27297 @c COMMON
27298
27299 @c EN
27300 The optional @var{name} argument can be any Scheme object, and
27301 used only for debugging. It is displayed when the latch object
27302 is printed.
27303 @c JP
27304 省略可能な@var{name}引数は任意のSchemeオブジェクトで、
27305 ラッチを表示する時にのみ使われます。
27306 @c COMMON
27307 @end defun
27308
27309 @defun latch? obj
27310 @c MOD gauche.threads
27311 @c EN
27312 Returns @code{#t} iff @var{obj} is a latch.
27313 @c JP
27314 @var{obj}がラッチなら@code{#t}を、そうでなければ@code{#f}を返します。
27315 @c COMMON
27316 @end defun
27317
27318 @defun latch-dec! latch :optional n
27319 @c MOD gauche.threads
27320 @c EN
27321 Decrement the counter of @var{latch} by @var{n}.
27322 If @var{n} is omitted, 1 is assumed.
27323
27324 If the value of the latch becomes 0 or less, threads waiting on the
27325 latch are woken up.
27326
27327 Returns the updated counter value.
27328 @c JP
27329 ラッチのカウンタを@var{n}だけ減らします。@var{n}が省略されたら1を使います。
27330
27331 カウンタの値が0以下になったら、ラッチで待っているスレッドを起こします。
27332
27333 更新後のカウンタの値を返します。
27334 @c COMMON
27335
27336 @c EN
27337 @var{N} must be an exact integer. Zero or negative value is allowed.
27338 @c JP
27339 @var{n}は正確な整数でなければなりません。0や負の値も許されます。
27340 @c COMMON
27341 @end defun
27342
27343 @defun latch-clear! latch
27344 @c MOD gauche.threads
27345 @c EN
27346 If @var{latch}'s count was non-zero, make it zero and wakes up
27347 the threads waiting on it.
27348 If @var{latch}'s count has already been zero, do nothing.
27349
27350 Returns the previous count.
27351 @c JP
27352 @var{latch}のカウンタが0でなければ、それを0にし、待っているスレッドを起こします。
27353 既に0であれば何もしません。
27354
27355 0にする前のカウンタの値を返します。
27356 @c COMMON
27357 @end defun
27358
27359 @defun latch-await latch :optional timeout timeout-val
27360 @c MOD gauche.threads
27361 @c EN
27362 If the counter of @var{latch} is zero or negative, returns @code{#t}
27363 immeiately. Otherwise, the calling thread is blocked until
27364 the counter value becomes zero or below, or timeout reaches.
27365 If the thread started by the counter value, @code{#t} is returned.
27366 If the thread started by timeout, @var{timeout-val} is returned,
27367 whose default is @code{#f}.
27368 @c JP
27369 ラッチ@var{latch}のカウンタが0以下なら直ちに@code{#t}を返します。
27370 そうでなければ、呼び出しスレッドはカウンタが0以下になるか、タイムアウトするまで
27371 ブロックされます。カウンタによりスレッドが再開された場合は@code{#t}が、
27372 タイムアウトした場合は@var{timeout-val}が返されます。
27373 @var{timeout-val}のデフォルトは@code{#f}です。
27374 @c COMMON
27375
27376 @c EN
27377 The @var{timeout} argument must be either @code{#f} (no timeout, default),
27378 a @code{<time>} object (absolute point of time), or a real number
27379 indicates number of seconds from the time this procedure is called.
27380 @c JP
27381 @var{timeout}引数は、
27382 @code{#f} (タイムアウトなし。デフォルト値)、
27383 絶対的な時刻を指定する@code{<time>}オブジェクト、
27384 あるいは現在からの秒数を相対的に指定する実数です。
27385 @c COMMON
27386 @end defun
27387
27388 @node Barrier, , Latch, Synchronization primitives
27389 @subsubsection Barrier
27390 @c NODE バリア
27391
27392 @deftp {Builtin Class} <barrier>
27393 @clindex barrier
27394 @c MOD gauche.threads
27395 @c EN
27396 A barrier is a synchronization primitive that multiple threads
27397 wait by @code{barrier-await}
27398 until a specified number of threads reach the point.
27399 Once the specified number of threads get to the barrier,
27400 all threads go, and the barrier automatically returns to the initial
27401 state; the next thread that comes to the barrier waits again.
27402 @c JP
27403 バリアは、指定された個数のスレッドが待ち状態になるまで待ち合わせる
27404 同期プリミティブです。
27405 @code{barrier-await}を呼んだスレッドが指定の個数に達したら、
27406 全てのスレッドが再開し、バリアは初期状態に戻ります。
27407 次にバリアに到達したスレッドは再び待ちに入ります。
27408 @c COMMON
27409
27410 @c EN
27411 A barrier can have an optional @emph{action}, which is run by the
27412 last thread that reached to the barrier before everyone goes.
27413 @c JP
27414 バリアは「アクション」を持つことができます。アクションは、待ち合わせスレッドが
27415 しきい値に到達した時に、他のスレッドが走り出す前に実行されます。
27416 @c COMMON
27417
27418 @c EN
27419 A barrier can be in a ``broken'' state when any one of the threads
27420 timeout, or the action raises an uncaptured exception. Once the barrier
27421 is broken, all threads waiting on it is released as if timeout has
27422 occured. The broken barrier remains broken (so any thread that reaches
27423 it just passes through) until it is reset by @code{barrier-reset!}.
27424 @c JP
27425 待っているスレッドのいずれかがタイムアウトするか、アクションで捕捉されない例外が
27426 投げられた場合、バリアは「破れた」状態になります。
27427 バリアが壊れると、待っていたスレッドはあたかもタイムアウトが起きたかのように
27428 再開されます。破れた状態は@code{barrier-reset!}で明示的にリセットされるまで
27429 保たれ、その間にバリアに到達したスレッドはあたかも0のタイムアウトが指定されたかのように
27430 そのまま素通りします。
27431 @c COMMON
27432 @end deftp
27433
27434 @defun make-barrier threshold :optional action name
27435 @c MOD gauche.threads
27436 @c EN
27437 Craetes and returns a new barrier. The @var{threshold} argument
27438 must be an exact nonnegative integer to specify the number of threads
27439 to let them go---threads calling @code{barrier-await} waits until
27440 the number of threads waiting reaches @var{threshold}.
27441 @c JP
27442 新しいバリアを作って返します。@var{threshold}は正確な非負整数でなければならず、
27443 待ち合わせるスレッドの数を指定します。@code{barrier-await}を
27444 呼んだスレッドがこの数に達した時に、それら全てのスレッドで
27445 @code{barrier-await}から制御が戻ります。
27446 @c COMMON
27447
27448 @c EN
27449 The optional @var{action} argument must be either @code{#f} (no action)
27450 or a thunk. If it is a thunk, it is run by the last thread
27451 that calls @code{barrier-await}, before all the thread will go.
27452 @c JP
27453 省略可能な@var{action}引数は@code{#f}(アクションなし)かサンクでなければなりません。
27454 サンクの場合、それはバリアが開放される前の最後に@code{barrier-await}を呼んだ
27455 スレッドによって、他のスレッドが走り始める前に実行されます。
27456 @c COMMON
27457
27458 @c EN
27459 The optional @var{name} argument can be any Scheme object,
27460 and only used to print the barrier instance, to help debugging.
27461 @c JP
27462 @var{name}引数は任意のSchemeオブジェクトで、バリアを表示する際にのみ使われます。
27463 @c COMMON
27464 @end defun
27465
27466 @defun barrier? obj
27467 @c MOD gauche.threads
27468 @c EN
27469 Returns @code{#t} iff @var{obj} is a barrier.
27470 @c JP
27471 @var{obj}がバリアなら@code{#t}を、そうでなければ@code{#f}を返します。
27472 @c COMMON
27473 @end defun
27474
27475 @defun barrier-await barrier :optional timeout timeout-val
27476 @c MOD gauche.threads
27477 @c EN
27478 Waits on @var{barrier} until the number of waiting threads reaches
27479 the threshold of the barrier, or the barrier is broken.
27480 @c JP
27481 @var{barrier}で待っているスレッドが閾値に達するか、バリアが破れるまで、
27482 呼び出したスレッドを待たせます。
27483 @c COMMON
27484
27485 @c EN
27486 A barrier can be broken if any of waiting threads hit the timeout,
27487 or an uncaptured exception is raised from the action thunk of the barrier.
27488 @c JP
27489 バリアが破れるのは、待っているスレッドのどれかがタイムアウトするか、
27490 バリアのアクションから例外が投げられた時です。
27491 @c COMMON
27492
27493 @c EN
27494 The @var{timeout} and @var{timeout-val} are the same as other synchronization
27495 primitives; @var{timeout} may be @code{#f} (no timeout, default),
27496 a @code{<time>} object
27497 to specify an absolute time point, or a real number indicating relative
27498 time in number of seconds; @var{timeout-val} is the value returned
27499 when @code{barrier-await} returns prematurely---either timeout, or
27500 other barrier breakage conditions.
27501 The default of @var{timeout-val} is @code{#f}.
27502 @c JP
27503 @var{timeout}と@var{timeout-val}引数は他の同期プリミティブと同じです。
27504 @var{timeout}は@code{#t} (タイムアウトなし、デフォルト)か、
27505 絶対的時刻を指定する@code{<time>}オブジェクトか、
27506 相対的な秒数を指定する実数です。
27507 @var{timeout-val}は@code{barrier-await}がタイムアウトかバリア破れで
27508 戻る場合に返される値で、デフォルトは@code{#f}です。
27509 @c COMMON
27510
27511 @c EN
27512 It returns an integer if the thread is released by reaching the threshold,
27513 or @var{timeout-val} if the barrier is broken. The integer indicates
27514 the number of threads required to reach the threshold at the time
27515 @code{barrier-wait} is called; that is, if you're the first to reach
27516 the barrier it is threshold - 1, and if you're the last it is 0.
27517 @c JP
27518 この手続きの戻り値は、待ちスレッド数が閾値に達して戻った場合は正確な整数、
27519 バリアが破れた場合は@var{timeout-val}です。
27520 正確な整数は、@code{barrier-await}を呼び出した時点であといくつ待ちスレッドが
27521 必要だったかを示します。つまり、最初にバリアに到達したスレッドなら @code{threshold - 1}、
27522 最後に到達したなら0です。
27523 @c COMMON
27524
27525 @c EN
27526 If the barrier is already broken when you call @code{barrier-await},
27527 it returns immediately with @var{timeout-val}.
27528 @c JP
27529 @code{barrier-await}を呼んだ時点で既にバリアが破れていたら、
27530 直ちに@var{timeout-val}が返されます。
27531 @c COMMON
27532
27533 @c EN
27534 If the threads are released normally, the barrier turns back to the
27535 initial state so you can wait on it again. If the threads are released
27536 because the barrier is broken, it remains in broken state until
27537 reset by @code{barrier-reset!}.
27538 @c JP
27539 スレッド数が閾値に達して全スレッドを解放した場合は、
27540 バリアは初期状態に戻ります。つまり、次に@code{barrier-await}を呼んだスレッドは
27541 再び待たされることになります。
27542 バリアが破れたば場合、@code{barrier-reset!}が呼ばれるまでバリアはずっと破れた
27543 状態のままになります。
27544 @c COMMON
27545 @end defun
27546
27547 @defun barrier-broken? barrier
27548 @c MOD gauche.threads
27549 @c EN
27550 Returns @code{#t} iff @var{barrier} is in broken state.
27551 @c JP
27552 バリア@var{barrier}が破れた状態なら@code{#t}を、そうでなければ@code{#f}を返します。
27553 @c COMMON
27554 @end defun
27555
27556 @defun barrier-reset! barrier
27557 @c MOD gauche.threads
27558 @c EN
27559 Resets the barrier to the initial state. If the barrire is broken,
27560 the broken state is cleared. If any thread is waiting on the barrier,
27561 it is released as if the number of threads reaches the threshold.
27562 @c JP
27563 バリアを初期状態にリセットします。バリアが破れた状態なら、破れていない状態に戻ります。
27564 バリアで待っているスレッドがいた場合、それはあたかもスレッド数が閾値に達したかのように
27565 解放されます。
27566 @c COMMON
27567 @end defun
27568
27569
27570 @node Thread exceptions, , Synchronization primitives, Threads
27571 @subsection Thread exceptions
27572 @c NODE スレッド例外
27573
27574 @c EN
27575 Some types of exceptions may be thrown from thread-related procedures.
27576 These exceptions can be handled by Gauche's exception mechanism
27577 (@pxref{Exceptions}).
27578 @c JP
27579 例外のいくつかのタイプは、スレッド関連の手続きから投げられます。
27580 これらの例外は、Gaucheの例外メカニズム(@ref{Exceptions}参照)により
27581 扱われます。
27582 @c COMMON
27583
27584 @c EN
27585 These are originally defined in SRFI-18. SRFI-226 follows them,
27586 but uses slightly different names for the consistency with
27587 modern Scheme. We support both.
27588 @c JP
27589 これらは元々SRFI-18で定義されました。SRFI-226もそれに倣いましたが、
27590 名前については現代的なSchemeの名前付けを意識したものに変えています。
27591 Gaucheではどちらの名前もサポートします。
27592 @c COMMON
27593
27594 @deftp {Builtin Class} <thread-exception>
27595 @deftpx {Condition Type} &thread
27596 @clindex thread-exception
27597 @vrindex &thread
27598 [SRFI-226]
27599 @c MOD gauche.threads
27600 @c EN
27601 A base class of thread-related exceptions. Inherits @code{<exception>} class.
27602 It has one slot.
27603 @c JP
27604 スレッド関連の例外の基底クラスです。@code{<exception>}クラスを継承しています。
27605 スロットを1つ持っています。
27606 @c COMMON
27607
27608 @defivar <thread-exception> thread
27609 @c EN
27610 A thread that threw this exception.
27611 @c JP
27612 この例外を投げたスレッド。
27613 @c COMMON
27614 @end defivar
27615
27616 @c EN
27617 The name @code{&thread} is defined by SRFI-226. Note that SRFI-226
27618 does not define @code{thread} slot; it's Gauche's extension.
27619 @c JP
27620 @code{&thread}というコンディション名はSRFI-226での定義です。
27621 ただし、SRFI-226のコンディションは@code{thread}スロットは規定していません。
27622 @c COMMON
27623 @end deftp
27624
27625 @deftp {Builtin Class} <join-timeout-exception>
27626 @deftpx {Condition Type} &thread-timeout
27627 @clindex join-timeout-exception
27628 @vrindex &thread-timeout
27629 [SRFI-226]
27630 @c MOD gauche.threads
27631 @c EN
27632 An exception thrown by @code{thread-join!} when a timeout reaches
27633 before the waited thread returns. Inherits @code{<thread-exception>}.
27634 @c JP
27635 待機していたスレッドが戻る前にタイムアウトに達した時に@code{thread-join!}によって
27636 投げられる例外。@code{<thread-exception>}を継承しています。
27637 @c COMMON
27638
27639 @c EN
27640 The name @code{&thread-timeout} is defined by SRFI-226.
27641 @c JP
27642 @code{&thread-timeout}という名前はSRFI-226で定義されています。
27643 @c COMMON
27644 @end deftp
27645
27646 @deftp {Builtin Class} <abandoned-mutex-exception>
27647 @deftpx {Condition Type} &thread-abandoned-mutex
27648 @clindex abandoned-mutex-exception
27649 @vrindex &thread-abandoned-mutex
27650 [SRFI-226]
27651 @c MOD gauche.threads
27652 @c EN
27653 An exception thrown by @code{mutex-lock!} when a @var{mutex} to be
27654 locked is in unlocked/abandoned state. Inherits @code{<thread-exception>}.
27655 It has one additional slot.
27656 @c JP
27657 ロックされる@var{mutex}が、unlocked/abandoned(ロックされておらず、放棄された状態)
27658 であるときに@code{mutex-lock!}により投げられる例外。
27659 @code{<thread-exception>}を継承しています。スロットを1つ持ちます。
27660 @c COMMON
27661
27662 @defivar <abandoned-mutex-exception> mutex
27663 @c EN
27664 A mutex that caused this exception.
27665 @c JP
27666 この例外の原因となったmutex。
27667 @c COMMON
27668 @end defivar
27669
27670 @c EN
27671 The name @code{&thread-abandoned-mutex} is defined by SRFI-226.
27672 @c JP
27673 @code{&thread-abandoned-mutex}という名前はSRFI-226で定義されています。
27674 @c COMMON
27675 @end deftp
27676
27677 @deftp {Builtin Class} <terminated-thread-exception>
27678 @deftpx {Condition Type} &thread-already-terminated
27679 @clindex terminated-thread-exception
27680 @vrindex &thread-already-terminated
27681 [SRFI-226]
27682 @c MOD gauche.threads
27683 @c EN
27684 An exception thrown by @code{thread-join!} when the waited thread
27685 is terminated abnormally (by @code{thread-terminate!}).
27686 Inherits @code{<thread-exception>}. It has one additional slot.
27687 @c JP
27688 待機していたスレッドが(@code{thread-terminate!}により)異常終了した
27689 場合に(@code{thread-join!}により)投げられる例外。
27690 @code{<thread-exception>}を継承し、スロットを1つ持ちます。
27691 @c COMMON
27692
27693 @defivar <terminated-thread-exception> terminator
27694 @c EN
27695 A thread that terminated the thread that causes this exception.
27696 @c JP
27697 この例外の原因となったスレッドを終了したスレッド。
27698 @c COMMON
27699 @end defivar
27700
27701 @c EN
27702 The name @code{&thread-already-terminated} is defined by SRFI-226.
27703 SRFI-226 doesn't define @code{terminator} slot, though.
27704 @c JP
27705 @code{&thread-abandoned-mutex}という名前はSRFI-226で定義されています。
27706 ただし、SRFI-226は@code{terminator}スロットは定義していません。
27707 @c COMMON
27708 @end deftp
27709
27710 @deftp {Builtin Class} <uncaught-exception>
27711 @deftpx {Condition Type} &uncaught-exception
27712 @clindex uncaught-exception
27713 @vrindex &uncaught-exception
27714 [SRFI-226]
27715 @c MOD gauche.threads
27716 @c EN
27717 An exception thrown by @code{thread-join!} when the waited thread
27718 is terminated by an uncaught exception.
27719 Inherits @code{<thread-exception>}. It has one additional slot.
27720 @c JP
27721 待機していたスレッドが捕捉されない例外により終了された場合に
27722 @code{thread-join!}により投げられる例外。
27723 @code{<thread-exception>}を継承し、スロットを1つ持ちます。
27724 @c COMMON
27725
27726 @defivar <uncaught-exception> reason
27727 @c EN
27728 An exception that caused the termination of the thread.
27729 @c JP
27730 そのスレッドの終了の原因となった例外。
27731 @c COMMON
27732 @end defivar
27733
27734 @c EN
27735 The name @code{&uncaught-exception} is defined by SRFI-226.
27736 @c JP
27737 @code{&uncaught-exception}という名前はSRFI-226で定義されています。
27738 @c COMMON
27739 @end deftp
27740
27741 @deftp {Builtin Class} <concurrent-modification-violation>
27742 @deftpx {Condition Type} &concurrent-modification
27743 @clindex concurrent-modification-violation
27744 @vrindex &concurrent-modification
27745 [SRFI-226]
27746 @c EN
27747 This is a condition thrown when the runtime detects non-thread-safe
27748 data is being modified by multiple threads concurrently.
27749 SRFI-226 defines this, but it allows implementations not to detect
27750 this situation if it's costly. Currently, no Gauche APIs detect
27751 this condition, though it may do so in future. For now, this is
27752 provided for the compatibility with SRFI-226.
27753 @c JP
27754 これはスレッドセーフでないデータを複数スレッドで同時に変更しようとした場合に
27755 投げられるコンディションです。SRFI-226で定義されていますが、
27756 SRFIはこの状況を検出するのにオーバヘッドがある場合は検出しなくても良いとしています。
27757 今のところ、GaucheのAPIでこのコンディションを検出するものはありません。
27758 将来はできるかもしれません。今はこれはSRFI-226との互換性のためのみで提供されています。
27759 @c COMMON
27760 @end deftp
27761
27762 @defun make-thread-condition
27763 [SRFI-226]
27764 @c MOD gauche.threads
27765 @c EN
27766 Creates a new @code{<thread-exception>} condition. This is for SRFI-226
27767 compatibility. Usually you don't need to use this directly, for
27768 the actual condition is of a subclass of @code{<thread-exception>}.
27769 The @code{thread} slot is initialized with the calling thread.
27770 @c JP
27771 新しい@code{<thread-exception>}コンディションを作ります。
27772 これはSRFI-226との互換のために用意されていますが、直接使う必要はほとんどないでしょう。
27773 実際には@code{<thread-exception>}のサブクラスのコンディションが使われるからです。
27774 コンディションの@code{thread}スロットは呼び出したスレッドで初期化されます。
27775 @c COMMON
27776 @end defun
27777
27778 @defun thread-condition? obj
27779 [SRFI-226]
27780 @c MOD gauche.threads
27781 @c EN
27782 Returns @code{#t} if @var{obj} is a @code{<thread-exception>}
27783 (@code{&thread}) condition,
27784 @code{#f} otherwise.
27785 @c JP
27786 @var{obj}が@code{<thread-exception>}
27787 (@code{&thread})コンディションなら@code{#t}を、
27788 そうでなければ@code{#f}を返します。
27789 @c COMMON
27790 @end defun
27791
27792 @defun make-thread-timeout-condition
27793 [SRFI-226]
27794 @c MOD gauche.threads
27795 @c EN
27796 Creates a new @code{<join-timeout-exception>} (@code{&thread-timeout}) condition.
27797 @c JP
27798 新たな@code{<join-timeout-exception>} (@code{&thread-timeout})コンディション
27799 を作ります。
27800 @c COMMON
27801 @end defun
27802
27803 @defun join-timeout-exception? obj
27804 @defunx thread-timeout-condition? obj
27805 [SRFI-18], [SRFI-21], [SRFI-226]
27806 @c MOD gauche.threads
27807 @c EN
27808 Returns @code{#t} if @var{obj} is a
27809 @code{<join-timeout-exception>} (@code{&thread-timeout}) condition,
27810 @code{#f} otherwise.
27811 The name @code{join-timeout-exception?} is defined by SRFI-18/21,
27812 and @code{thread-timeout-condition?} is by SRFI-226. They are the same.
27813 @c JP
27814 @var{obj}が@code{<join-timeout-exception>} (@code{&thread-timeout})
27815 コンディションなら@code{#t}を、
27816 そうでなければ@code{#f}を返します。
27817 @code{join-timeout-exception?}はSRFI-18/21で、
27818 @code{thread-timeout-condition?}はSRFI-226で定義された名前です。どちらも同じです。
27819 @c COMMON
27820 @end defun
27821
27822 @defun make-thread-abandoned-mutex
27823 [SRFI-226]
27824 @c MOD gauche.threads
27825 @c EN
27826 Creates a new @code{<abandoned-mutex-exception>}
27827 (@code{&thread-abandoned-mutex}) condition.
27828 @c JP
27829 新たな@code{<abandoned-mutex-exception>}
27830 (@code{&thread-abandoned-mutex})コンディションを作ります。
27831 @c COMMON
27832 @end defun
27833
27834 @defun abandoned-mutex-exception? obj
27835 @defunx thread-abandoned-mutex-condition? obj
27836 [SRFI-18], [SRFI-21], [SRFI-226]
27837 @c MOD gauche.threads
27838 @c EN
27839 Returns @code{#t} if @var{obj} is a
27840 @code{<abandoned-mutex-exception>} (), @code{#f} otherwise.
27841 The name @code{abandoned-mutex-exception?} is defined by SRFI-18/21,
27842 and @code{thread-abandoned-mutex-condition?} is by SRFI-226. They are the same.
27843 @c JP
27844 @var{obj}が@code{<abandoned-mutex-exception>}のインスタンスなら@code{#t}を、
27845 そうでなければ@code{#f}を返します。
27846 @code{abandoned-mutex-exception?}はSRFI-18/21で、
27847 @code{thread-abandoned-mutex-condition?}はSRFI-226で定義された名前です。どちらも同じです。
27848 @end defun
27849
27850 @defun make-thread-already-terminated-condition
27851 [SRFI-226]
27852 @c MOD gauche.threads
27853 @c EN
27854 Creates a new @code{<terminated-thread-exception>}
27855 (@code{&thread-already-terminated}) condition.
27856 @c JP
27857 新たな@code{<termianted-thread-exception>}
27858 (@code{&thread-already-terminated})コンディションを作ります。
27859 @c COMMON
27860 @end defun
27861
27862 @defun terminated-thread-exception? obj
27863 @defunx thread-already-terminated-condition? obj
27864 [SRFI-18], [SRFI-21], [SRFI-226]
27865 @c MOD gauche.threads
27866 @c EN
27867 Returns @code{#t} if @var{obj} is an instance of
27868 @code{<terminated-thread-exception>}, @code{#f} otherwise.
27869 The name @code{terminated-thread-exception?} is defined by SRFI-18/21,
27870 and @code{thread-already-terminated-condition?} is by SRFI-226. They are the same.
27871 @c JP
27872 @var{obj}が@code{<terminated-thread-exception>}のインスタンスなら@code{#t}を、
27873 そうでなければ@code{#f}を返します。
27874 @code{terminated-thread-exception?}はSRFI-18/21で、
27875 @code{thread-already-termianted-condition?}はSRFI-226で定義された名前です。どちらも同じです。
27876 @end defun
27877
27878 @defun make-uncaught-exception-condition reason
27879 [SRFI-226]
27880 @c MOD gauche.threads
27881 @c EN
27882 Creates a new @code{<uncaught-exception>}
27883 (@code{&uncaught-exception}) condition.
27884 The argument is set to the @code{reason} slot of the condition.
27885 @c JP
27886 新たな@code{<uncaught-exception>}
27887 (@code{&uncaught-exception})コンディションを作ります。
27888 引数はコンディションの@code{reason}スロットに保持されます。
27889 @c COMMON
27890 @end defun
27891
27892 @defun uncaught-exception? obj
27893 @defunx uncaught-exception-condition? obj
27894 [SRFI-18], [SRFI-21], [SRFI-226]
27895 @c MOD gauche.threads
27896 @c EN
27897 Returns @code{#t} if @var{obj} is an instance of
27898 @code{<uncaught-exception>}, @code{#f} otherwise.
27899 The name @code{uncaught-exception?} is defined by SRFI-18/21,
27900 and @code{uncaught-exception-condition?} is by SRFI-226. They are the same.
27901 @c JP
27902 @var{obj}が@code{<uncaught-exception>}のインスタンスなら@code{#t}を、
27903 そうでなければ@code{#f}を返します。
27904 @code{uncaught-exception?}はSRFI-18/21で、
27905 @code{uncaught-exception-condition?}はSRFI-226で定義された名前です。どちらも同じです。
27906 @end defun
27907
27908 @defun uncaught-exception-reason exc
27909 @defunx uncaught-exception-condition-reason exc
27910 [SRFI-18], [SRFI-21], [SRFI-226]
27911 @c MOD gauche.threads
27912 @c EN
27913 Returns the value of @code{reason} slot of @code{<uncaught-exception>}
27914 object.
27915 @c JP
27916 @code{<uncaught-exception>}オブジェクトの@code{reason}スロットの値を
27917 返します。
27918 @c COMMON
27919
27920 @c EN
27921 The name @code{uncaught-exception-reason} is defined in
27922 SRFI-18/21, and @code{uncaught-exception-condition-reason} is
27923 defined in SRFI-226. Both works the same.
27924 @c JP
27925 @code{uncaught-exception-reason}はSRFI-18/21で、
27926 @code{uncaught-exception-condition-reason}はSRFI-226で定義された名前です。
27927 どちらも同じ動作です。
27928 @c COMMON
27929 @end defun
27930
27931 @defun make-concurrent-modification-violation
27932 [SRFI-226]
27933 @c MOD gauche.threads
27934 @c EN
27935 Creates a new @code{<concurrent-modification-violation>}
27936 (@code{&concurrent-modification}) condition.
27937 @c JP
27938 新たな@code{<concurrent-modification-violation>}
27939 (@code{&concurrent-modification})コンディションを作ります。
27940 @c COMMON
27941 @end defun
27942
27943 @defun concurrent-modification-violation? obj
27944 [SRFI-226]
27945 @c MOD gauche.threads
27946 @c EN
27947 Returns @code{#t} if @var{obj} is a
27948 @code{<concurrent-modification-violation>}
27949 (@code{&concurrent-modification}) condition, @code{#f} otherwise.
27950 @c JP
27951 @var{obj}が@code{<concurrent-modification-violation}
27952 (@code{&concurrent-modification})コンディションなら@code{#t}を、
27953 そうでなければ@code{#f}を返します。
27954 @c COMMON
27955 @end defun
27956
27957 @c ----------------------------------------------------------------------
27958 @node Measure timings, Unicode utilities, Threads, Library modules - Gauche extensions
27959 @section @code{gauche.time} - Measure timings
27960 @c NODE 時間の計測, @code{gauche.time} - 時間の計測
27961
27962 @deftp {Module} gauche.time
27963 @mdindex gauche.time
27964 @c EN
27965 Provides three ways to measure execution time of Scheme code.
27966 A macro @code{time}, which is convenient for interactive use,
27967 a set of procedures for benchmarking,
27968 and @code{<time-counter>} objects which are useful to be embedded
27969 in the program.
27970 @c JP
27971 Schemeコードの実行時間を測る3つの方法を提供します。
27972 インタラクティブな使用に便利な@code{time}マクロ、
27973 ベンチマークのための手続きのセット、
27974 プログラム中に埋め込んで使える@code{<time-counter>}オブジェクトです。
27975 @c COMMON
27976 @end deftp
27977
27978 @c EN
27979 @subheading Interactive measurement of execution time
27980 @c JP
27981 @subheading インタラクティブな実行時間の計測
27982 @c COMMON
27983
27984 @c EN
27985 Note: The @code{time} macro is pre-defined to autoload @code{gauche.time}
27986 for the convenience; you don't need to say @code{(use gauche.time)}
27987 to use the @code{time} macro.
27988 @c JP
27989 註: @code{time}マクロは@code{gauche.time}モジュールをオートロードする
27990 ようにあらかじめ定義されているので、@code{time}マクロを使うだけなら
27991 @code{(use gauche.time)}としておく必要はありません。
27992 @c COMMON
27993
27994 @defmac time expr expr2 @dots{}
27995 @c MOD gauche.time
27996 @c EN
27997 Evaluates @var{expr} @var{expr2} @dots{} sequentially, as @code{begin},
27998 and returns the result(s) of the last expression.
27999 Before returning the value(s), the macro reports the elapsed (real) time
28000 and CPU times in the user space and the kernel space to the current
28001 error port, much like the bourne shell's time command.
28002 @c JP
28003 式@var{expr} @var{expr2} @dots{} を順に評価し、最後の式の結果を返します。
28004 結果が返される前に、全ての式の評価にかかった実(経過)時間および
28005 ユーザースペース、カーネルスペースで費されたCPU時間がカレントエラーポートに
28006 報告されます。
28007 @c COMMON
28008
28009 @c EN
28010 The current version uses @code{sys-gettimeofday} (@pxref{Time}) to
28011 calculate the elapsed time, and @code{sys-times} (@pxref{System inquiry})
28012 to calculate user and system CPU times. So the resolution of these numbers
28013 depends on these underlying system calls. Usually the CPU
28014 time has 10ms resolution, while the elapsed time might have higher
28015 resolution. On the systems that doesn't have gettimeofday(2) support,
28016 however, the elapsed time resolution can be as bad as a second.
28017 @c JP
28018 現在の実装は、経過時間に対しては@code{sys-gettimeofday}
28019 (@ref{Time}参照)を、CPU時間に対しては@code{sys-times}
28020 (@ref{System inquiry}参照)を用いています。従って、
28021 それぞれの数値の分解能はこれらの手続きが用いているシステムコールに依存します。
28022 CPU時間は10ms単位で、経過時間はそれより細かいことが多いです。
28023 但しgettimeofday(2)コールをサポートしていないOSでは経過時間が最悪の場合
28024 秒単位になります。
28025 @c COMMON
28026
28027 @smallexample
28028 gosh> (time (length (sort (call-with-input-file "/usr/share/dict/words"
28029 port->string-list))))
28030 ;(time (length (sort (call-with-input-file "/usr/share/dict/words" port- ...
28031 ; real 0.357
28032 ; user 0.350
28033 ; sys 0.000
28034 45427
28035 @end smallexample
28036 @end defmac
28037
28038 @c EN
28039 @subheading Benchmarking
28040 @c JP
28041 @subheading ベンチマーク
28042 @c COMMON
28043
28044 @c EN
28045 It is not unusual that the routine you want to measure takes only
28046 a fraction of second, so you have to run it many times for better
28047 measurement. It is also common that you want to compare results
28048 of measurement of two or more implementation strategies.
28049 Here are useful procedures to do so.
28050 @c JP
28051 計測したいルーチンの一回の実行が一瞬で終わるために、
28052 何度も繰り返して実行してより正確に時間を測りたいということはよくあります。
28053 また、複数の実装を計測して比べてみたいということもよくあります。
28054 ここに挙げるのは、そのために便利な手続きです。
28055 @c COMMON
28056
28057 @c EN
28058 The name and behavior of those benchmarking routines are inspired
28059 by Perl's Benchmark module.
28060 @c JP
28061 これらベンチマーク手続きの名前と振る舞いは、PerlのBenchmarkモジュールを
28062 参考にしています。
28063 @c COMMON
28064
28065 @defun time-this how thunk
28066 @c MOD gauche.time
28067 @c EN
28068 Calls @var{thunk} many times and measure its execution time.
28069 The argument @var{how} can be one of the following forms.
28070 @c JP
28071 @var{thunk}を何度も呼び出し、実行時間を測ります。
28072 @var{how}には次の形が指定できます。
28073 @c COMMON
28074
28075 @table @code
28076 @item @var{integer}
28077 @c EN
28078 It calls @var{thunk} as many times as the given number.
28079 @c JP
28080 指定された回数だけ、@var{thunk}を呼びます。
28081 @c COMMON
28082 @item (@var{metric} @var{real})
28083 @c EN
28084 It calls @var{thunk} as many times as the total time exceeds
28085 the given number of seconds. @var{Metric} is either one of symbols
28086 @code{cpu}, @code{user}, @code{sys}, or @code{real}, to specify how
28087 the time is measured.
28088 @c JP
28089 時間の合計が指定された数値(秒)を越えるまで@var{thunk}を繰り返し呼びます。
28090 @var{metric}はシンボル@code{cpu}、@code{user}、@code{sys}、@code{real}の
28091 いずれかで、どの時間で測るかを指定します。
28092 @c COMMON
28093 @end table
28094
28095 @c EN
28096 It also runs an empty loop as the same times and subtract the
28097 time took for the empty loop from the measured time, to get
28098 more accurate result.
28099 @c JP
28100 このルーチンはまた、@var{thunk}を実行するのと同じ回数だけ
28101 空のループを実行して、その時間を結果から引くので、
28102 結果には@var{thunk}の実行時間のみが反映されます。
28103 @c COMMON
28104
28105 @c EN
28106 The result is returned in a @code{<time-result>} record, described below.
28107 Here are some examples:
28108 @c JP
28109 戻り値は後述する@code{<time-result>}レコードです。先に例を示しておきます。
28110 @c COMMON
28111 @smallexample
28112 ;; Run the thunk 1,000,000 times
28113 (time-this 1000000 (lambda () (expt 100 30)))
28114 @result{} #<time-result 1000000 times/ 1.030 real/ 1.040 user/ 0.000 sys>
28115
28116 ;; Run the thunk at least 5.0 cpu seconds
28117 (time-this '(cpu 5.0) (lambda () (expt 100 30)))
28118 @result{} #<time-result 4903854 times/ 5.090 real/ 5.050 user/ 0.010 sys>
28119 @end smallexample
28120 @end defun
28121
28122 @deftp {Record} <time-result>
28123 @c MOD gauche.time
28124 @c EN
28125 A record to hold the benchmark result.
28126 Following slots are defined.
28127 @c JP
28128 ベンチマーク結果を保持するレコードです。以下のスロットがあります。
28129 @c COMMON
28130
28131 @defivar {<time-result>} count
28132 @fnindex time-result-count
28133 @c EN
28134 The number of times the thunk was run. This slot is also
28135 accessed by a procedure @code{time-result-count}.
28136 @c JP
28137 @var{thunk}が実行された回数です。
28138 このスロットはアクセサ手続き@code{time-result-count}でもアクセスできます。
28139 @c COMMON
28140 @end defivar
28141
28142 @defivar {<time-result>} real
28143 @fnindex time-result-real
28144 @c EN
28145 The total real (elapsed) time running the thunk took.
28146 This slot is also accessed by a procedure @code{time-result-real}.
28147 @c JP
28148 @var{thunk}の実行にかかった実経過時間の合計です。
28149 このスロットはアクセサ手続き@code{time-result-real}でもアクセスできます。
28150 @c COMMON
28151 @end defivar
28152
28153 @defivar {<time-result>} user
28154 @fnindex time-result-user
28155 @c EN
28156 The total user cpu time running the thunk took.
28157 This slot is also accessed by a procedure @code{time-result-user}.
28158 @c JP
28159 @var{thunk}の実行にかかったユーザCPU時間の合計です。
28160 このスロットはアクセサ手続き@code{time-result-user}でもアクセスできます。
28161 @c COMMON
28162 @end defivar
28163
28164 @defivar {<time-result>} sys
28165 @fnindex time-result-sys
28166 @c EN
28167 The total system cpu time running the thunk took.
28168 This slot is also accessed by a procedure @code{time-result-sys}.
28169 @c JP
28170 @var{thunk}の実行にかかったシステムCPU時間の合計です。
28171 このスロットはアクセサ手続き@code{time-result-sys}でもアクセスできます。
28172 @c COMMON
28173 @end defivar
28174 @end deftp
28175
28176 @defun make-time-result count real user sys
28177 @c MOD gauche.time
28178 @c EN
28179 The constructor of @code{<time-result>} records.
28180 @c JP
28181 @code{<time-result>}レコードのコンストラクタです。
28182 @c COMMON
28183 @end defun
28184
28185 @defun time-result? obj
28186 @c MOD gauche.time
28187 @c EN
28188 The predicate of @code{<time-result>} records.
28189 @c JP
28190 @code{<time-result>}レコードかどうかを判定します。
28191 @c COMMON
28192 @end defun
28193
28194 @defun time-result+ t1 t2 :key (with-count #f)
28195 @defunx time-result- t1 t2 :key (with-count #f)
28196 @c MOD gauche.time
28197 @c EN
28198 Add or subtract two @code{<time-result>} records and returns a new record.
28199
28200 If @var{with-count} is false,
28201 only the real, user and sys slots are added or subtracted,
28202 and the result's count slot is set to the same as @var{t1}'s count slot.
28203 It is supposed to be used to calculate on measurement
28204 from different chunk of code.
28205
28206 If @var{with-count} is true,
28207 then the values of count slot is also added or subtracted.
28208 It is supposed to calculate on
28209 multiple benchmark results of the same code.
28210 @c JP
28211 ふたつの@code{<time-result>}レコードの和と差を求め、新しいレコードを返します。
28212
28213 @var{with-count}が偽なら、
28214 real, user, sysの各スロットのみが計算対象となり、
28215 結果のcountスロットは@var{t1}のcountスロットの値がそのまま引き継がれます。
28216 これは、部分ごとに別々に計測された結果を対象に計算する場合を意図しています。
28217
28218 @var{with-count}が真なら、
28219 countスロットも同様に計算対象となります。
28220 これは、何度か走らせたベンチマーク結果を対象に計算する場合を意図しています。
28221 @c COMMON
28222 @end defun
28223
28224 @defun time-these how alist
28225 @defunx time-these/report how alist :key metric
28226 @c MOD gauche.time
28227 @c EN
28228 These procedures benchmarks multiple chunks of code to compare.
28229 @c JP
28230 複数のコード片をベンチマークして比較する手続きです。
28231 @c COMMON
28232
28233 @c EN
28234 The @var{alist} argument must be the form of
28235 @code{((key . thunk) @dots{})}, where @code{key} is a symbol
28236 and @var{thunk} is a procedure taking no arguments.
28237 @c JP
28238 @var{alist}は@code{((key . thunk) @dots{})}という形でなければなりません。
28239 ここで、@code{key}はシンボル、@var{thunk}は引数を取らない手続きです。
28240 @c COMMON
28241
28242 @c EN
28243 The @var{how} argument is the same as @code{time-this}; that is,
28244 either an integer for number of iterations, or a list
28245 @code{(cpu @var{x})} to indicate @var{x} seconds of cpu time.
28246 @c JP
28247 @var{how}引数は@code{time-this}と同じです。すなわち、
28248 実行の繰り返し回数を指定する整数か、
28249 使うCPU時間を@var{x}として@code{(cpu @var{x})}の形のリストか、です。
28250 @c COMMON
28251
28252 @c EN
28253 @code{time-these} runs benchmarks for each thunk in @var{alist}
28254 using @code{time-this}, and returns the result in a list of
28255 the form
28256 @code{(@var{how} (@var{key1} . @var{result1}) (@var{key2} . @var{result2}) @dots{})},
28257 where each @var{result} is a @code{<time-result>} object.
28258 @c JP
28259 @code{time-these}は@var{alist}中の@var{thunk}それぞれを走らせて計測し、
28260 結果を
28261 @code{(@var{how} (@var{key1} . @var{result1}) (@var{key2} . @var{result2}) @dots{})}
28262 の形で返します。ここで@var{result}は@code{<time-result>}オブジェクトです。
28263 @c COMMON
28264
28265 @c EN
28266 @code{time-these/report} outputs the benchmark results and
28267 comparison matrix in human readable way to the current output port.
28268 @c JP
28269 @code{time-these/report}はベンチマーク結果を、人間が読みやすい
28270 形式にして表示します。
28271 @c COMMON
28272
28273 @smallexample
28274 gosh> (time-these/report '(cpu 3.0)
28275 `((real1 . ,(cut expt 100 20))
28276 (real2 . ,(cut %expt 100 20))
28277 (imag . ,(cut expt +100i 20))))
28278 Benchmark: ran real1, real2, imag, each for at least 3.0 cpu seconds.
28279 real1: 3.312 real, 3.320 cpu (3.320 user + 0.000 sys)@@ 1694277.11/s n=5625000
28280 real2: 2.996 real, 3.010 cpu (3.010 user + 0.000 sys)@@35595634.55/s n=107142860
28281 imag: 3.213 real, 3.190 cpu (3.190 user + 0.000 sys)@@ 862068.97/s n=2750000
28282
28283 Rate real1 real2 imag
28284 real1 1694277/s -- 0.048 1.965
28285 real2 35595635/s 21.009 -- 41.291
28286 imag 862069/s 0.509 0.024 --
28287 @end smallexample
28288
28289 @c EN
28290 The first part of the report shows, for each thunks,
28291 the real (elapsed) time,
28292 the cpu time used (and its breakdown of user and system time),
28293 the rate of iteration per second, and the total number of iterations.
28294 @c JP
28295 レポートの最初の部分は、各thunkについて、
28296 実経過時間、CPU時間(およびその内訳としてのuser時間とsystem時間)、
28297 一秒あたりの繰り返し回数、そしてトータルの繰り返し回数です。
28298 @c COMMON
28299
28300 @c EN
28301 The second part compares the speed between each pair of the benchmarks.
28302 For example, its first row tells that the benchmark @code{real1} is
28303 0.048 times faster than @code{real2} and 1.965 times faster than
28304 @code{imag}.
28305 @c JP
28306 次の部分は、ベンチマーク間の比較です。
28307 例えば最初の行は、@code{real1}は@code{real2}の0.048倍、
28308 @code{imag}の1.965倍の速度で実行されたことを示しています。
28309 @c COMMON
28310
28311 @c EN
28312 The @var{metric} argument specifies which time metric should be used
28313 for rate calculation and comparison. It must be either @code{#f}
28314 or one of the symbols @code{cpu}, @code{user}, @code{sys}, or @code{real}.
28315 If it is @code{#f} (default), the same metric as @var{how} argument is used
28316 (if @var{how} is an integer count, @code{cpu} is assumed).
28317 @c JP
28318 @var{metric}引数は、速度計算および比較マトリクスにどの時間を使うかを指定します。
28319 渡す値は@code{#f}か、シンボル@code{cpu}、@code{real}、
28320 @code{user}、@code{sys}のいずれかでなければなりません。
28321 デフォルトは@code{#f}で、その場合は@var{how}に渡したメトリックが使われます
28322 (@var{how}が回数を指定する整数の場合は、@code{cpu}が使われます)。
28323 @c COMMON
28324 @end defun
28325
28326 @defun report-time-results result :optional metric
28327 @c MOD gauche.time
28328 @c EN
28329 This is a utility procedure to create a report from
28330 the result of @code{time-these}. Actually, @code{time-these/report}
28331 is just a combination of @code{time-these} and this procedure:
28332 @c JP
28333 これは@code{time-these}の結果を見やすいレポートとして表示する
28334 ユーティリティ手続きです。@code{time-these/report}は
28335 @code{time-these}とこの手続きを組み合わせているだけです。
28336 @c COMMON
28337
28338 @c EN
28339 The meaning of the optional @var{metric} argument is the same
28340 as the @var{metric} keyword argument of @code{time-these/report}.
28341 @c JP
28342 省略可能な@var{metric}引数の意味は、
28343 @code{time-these/report}の@var{metric}キーワード引数と同じです。
28344 @c COMMON
28345
28346 @example
28347 (define (time-these/report how samples :key metric)
28348 (report-time-results (time-these how samples) metric))
28349 @end example
28350 @end defun
28351
28352
28353 @c EN
28354 @subheading Finer measurement
28355 @c JP
28356 @subheading より細かい計測
28357 @c COMMON
28358
28359 @deftp {Class} <time-counter>
28360 @clindex time-counter
28361 @c MOD gauche.time
28362 @c EN
28363 An abstract class of time counters. Time counter is a kind of timer
28364 whose value is incremented as the time passes. The counting
28365 can be started and stopped any number of times.
28366 The value of the counter can be read
28367 when the timer is stopping.
28368 You can have multiple time counters. It is useful, for example,
28369 to measure the time in two parts inside a loop independently.
28370 @c JP
28371 時間カウンタの抽象クラスです。時間カウンタは
28372 時間の経過と共にその値が増加してゆく一種のタイマーです。
28373 何度でもカウントを止めたり開始したりできます。
28374 カウンタの値はカウントが止まっている時に読み出すことができます。
28375 複数の時間カウンタを使えば、
28376 例えばループ中の二つの部分について費される時間を別々に計測することもできます。
28377 @c COMMON
28378
28379 @c EN
28380 The concrete subclass determines which time it is counting.
28381 You have to instantiate one of those subclasses described below
28382 to use the time counter.
28383 @c JP
28384 具体的なサブクラスが、どの時間をカウントするかを決定します。
28385 時間カウンタを使うには、下に挙げるサブクラスのいずれかを
28386 インスタンシエイトしなければなりません。
28387 @c COMMON
28388 @end deftp
28389
28390 @deftp {Class} <real-time-counter>
28391 @deftpx {Class} <user-time-counter>
28392 @deftpx {Class} <system-time-counter>
28393 @deftpx {Class} <process-time-counter>
28394 @clindex real-time-counter
28395 @clindex user-time-counter
28396 @clindex system-time-counter
28397 @clindex process-time-counter
28398 @c MOD gauche.time
28399 @c EN
28400 Classes for time counters that count real (elapsed) time, user-space CPU time,
28401 kernel-space CPU time, and total CPU time (user + system), respectively.
28402 @c JP
28403 それぞれ、実経過時間、ユーザースペースCPU時間、カーネルスペースCPU時間、
28404 総CPU時間 (ユーザー+カーネル)を計測する時間カウンタのクラスです。
28405 @c COMMON
28406 @end deftp
28407
28408 @deffn {Method} time-counter-start! (counter <time-counter>)
28409 @deffnx {Method} time-counter-stop! (counter <time-counter>)
28410 @c MOD gauche.time
28411 @c EN
28412 Starts and stops the @var{counter}. The time during the counter is
28413 running is accumulated to the counter value when the counter is stopped.
28414 @c JP
28415 時間カウンタ@var{counter}を開始/停止します。カウンタが走っている間の時間が、
28416 カウンタが停止した時点でカウンタの値に加算されます。
28417 @c COMMON
28418
28419 @c EN
28420 Start/stop pairs can be nested,
28421 but only the outermost pair takes the effect. That is, if you call
28422 @code{time-counter-start!} on the counter that is already started,
28423 it doesn't have any effect except that to stop such a counter
28424 you have to call @code{time-counter-stop!} one more time. It is useful
28425 when you want to measure the time spent in the larger block that
28426 may already contain timer start/stop pairs.
28427 @c JP
28428 開始/停止の対はネストすることができます。その場合は、一番外側の対のみが
28429 有効です。
28430 つまり、既に走っているカウンタに対し@code{time-counter-start!}を呼んでも
28431 何も起こりませんが、一度余分に@code{time-counter-stop!}を呼ばないと
28432 カウンタは止まりません。
28433 これは、内部に既に開始/停止の対を含んでいるかもしれない大きなコードブロックの
28434 全体の時間を計測したいというような場合に便利です。
28435 @c COMMON
28436
28437 @c EN
28438 Calling @code{time-counter-stop!} on the already stopped counter
28439 has no effect.
28440 @c JP
28441 既に停止しているカウンタに対して@code{time-counter-stop!}を呼んでも
28442 何も起こりません。
28443 @c COMMON
28444 @end deffn
28445
28446 @deffn {Method} time-counter-reset! (counter <time-counter>)
28447 @c MOD gauche.time
28448 @c EN
28449 Resets the value of @var{counter}. If @var{counter} is already
28450 running, it is forced to stop before being reset.
28451 @c JP
28452 カウンタ@var{counter}の値をリセットします。既に@var{counter}が走っている
28453 場合は、リセットの前にカウンタは停止させられます。
28454 @c COMMON
28455 @end deffn
28456
28457 @deffn {Method} time-counter-value (counter <time-counter>)
28458 @c MOD gauche.time
28459 @c EN
28460 Returns the current value of the counter as the number of seconds,
28461 in a real number. The resolution depends on the source of the counter.
28462 @c JP
28463 カウンタ@var{counter}の現在の値(秒数)を実数で返します。
28464 分解能はそれぞれのカウンタが用いているシステムコールに依存します。
28465 @c COMMON
28466 @end deffn
28467
28468 @defmac with-time-counter counter expr @dots{}
28469 @c MOD gauche.time
28470 @c EN
28471 A convenience macro to run the @var{counter} while @var{expr} @dots{}
28472 are evaluated. Returns the result(s) of the last expression.
28473 It is defined as follows.
28474 @c JP
28475 式@var{expr} @dots{}が評価される間だけ@var{counter}を走らせる、
28476 便利なマクロです。最後の式の結果を返します。このマクロは次のように
28477 定義されます。
28478 @c COMMON
28479 @example
28480 (define-syntax with-time-counter
28481 (syntax-rules ()
28482 ((_ counter . exprs)
28483 (dynamic-wind
28484 (lambda () (time-counter-start! counter))
28485 (lambda () . exprs)
28486 (lambda () (time-counter-stop! counter))))
28487 ))
28488 @end example
28489 @end defmac
28490
28491 @c EN
28492 The following example measures approximate times
28493 spend in process-A and process-B inside a loop.
28494 @c JP
28495 下の例では、ループ内でのprocess-Aとprocess-Bにて費された
28496 概略の時間をそれぞれ計測します。
28497 @c COMMON
28498
28499 @example
28500 (let ((ta (make <real-time-counter>))
28501 (tb (make <real-time-counter>)))
28502 (dotimes (i 100000)
28503 (with-time-counter ta
28504 (process-A))
28505 (with-time-counter tb
28506 (process-B)))
28507 (format #t "Time spent in process-A: ~s\n" (time-counter-value ta))
28508 (format #t "Time spent in process-B: ~s\n" (time-counter-value tb))
28509 )
28510 @end example
28511
28512 @c ----------------------------------------------------------------------
28513 @node Unicode utilities, Uniform vector library, Measure timings, Library modules - Gauche extensions
28514 @section @code{gauche.unicode} - Unicode utilities
28515 @c NODE Unicodeユーティリティ, @code{gauche.unicode} - Unicodeユーティリティ
28516
28517 @deftp {Module} gauche.unicode
28518 @mdindex gauche.unicode
28519 @c EN
28520 This module provides various operations on a sequence of Unicode codepoints.
28521
28522 Gauche used to support a native encoding other than Unicode,
28523 and the full Unicode-compatible behavior on characters and strings may
28524 not have been available on such systems. So we provide most operations in two
28525 flavors: Operations on characters and strings, or operations on
28526 codepoints represented as a sequence of integers.
28527 @c JP
28528 このモジュールは、Unicodeのコードポイントの列に対する様々な操作を提供します。
28529
28530 Gaucheは以前、内部文字エンコーディングとしてUnicode以外も選べるようになっていました。
28531 その場合、文字列に対して完全にUnicode互換の動作を提供できない場合があったため、
28532 そこで、本モジュールの多くの操作は、文字列を対象にするものと、
28533 コードポイントの数値のシーケンスを対象にするものの両方で提供されます。
28534 @c COMMON
28535 @end deftp
28536
28537 @menu
28538 * Unicode transfer encodings::
28539 * Unicode text segmentation::
28540 * Full string case conversion::
28541 * East asian width property::
28542 @end menu
28543
28544 @node Unicode transfer encodings, Unicode text segmentation, Unicode utilities, Unicode utilities
28545 @subsection Unicode transfer encodings
28546
28547 @c EN
28548 The procedures in this group operate on codepoints represented as integers.
28549 In the following descriptions, an octet refers to an integer
28550 between 0 to 255, inclusive.
28551 @c JP
28552 このグループの手続きは、整数で表現されたコードポイントを扱います。
28553 以下の説明で「オクテット」は0から255までの整数です。
28554 @c COMMON
28555
28556 @c EN
28557 They take optional @var{strictness} argument. It specifies
28558 what to do when the procedure encounters a datum outside
28559 of the defined domain. Its value can be either one of the
28560 following symbols:
28561 @c JP
28562 これらの手続きは省略可能な@var{strictness}引数を取ります。
28563 この引数は、定義域外の入力が来たときの振る舞いを指定します。
28564 指定できる値は次のいずれかです。
28565 @c COMMON
28566
28567 @table @code
28568 @item strict
28569 @c EN
28570 Raises an error when the procedure encounters such input.
28571 This is the default behavior.
28572 @c JP
28573 定義域外の入力が来たらエラーを投げます。これがデフォルトの振る舞いです。
28574 @c COMMON
28575 @item permissive
28576 @c EN
28577 Whenever possible, treat the date as if it is a valid value.
28578 For example, codepoint value beyond @code{#x10ffff} is invalid
28579 in Unicode standard, but it may be useful for some other purpose
28580 that just want to use UTF-8 as an encoding scheme of binary data.
28581 @c JP
28582 可能な限り、入力を有効な値であるかのように扱います。
28583 例えば@code{#x10ffff}を越えるコードポイント値はUnicode標準では不正な値ですが、
28584 utf-8の規則を拡張することでエンコード可能であり、文字列以外のバイナリデータを単にutf-8風に
28585 エンコードしたいだけの場合などには便利かもしれません。
28586 @c COMMON
28587 @item replace
28588 @c EN
28589 If the procedure sees invalid input, replaces it with a unicode
28590 replacement character @code{U+FFFD} and proceed.
28591 @c JP
28592 不正な入力を見たら、それをユニコード置換文字@code{U+FFFD}に置き換え処理を続行します。
28593 @c COMMON
28594 @item ignore
28595 @c EN
28596 Whenver possible, treat the invalid input as if they do not exist.
28597 @c JP
28598 可能であれば、不正な入力は無視します。
28599 @c COMMON
28600 @end table
28601
28602 @c EN
28603 The procedure may still raise an error in @code{permissive}, @code{replace} or
28604 @code{ignore} strictness mode, if there can't be a sensible
28605 way to handle the input data.
28606 @c JP
28607 @var{strictness}が@code{permissive}や@code{replace}や@code{ignore}であっても、
28608 入力データの妥当な解釈ができない場合はエラーが投げられる可能性があります。
28609 @c COMMON
28610
28611 @defun ucs4->utf8 codepoint :optional strictness
28612 @c MOD gauche.unicode
28613 @c EN
28614 Takes an integer codepoint and returns a list of octets that
28615 encodes the input in UTF-8.
28616 @c JP
28617 整数のコードポイント値を受け取り、utf-8でエンコードされたオクテットのリストを返します。
28618 @c COMMON
28619
28620 @example
28621 (ucs4->utf8 #x3bb) @result{} (206 187)
28622 (ucs4->utf8 #x3042) @result{} (227 129 130)
28623 @end example
28624
28625 @c EN
28626 If @var{strictness} is @code{strict} (default), input codepoint
28627 between @code{#xd800} to @code{#xdfff}, and beyond @code{#x110000},
28628 are rejected. If @var{strictness} is @code{replace}, such input
28629 yields a utf8 sequence @code{#xef, #xbf, #xbd}, which encodes
28630 @code{U+FFFD}.
28631 If @var{strictness} is @code{permissive}, it accepts
28632 input between @code{0} and @code{#x7fffffff}, inclusive; it may produce
28633 5 or 6 octets if the input is large (as the original UTF-8 definition).
28634 If @var{strictness} is @code{ignore}, it returns an empty list
28635 for invalid codepoints.
28636 @c JP
28637 @var{strictness}が@code{strict}の場合(デフォルト)、
28638 入力が@code{#xd800}と@code{#xdfff}の間か、@code{#x110000}以上の場合は
28639 エラーを投げます。
28640 @var{strictness}が@code{replace}であれば、そのような入力に対しては
28641 utf8シーケンス@code{#xef, #xbf, #xbd} (@code{U+FFFD}) がせ生成されます。
28642 @var{strictness}が@code{permissive}の場合は、
28643 @code{0}から@code{#x7fffffff}までの入力が許されます。
28644 入力が大きい場合はエンコードされた出力は5〜6オクテットになるでしょう
28645 (初期のutf-8の定義通り)。
28646 @var{strictness}が@code{ignore}の場合は、
28647 Unicodeとして不正なコードポイントに対しては空リストが返されます。
28648 @c COMMON
28649 @end defun
28650
28651 @defun utf8-length octet :optional strictness
28652 @c MOD gauche.unicode
28653 @c EN
28654 Takes @var{octet} as the first octet of UTF-8 sequence, and
28655 returns the number of total octets required to decode
28656 the codepoint.
28657 @c JP
28658 @var{octet}をutf-8シーケンスの最初のオクテットとみなし、
28659 そこからひとつのコードポイントをデコードするのに全部で何オクテット必要かを返します。
28660 @c COMMON
28661
28662 @c EN
28663 If @var{octet} is not an exact integer between 0 and 255 (inclusive),
28664 an error is thrown, regardless of @var{strictness} argument.
28665 @c JP
28666 @var{octet}引数が0から255の間の正確な整数でなければ、
28667 @var{strictness}引数の値にかかわらず、エラーが投げられます。
28668 @c COMMON
28669
28670 @c EN
28671 If @var{strictness} is @code{strict} (default), this
28672 procedure returns either 1, 2, 3 or 4. An error is
28673 thrown if @var{octet} cannot be a leading octet of
28674 a proper UTF-8 encoded Unicode codepoint.
28675 @c JP
28676 @var{strictness}が@code{strict}の場合(デフォルト)、
28677 戻り値は1,2,3,4のいずれかです。@var{octet}がutf-8でエンコードされた
28678 Unicodeコードポイントの最初のオクテットとしてありえない値であれば
28679 エラーが投げられます。
28680 @c COMMON
28681
28682 @c EN
28683 If @var{strictness} is @code{permissive} or @code{replace}, this procedure
28684 may return an integer between 0 and 6, inclusive.
28685 If the input is from @code{#xf8} to @code{#xfd}, inclusive,
28686 this returns 5 or 6, according to the original utf-8 spec
28687 (these values corresponds to the codepoint
28688 range @code{#x110000} to
28689 @code{#x7fffffff}).
28690 If the input is in the range between @code{#x80}
28691 and @code{#xbf}, inclusive, or @var{#xfe} or @code{#xff},
28692 this procedure returns 1--it's up to the application how to treat these illegal
28693 octets.
28694 @c JP
28695 @var{strictness}が@code{permissive}か@code{replace}の場合、
28696 この手続きは0から6までの整数を返します。
28697 入力が@code{#xf8}から@code{#xfd}の間の値(両端含む)の場合は
28698 元々のutf-8仕様に基づいて5か6を返します
28699 (これらのオクテットはコードポイントが@code{#x110000}から
28700 @code{#x7fffffff}になるような値に相当します)。
28701 引数が@code{#x80}から@code{#xbf}までの値、および@code{#xfe}と@code{#xff}の場合は、
28702 utf-8の先頭バイトになり得ませんが、アプリケーションがこの不正なバイトだけを
28703 適切に処理することを前提にして、1が返されます。
28704 @c COMMON
28705
28706 @c EN
28707 If @var{strictness} is @code{ignore}, this procedure
28708 returns @code{0} when it would raise an error if
28709 @var{strictness} is @code{strict}. Other than that,
28710 it works the same as the default case.
28711 @c JP
28712 @var{strictness}が@code{ignore}の場合、この手続きは
28713 @code{strict}でエラーが投げられる入力値について@code{0}を返します。
28714 それ以外は@code{strict}の動作と同じです。
28715 @c COMMON
28716 @end defun
28717
28718 @defun utf8->ucs4 octet-list :optional strictness
28719 @c MOD gauche.unicode
28720 @c EN
28721 Takes a list of octets, and decodes it as a utf-8 sequence.
28722 Returns two values: The decoded ucs4 codepoint, and the
28723 rest of the input list.
28724 @c JP
28725 オクテットのリストを取り、それをutf-8のシーケンスとして解釈して、
28726 デコードされたコードポイント及び残りのリストの2つの値を返します。
28727 @c COMMON
28728
28729 @c EN
28730 If it finds a value other than exact integer
28731 between 0 and 255 in the input list, an error is thrown
28732 regardless of the value of @var{strictness}.
28733 @c JP
28734 もし処理中に、0から255の間の正確な整数以外の値が入力に見つかったら、
28735 @var{strictness}の設定に関わらずエラーが投げられます。
28736 @c COMMON
28737
28738 @c EN
28739 An invalid utf8 sequence causes an error if @var{strictness}
28740 is @code{strict}, or skipped if it is @code{ignore}.
28741 If @var{strictness} is @code{replace}, such utf8 sequence
28742 yields @code{U+FFFD}.
28743 If @var{strictness} is @code{permissive}, the procedure accepts
28744 the original utf-8 sequence which can produce surrogated pair
28745 range (between @code{#xd800} and @code{#dfff}) and the range
28746 between @code{#x110000} to @code{#x7fffffff}. The invalid
28747 octet sequence is still an error with @code{permissive} mode.
28748 @c JP
28749 それ以外の不正なutf-8シーケンスは、@var{strictness}が@code{strict}であれば
28750 エラーに、@code{ignore}であればスキップされます。
28751 @var{strictness}が@code{replace}の場合は、そういったutf8シーケンスは
28752 @code{U+FFFD}を生成します。
28753 @var{strictness}が@code{permissive}の場合は、
28754 最初のutf-8仕様で許されていた全てのコードポイント、すなわち
28755 サロゲートペア領域(@code{#xd800}から@code{#dfff}まで)及び
28756 @code{#x110000}以上@code{#x7fffffff}以下のコードポイントも認識されます。
28757 それ以外の不正なコードポイントは@code{permissive}であってもエラーになります。
28758 @c COMMON
28759 @end defun
28760
28761 @defun utf8->string u8vector :optional start end
28762 [R7RS base]
28763 @c MOD gauche.unicode
28764 @c EN
28765 Converts a sequence of utf8 octets in @var{u8vector} to a string.
28766 Optional @var{start} and/or @var{end} argument(s) will limit the
28767 range of the input.
28768 @c JP
28769 @var{u8vector}の、インデックス@var{start}(含む)から@var{end}(含まない)までに
28770 格納された値をutf-8オクテット列と見なし、文字列に変換して返します。
28771 @var{start}、@var{end}が省略された場合はそれぞれベクタの最初と最後が指定されたものと
28772 解釈します。
28773 @c COMMON
28774
28775 @c EN
28776 If Gauche's native encoding is utf8, this procedure first tries
28777 @code{u8vector->string} (@pxref{Uniform vectors}).
28778 If the input utf8 sequence is valid, this is the fastest way.
28779 If the input contains invalid utf8 sequence, the procedure falls
28780 back to construct a string by one character at at time,
28781 replacing invalid sequence with Unicode replacement character @code{U+FFFD}.
28782 Hence it always returns a complete string.
28783 To know if the input contains invalid utf8 sequence, you can use
28784 @code{u8vector->string} directly.
28785 @c JP
28786 Gaucheのネイティブエンコーディングがutf8の場合、
28787 この手続きはまず@code{u8vector->string}を試します
28788 (@ref{Uniform vectors}参照)。
28789 もし入力がutf8シーケンスとして有効であれば、それが最も速いです。
28790 しかし、入力に無効なutf8シーケンスが含まれていた場合、
28791 この手続きは1文字づつ文字列を構築するモードにフォールバックし、
28792 無効なutf8シーケンスの部分はUnicode置換文字@code{U+FFFD}に置き換えられます。
28793 従って戻り値は常に完全な文字列です。
28794 入力に不正なuft8シーケンスが含まれていたかどうかを知りたい場合は
28795 @code{u8vector->string}を直接呼んでください。
28796 @c COMMON
28797
28798 @c EN
28799 If Gauche's native encoding is other than utf8,
28800 there's no @code{U+FFFD} so invalid utf8 sequence throws an error.
28801 @c JP
28802 Gaucheのネイティブエンコーディングがutf8以外の場合、
28803 @code{U+FFFD}に相当するコードがないので、無効なutf8シーケンスに出会うと
28804 エラーが投げられます。
28805 @c COMMON
28806 @end defun
28807
28808 @defun string->utf8 string :optional start end
28809 [R7RS base]
28810 @c MOD gauche.unicode
28811 @c EN
28812 Converts a string to a u8vector of utf8 octets.
28813 Optional @var{start} and/or @var{end} argument(s) will limit the
28814 range of the input.
28815 @c JP
28816 文字列をutf8オクテットの並びにエンコードしてu8vectorとして返します。
28817 省略可能な@var{start}と@var{end}引数は対象とする文字列の範囲を指定します。
28818 @c COMMON
28819
28820 @c EN
28821 If Gauche's native encoding is utf8, this procedure
28822 just calls @code{string->u8vector} (@pxref{Uniform vectors}).
28823 Otherwise, it first converts the input string to utf-8, then
28824 @code{string->u8vector} is called.
28825 @c JP
28826 Gaucheのネイティブエンコーディングがutf8であれば、この手続きは
28827 単に@code{string->u8vector}を呼び出すだけです。
28828 (@ref{Uniform vectors}参照)。
28829 そうでなければまず入力文字列がutf8に変換されてから
28830 @code{string->u8vector}が呼ばれます。
28831 @c COMMON
28832 @end defun
28833
28834 @defun ucs4->utf16 codepoint :optional strictness
28835 @c MOD gauche.unicode
28836 @c EN
28837 Takes an integer codepoint and returns a list of integers
28838 that encodes the input in UTF-16.
28839 @c JP
28840 整数で与えられたコードポイントをutf-16にエンコードして整数のリストとして返します。
28841 @c COMMON
28842
28843 @c EN
28844 If @var{strictness} is @code{strict} (default),
28845 the input must be either
28846 between @code{0} and @code{#xd7ff} or between @code{#xe000} and
28847 @code{#x10ffff}. An error is thrown otherwise. The 'hole' is the
28848 codepoint reserved for surrogates, and there's no valid
28849 mapping from them to utf-16 is defined.
28850 @c JP
28851 @var{strictness}が@code{strict}の場合(デフォルト)、
28852 入力値は@code{0}から@code{#xd7ff}までの間か、
28853 @code{#xe000}から@code{#x10ffff}までの間でなければなりません。
28854 それ以外の場合はエラーが投げられます。
28855 開いている部分はサロゲートに予約されているコードで、
28856 この領域をutf-16にエンコードする方法は定義されていません。
28857 @c COMMON
28858
28859 @c EN
28860 If @var{strictness} is @code{replace}, such input is replaced
28861 with @code{#xfffd}, which encodes Unicode replacement character.
28862 @c JP
28863 @var{strictness}が@code{replace}であれば、そのような入力は
28864 @code{#xfffd}(Unicode置換文字)に置き換えられます。
28865 @c COMMON
28866
28867 @c EN
28868 If @var{strictness} is @code{permissive}, it accepts
28869 high surrogates and low surrogates, in which case the result is
28870 single element list of input. An error is still thrown for
28871 negative input and input greater than or equal to @code{#x110000}.
28872 @c JP
28873 @var{strictness}が@code{permissive}の場合、サロゲート領域の入力は
28874 エラーにならず、その値を唯一の要素とするリストが返されます。
28875 負の値および@code{#x110000}の値についてはやはりエラーになります。
28876 @c COMMON
28877
28878 @c EN
28879 If @var{strictness} is @code{ignore},
28880 an empty list is returned for an invalid codepoint (including surrogates).
28881 @c JP
28882 @var{strictness}が@code{ignore}の場合は、不正なコードポイント(サロゲート領域含む)
28883 については空リストが返されます。
28884 @c COMMON
28885
28886 @c EN
28887 Note: We can encode values larger than @code{#x10ffff} in utf-8
28888 in the permissive mode, but not in utf-16.
28889 @c JP
28890 註: permissiveモードでは@code{#x10ffff}より大きな値をutf-8にはエンコードできますが、
28891 utf-16にはエンコードできません。
28892 @c COMMON
28893 @end defun
28894
28895 @defun utf16-length code :optional strictness
28896 @c MOD gauche.unicode
28897 @c EN
28898 @var{Code} must be an exact integer between 0 and 65535, inclusive.
28899 Returns 1 if @var{code} is BMP character codepoint, or
28900 2 if @var{code} is a high surrogate.
28901 @c JP
28902 @var{code}は0から65535までの正確な整数でなければなりません。
28903 @code{code}がBMPのコードポイントなら1を、utf-16の上位サロゲートであれば2を返します。
28904 @c COMMON
28905
28906 @c EN
28907 If @var{strictness} is @code{strict} (default), an error is
28908 signalled if @var{code} is a low surrogate, or it is out of range.
28909 If @var{strictness} is @code{permissive} or @code{replace}, 1 is returned
28910 for low surrogates, but an error is signalled for out of range arguments.
28911 If @var{strictness} is @code{ignore}, 0 is returned
28912 for low surrogates and out of range arguments.
28913 @c JP
28914 @var{strictness}が@code{strict}の場合(デフォルト)、@var{code}が
28915 下位サロゲートであったり、定義外の値であればエラーが投げられます。
28916 @var{strictness}が@code{permissive}や@code{replace}の場合は、
28917 やはり定義外の値であればエラーが投げられますが、
28918 下位サロゲートの場合には1が返されます。
28919 @var{strictness}が@code{ignore}の場合、
28920 定義域外および下位サロゲートに対しては0が返されます。
28921 @c COMMON
28922 @end defun
28923
28924 @defun utf16->ucs4 code-list :optional strictness
28925 @c MOD gauche.unicode
28926 @c EN
28927 Takes a list of exact integers and decodes it as a utf-16 sequence.
28928 Returns two values: The decoded ucs4 codepoint, and the rest of
28929 input list.
28930 @c JP
28931 正確な整数のリストを取り、それをutf-16の並びとして解釈します。
28932 デコードされたucs4コードポイントおよび、残りのリストの二つの値を返します。
28933 @c COMMON
28934
28935 @c EN
28936 If @var{strictness} is @code{strict} (default), an invalid utf-16
28937 sequence and out-of-range integer raise an error. If @var{strictness}
28938 is @code{permissive}, an out-of-range integer causes an error, but
28939 a lone surrogate is allowed and returned as is.
28940 If @var{strictness} is @code{replace}, a lone surrogate is
28941 replaced with @code{U+FFFD}.
28942 If @var{strictness}
28943 is @code{ignore}, lone surrogates and out-of-range integers are just
28944 ignored.
28945 @c JP
28946 @var{strictness}が@code{strict}の場合(デフォルト)、不正なutf-16の並びや
28947 定義域外の値に出会ったらエラーが投げられます。
28948 @var{strictness}が@code{permissive}の場合は、
28949 やはり定義外の値であればエラーが投げられますが、
28950 片方だけのサロゲートの場合にはそれがそのまま(コードポイントとして)返されます。
28951 @var{strictness}が@code{replace}の場合は、
28952 片方だけのサロゲートは@code{U+FFFD}に置換されます。
28953 @var{strictness}が@code{ignore}の場合、
28954 定義域外および片方だけのサロゲートは無視されます。
28955 @c COMMON
28956 @end defun
28957
28958
28959 @defun utf16->string u8vector :optional endian ignore-bom? start end
28960 @defunx utf32->string u8vector :optional endian ignore-bom? start end
28961 @c MOD guache.unicode
28962 [R7RS scheme.bytevector]
28963 @c EN
28964 Convert utf16 and utf32 sequence stored in @var{u8vector} to a string,
28965 respectively.
28966 For @code{utf16->string},
28967 if the input contains invlaid utf16 sequence (unpaired surrogate),
28968 it is replaced with Unicode replacement character @code{U+FFFD}.
28969 If the number of input octet is not the multiple of unit (2 octets
28970 for utf16, and 4 octets for utf32), an error is thrown.
28971 @c JP
28972 @var{u8vector}に格納されたutf16およびutf32シーケンスを文字列に変換します。
28973 @code{utf16->string}は、
28974 もし入力に不正なutf16シーケンス (ペアになっていないサロゲート) があった場合は、
28975 それがUnicode置換文字(@code{U+FFFD})に置き換えます。
28976 入力のオクテット数がエンコーディング単位(utf16なら2オクテット、utf32なら4オクテット)
28977 の倍数でない場合はエラーが投げられます。
28978 @c COMMON
28979
28980 @c EN
28981 The optional @var{endian} and @var{ignore-bom?} arguments
28982 determines whether the input is in UTF16BE/UTF32BE or UTF16LE/UTF32LE.
28983 If @var{ignore-bom?} is @code{#f} or omitted, the first two octets
28984 of input is examined; if it's BOM, it deterimines the endianness
28985 regardless of @var{endian} argument,
28986 and the BOM won't be included in the output.
28987 If the input does not begin with BOM, or @var{ignore-bom?} is true,
28988 then the endianness is determined by @var{endian} argument: It can be
28989 @code{big-endian} or @code{big} for UTF16BE/UTF32BE, and
28990 @code{little-endian} or @code{little} or @code{arm-big-endian}
28991 for UTF16LE/UTF32LE (@pxref{Endianness}, for the details of endianness).
28992
28993 Note that if @var{ignore-bom?} is given and true,
28994 the initial BOM is interpreted as a codepoint @code{U+FEFF}.
28995 If @var{endian} is @code{#f} or omitted, UTF16BE/UTF32BE
28996 is assumed (it is defined so in R7RS @code{scheme.bytevector}).
28997
28998 In R7RS @code{scheme.bytevector}, @var{ignore-bom?} argument
28999 is called @var{endianness-mandatory}. The behavior is the same.
29000 @c JP
29001 省略可能な@var{endian}と@var{ignore-bom?}引数は入力がUTF16BE/UTF32BEか
29002 UTF16LE/UTF32LEかを
29003 決めます。@var{ignore-bom?}が@code{#f}または省略された場合、まず入力の
29004 最初の2オクテットが調べられ、BOMであれば@var{endian}の値にかかわらず
29005 それがバイトオーダーを決定します。
29006 入力がBOMで始まっていないか、@var{ignore-bom?}が真の値であれば、
29007 @var{endian}引数がバイトオーダーを決定します。それが
29008 @code{big-endian}か@code{big}であればUTF16BE/UTF32BE、
29009 @code{little-endian}か@code{little}か@code{arm-little-endian}であれば
29010 UTF16LE/UTF32LEとなります (エンディアンについては@ref{Endianness}参照)。
29011
29012 @var{ignore-bom?}が与えられて真の値であった場合、
29013 入力の先頭のBOMはコードポイントとみなされます。
29014 @var{endian}が@code{#f}または省略された場合は、
29015 UTF16BE/UTF32BEとみなされます
29016 (これはR7RS @code{scheme.bytevector}で定義された仕様です)。
29017
29018 なおR7RS @code{scheme.bytevector}では@var{ignore-bom?}引数は
29019 @var{endianness-mandatory}と呼ばれています。動作は同じです。
29020 @c COMMON
29021
29022 @c EN
29023 Optinoal argument @var{start} and @var{end} trims the input octet sequence
29024 before other processing (including BOM detection). These arguments are
29025 Gauche's extension, and not the part of R7RS @code{scheme.bytevector}.
29026 @c JP
29027 省略可能な@var{start}と@var{end}引数は処理に先立って入力のオクテットシーケンスの
29028 範囲を制限します(BOM検出も範囲制限後に行われます)。
29029 この2つの引数はGauche独自拡張で、R7RS @code{scheme.bytevector}では定義されていません。
29030 @c COMMON
29031 @end defun
29032
29033 @defun string->utf16 str :optional endian add-bom? start end
29034 @defunx string->utf32 str :optional endian add-bom? start end
29035 @c MOD gauche.unicode
29036 [R7RS scheme.bytevector]
29037 @c EN
29038 Encode a string @var{str} to utf-16 and utf-32 sequences stored in a u8vector,
29039 respectively.
29040
29041 The optional @var{endian} argument specifies whether the encoding
29042 is UTF16BE/UTF32BE or UTF16LE/UTF32LE. If it is a symobl @code{big-endian} or
29043 @code{big}, the encoding is UTF16BE/UTF32BE. If it is a symbol
29044 @code{little-endian}, @code{little} or @code{arm-little-endian},
29045 the encoding is UTF16LE/UTF32LE.
29046 @xref{Endianness}, for the details of endianness.
29047 If it is omitted or @code{#f}, UTF16BE/UTF32BE is assumed.
29048
29049 The second optional argument @var{add-bom?} specifies, if true value is
29050 given, the output contains BOM. When omitted BOM won't be added.
29051
29052 The @var{start} and @var{end} arguments limits the range of @var{str}
29053 to be converted.
29054
29055 R7RS @code{scheme.bytevector} only defines @var{endian} optional
29056 argument. The rest is Gauche's extension.
29057 @c JP
29058 文字列@var{str}をutf-16またはutf-32にエンコードしたオクテット列をu8vectorで返します。
29059
29060 省略可能な@var{endian}引数は、エンコーディングがUTF16BE/UTF32BEかUTF16LE/UTF32LEかを決めます。
29061 シンボル@code{big-endian}か@code{big}が渡されたらUTF16BE/UTF32BE、
29062 シンボル@code{little-endian}か@code{little}か@code{arm-little-endian}が
29063 渡されたらUTF16LE/UTF32LEになります。省略されるか@code{#f}ならUTF16BE/UTF32BEになります。
29064 バイトオーダーについての詳細は@ref{Endianness}を参照してください。
29065
29066 二つめの省略可能引数@var{add-bom?}にもし真の値が与えられたら、
29067 出力の先頭にBOMが含められます。省略されるか@code{#f}であればBOMは付加されません。
29068
29069 続く省略可能引数@var{start}と@var{end}は入力文字列@var{str}の特定の範囲だけを
29070 対象とするのに使います。
29071
29072 R7RSの@code{scheme.bytevector}では@var{endian}引数だけを認めています。
29073 残りはGaucheの拡張です。
29074 @c COMMON
29075 @end defun
29076
29077
29078
29079 @node Unicode text segmentation, Full string case conversion, Unicode transfer encodings, Unicode utilities
29080 @subsection Unicode text segmentation
29081
29082 These procedures implements grapheme-cluster and
29083 word breaking algorithms defined in UAX #29: Unicode Text Segmentation.
29084
29085 @defun string->words string
29086 @defunx codepoints->words sequence
29087 @c MOD gauche.unicode
29088 @c EN
29089 From given string or codepoint sequence (a @code{<sequence>}
29090 object containing codepoints), returns a list of
29091 words. Each word is represented as a string, or
29092 a sequence of the same type as input, respectively.
29093 @c JP
29094 与えられた文字列あるいはコードポイントシーケンス(コードポイントを要素とする
29095 @code{<sequence>}オブジェクト)から、単語のリストを返します。
29096 各単語はそれぞれ、文字列あるいはコードポイントシーケンスで表現されます。
29097 @c COMMON
29098
29099 @example
29100 (string->words "That's it.")
29101 @result{} ("That's" " " "it" ".")
29102 (codepoints->words '(84 104 97 116 39 115 32 105 116 46)
29103 @result{} ((84 104 97 116 39 115) (32) (105 116) (46))
29104 (codepoints->words '#(84 104 97 116 39 115 32 105 116 46)
29105 @result{} (#(84 104 97 116 39 115) #(32) #(105 116) #(46))
29106 @end example
29107
29108 @c EN
29109 In the second and third example, the input is a sequence of codepoints
29110 of characters in "That's it."
29111 @c JP
29112 二番めと三番目の例の入力は "That's it." をコードポイント列にしたものです。
29113 @c COMMON
29114 @end defun
29115
29116
29117 @defun string->grapheme-clusters string
29118 @defunx codepoints->grapheme-clusters sequence
29119 @c MOD gauche.unicode
29120 @c EN
29121 From given string or codepoint sequence (a @code{<sequence>}
29122 object containing codepoints), returns a list of
29123 grapheme clusters. Each cluster is represented as a string,
29124 or a sequence of the same type as input, respectively.
29125 @c JP
29126 与えられた文字列あるいはコードポイントシーケンス(コードポイントを要素とする
29127 @code{<sequence>}オブジェクト)から、graphemeクラスタのリストを返します。
29128 各クラスタはそれぞれ、文字列あるいはコードポイントシーケンスで表現されます。
29129 @c COMMON
29130 @end defun
29131
29132 @c EN
29133 The following procedures are low-level building blocks
29134 to build the above @code{string->words} etc.
29135 @c JP
29136 以下の手続きは上記の@code{string->words}等の高レベル手続きを作る部品となる、
29137 低レベル手続きです。
29138 @c COMMON
29139
29140 @defun make-word-breaker generator
29141 @defunx make-grapheme-cluster-breaker generator
29142 @c MOD gauche.unicode
29143 @c EN
29144 From given @var{generator}, which is a generator of characters or codepoints,
29145 returns a generator that returns two values: The first value is the
29146 character or codepoint generated from the original generator, and the
29147 second value is a boolean flag, which is @code{#t} if a word
29148 or a grapheme cluster
29149 breaks before the character/codepoint, and @code{#f} otherwise.
29150 @c JP
29151 文字かコードポイントを生成するジェネレータ@var{generator}を取り、
29152 二つの値を返すジェネレータを返します。最初の値は元のジェネレータから受け取った
29153 文字またはコードポイントで、二つめの値は、その文字またはコードポイントの直前に
29154 単語もしくはgraphemeクラスタ境界があった時に@code{#t}、そうでない時に@code{#f}となる
29155 真偽値です。
29156 @c COMMON
29157
29158 @c EN
29159 Suppose a generator @var{g} returns characters in a string
29160 @code{That's it.}, one at a time. Then the created generator
29161 will work as follows:
29162 @c JP
29163 ジェネレータ@code{g}が文字列@code{That's it.}に含まれる文字を順に返す
29164 ジェネレータとすれば、作られるジェネレータの動作は次の通りです。
29165 @c COMMON
29166
29167 @example
29168 (define brk (make-word-breaker g))
29169 (brk) @result{} #\T and #t
29170 (brk) @result{} #\h and #f
29171 (brk) @result{} #\a and #f
29172 (brk) @result{} #\t and #f
29173 (brk) @result{} #\' and #f
29174 (brk) @result{} #\s and #f
29175 (brk) @result{} #\space and #t
29176 (brk) @result{} #\i and #t
29177 (brk) @result{} #\t and #f
29178 (brk) @result{} #\. and #t
29179 (brk) @result{} #<eof> and #t
29180 @end example
29181
29182 @c EN
29183 It shows the word breaks at those character boundaries shown
29184 by the caret @code{^} below (for clearity, I use @code{_} to indicate
29185 the space).
29186 @c JP
29187 つまり、下図で@code{^}で示される箇所が単語境界となっています
29188 (空白字を@code{_}で表しています)。
29189 @c COMMON
29190
29191 @example
29192 T h a t ' s _ i t .
29193 ^ ^ ^ ^ ^
29194 @end example
29195 @end defun
29196
29197 @defun make-word-reader generator return
29198 @defunx make-grapheme-cluster-reader generator return
29199 @c MOD gauche.unicode
29200 @c EN
29201 The input @var{generator} is a generator of characters or codepoints,
29202 and @var{return} is a procedure that takes a list of characters or
29203 codepoints, and returns an object. These procedures creates a
29204 generator that returns an object at at time, each consists of a
29205 word or a grapheme cluster, respectively.
29206 @c JP
29207 @var{generator}は文字またはコードポイントを生成するジェネレータで、
29208 @var{return}は文字またはコードポイントのリストを受け取り、オブジェクトを返す手続きです。
29209 これらの手続きは、オブジェクト (単語またはgraphemeクラスタ) をひとつづつ生成する
29210 ジェネレータを返します。
29211 @c COMMON
29212
29213 @c EN
29214 Suppose a generator @var{g} returns characters in a string
29215 @code{That's it.}, one at a time, again.
29216 Then the created generator works as follows:
29217 @c JP
29218 ジェネレータ@code{g}が文字列@code{That's it.}に含まれる文字を順に返す
29219 ジェネレータとすれば、作られるジェネレータの動作は次の通りです。
29220 @c COMMON
29221
29222 @example
29223 (define brk (make-word-reader g list->string))
29224 (brk) @result{} "That's"
29225 (brk) @result{} " "
29226 (brk) @result{} "it"
29227 (brk) @result{} "."
29228 (brk) @result{} #<eof>
29229 @end example
29230
29231 @end defun
29232
29233
29234 @node Full string case conversion, East asian width property, Unicode text segmentation, Unicode utilities
29235 @subsection Full string case conversion
29236 @c NODE フルセットの大文字小文字変換
29237
29238 @defun string-upcase string
29239 @defunx string-downcase string
29240 @defunx string-titlecase string
29241 @defunx string-foldcase string
29242 [R6RS][R7RS char][SRFI-129]
29243 @c MOD gauche.unicode
29244 @c EN
29245 Converts the case of given @var{string}
29246 using language-independent full case folding defined by Unicode standard.
29247 They differ from SRFI-13's procedures
29248 with the same names (@pxref{SRFI-13 String case mapping}),
29249 which simply uses character-by-character case mapping.
29250 Notably, the length of resulting string may differ from the source string,
29251 and some conversions are sensitive to whether the character is at the
29252 word boundary or not. The word boundaries are determined according
29253 to UAX #29 text segmentation rules.
29254 @c JP
29255 与えられた文字列@var{string}の大文字小文字を、Unicodeで定義された
29256 言語独立のcase folding規則に基づいて変換します。
29257 SRFI-13にも同名の手続きがありますが、そちらは文字ごとに変換する点で
29258 これらの手続きと異なります(@ref{SRFI-13 String case mapping}参照)。
29259 特に、こちらの手続きは元の文字列と変換後の文字列の長さが異なる場合があり、
29260 また文字が単語境界にあるかどうかで変換が変わることもあります。
29261 単語境界はUAX #29の規則に基づいて判断されます。
29262 @c COMMON
29263
29264 @example
29265 (string-upcase "straße")
29266 @result{} "STRASSE"
29267 (string-downcase "ΧΑΟΣΧΑΟΣ.ΧΑΟΣ. Σ.")
29268 @result{} "χαοσχαοσ.χαος. σ."
29269 (string-titlecase "You're talking about R6RS, right?")
29270 @result{} "You're Talking About R6rs, Right?"
29271 (string-foldcase "straße")
29272 @result{} "strasse"
29273 (string-foldcase "ΧΑΟΣΣ")
29274 @result{} "χαοσσ"
29275 @end example
29276
29277 @c EN
29278 Procedures @code{string-upcase}, @code{string-downcase},
29279 and @code{string-foldcase} are also in R7RS @code{scheme.char} module.
29280 @c JP
29281 @code{string-upcase}、@code{string-downcase}、@code{string-foldcase}は
29282 R7RSの@code{scheme.char}モジュールでも提供されます。
29283 @c COMMON
29284
29285 @c EN
29286 Procedure @code{string-titlecase} is also defined in SRFI-129.
29287 @c JP
29288 @code{string-titlecase}はSRFI-129でも定義されています。
29289 @c COMMON
29290 @end defun
29291
29292 @defun codepoints-upcase sequence
29293 @defunx codepoints-downcase sequence
29294 @defunx codepoints-titlecase sequence
29295 @defunx codepoints-foldcase sequence
29296 @c MOD gauche.unicode
29297 @c EN
29298 Like @code{string-upcase} etc, but these work on a sequence of
29299 codepoints instead. Returns a sequence of the same type of the input.
29300 @c JP
29301 @code{string-upcase}などと同じですが、文字列ではなくコードポイント例を対象にします。
29302 戻り値は入力と同じ型になります。
29303 @c COMMON
29304
29305 @example
29306 (codepoints-upcase '#(115 116 114 97 223 101))
29307 @result{} #(83 84 82 65 83 83 69)
29308 @end example
29309 @end defun
29310
29311 @defun string-ci=? string1 string2 string3 @dots{}
29312 @defunx string-ci<? string1 string2 string3 @dots{}
29313 @defunx string-ci<=? string1 string2 string3 @dots{}
29314 @defunx string-ci>? string1 string2 string3 @dots{}
29315 @defunx string-ci>=? string1 string2 string3 @dots{}
29316 [R7RS char]
29317 @c MOD gauche.unicode
29318 @c EN
29319 Case-insensitive string comparison, using full-string case conversion.
29320 @c JP
29321 文字列全体の大文字小文字変換を使って、大文字小文字の違いを無視した文字列比較を行います。
29322 @c COMMON
29323
29324 @c EN
29325 Note that Gauche has builtin @code{string-ci=?} etc., which use
29326 character-wise case folding (@pxref{String comparison}). These are
29327 different procedures.
29328 @c JP
29329 Gaucheは組み込みで@code{string-ci=?}などを持っていますが、そちらは
29330 文字ごとの大文字小文字変換を使います(@ref{String comparison}参照)。
29331 それとは異なる手続きです。
29332 @c COMMON
29333
29334 @example
29335 (string-ci=? "\u00df" "SS") @result{} #t
29336 @end example
29337 @end defun
29338
29339 @node East asian width property, , Full string case conversion, Unicode utilities
29340 @subsection East asian width property
29341 @c NODE 東アジア文字幅プロパティ
29342
29343 @defun char-east-asian-width char-or-codepoint
29344 @c MOD gauche.unicode
29345 @c EN
29346 The argument may be a character or a nonnegative integer of Unicode
29347 codepoint. Returns one of the symbols @code{N} (neutral),
29348 @code{F} (fullwidth), @code{H} (halfwidth), @code{W} (wide),
29349 @code{Na} (narrow), and @code{A} (ambiguous).
29350
29351 The meaning of this property is explained in Unicode standard annex #11,
29352 @url{http://unicode.org/reports/tr11/}.
29353 @c JP
29354 引数は文字か、Unicodeコードポイントを表す非負整数でなければなりません。
29355 次のいずれかのシンボルを返します:
29356 @code{N} (neutral)、
29357 @code{F} (fullwidth)、 @code{H} (halfwidth)、 @code{W} (wide)、
29358 @code{Na} (narrow)、@code{A} (ambiguous)。
29359
29360 各シンボルの意味についてはUnicode standard annex #11を参照してください:
29361 @url{http://unicode.org/reports/tr11/}。
29362 @c COMMON
29363 @end defun
29364
29365 @defun string-east-asian-width str :key F H W Na N A
29366 @c MOD gauche.unicode
29367 @c EN
29368 Computes the 'width' of the given string @var{str}, taking each character's
29369 East Asian Width int account. It gives you a rough estimate of
29370 how much space the string will occupy on the screen, when displayed
29371 with monospace fonts.
29372 @c JP
29373 東アジア文字幅プロパティを考慮して、文字列@var{str}の「幅」を計算して返します。
29374 この幅は、概ね文字列を等幅フォントでターミナルに表示した場合の近似と考えることが
29375 できます。
29376 @c COMMON
29377
29378 @c EN
29379 Although it is true that the exact width is generally undecidable without
29380 actually rendering them with glyphs, heuristics can give a good estimate
29381 if the string consists of limited scripts. For example, if the string
29382 is with ASCII and CJK ideographs, computing 'Full-width' and 'Wide'
29383 letters as twice wide as ASCII character is likely to work.
29384 @c JP
29385 もちろん実際に文字列が表示された時にどのくらいの幅を取るかは、実際にグリフを使って
29386 レンダリングしてみないとわかりません。が、文字列の構成要素がある程度限られている
29387 場合は、ヒューリスティクスでだいたいうまくいきます。
29388 例えば文字列がASCII文字とCJK漢字からなる場合、'Full-width'と'Wide'
29389 プロパティの文字をASCII文字の2倍幅とみなすことができるでしょう。
29390 @c COMMON
29391
29392 @c EN
29393 This procedure assigns the following widths for each character's
29394 East Asian Width category. They can be altered by giving
29395 keyword arguments @code{F}, @code{H}, @code{W}, @code{Na}, @code{N},
29396 and @code{A}, respectively:
29397 @c JP
29398 この手続きは、各文字の「東アジア文字幅プロパティ」カテゴリに次の幅を割り当てます。
29399 キーワード引数@code{F}, @code{H}, @code{W}, @code{Na}, @code{N}, @code{A}
29400 によってそれぞれの幅に違う値を割り当てることも可能です。
29401 @c COMMON
29402
29403 @table @asis
29404 @item F (Full width)
29405 2
29406 @item H (Half width)
29407 1
29408 @item W (Wide)
29409 2
29410 @item Na (Narrow)
29411 1
29412 @item N (Neutral)
29413 1
29414 @item A (Ambiguous)
29415 2
29416 @end table
29417
29418 @c EN
29419 See UAX #11 (@url{http://unicode.org/reports/tr11/}), section 5,
29420 for more detailed discussions of computing the width of displayed strings.
29421 @c JP
29422 文字幅の考慮について詳しくは、UAX #11 (@url{http://unicode.org/reports/tr11/})
29423 の5節を見てください。
29424 @c COMMON
29425
29426 @example
29427 (string-east-asian-width "abc") @result{} 3
29428 (string-east-asian-width "いろは") @result{} 6
29429 (string-east-asian-width "1番目" :W 1.5) @result{} 4.0
29430 @end example
29431 @end defun
29432
29433 @defun string-take-width str width :key F H W Na N A
29434 @defunx string-drop-width str width :key F H W Na N A
29435 @c MOD gauche.unicode
29436 @c EN
29437 Like @code{string-take} and @code{string-drop} (@pxref{String library}),
29438 returns a prefix and
29439 suffix of the input string @var{str}, but using the string's width
29440 instead of the number of characters.
29441 @c JP
29442 @code{string-take}と@code{string-drop} (@ref{String library}参照) のように、
29443 文字列@var{str}を指定箇所で切った前部分と後部分を返しますが、
29444 文字数で切るかわりに文字の幅で切ります。
29445 @c COMMON
29446
29447 @c EN
29448 @code{string-take-width} returns the longest prefix of a
29449 string @var{str} such that its @code{string-east-asian-width} does
29450 not exceed @var{width}. On the other hand, @code{string-drop-width}
29451 removes such prefix from @var{str} and returns the rest.
29452 @c JP
29453 @code{string-take-width}は、@var{str}のプレフィクスのうち、
29454 その@code{string-east-asian-width}が@var{width}を越えない部分を返します。
29455 一方@code{string-drop-width}はそのプレフィクスを取り除いた部分を返します。
29456 @c COMMON
29457
29458 @c EN
29459 The keyword arguments are to customize mappings of East Asian Width
29460 categories to numerical widths. See @code{string-east-asian-width}
29461 above for the details.
29462 @c JP
29463 キーワード引数は東アジア文字幅のカテゴリから幅へのマッピングをカスタマイズするものです。
29464 詳しくは上の@code{string-east-asian-width}の説明を見てください。
29465 @c COMMON
29466 @end defun
29467
29468 @c ----------------------------------------------------------------------
29469 @node Uniform vector library, Comparing version numbers, Unicode utilities, Library modules - Gauche extensions
29470 @section @code{gauche.uvector} - Uniform vector library
29471 @c NODE ユニフォームベクタライブラリ, @code{gauche.uvector} - ユニフォームベクタライブラリ
29472
29473 @deftp {Module} gauche.uvector
29474 @mdindex gauche.uvector
29475 @c EN
29476 Provides procedures that work on uniform vectors
29477 (@pxref{Uniform vectors}).
29478 This module is a superset of R7RS uniform vector library
29479 (@code{scheme.vector.@@}) and SRFI-4.
29480 @c JP
29481 ユニフォームベクタを扱う手続きを提供します
29482 (@ref{Uniform vectors}参照)。
29483 このモジュールは、R7RSユニフォームベクタライブラリ
29484 (@code{scheme.vector.@@})とSRFI-4のスーパーセットです。
29485 @c COMMON
29486
29487 @c EN
29488 The @code{@@} part is actually one of @code{u8}, @code{s8}, @code{u16},
29489 @code{s16}, @code{u32}, @code{s32}, @code{u64}, @code{s64},
29490 @code{f16}, @code{f32}, @code{f64}, @code{c32}, @code{c64} or @code{c128}.
29491 @c JP
29492 @code{@@}の部分は実際には要素の型を示す次タグのいずれかです:
29493 @code{u8}, @code{s8}, @code{u16},
29494 @code{s16}, @code{u32}, @code{s32}, @code{u64}, @code{s64},
29495 @code{f16}, @code{f32}, @code{f64}, @code{c32}, @code{c64}, @code{c128}。
29496 @c COMMON
29497
29498 @end deftp
29499
29500 @c EN
29501 Gauche's extension to SRFI-160 is as follows:
29502 @c JP
29503 Gaucheで拡張されている機能は次のとおりです:
29504 @c COMMON
29505 @itemize @bullet
29506 @item
29507 @c EN
29508 Support of @code{f16vector} and @code{c32vector}, using 16-bit floating
29509 point numbers as used in high-dynamic range image format.
29510 @c JP
29511 HDR画像フォーマットなどで使われる、16ビット浮動小数点数を使った
29512 @code{f16vector}と@code{c32vector}のサポート。
29513 @c COMMON
29514 @item
29515 @c EN
29516 Efficient element-wise arithmetic procedures, e.g. @code{@@vector-add}.
29517 @c JP
29518 @code{@@vector-add}など、効率の良い要素単位の演算手続き。
29519 @c COMMON
29520 @item
29521 @c EN
29522 Implements the collection framework (@pxref{Collection framework})
29523 and the sequence framework (@pxref{Sequence framework}). So the
29524 methods like @code{map}, @code{for-each}, @code{ref} or @code{subseq}
29525 can be used.
29526 @c JP
29527 コレクションフレームワーク (@ref{Collection framework}参照)と
29528 シーケンスフレームワーク (@ref{Sequence framework}参照)の実装。
29529 例えば @code{map}, @code{for-each}, @code{ref}, @code{subseq}等の
29530 メソッドが使えます。
29531 @c COMMON
29532 @item
29533 @c EN
29534 Some routines takes optional parameters: @code{@@vector-ref}
29535 takes optional fallback value.
29536 @c JP
29537 いくつかの手続きはSRFI-160に無い省略可能な引数を取ります。
29538 例えば@code{@@vector-ref}は省略可能なデフォルト値を取ります。
29539 @c COMMON
29540 @end itemize
29541
29542 @c EN
29543 When you try to store a number out of the range of the vector type,
29544 an error is signaled by default. However, some procedures take
29545 an optional argument @var{clamp} that specifies alternative behavior
29546 in such a case. @var{Clamp} argument may take one of the following values.
29547 @c JP
29548 ベクタの型が許す範囲外の値を格納しようとした場合、通常はエラーとなります。
29549 いくつかの手続きは省略可能な引数@var{clamp}によって、
29550 そのような場合に別のふるまいを指定することができます。
29551 @var{clamp}には以下のいずれかの値を与えることが出来ます。
29552 @c COMMON
29553 @table @code
29554 @item #f
29555 @c EN
29556 Default behavior (signals an error).
29557 @c JP
29558 デフォルト (エラーを通知)
29559 @c COMMON
29560 @item high
29561 @c EN
29562 Clamps high bound; i.e. if the value to be stored is beyond the higher bound
29563 of the range, the maximum value is stored instead.
29564 @c JP
29565 高い方の値をクランプ、すなわち、格納しようとする値が許される値の最大値より大きかった
29566 場合は、可能な最大値を代わりに格納します。
29567 @c COMMON
29568 @item low
29569 @c EN
29570 Clamps low bound; i.e. if the value to be stored is below the lower bound
29571 of the range, the minimum value is stored instead.
29572 @c JP
29573 低い方の値をクランプ、すなわち、格納しようとする値が許される値の最小値より大きかった
29574 場合は、可能な最小値を代わりに格納します。
29575 @c COMMON
29576 @item both
29577 @c EN
29578 Clamps both sides; does both @code{high} and @code{low}.
29579 @c JP
29580 高いほうと低いほうの両方の値をクランプします。
29581 @c COMMON
29582 @end table
29583
29584 @example
29585 (list->u8vector '(-1)) @result{} @r{error}
29586 (list->u8vector '(-1) 'low) @result{} #u8(0)
29587 (list->u8vector '(-1) 'high) @result{} @r{error}
29588 (list->u8vector '(3000) 'high) @result{} #u8(255)
29589 (list->u8vector '(-100 20 300) 'both) @result{} #u8(0 20 255)
29590 @end example
29591
29592 @c EN
29593 In the following description, @code{@@} can be replaced
29594 for any of @code{s8}, @code{u8}, @code{s16}, @code{u16},
29595 @code{s32}, @code{u32}, @code{s64}, @code{u64},
29596 @code{f16}, @code{f32}, @code{f64}, @code{c32}, @code{c64} or @code{c128}.
29597 @c JP
29598 以下の記述では、@code{@@}は
29599 @code{s8}, @code{u8}, @code{s16}, @code{u16},
29600 @code{s32}, @code{u32}, @code{s64}, @code{u64},
29601 @code{f16}, @code{f32}, @code{f64}, @code{c32}, @code{c64}, @code{c128}
29602 のいずれにも置き換えて読むことができるものとします。
29603 @c COMMON
29604
29605 @c EN
29606 Note: R7RS-large provides separate library for each type,
29607 and you should import them individually, for example,
29608 @code{(use scheme.vector.u8)} (Gauche way) or
29609 @code{(import (scheme vector u8))} (R7RS way).
29610
29611 On the other hand, using @code{gauche.uvector} imports all the bindings.
29612 @c JP
29613 註: R7RS-largeでは、それぞれの型に対して個別のライブラリがあり、
29614 例えば@code{u8}ベクタが使いたければ
29615 @code{(use scheme.vector.u8)} (Gauche式)
29616 あるいは @code{(import (scheme vector u8))} (R7RS式)
29617 のようにする必要があります。
29618
29619 一方、@code{gauche.uvector}使った場合は全ての手続きがインポートされます。
29620 @c COMMON
29621
29622 @menu
29623 * Uvector basic operations::
29624 * Uvector conversion operations::
29625 * Uvector numeric operations::
29626 * Uvector block I/O::
29627 * Bytevector compatibility::
29628 @end menu
29629
29630 @node Uvector basic operations, Uvector conversion operations, Uniform vector library, Uniform vector library
29631 @subsection Uvector basic operations
29632 @c NODE ユニフォームベクタの基本操作
29633
29634 @c EN
29635 The following procedures are built-in; @pxref{Uniform vectors}:
29636 @c JP
29637 次の手続きは組み込みです。@ref{Uniform vectors}参照:
29638 @c COMMON
29639
29640 @example
29641 make-@@vector
29642 uvector? @@vector?
29643 uvector-ref @@vector-ref
29644 uvector-set! @@vector-set!
29645 uvector-length
29646 @end example
29647
29648 @deffn {Function} @@? obj
29649 @findex s8?
29650 @findex u8?
29651 @findex s16?
29652 @findex u16?
29653 @findex s32?
29654 @findex u32?
29655 @findex s64?
29656 @findex u64?
29657 @findex f16?
29658 @findex f32?
29659 @findex f64?
29660 @findex c32?
29661 @findex c64?
29662 @findex c128?
29663 [R7RS vector.@@]
29664 @c MOD gauche.uvector
29665 @c EN
29666 Returns @code{#t} iff @var{obj} can be an element of @code{@@vector}.
29667 @c JP
29668 引数が@@ベクタの要素に収まるなら@code{#t}を、そうでなければ@code{#f}を返します。
29669 @c COMMON
29670 @end deffn
29671
29672 @deffn {Function} @@vector-empty? obj
29673 @findex u8vector-empty?
29674 @findex s8vector-empty?
29675 @findex u16vector-empty?
29676 @findex s16vector-empty?
29677 @findex u32vector-empty?
29678 @findex s32vector-empty?
29679 @findex u64vector-empty?
29680 @findex s64vector-empty?
29681 @findex f16vector-empty?
29682 @findex f32vector-empty?
29683 @findex f64vector-empty?
29684 @findex c32vector-empty?
29685 @findex c64vector-empty?
29686 @findex c128vector-empty?
29687 [R7RS vector.@@]
29688 @c MOD gauche.uvector
29689 @c EN
29690 The argument must be a @@vector.
29691 Returns @code{#t} iff it is empty.
29692 @c JP
29693 引数は@@vectorでなければなりません。
29694 それが空なら@code{#t}を、そうでなければ@var{#f}を返します。
29695 @c COMMON
29696 @end deffn
29697
29698 @deffn {Function} @@vector x @dots{}
29699 @findex s8vector
29700 @findex u8vector
29701 @findex s16vector
29702 @findex u16vector
29703 @findex s32vector
29704 @findex u32vector
29705 @findex s64vector
29706 @findex u64vector
29707 @findex f16vector
29708 @findex f32vector
29709 @findex f64vector
29710 @findex c32vector
29711 @findex c64vector
29712 @findex c128vector
29713 [R7RS vector.@@]
29714 @c MOD gauche.uvector
29715 @c EN
29716 Constructs @@vector whose elements are numbers @var{x} @dots{}.
29717 The numbers must be exact integer for exact integer vectors,
29718 and in the valid range of the vector.
29719 @c JP
29720 数値@var{x} @dots{} を要素に持つ@@vectorを作成して返します。
29721 正確な整数のベクタに対しては、数値は正確な整数でなければならず、
29722 また有効な範囲内の値でなければなりません。
29723 @c COMMON
29724 @example
29725 (s8vector 1 2 3) @result{} #s8(1 2 3)
29726 @end example
29727 @end deffn
29728
29729 @defun make-uvector @code{class} @code{len} :optional @code{fill}
29730 @c MOD gauche.uvector
29731 @c EN
29732 This is a Gauche extension; instead of using separate constructor for
29733 each uvector type, you can pass the class of desired uvector.
29734
29735 Type-specific constructors (@code{make-s8vector} etc.) are defined
29736 in the core library (@pxref{Uniform vectors}).
29737 @c JP
29738 これはGaucheの拡張です。各ユニフォームベクタの型に対応する関数を呼ぶかわりに、
29739 欲しいユニフォームベクタのクラスを渡してベクタを作ることができます。
29740
29741 型ごとのコンストラクタ (@code{make-s8vector}等)はコアのライブラリで提供
29742 されています (@ref{Uniform vectors}参照)。
29743 @c COMMON
29744
29745 @example
29746 (make-uvector <u8vector> 3) @result{} #u8(0 0 0)
29747 (make-uvector <s8vector> 5 -1) @result{} #s8(-1 -1 -1 -1 -1)
29748 @end example
29749 @end defun
29750
29751 @deffn {Function} @@vector-unfold f len seed
29752 @deffnx {Function} @@vector-unfold-right f len seed
29753 @findex u8vector-unfold
29754 @findex s8vector-unfold
29755 @findex u16vector-unfold
29756 @findex s16vector-unfold
29757 @findex u32vector-unfold
29758 @findex s32vector-unfold
29759 @findex u64vector-unfold
29760 @findex s64vector-unfold
29761 @findex f16vector-unfold
29762 @findex f32vector-unfold
29763 @findex f64vector-unfold
29764 @findex c32vector-unfold
29765 @findex c64vector-unfold
29766 @findex c128vector-unfold
29767 @findex u8vector-unfold-right
29768 @findex s8vector-unfold-right
29769 @findex u16vector-unfold-right
29770 @findex s16vector-unfold-right
29771 @findex u32vector-unfold-right
29772 @findex s32vector-unfold-right
29773 @findex u64vector-unfold-right
29774 @findex s64vector-unfold-right
29775 @findex f16vector-unfold-right
29776 @findex f32vector-unfold-right
29777 @findex f64vector-unfold-right
29778 @findex c32vector-unfold-right
29779 @findex c64vector-unfold-right
29780 @findex c128vector-unfold-right
29781 [R7RS vector.@@]
29782 @c MOD gauche.uvector
29783 @c EN
29784 Construct a @@vector of length @var{len}, with each element
29785 as a result of @code{(f seed)}, @code{(f (f seed))},
29786 @code{(f (f (f seed)))}, @dots{}.
29787 @@vector-unfold fills the element from left to right,
29788 while @@vector-unfold-right from right to left.
29789 @c JP
29790 長さ@var{len}の@@vectorを作り、
29791 @code{(f seed)}、@code{(f (f seed))}、
29792 @code{(f (f (f seed)))}、@dots{} の結果を順に要素とします。
29793 @@vector-unfoldは左から右に、
29794 @@vector-unfold-rightは右から左に埋めてゆきます。
29795 @c COMMON
29796 @example
29797 (u8vector-unfold (cut + 2 <>) 5 0)
29798 @result{} #u8(2 4 6 8 10)
29799 (u8vector-unfold-right (pa$ + 2) 5 0)
29800 @result{} #u8(10 8 6 4 2)
29801 @end example
29802 @end deffn
29803
29804 @deffn {Function} @@vector-unfold! f vec start end seed
29805 @deffnx {Function} @@vector-unfold-right! f vec start end seed
29806 @findex u8vector-unfold!
29807 @findex s8vector-unfold!
29808 @findex u16vector-unfold!
29809 @findex s16vector-unfold!
29810 @findex u32vector-unfold!
29811 @findex s32vector-unfold!
29812 @findex u64vector-unfold!
29813 @findex s64vector-unfold!
29814 @findex f16vector-unfold!
29815 @findex f32vector-unfold!
29816 @findex f64vector-unfold!
29817 @findex c32vector-unfold!
29818 @findex c64vector-unfold!
29819 @findex c128vector-unfold!
29820 @findex u8vector-unfold-right!
29821 @findex s8vector-unfold-right!
29822 @findex u16vector-unfold-right!
29823 @findex s16vector-unfold-right!
29824 @findex u32vector-unfold-right!
29825 @findex s32vector-unfold-right!
29826 @findex u64vector-unfold-right!
29827 @findex s64vector-unfold-right!
29828 @findex f16vector-unfold-right!
29829 @findex f32vector-unfold-right!
29830 @findex f64vector-unfold-right!
29831 @findex c32vector-unfold-right!
29832 @findex c64vector-unfold-right!
29833 @findex c128vector-unfold-right!
29834 [R7RS vector.@@]
29835 @c MOD gauche.uvector
29836 @c EN
29837 Fill an @@vector @var{vec} between @var{start}-th index (inclusive)
29838 and @var{end}-th index (exclusive), with the values generated by @var{f},
29839 which is called with two arguments, the integer index and
29840 the current seed value.
29841
29842 In @code{@@vector-unfold!}, @var{f} is first called with
29843 @var{start} and @var{seed}. It must return two values,
29844 the element to put to @var{vec} and the next seed value.
29845 Then @var{f} is called with @var{start} + 1 and the previously
29846 returnd seed value, and so on, until @var{end} - @var{start} elements
29847 are generated.
29848
29849 @code{@@vector-unfold-right!} works similarly, but the elements
29850 are generated from right (@var{end}-1) to left (@var{start}).
29851
29852 If @var{start} >= @var{end}, @var{f} is never called and @var{vec} isn't
29853 altered. It is an error if the index falls out of range of @var{vec}.
29854
29855 Return an unspecified vlaue.
29856 @c JP
29857 @@vectorである@var{vec}の、@var{start}要素目(含む)から@var{end}要素目(含まない)
29858 までを、@var{f}の呼び出し結果で埋めてゆきます。@var{f}は整数のインデックスと
29859 現在のシード値を引数にして呼ばれます。
29860
29861 @code{@@vector-unfold!}では、@var{f}はまず@var{start}と@var{seed}を引数にして
29862 呼ばれます。@var{f}は@var{start}に埋めるべき値と次のシード値の2値を返さねばなりません。
29863 次に@var{f}は@var{start}+1と戻されたシード値を引数に呼ばれ…と、
29864 それが@var{end}-@var{start}回繰り返されます。
29865
29866 @code{@@vector-unfold-right!}も同様に動作しますが、右から左、
29867 つまり@var{end}-1から始めて@var{start}に向けて値が埋めてゆかれます。
29868
29869 @var{start} >= @var{end} であった場合、@var{f}は呼ばれることなく、
29870 @var{vec}は変更されません。もしインデックスが@var{vec}の範囲の外に出た場合は
29871 エラーが投げられます。
29872
29873 戻り値は未規定です。
29874 @c COMMON
29875 @end deffn
29876
29877
29878 @deffn {Function} @@vector-length vec
29879 @findex u8vector-length
29880 @findex s8vector-length
29881 @findex u16vector-length
29882 @findex s16vector-length
29883 @findex u32vector-length
29884 @findex s32vector-length
29885 @findex u64vector-length
29886 @findex s64vector-length
29887 @findex f16vector-length
29888 @findex f32vector-length
29889 @findex f64vector-length
29890 @findex c32vector-length
29891 @findex c64vector-length
29892 @findex c128vector-length
29893 [R7RS vector.@@]
29894 @c MOD gauche.uvector
29895 @c EN
29896 Returns the length of the @@vector @var{vec}.
29897
29898 Note that the generic function @code{size-of} can be used
29899 to obtain the length of @var{vec} as well,
29900 if you import @code{gauche.collection}
29901 (@pxref{Collection framework}).
29902 @c JP
29903 @@vector @var{vec}の長さを返します。
29904
29905 モジュール@code{gauche.collection}をインポートしていれば、
29906 @var{vec}の長さを知るのに、総称関数@code{size-of}を使うこともできます
29907 (@ref{Collection framework}参照)。
29908 @c COMMON
29909 @example
29910 (s16vector-length '#s16(111 222 333)) @result{} 3
29911
29912 (use gauche.collection)
29913 (size-of '#s16(111 222 333)) @result{} 3
29914 @end example
29915 @end deffn
29916
29917 @defun uvector-size uvector :optional start end
29918 @c MOD gauche.uvector
29919 @c EN
29920 This function can be applied to any type of uniform vectors, and
29921 returns the raw size of the @var{uvector} in number of octets.
29922
29923 When @var{start} and/or @var{end} is/are given, the size of data
29924 between those indices are calculated. The special value @code{-1}
29925 for @var{end} indicates the end of the vector.
29926 The returned value matches the number of octets to be written out
29927 by @code{(write-uvector @var{uvector} port @var{start} @var{end})}.
29928
29929 (Do not confuse this with @code{uvector-length}, which returns
29930 the number of elements.)
29931 @c JP
29932 この手続きは全てのユニフォームベクタに適用することができます。
29933 @var{uvector}のバイナリデータとしてのサイズをオクテット数で返します。
29934
29935 @var{start}および/または@var{end}が与えられた場合は、
29936 これらのインデックスの間のデータについてのみサイズが計算されます。
29937 @var{end}には、ベクタ終端を示すために@code{-1}を与えることもできます。
29938 返される値は
29939 @code{(write-uvector @var{uvector} port @var{start} @var{end})} によって
29940 出力されるオクテット数と一致します。
29941
29942 (要素数を返す@code{uvector-length}と混同しないようにしてください。)
29943 @c COMMON
29944
29945 @example
29946 (uvector-size '#u8(1 2 3)) @result{} 3
29947 (uvector-size '#u64(1 2 3)) @result{} 24
29948
29949 (uvector-size '#u32(0 1 2 3) 2) @result{} 8
29950 (uvector-size '#u32(0 1 2 3) 0 1) @result{} 4
29951 @end example
29952 @end defun
29953
29954 @defun uvector-class-element-size class
29955 @c MOD gauche.uvector
29956 @c EN
29957 Returns the size of an element of a uvector of the given class, in bytes.
29958 An error is raised when @var{class} is not a uvector class.
29959 @c JP
29960 与えられたクラスのユニフォームベクタの1要素が占める大きさをバイト数で返します。
29961 @var{class}がユニフォームベクタのクラスでない場合はエラーが投げられます。
29962 @c COMMON
29963
29964 @example
29965 (uvector-class-element-size <u8vector>) @result{} 1
29966 (uvector-class-element-size <s64vector>) @result{} 8
29967 @end example
29968 @end defun
29969
29970 @deffn {Function} @@vector-swap! vec i j
29971 @findex u8vector-swap!
29972 @findex s8vector-swap!
29973 @findex u16vector-swap!
29974 @findex s16vector-swap!
29975 @findex u32vector-swap!
29976 @findex s32vector-swap!
29977 @findex u64vector-swap!
29978 @findex s64vector-swap!
29979 @findex f16vector-swap!
29980 @findex f32vector-swap!
29981 @findex f64vector-swap!
29982 @findex c32vector-swap!
29983 @findex c64vector-swap!
29984 @findex c128vector-swap!
29985 [R7RS vector.@@]
29986 @c MOD gauche.uvector
29987 @c EN
29988 Interchanges @var{i}th and @var{j}th elements of the uvector @var{vec}.
29989 Return value is not specified.
29990 @c JP
29991 ユニフォームベクタ@var{vec}の@var{i}番目と@var{j}番目の要素を入れ替えます。
29992 戻り値は規定されていません。
29993 @c COMMON
29994 @end deffn
29995
29996 @deffn {Function} @@vector-fill! vec fill :optional start end
29997 @findex u8vector-fill!
29998 @findex s8vector-fill!
29999 @findex u16vector-fill!
30000 @findex s16vector-fill!
30001 @findex u32vector-fill!
30002 @findex s32vector-fill!
30003 @findex u64vector-fill!
30004 @findex s64vector-fill!
30005 @findex f16vector-fill!
30006 @findex f32vector-fill!
30007 @findex f64vector-fill!
30008 @findex c32vector-fill!
30009 @findex c64vector-fill!
30010 @findex c128vector-fill!
30011 @c MOD gauche.uvector
30012 @c EN
30013 Stores @var{fill} in every element of @var{vec},
30014 ranging from @var{start} to @var{end} of @var{vec},
30015 if they are given.
30016 Return value is not specified.
30017 @c JP
30018 @var{vec}のすべて要素に@var{fill}をセットします。
30019 @var{start}と@var{end}で要素の範囲を指定することも出来ます。
30020 戻り値は規定されていません。
30021 @c COMMON
30022 @end deffn
30023
30024 @deffn {Function} @@vector= @var{vec1} @dots{}
30025 @findex u8vector=
30026 @findex s8vector=
30027 @findex u16vector=
30028 @findex s16vector=
30029 @findex u32vector=
30030 @findex s32vector=
30031 @findex u64vector=
30032 @findex s64vector=
30033 @findex f16vector=
30034 @findex f32vector=
30035 @findex f64vector=
30036 @findex c32vector=
30037 @findex c64vector=
30038 @findex c128vector=
30039 [R7RS vector.@@]
30040 @c MOD gauche.uvector
30041 @c EN
30042 All arguments must be @@vectors. Returns @code{#t} iff
30043 all arguments have the same length and has the same values (in terms of @code{=})
30044 at the corresponding position. Zero arguments
30045 return @var{#t}.
30046
30047 Note that in Gauche you can compare uvectors with @code{equal?}as well.
30048 @c JP
30049 全ての引数は@@vectorでなければなりません。
30050 引数が全て同じ長さで、対応する要素が同じ価(@code{=}の意味で)なら@code{#t}を、
30051 そうでなければ@code{#f}を返します。
30052
30053 Gaucheでは、uvectorは@code{equal?}で比較することができます。
30054 @c COMMON
30055 @end deffn
30056
30057
30058 @deffn {Function} @@vector=? @var{vec1} @var{vec2}
30059 @findex u8vector=?
30060 @findex s8vector=?
30061 @findex u16vector=?
30062 @findex s16vector=?
30063 @findex u32vector=?
30064 @findex s32vector=?
30065 @findex u64vector=?
30066 @findex s64vector=?
30067 @findex f16vector=?
30068 @findex f32vector=?
30069 @findex f64vector=?
30070 @findex c32vector=?
30071 @findex c64vector=?
30072 @findex c128vector=?
30073 [SRFI-66]
30074 @c MOD gauche.uvector
30075 @c EN
30076 Note: This is provided only for the SRFI-66 compatibility.
30077 Use @code{@@vector=} instead.
30078
30079 Both arguments must be a @@vector. Returns @code{#t} if
30080 @var{vec1} and @var{vec2} are equal to each other, @code{#f} otherwise.
30081 @c JP
30082 註: これはSRFI-66との互換性のためだけに提供されています。
30083 @code{@@vector=} を使ってください。
30084
30085 引数はどちらも@@vectorでなければなりません。
30086 両引数が等価なら@code{#t}が、そうでなければ@code{#f}が返されます。
30087 @c COMMON
30088 @end deffn
30089
30090 @deffn {Function} @@vector-compare @var{vec1} @var{vec2}
30091 @findex u8vector-compare
30092 @findex s8vector-compare
30093 @findex u16vector-compare
30094 @findex s16vector-compare
30095 @findex u32vector-compare
30096 @findex s32vector-compare
30097 @findex u64vector-compare
30098 @findex s64vector-compare
30099 @findex f16vector-compare
30100 @findex f32vector-compare
30101 @findex f64vector-compare
30102 @findex c32vector-compare
30103 @findex c64vector-compare
30104 @findex c128vector-compare
30105 [SRFI-66]
30106 @c MOD gauche.uvector
30107 @c EN
30108 Both arguments must be a @@vector. Returns @code{-1} if
30109 @var{vec1} is smaller than @var{vec2},
30110 @code{0} if both are equal to each other,
30111 and @code{1} if @var{vec1} is greater than @var{vec2}.
30112
30113 Shorter vector is smaller than longer vectors. If the lengths of
30114 both vectors are the same, elements are compared from left to right.
30115
30116 Note that you can compare uvectors with @code{compare} in Gauche.
30117 These are provided because SRFI-66 defines @code{u8vector-compare}.
30118 You can also use them to indicate arguments are vectors of the specific type.
30119 @c JP
30120 引数はどちらも@@vectorでなければなりません。
30121 @var{vec1}が@var{vec2}よりも小さければ@code{-1}が、
30122 両者が等しければ@code{0}が、
30123 @var{vec1}が@var{vec2}よりも大きければ@code{1}が返されます。
30124
30125 短い方のベクタが常に小さいと評価されます。長さが等しい場合は要素を左から順に比較します。
30126
30127 Gaucheでは、uvectorは@code{compare}で比較することができます。
30128 これらの手続きが提供されるのは、SRFI-66が@code{u8vector-compare}を定義しているためです。
30129 引数が特定の型のベクタであることを明示したい場合に使っても良いでしょう。
30130 @c COMMON
30131 @end deffn
30132
30133 @deffn {Function} @@vector-copy vec :optional start end
30134 @findex u8vector-copy
30135 @findex s8vector-copy
30136 @findex u16vector-copy
30137 @findex s16vector-copy
30138 @findex u32vector-copy
30139 @findex s32vector-copy
30140 @findex u64vector-copy
30141 @findex s64vector-copy
30142 @findex f16vector-copy
30143 @findex f32vector-copy
30144 @findex f64vector-copy
30145 @findex c32vector-copy
30146 @findex c64vector-copy
30147 @findex c128vector-copy
30148 [R7RS vector.@@]
30149 @c MOD gauche.uvector
30150 @c EN
30151 Returns a fresh copy of uniform vector @var{vec}.
30152 If @var{start} and/or @var{end} are given, they limit the range of
30153 @var{vec} to be copied.
30154 @c JP
30155 ベクタ@var{vec}の新たなコピーを返します。
30156 省略可能な引数@var{start}と@var{end}が与えられた場合、
30157 それらは取り出される要素の範囲を制限します。
30158 @c COMMON
30159
30160 @example
30161 (u8vector-copy '#u8(1 2 3 4)) @result{} #u8(1 2 3 4)
30162 (u8vector-copy '#u8(1 2 3 4) 2) @result{} #u8(3 4)
30163 (u8vector-copy '#u8(1 2 3 4) 1 3) @result{} #u8(2 3)
30164 @end example
30165 @end deffn
30166
30167 @defun uvector-copy vec :optional start end
30168 @c MOD gauche.uvector
30169 @c EN
30170 This is a generic version of @code{@@vector-copy}.
30171 You can give any type of uvector to @var{vec}, and get its copy
30172 (or copy of its part, depending on @var{start}/@var{end} argument).
30173 @c JP
30174 これは@code{@@vector-copy}の汎用バージョンです。
30175 どんな型のuvectorでも@var{vec}に渡すことができ、そのコピー
30176 (もしくは、@var{start}/@var{end}によっては一部のコピー)が返されます。
30177 @c COMMON
30178 @end defun
30179
30180 @deffn {Function} @@vector-reverse-copy vec :optional start end
30181 @findex u8vector-reverse-copy
30182 @findex s8vector-reverse-copy
30183 @findex u16vector-reverse-copy
30184 @findex s16vector-reverse-copy
30185 @findex u32vector-reverse-copy
30186 @findex s32vector-reverse-copy
30187 @findex u64vector-reverse-copy
30188 @findex s64vector-reverse-copy
30189 @findex f16vector-reverse-copy
30190 @findex f32vector-reverse-copy
30191 @findex f64vector-reverse-copy
30192 @findex c32vector-reverse-copy
30193 @findex c64vector-reverse-copy
30194 @findex c128vector-reverse-copy
30195 [R7RS vector.@@]
30196 @c MOD gauche.uvector
30197 @c EN
30198 Copies @var{vec} between @var{strat} and @var{end} index, but
30199 reversing it.
30200 @c JP
30201 @var{vec}の要素を逆順にしたコピーを作って返します。
30202 省略可能な@var{start}と@var{end}はコピー範囲を限定します。
30203 @c COMMON
30204 @example
30205 (u8vector-reverse-copy '#u8(1 2 3 4 5))
30206 @result{} #u8(5 4 3 2 1)
30207
30208 (u8vector-reverse-copy '#u8(1 2 3 4 5) 1 4)
30209 @result{} #u8(4 3 2)
30210 @end example
30211 @end deffn
30212
30213 @deffn {Function} @@vector-copy! target tstart source :optional sstart send
30214 @findex u8vector-copy!
30215 @findex s8vector-copy!
30216 @findex u16vector-copy!
30217 @findex s16vector-copy!
30218 @findex u32vector-copy!
30219 @findex s32vector-copy!
30220 @findex u64vector-copy!
30221 @findex s64vector-copy!
30222 @findex f16vector-copy!
30223 @findex f32vector-copy!
30224 @findex f64vector-copy!
30225 @findex c32vector-copy!
30226 @findex c64vector-copy!
30227 @findex c128vector-copy!
30228 [R7RS vector.@@]
30229 @c MOD gauche.uvector
30230 @c EN
30231 Both @var{target} and @var{source} must be @@vectors, and
30232 @var{target} must be mutable.
30233 This procedure copies the elements of @var{source}, beginning from index
30234 @var{sstart} (inclusive) and up to @var{send}, into @var{target},
30235 beginning from index @var{tstart}. @var{sstart} and @var{send}
30236 may be omitted, and in that case 0 and the length of @var{source}
30237 are assumed, respectively.
30238 @c JP
30239 @var{target} および @var{source} はともに @@vector でなければ
30240 なりません。さらに、@var{target} は変更可能でなければなりません。
30241 この手続きは、@var{source}の要素を、インデックス@var{sstart}から(これを含み)
30242 @var{send} までを、@var{target} へインデックス @var{tstart}からコピーします。
30243 @var{sstart}および@var{send}は省略可能で、その場合には、それぞれ、
30244 0 および @var{source}の長さが仮定されます。
30245 @c COMMON
30246
30247 @example
30248 (let ((target (u8vector 0 1 2 3 4 5 6)))
30249 (u8vector-copy! target 2 '#u8(10 11 12 13 14) 1 4)
30250 target)
30251 @result{} #u8(0 1 11 12 13 6)
30252 @end example
30253
30254 @c EN
30255 If the number of elements in the source vector between @var{sstart}
30256 and @var{send} is larger than the target vector beginning from @var{tstart},
30257 the excess elements are silently discarded.
30258 @c JP
30259 もし、コピー元のベクタの @var{sstart} と @var{send} の間にある要素の
30260 数がコピー先のベクタの@var{tstart}以降の部分よりも大きければ、超過分の
30261 ベクタはだまって捨てられます。
30262 @c COMMON
30263
30264 @c EN
30265 It is ok to pass the same vector to @var{target} and @var{source};
30266 it always works even if the regions of source and destination are
30267 overlapping.
30268 @c JP
30269 @var{target}と@var{source}に同一のベクタを渡しても構いません。
30270 コピー先とコピー元の領域が重なっていても、コピーは常に正しく行われます。
30271 @c COMMON
30272
30273 @c EN
30274 @emph{Note:} This procedure used to take just two uniform vectors, @var{target}
30275 and @var{source}, and just copies contents of @var{source} to @var{target}.
30276 Both vectors had to be the same type and same length. The API is revised
30277 according to SRFI-160. The old interface is still supported
30278 for the backward compatibility, but it is deprecated and will be gone
30279 in the future releases.
30280
30281 Also note that SRFI-66 provides @code{uvector-copy!} with different
30282 argument order (@pxref{Octet vectors}).
30283 @c JP
30284 @emph{注意事項:} この手続きは以前はユニフォームベクタ @var{target} および
30285 @var{source} のみを引数としてとり、@var{source} の内容を @var{target} へ
30286 コピーするためだけに使われました。両方のベクタは同じ型で、同じ長さでなけ
30287 ればなりませんでした。この API はSRFI-160にあわせて現在の形式に改訂されています。
30288 旧来のインタフェースも後方互換性のためにサポートされて
30289 いますが、これは廃止予定で、将来のリリースではサポートされなくなります。
30290
30291 また、SRFI-66も@code{u8vector-copy!}を提供していますが、
30292 引数の順序が異なります(@ref{Octet vectors}参照)。
30293 @c COMMON
30294 @end deffn
30295
30296 @deffn {Function} @@vector-reverse! vec :optional start end
30297 @findex u8vector-reverse!
30298 @findex s8vector-reverse!
30299 @findex u16vector-reverse!
30300 @findex s16vector-reverse!
30301 @findex u32vector-reverse!
30302 @findex s32vector-reverse!
30303 @findex u64vector-reverse!
30304 @findex s64vector-reverse!
30305 @findex f16vector-reverse!
30306 @findex f32vector-reverse!
30307 @findex f64vector-reverse!
30308 @findex c32vector-reverse!
30309 @findex c64vector-reverse!
30310 @findex c128vector-reverse!
30311 [R7RS vector.@@]
30312 @c MOD gauche.uvector
30313 @c EN
30314 @c JP
30315 @c COMMON
30316 @end deffn
30317
30318 @deffn {Function} @@vector-reverse-copy! target tstart source :optional start end
30319 @findex u8vector-reverse-copy!
30320 @findex s8vector-reverse-copy!
30321 @findex u16vector-reverse-copy!
30322 @findex s16vector-reverse-copy!
30323 @findex u32vector-reverse-copy!
30324 @findex s32vector-reverse-copy!
30325 @findex u64vector-reverse-copy!
30326 @findex s64vector-reverse-copy!
30327 @findex f16vector-reverse-copy!
30328 @findex f32vector-reverse-copy!
30329 @findex f64vector-reverse-copy!
30330 @findex c32vector-reverse-copy!
30331 @findex c64vector-reverse-copy!
30332 @findex c128vector-reverse-copy!
30333 [R7RS vector.@@]
30334 @c MOD gauche.uvector
30335 @c EN
30336 @c JP
30337 @c COMMON
30338 @end deffn
30339
30340
30341
30342 @deffn {Function} @@vector-multi-copy! target tstart tstride source :optional sstart ssize sstride count
30343 @findex u8vector-multi-copy!
30344 @findex s8vector-multi-copy!
30345 @findex u16vector-multi-copy!
30346 @findex s16vector-multi-copy!
30347 @findex u32vector-multi-copy!
30348 @findex s32vector-multi-copy!
30349 @findex u64vector-multi-copy!
30350 @findex s64vector-multi-copy!
30351 @findex f16vector-multi-copy!
30352 @findex f32vector-multi-copy!
30353 @findex f64vector-multi-copy!
30354 @findex c32vector-multi-copy!
30355 @findex c64vector-multi-copy!
30356 @findex c128vector-multi-copy!
30357 @c MOD gauche.uvector
30358 @c EN
30359 This procedure allows different parts of the source uvector @var{source} into
30360 various parts of the target uvector @var{target}, all at once.
30361
30362 When @var{ssize} is omitted or zero, this procedure does the following:
30363 @c JP
30364 この手続きは、コピー元ベクタ@var{source}の異なる部分を
30365 コピー先ベクタ@var{target}の異なる部分へと一度にコピーするのに使えます。
30366
30367 @var{ssize}が省略されるか0の場合、この手続きは次の動作をします。
30368 @c COMMON
30369
30370 @example
30371 ;; For each @var{i} from 0 to @var{count}:
30372 (u8vector-copy! target (+ tstart (* i tstride))
30373 source sstart)
30374 @end example
30375
30376 @c EN
30377 That is, it copies the content of @var{source} (offset by @var{sstart},
30378 which defaults to 0)
30379 into the @var{target} repeatedly, advancing index with @var{tstride}.
30380 If either the target index reaches the end or @var{count} copies
30381 are made, the procedure returns. See the example:
30382 @c JP
30383 つまり、@var{source}ベクタの内容 (@var{sstart}が指定されてればそこから、
30384 指定が無ければ最初から)を@var{target}ベクタに、@var{tstride}づつインデックスを
30385 進めながらコピーします。コピー先のインデックスが@var{target}ベクタの範囲を
30386 越えるか、@var{count}が指定されていればその回数分だけコピーが済むかすれば
30387 手続きは終了します。次の例を見てください。
30388 @c COMMON
30389
30390 @example
30391 (define t (make-u8vector 10 0))
30392 (u8vector-multi-copy! t 0 4 '#u8(1 2 3))
30393
30394 t @result{} #u8(1 2 3 0 1 2 3 0 1 2)
30395 @end example
30396
30397 @c EN
30398 If @var{ssize} is given and positive, the source is also splitted
30399 as follows:
30400 @c JP
30401 @var{ssize}に正の整数が与えられた場合は、コピー元ベクタも@var{ssize}ごとに
30402 分割されます。
30403 @c COMMON
30404
30405 @example
30406 ;; For each @var{i} from 0 to @var{count}:
30407 (u8vector-copy! target (+ tstart (* i tstride))
30408 source (+ sstart (* i sstride))
30409 (+ sstart (* i sstride) ssize))
30410 @end example
30411
30412 @c EN
30413 That is, each @var{ssize} slice from @var{source},
30414 is copied into @var{target}, advancing source index
30415 by @var{sstride} and the destination index by @var{dstride}.
30416 In this case, @var{sstride} defaults to @var{ssize} if omitted.
30417 @c JP
30418 つまり、コピー元インデックスを@var{sstride}づつ、コピー先を
30419 @var{dstride}づつ増やしながら、コピー元からそれぞれ@var{ssize}分のデータが切り出されて
30420 @var{target}にコピーされます。この場合、@var{sstride}は省略されると
30421 @var{ssize}と同じになります。
30422 @c COMMON
30423
30424 @example
30425 (define t (make-u8vector 12 0))
30426 (u8vector-multi-copy! t 0 4 '#u8(1 2 3 4 5 6 7 8 9) 0 3)
30427
30428 t @result{} #u8(1 2 3 0 4 5 6 0 7 8 9 0)
30429 @end example
30430
30431 @c EN
30432 The operation ends when either @var{count} slices are copied,
30433 or destination index or source index reaches the end.
30434 @c JP
30435 操作は@var{count}個のデータ片がコピーされるか、コピー元あるいはコピー先の
30436 インデックスがそれぞれのベクタの終端に達したら終わります。
30437 @c COMMON
30438
30439 @c EN
30440 Hint: If you want to copy a part of the source vector repeatedly
30441 (instead of to its end), you can specify 0 to @var{sstride}:
30442 @c JP
30443 ヒント: コピー元のベクタの中程だけ (最後までではなく) をコピーしたい場合は、
30444 @var{sstride}に0を与えればできます。
30445 @c COMMON
30446
30447 @example
30448 (define t (make-u8vector 12 0))
30449 (u8vector-multi-copy! t 0 4 '#u8(1 2 3 4 5 6 7 8 9) 2 4 0)
30450
30451 t @result{} #u8(3 4 5 6 3 4 5 6 3 4 5 6)
30452 @end example
30453 @end deffn
30454
30455
30456 @c EN
30457 Using collection and sequence framework, you can perform
30458 various operations on the homogeneous vectors.
30459 @c JP
30460 コレクションやシーケンスフレームワークを使うと、さらに様々な操作を
30461 行うことができます。
30462 @c COMMON
30463
30464 @example
30465 (use gauche.collection)
30466 (use gauche.sequence)
30467
30468 (fold + 0 '#s32(1 2 3 4)) @result{} 10
30469
30470 (map-to <f32vector> * '#f32(3.2 1.1 4.3) '#f32(-4.3 2.2 9.4))
30471 @result{} #f32(-13.760001 2.420000 40.420002)
30472
30473 (subseq #u32(1 4 3 4 5) 2 4) @result{} #u32(3 4)
30474 @end example
30475
30476
30477 @defun uvector-copy! target tstart source :optional sstart send
30478 @c MOD gauche.uvector
30479 @c EN
30480 This is a generic version of @code{@@vector-copy!}.
30481 The destination @var{target} and the source @var{source} can be
30482 any type of uniform vectors, and they don't need to match.
30483 The copy is done bit-by-bit. So if you copy to a different type
30484 of uvector, the result depends on how the numbers are represented
30485 internally. This is mainly to manipulate binary data.
30486
30487 @var{Tstart} is interpreted according to the type of @var{target},
30488 and @var{sstart} and @var{send} are interpreted according to the
30489 type of @var{source}.
30490 @c JP
30491 これは@code{@@vector-copy!}の汎用バージョンです。
30492 コピー元@var{source}とコピー先@var{target}はユニフォームベクタであれば
30493 どの型でも許され、また両者の型が異なっていても構いません。
30494 ビット表現がそのままコピーされます。従って異なる型のユニフォームベクタ間で
30495 コピーした場合は、結果は数値の内部表現に依存します。
30496 そのような用法は、バイナリデータを扱う時には便利でしょう。
30497
30498 @var{tstart}は@var{target}の型によって解釈され、
30499 @var{sstart}と@var{send}は@var{source}の型によって解釈されます。
30500 @c COMMON
30501
30502 @example
30503 (rlet1 v (make-u8vector 6 0)
30504 (uvector-copy! v 1 '#u32(0 #x01020304 0) 1 2))
30505 @result{} #u8(0 1 2 3 4 0) or #u8(0 4 3 2 1 0)
30506 @end example
30507 @end defun
30508
30509
30510 @deffn {Function} @@vector-append vec @dots{}
30511 @findex u8vector-append
30512 @findex s8vector-append
30513 @findex u16vector-append
30514 @findex s16vector-append
30515 @findex u32vector-append
30516 @findex s32vector-append
30517 @findex u64vector-append
30518 @findex s64vector-append
30519 @findex f16vector-append
30520 @findex f32vector-append
30521 @findex f64vector-append
30522 @findex c32vector-append
30523 @findex c64vector-append
30524 @findex c128vector-append
30525 [R7RS vector.@@]
30526 @c MOD gauche.uvector
30527 @c EN
30528 All arguments must be @@vectors. Returns a fresh vector
30529 whose contents are concatenation of the given vectors.
30530 (It returns a fresh vector even there's only one argument).
30531 @c JP
30532 引数はすべて@@vectorでなければなりません。
30533 引数ベクタの内容を全てつなぎ合わせた新たなベクタを返します。
30534 (引数が一つだけの場合も、新たにアロケートされたベクタが返されます。)
30535 @c COMMON
30536
30537 @example
30538 (u8vector-append '#u8(1 2 3) '#u8(4 5) '#u8() '#u8(6 7 8))
30539 @result{} #u8(1 2 3 4 5 6 7 8)
30540 @end example
30541 @end deffn
30542
30543 @deffn {Function} @@vector-concatenate vecs
30544 @findex u8vector-concatenate
30545 @findex s8vector-concatenate
30546 @findex u16vector-concatenate
30547 @findex s16vector-concatenate
30548 @findex u32vector-concatenate
30549 @findex s32vector-concatenate
30550 @findex u64vector-concatenate
30551 @findex s64vector-concatenate
30552 @findex f16vector-concatenate
30553 @findex f32vector-concatenate
30554 @findex f64vector-concatenate
30555 @findex c32vector-concatenate
30556 @findex c64vector-concatenate
30557 @findex c128vector-concatenate
30558 [R7RS vector.@@]
30559 @c MOD gauche.uvector
30560 @c EN
30561 Returns a new @@vector which is concatenation of the list of
30562 @@vectors @var{vecs}.
30563 @c JP
30564 @@vectorのリスト@var{vecs}にあるベクタを全て連結した新たな
30565 @@vectorを返します。
30566 @c COMMON
30567 @example
30568 (u8vector-concatenate '(#u8(1 2 3) #u8(4 5 6)))
30569 @result{} #u8(1 2 3 4 5 6)
30570 @end example
30571 @end deffn
30572
30573 @deffn {Function} @@vector-append-subvectors :optional vec start end @dots{}
30574 @findex u8vector-append-subvectors
30575 @findex s8vector-append-subvectors
30576 @findex u16vector-append-subvectors
30577 @findex s16vector-append-subvectors
30578 @findex u32vector-append-subvectors
30579 @findex s32vector-append-subvectors
30580 @findex u64vector-append-subvectors
30581 @findex s64vector-append-subvectors
30582 @findex f16vector-append-subvectors
30583 @findex f32vector-append-subvectors
30584 @findex f64vector-append-subvectors
30585 @findex c32vector-append-subvectors
30586 @findex c64vector-append-subvectors
30587 @findex c128vector-append-subvectors
30588 [R7RS vector.@@]
30589 @c MOD gauche.uvector
30590 @c EN
30591 Returns a new @@vector which is concatenation of the subvectors of
30592 given @var{vec}s, using accompanied @var{start} and @var{end} index.
30593 @c JP
30594 各@var{vec}の@var{start}と@var{end}で指定される範囲のサブベクタを
30595 連結した新たな@@vectorを返します。
30596 @c COMMON
30597 @example
30598 (u8vector-append-subvectors '#u8(1 2 3 4) 1 3 '#u8(5 6 7 8) 0 2)
30599 @result{} #u8(2 3 5 6)
30600 @end example
30601 @end deffn
30602
30603 @deffn {Function} @@vector-take vec n
30604 @deffnx {Function} @@vector-take-right vec n
30605 @deffnx {Function} @@vector-drop vec n
30606 @deffnx {Function} @@vector-drop-right vec n
30607 @findex u8vector-take
30608 @findex s8vector-take
30609 @findex u16vector-take
30610 @findex s16vector-take
30611 @findex u32vector-take
30612 @findex s32vector-take
30613 @findex u64vector-take
30614 @findex s64vector-take
30615 @findex f16vector-take
30616 @findex f32vector-take
30617 @findex f64vector-take
30618 @findex c32vector-take
30619 @findex c64vector-take
30620 @findex c128vector-take
30621 @findex u8vector-take-right
30622 @findex s8vector-take-right
30623 @findex u16vector-take-right
30624 @findex s16vector-take-right
30625 @findex u32vector-take-right
30626 @findex s32vector-take-right
30627 @findex u64vector-take-right
30628 @findex s64vector-take-right
30629 @findex f16vector-take-right
30630 @findex f32vector-take-right
30631 @findex f64vector-take-right
30632 @findex c32vector-take-right
30633 @findex c64vector-take-right
30634 @findex c128vector-take-right
30635 @findex u8vector-drop
30636 @findex s8vector-drop
30637 @findex u16vector-drop
30638 @findex s16vector-drop
30639 @findex u32vector-drop
30640 @findex s32vector-drop
30641 @findex u64vector-drop
30642 @findex s64vector-drop
30643 @findex f16vector-drop
30644 @findex f32vector-drop
30645 @findex f64vector-drop
30646 @findex c32vector-drop
30647 @findex c64vector-drop
30648 @findex c128vector-drop
30649 @findex u8vector-drop-right
30650 @findex s8vector-drop-right
30651 @findex u16vector-drop-right
30652 @findex s16vector-drop-right
30653 @findex u32vector-drop-right
30654 @findex s32vector-drop-right
30655 @findex u64vector-drop-right
30656 @findex s64vector-drop-right
30657 @findex f16vector-drop-right
30658 @findex f32vector-drop-right
30659 @findex f64vector-drop-right
30660 @findex c32vector-drop-right
30661 @findex c64vector-drop-right
30662 @findex c128vector-drop-right
30663 [R7RS vector.@@]
30664 @c MOD gauche.uvector
30665 @c EN
30666 Returns a new uvector that has the first @var{n} elements,
30667 the last @var{n} elements, the elements without the first @var{n} elements,
30668 and the elements without the last @var{n} elements, respectively.
30669
30670 @var{N} must be a nonnegative exact integer no greater than the
30671 length of @var{vec}.
30672 @c JP
30673 それぞれ、最初の@var{n}要素、最後の@var{n}要素、最初の@var{n}要素を取り残り、
30674 および最後の@var{n}要素を取り除いた残り、を要素とするuvectorを作って返します。
30675
30676 @var{n}は非負の正確な整数で、@var{vec}の長さを越えてはいけません。
30677 @c COMMON
30678
30679 @example
30680 (u8vector-take '#u8(0 1 2 3 4 5) 4) @result{} #u8(0 1 2 3)
30681 (u8vector-drop '#u8(0 1 2 3 4 5) 4) @result{} #u8(4 5)
30682
30683 (u8vector-take-right '#u8(0 1 2 3 4 5) 4) @result{} #u8(2 3 4 5)
30684 (u8vector-drop-right '#u8(0 1 2 3 4 5) 4) @result{} #u8(0 1)
30685 @end example
30686
30687 @c EN
30688 You can also use @code{uvector-alias} to obtain a partial uvector
30689 that shares the storage with the original uvector, avoiding copying overhead.
30690 @c JP
30691 なお、@code{uvector-alias}を使うと、元のuvectorと記憶領域を共有する
30692 部分的なuvectorを得ることができます。コピーのオーバヘッドを避けることができます。
30693 @c COMMON
30694 @end deffn
30695
30696 @deffn {Function} @@vector-segment vec n
30697 @findex u8vector-segment
30698 @findex s8vector-segment
30699 @findex u16vector-segment
30700 @findex s16vector-segment
30701 @findex u32vector-segment
30702 @findex s32vector-segment
30703 @findex u64vector-segment
30704 @findex s64vector-segment
30705 @findex f16vector-segment
30706 @findex f32vector-segment
30707 @findex f64vector-segment
30708 @findex c32vector-segment
30709 @findex c64vector-segment
30710 @findex c128vector-segment
30711 [R7RS vector.@@]
30712 @c MOD gauche.uvector
30713 @c EN
30714 Segment @var{vec} into fresh uvectors of length @var{n}, and returns
30715 a list of them. The last uvector may be shorter than @var{n} if the
30716 length of @var{vec} is not a multiple of @var{n}.
30717
30718 @var{N} must be a positive exact integer.
30719 @c JP
30720 @var{vec}を長さ@var{n}の新たなuvectorに分割し、そのリストを返します。
30721 @var{vec}の長さが@var{n}の倍数でなければ、最後のuvectorは@var{n}より短くなります。
30722
30723 @var{n}は正の正確な整数でなければなりません。
30724 @c COMMON
30725
30726 @example
30727 (u8vector-segment '#u8(0 1 2 3 4 5 6 7) 3)
30728 @result{} (#u8(0 1 2) #u8(3 4 5) #u8(6 7))
30729 @end example
30730 @end deffn
30731
30732 @deffn {Function} @@vector-fold kons knil vec vec2 @dots{}
30733 @deffnx {Function} @@vector-fold-right kons knil vec vec2 @dots{}
30734 @findex u8vector-fold
30735 @findex s8vector-fold
30736 @findex u16vector-fold
30737 @findex s16vector-fold
30738 @findex u32vector-fold
30739 @findex s32vector-fold
30740 @findex u64vector-fold
30741 @findex s64vector-fold
30742 @findex f16vector-fold
30743 @findex f32vector-fold
30744 @findex f64vector-fold
30745 @findex c32vector-fold
30746 @findex c64vector-fold
30747 @findex c128vector-fold
30748 @findex u8vector-unfold
30749 @findex s8vector-unfold
30750 @findex u16vector-unfold
30751 @findex s16vector-unfold
30752 @findex u32vector-unfold
30753 @findex s32vector-unfold
30754 @findex u64vector-unfold
30755 @findex s64vector-unfold
30756 @findex f16vector-unfold
30757 @findex f32vector-unfold
30758 @findex f64vector-unfold
30759 @findex c32vector-unfold
30760 @findex c64vector-unfold
30761 @findex c128vector-unfold
30762 [R7RS vector.@@]
30763 @c MOD gauche.uvector
30764 @c EN
30765 @c JP
30766 @c COMMON
30767 @end deffn
30768
30769 @deffn {Function} @@vector-unfold! f vec start end seed
30770 @deffnx {Function} @@vector-unfold-right! f vec start end seed
30771 @findex u8vector-unfold!
30772 @findex s8vector-unfold!
30773 @findex u16vector-unfold!
30774 @findex s16vector-unfold!
30775 @findex u32vector-unfold!
30776 @findex s32vector-unfold!
30777 @findex u64vector-unfold!
30778 @findex s64vector-unfold!
30779 @findex f16vector-unfold!
30780 @findex f32vector-unfold!
30781 @findex f64vector-unfold!
30782 @findex c32vector-unfold!
30783 @findex c64vector-unfold!
30784 @findex c128vector-unfold!
30785 @findex u8vector-unfod-right!
30786 @findex s8vector-unfod-right!
30787 @findex u16vector-unfod-right!
30788 @findex s16vector-unfod-right!
30789 @findex u32vector-unfod-right!
30790 @findex s32vector-unfod-right!
30791 @findex u64vector-unfod-right!
30792 @findex s64vector-unfod-right!
30793 @findex f16vector-unfod-right!
30794 @findex f32vector-unfod-right!
30795 @findex f64vector-unfod-right!
30796 @findex c32vector-unfod-right!
30797 @findex c64vector-unfod-right!
30798 @findex c128vector-unfod-right!
30799 [R7RS vector.@@]
30800 @c MOD gauche.uvector
30801 @c EN
30802 @c JP
30803 @c COMMON
30804 @end deffn
30805
30806
30807 @deffn {Function} @@vector-map f vec vec2 @dots{}
30808 @deffnx {Function} @@vector-map! f vec vec2 @dots{}
30809 @deffnx {Function} @@vector-for-each f vec vec2 @dots{}
30810 @findex u8vector-map
30811 @findex s8vector-map
30812 @findex u16vector-map
30813 @findex s16vector-map
30814 @findex u32vector-map
30815 @findex s32vector-map
30816 @findex u64vector-map
30817 @findex s64vector-map
30818 @findex f16vector-map
30819 @findex f32vector-map
30820 @findex f64vector-map
30821 @findex c32vector-map
30822 @findex c64vector-map
30823 @findex c128vector-map
30824 @findex u8vector-map!
30825 @findex s8vector-map!
30826 @findex u16vector-map!
30827 @findex s16vector-map!
30828 @findex u32vector-map!
30829 @findex s32vector-map!
30830 @findex u64vector-map!
30831 @findex s64vector-map!
30832 @findex f16vector-map!
30833 @findex f32vector-map!
30834 @findex f64vector-map!
30835 @findex c32vector-map!
30836 @findex c64vector-map!
30837 @findex c128vector-map!
30838 @findex u8vector-for-each
30839 @findex s8vector-for-each
30840 @findex u16vector-for-each
30841 @findex s16vector-for-each
30842 @findex u32vector-for-each
30843 @findex s32vector-for-each
30844 @findex u64vector-for-each
30845 @findex s64vector-for-each
30846 @findex f16vector-for-each
30847 @findex f32vector-for-each
30848 @findex f64vector-for-each
30849 @findex c32vector-for-each
30850 @findex c64vector-for-each
30851 @findex c128vector-for-each
30852 [R7RS vector.@@]
30853 @c MOD gauche.uvector
30854 @c EN
30855 @c JP
30856 @c COMMON
30857 @end deffn
30858
30859 @deffn {Function} @@vector-count pred vec vec2 @dots{}
30860 @findex u8vector-count
30861 @findex s8vector-count
30862 @findex u16vector-count
30863 @findex s16vector-count
30864 @findex u32vector-count
30865 @findex s32vector-count
30866 @findex u64vector-count
30867 @findex s64vector-count
30868 @findex f16vector-count
30869 @findex f32vector-count
30870 @findex f64vector-count
30871 @findex c32vector-count
30872 @findex c64vector-count
30873 @findex c128vector-count
30874 [R7RS vector.@@]
30875 @c MOD gauche.uvector
30876 @c EN
30877 @c JP
30878 @c COMMON
30879 @end deffn
30880
30881 @deffn {Function} @@vector-cumulate f knil vec
30882 @findex u8vector-cumulate
30883 @findex s8vector-cumulate
30884 @findex u16vector-cumulate
30885 @findex s16vector-cumulate
30886 @findex u32vector-cumulate
30887 @findex s32vector-cumulate
30888 @findex u64vector-cumulate
30889 @findex s64vector-cumulate
30890 @findex f16vector-cumulate
30891 @findex f32vector-cumulate
30892 @findex f64vector-cumulate
30893 @findex c32vector-cumulate
30894 @findex c64vector-cumulate
30895 @findex c128vector-cumulate
30896 [R7RS vector.@@]
30897 @c MOD gauche.uvector
30898 @c EN
30899 @c JP
30900 @c COMMON
30901 @end deffn
30902
30903 @deffn {Function} @@vector-take-while pred vec
30904 @deffnx {Function} @@vector-take-while-right pred vec
30905 @deffnx {Function} @@vector-drop-while pred vec
30906 @deffnx {Function} @@vector-drop-while-right pred vec
30907 @findex u8vector-take-while
30908 @findex s8vector-take-while
30909 @findex u16vector-take-while
30910 @findex s16vector-take-while
30911 @findex u32vector-take-while
30912 @findex s32vector-take-while
30913 @findex u64vector-take-while
30914 @findex s64vector-take-while
30915 @findex f16vector-take-while
30916 @findex f32vector-take-while
30917 @findex f64vector-take-while
30918 @findex c32vector-take-while
30919 @findex c64vector-take-while
30920 @findex c128vector-take-while
30921 @findex u8vector-take-while-right
30922 @findex s8vector-take-while-right
30923 @findex u16vector-take-while-right
30924 @findex s16vector-take-while-right
30925 @findex u32vector-take-while-right
30926 @findex s32vector-take-while-right
30927 @findex u64vector-take-while-right
30928 @findex s64vector-take-while-right
30929 @findex f16vector-take-while-right
30930 @findex f32vector-take-while-right
30931 @findex f64vector-take-while-right
30932 @findex c32vector-take-while-right
30933 @findex c64vector-take-while-right
30934 @findex c128vector-take-while-right
30935 @findex u8vector-drop-while
30936 @findex s8vector-drop-while
30937 @findex u16vector-drop-while
30938 @findex s16vector-drop-while
30939 @findex u32vector-drop-while
30940 @findex s32vector-drop-while
30941 @findex u64vector-drop-while
30942 @findex s64vector-drop-while
30943 @findex f16vector-drop-while
30944 @findex f32vector-drop-while
30945 @findex f64vector-drop-while
30946 @findex c32vector-drop-while
30947 @findex c64vector-drop-while
30948 @findex c128vector-drop-while
30949 @findex u8vector-drop-while-right
30950 @findex s8vector-drop-while-right
30951 @findex u16vector-drop-while-right
30952 @findex s16vector-drop-while-right
30953 @findex u32vector-drop-while-right
30954 @findex s32vector-drop-while-right
30955 @findex u64vector-drop-while-right
30956 @findex s64vector-drop-while-right
30957 @findex f16vector-drop-while-right
30958 @findex f32vector-drop-while-right
30959 @findex f64vector-drop-while-right
30960 @findex c32vector-drop-while-right
30961 @findex c64vector-drop-while-right
30962 @findex c128vector-drop-while-right
30963 [R7RS vector.@@]
30964 @c MOD gauche.uvector
30965 @c EN
30966 @c JP
30967 @c COMMON
30968 @end deffn
30969
30970 @deffn {Function} @@vector-index pred vec vec2 @dots{}
30971 @deffnx {Function} @@vector-index-right pred vec vec2 @dots{}
30972 @findex u8vector-index
30973 @findex s8vector-index
30974 @findex u16vector-index
30975 @findex s16vector-index
30976 @findex u32vector-index
30977 @findex s32vector-index
30978 @findex u64vector-index
30979 @findex s64vector-index
30980 @findex f16vector-index
30981 @findex f32vector-index
30982 @findex f64vector-index
30983 @findex c32vector-index
30984 @findex c64vector-index
30985 @findex c128vector-index
30986 @findex u8vector-index-right
30987 @findex s8vector-index-right
30988 @findex u16vector-index-right
30989 @findex s16vector-index-right
30990 @findex u32vector-index-right
30991 @findex s32vector-index-right
30992 @findex u64vector-index-right
30993 @findex s64vector-index-right
30994 @findex f16vector-index-right
30995 @findex f32vector-index-right
30996 @findex f64vector-index-right
30997 @findex c32vector-index-right
30998 @findex c64vector-index-right
30999 @findex c128vector-index-right
31000 [R7RS vector.@@]
31001 @c MOD gauche.uvector
31002 @c EN
31003 @c JP
31004 @c COMMON
31005 @end deffn
31006
31007 @deffn {Function} @@vector-skip pred vec vec2 @dots{}
31008 @deffnx {Function} @@vector-skip-right pred vec vec2 @dots{}
31009 @findex u8vector-skip
31010 @findex s8vector-skip
31011 @findex u16vector-skip
31012 @findex s16vector-skip
31013 @findex u32vector-skip
31014 @findex s32vector-skip
31015 @findex u64vector-skip
31016 @findex s64vector-skip
31017 @findex f16vector-skip
31018 @findex f32vector-skip
31019 @findex f64vector-skip
31020 @findex c32vector-skip
31021 @findex c64vector-skip
31022 @findex c128vector-skip
31023 @findex u8vector-skip-right
31024 @findex s8vector-skip-right
31025 @findex u16vector-skip-right
31026 @findex s16vector-skip-right
31027 @findex u32vector-skip-right
31028 @findex s32vector-skip-right
31029 @findex u64vector-skip-right
31030 @findex s64vector-skip-right
31031 @findex f16vector-skip-right
31032 @findex f32vector-skip-right
31033 @findex f64vector-skip-right
31034 @findex c32vector-skip-right
31035 @findex c64vector-skip-right
31036 @findex c128vector-skip-right
31037 [R7RS vector.@@]
31038 @c MOD gauche.uvector
31039 @c EN
31040 @c JP
31041 @c COMMON
31042 @end deffn
31043
31044 @deffn {Function} @@vector-any pred vec vec2 @dots{}
31045 @deffnx {Function} @@vector-every pred vec vec2 @dots{}
31046 @findex u8vector-any
31047 @findex s8vector-any
31048 @findex u16vector-any
31049 @findex s16vector-any
31050 @findex u32vector-any
31051 @findex s32vector-any
31052 @findex u64vector-any
31053 @findex s64vector-any
31054 @findex f16vector-any
31055 @findex f32vector-any
31056 @findex f64vector-any
31057 @findex c32vector-any
31058 @findex c64vector-any
31059 @findex c128vector-any
31060 @findex u8vector-every
31061 @findex s8vector-every
31062 @findex u16vector-every
31063 @findex s16vector-every
31064 @findex u32vector-every
31065 @findex s32vector-every
31066 @findex u64vector-every
31067 @findex s64vector-every
31068 @findex f16vector-every
31069 @findex f32vector-every
31070 @findex f64vector-every
31071 @findex c32vector-every
31072 @findex c64vector-every
31073 @findex c128vector-every
31074 [R7RS vector.@@]
31075 @c MOD gauche.uvector
31076 @c EN
31077 @c JP
31078 @c COMMON
31079 @end deffn
31080
31081 @deffn {Function} @@vector-partition pred vec
31082 @findex u8vector-partition
31083 @findex s8vector-partition
31084 @findex u16vector-partition
31085 @findex s16vector-partition
31086 @findex u32vector-partition
31087 @findex s32vector-partition
31088 @findex u64vector-partition
31089 @findex s64vector-partition
31090 @findex f16vector-partition
31091 @findex f32vector-partition
31092 @findex f64vector-partition
31093 @findex c32vector-partition
31094 @findex c64vector-partition
31095 @findex c128vector-partition
31096 [R7RS vector.@@]
31097 @c MOD gauche.uvector
31098 @c EN
31099 @c JP
31100 @c COMMON
31101 @end deffn
31102
31103 @deffn {Function} @@vector-filter pred vec
31104 @deffnx {Function} @@vector-remove pred vec
31105 @findex u8vector-filter
31106 @findex s8vector-filter
31107 @findex u16vector-filter
31108 @findex s16vector-filter
31109 @findex u32vector-filter
31110 @findex s32vector-filter
31111 @findex u64vector-filter
31112 @findex s64vector-filter
31113 @findex f16vector-filter
31114 @findex f32vector-filter
31115 @findex f64vector-filter
31116 @findex c32vector-filter
31117 @findex c64vector-filter
31118 @findex c128vector-filter
31119 @findex u8vector-remove
31120 @findex s8vector-remove
31121 @findex u16vector-remove
31122 @findex s16vector-remove
31123 @findex u32vector-remove
31124 @findex s32vector-remove
31125 @findex u64vector-remove
31126 @findex s64vector-remove
31127 @findex f16vector-remove
31128 @findex f32vector-remove
31129 @findex f64vector-remove
31130 @findex c32vector-remove
31131 @findex c64vector-remove
31132 @findex c128vector-remove
31133 [R7RS vector.@@]
31134 @c MOD gauche.uvector
31135 @c EN
31136 @c JP
31137 @c COMMON
31138 @end deffn
31139
31140
31141 @deffn {Function} make-@@vector-generator vec
31142 @findex make-u8vector-generator
31143 @findex s8ke-u8vector-generator
31144 @findex u16ke-u8vector-generator
31145 @findex s16ke-u8vector-generator
31146 @findex u32ke-u8vector-generator
31147 @findex s32ke-u8vector-generator
31148 @findex u64ke-u8vector-generator
31149 @findex s64ke-u8vector-generator
31150 @findex f16ke-u8vector-generator
31151 @findex f32ke-u8vector-generator
31152 @findex f64ke-u8vector-generator
31153 @findex c32ke-u8vector-generator
31154 @findex c64ke-u8vector-generator
31155 @findex c128ke-u8vector-generator
31156 [R7RS vector.@@]
31157 @c MOD gauche.uvector
31158 @c EN
31159 @c JP
31160 @c COMMON
31161 @end deffn
31162
31163
31164 @defvar @@vector-comparator
31165 @vindex u8vector-comparator
31166 @vindex s8vector-comparator
31167 @vindex u16vector-comparator
31168 @vindex s16vector-comparator
31169 @vindex u32vector-comparator
31170 @vindex s32vector-comparator
31171 @vindex u64vector-comparator
31172 @vindex s64vector-comparator
31173 @vindex f16vector-comparator
31174 @vindex f32vector-comparator
31175 @vindex f64vector-comparator
31176 @vindex c32vector-comparator
31177 @vindex c64vector-comparator
31178 @vindex c128vector-comparator
31179 [R7RS vector.@@]
31180 @c MOD gauche.uvector
31181 @c EN
31182 Bound to comparators that can compare two @code{@@vector}s and
31183 to hash a @code{@@vector}. @xref{Basic comparators}, for the details
31184 of comparators. These comparators both provides ordering predicate
31185 and hash function.
31186 @c JP
31187 ふたつの@code{@@vector}を比較したり、@code{@@vector}のハッシュを取ったりできる
31188 比較器に束縛された変数です。比較器の詳細については
31189 @ref{Basic comparators}を参照してください。
31190 これらの比較器は順序手続きとハッシュ関数を両方とも実装しています。
31191 @c COMMON
31192 @end defvar
31193
31194
31195 @defun uvector-binary-search uvector key :optional start end skip rounding
31196 @c MOD gauche.uvector
31197 @c EN
31198 The @code{uvector} must contain values in increasing order.
31199 This procedure finds the index of an element that is equal to @var{key},
31200 using binary search. If such element can't be found, @code{#f} is returned.
31201 @c JP
31202 @var{uvector}は値が昇順に格納されたユニフォームベクタでなければなりません。
31203 この手続きは二分探索を使って、@var{key}と一致する要素を探し、そのインデックスを返します。
31204 一致する要素が無ければ@code{#f}が返されます。
31205 @c COMMON
31206
31207 @example
31208 (uvector-binary-search '#u8(0 5 19 32 58 96) 32)
31209 @result{} 3
31210
31211 (uvector-binary-search '#u8(0 5 19 32 58 96) 33)
31212 @result{} #f
31213 @end example
31214
31215 @c EN
31216 The optional @var{start} and @var{end} arguments limits the portion
31217 of @var{uvector} to search; @var{start} specifies starting index (inclusive)
31218 and @var{end} specifies ending index (exclusive).
31219 Passing @code{#f} indicates the default
31220 value (0 for @var{start}, the length of the vector for @var{end}).
31221 The returned index is the actual index of the vector, but the elements
31222 outside of @var{start}-@var{end} range don't need to be sorted.
31223 @c JP
31224 省略可能引数@var{start}と@var{end}は@var{uvector}中の探すべき部分を制限します。
31225 @var{start}が開始インデックス(その要素も含む)、@var{end}が終了インデックス
31226 (その要素自体は含まない)です。
31227 @code{#f}を渡すとデフォルト値(@var{start}は0、@var{end}はベクタの長さ)と
31228 みなされます。返ってくるインデックスはベクタ全体から見たインデックスになりますが、
31229 @var{start}-@var{end}間以外の@var{uvector}の要素はソートされている必要はありません。
31230
31231 @c COMMON
31232
31233 @example
31234 (uvector-binary-search '#u8(99 99 19 32 58 99) 32 2 5)
31235 @result{} 3
31236
31237 (uvector-binary-search '#u8(99 99 19 32 58 99) 99 2 5)
31238 @result{} #f
31239 @end example
31240
31241 @c EN
31242 The optional @var{skip} argument must be a nonnegative exact integer
31243 or @code{#f}. If it is a positive integer, the number of elements after
31244 every key in the @var{uvector} is ignored. For example, if @var{skip} is 2
31245 and @var{uvector} is @code{#u8(3 100 101 5 102 103 13 104 105)},
31246 only @code{3}, @code{5} and @code{13} are subject to search, and elements
31247 inbetween are ignored. This allows the caller to store @emph{payload},
31248 or associated value to each key, in the @var{uvector} itself.
31249 If @var{skip} is positive integer, the length of the searched portion
31250 of @var{uvector} must be a multiple of the record size (@var{skip}+1).
31251 @c JP
31252 省略可能な@var{skip}引数は、非負の正確な整数か@code{#f}でなければなりません。
31253 @var{skip}が正の整数の場合、@var{uvector}中の各キーに続く@var{skip}個の要素を
31254 飛ばして探索します。例えば@var{skip}が2で@var{uvector}が
31255 @code{#u8(3 100 101 5 102 103 13 104 105)}であれば、
31256 @code{3}、@code{5}、@code{13}だけが探索の対象となります。
31257 この機能を使うと、キーに結びつけられた値(ペイロード)を@var{uvector}中に直接
31258 格納したまま探索を行うことができます。@var{skip}が正の整数の場合、
31259 @var{uvector}の探索が行われる部分の大きさは@var{skip}+1の整数倍でなければなりません。
31260 @c COMMON
31261
31262 @example
31263 (uvector-binary-search '#u8(3 100 101 5 102 103 13 104 105) 13 #f #f 2)
31264 @result{} 6
31265
31266 (uvector-binary-search '#u8(3 100 101 5 102 103 13 104) 13 #f #f 2)
31267 @result{} ; @r{Error: uvector size (8) isn't multiple of record size (3)}
31268 @end example
31269
31270 @c EN
31271 Finally, @var{rounding} argument adjusts the behavior when the exact
31272 match isn't found. It can be either one of the following values:
31273 @c JP
31274 最後に、@var{rounding}引数は一致する要素が見つからなかった場合の振る舞いを
31275 調整します。値は以下のいずれかでなければなりません。
31276 @c COMMON
31277
31278 @table @asis
31279 @item @code{#f}
31280 @c EN
31281 This is the default.
31282 The procedure searches the element that is equal to @var{key}, and
31283 returns @code{#f} if such element isn't found.
31284 @c JP
31285 これがデフォルトです。@var{key}と等しい要素だけを探し、
31286 見つからなければ@code{#f}を返します。
31287 @c COMMON
31288 @item a symbol @code{floor}
31289 @c EN
31290 When the exact match isn't found, the procedure
31291 returns an index of the element that's closest to but
31292 not greater than @var{key}. If @var{key} is smaller than all the elements,
31293 @code{#f} is returned.
31294 @c JP
31295 @var{key}と等しい要素がみつからなかった場合、@var{key}を越えない、もっとも近い
31296 要素のインデックスを返します。@var{key}がどの要素よりも小さい場合は@code{#f}が
31297 返されます。
31298 @c COMMON
31299 @item a symbol @code{ceiling}
31300 @c EN
31301 When the exact match isn't found, the procedure
31302 returns an index of the element that's closest to but
31303 not smaller than @var{key}. If @var{key} is greater than all the elements,
31304 @code{#f} is returned.
31305 @c JP
31306 @var{key}と等しい要素がみつからなかった場合、@var{key}を下回らない、もっとも近い
31307 要素のインデックスを返します。@var{key}がどの要素よりも大きい場合は@code{#f}が
31308 返されます。
31309 @c COMMON
31310 @end table
31311
31312 @example
31313 (uvector-binary-search '#u32(1 10 100 1000 10000) 3757)
31314 @result{} #f
31315
31316 (uvector-binary-search '#u32(1 10 100 1000 10000) 3757 #f #f #f 'floor)
31317 @result{} 3
31318
31319 (uvector-binary-search '#u32(1 10 100 1000 10000) 3757 #f #f #f 'ceiling)
31320 @result{} 4
31321 @end example
31322
31323 @c EN
31324 Note: SRFI-133 has @code{vector-binary-search}, which is quite similar to
31325 this procedure (@pxref{R7RS vectors}) but it requires comparison
31326 procedure, for it needs to compare general Scheme values. And it
31327 does not support @var{skip} and @var{rounding} arguments.
31328 @c JP
31329 註: SRFI-133の@code{vector-binary-search}はこの手続きと良く似ています
31330 (@ref{R7RS vectors}参照)。ただし、
31331 そちらは一般のScheme値を相手にするために、比較手続きも取ります。
31332 また@var{skip}と@var{rounding}引数の機能はサポートされません。
31333 @c COMMON
31334 @end defun
31335
31336 @node Uvector conversion operations, Uvector numeric operations, Uvector basic operations, Uniform vector library
31337 @subsection Uvector conversion operations
31338 @c NODE ユニフォームベクタの変換
31339
31340 @deffn {Function} @@vector->list vec :optional start end
31341 @findex u8vector->list
31342 @findex s8vector->list
31343 @findex u16vector->list
31344 @findex s16vector->list
31345 @findex u32vector->list
31346 @findex s32vector->list
31347 @findex u64vector->list
31348 @findex s64vector->list
31349 @findex f16vector->list
31350 @findex f32vector->list
31351 @findex f64vector->list
31352 @findex c32vector->list
31353 @findex c64vector->list
31354 @findex c128vector->list
31355 [R7RS vector.@@]
31356 @c MOD gauche.uvector
31357 @c EN
31358 Converts @@vector @var{vec} to a list.
31359 If @var{start} and/or @var{end} are given, they limit the range of
31360 @var{vec} to be extracted.
31361
31362 Note that the generic function @code{coerce-to} can be used as well,
31363 if you import @code{gauche.collection}.
31364 @c JP
31365 @@vector @var{vec}をリストに変換します。
31366 省略可能な引数@var{start}と@var{end}が与えられた場合、
31367 それらは取り出される要素の範囲を制限します。
31368
31369 モジュール@code{gauche.collection}をインポートしていれば、
31370 総称関数@code{coerce-to}を使うこともできます。
31371 @c COMMON
31372 @example
31373 (u32vector->list '#u32(9 2 5)) @result{} (9 2 5)
31374
31375 (use gauche.collection)
31376 (coerce-to <list> '#u32(9 2 5)) @result{} (9 2 5)
31377 @end example
31378 @end deffn
31379
31380 @defun uvector->list uvec :optional start end
31381 @c MOD gauche.uvector
31382 @c EN
31383 This is a generic version of @code{@@vector->list}.
31384 It can take any kind of uvector as @var{uvec}. The meaning of
31385 optional arguments are the same as @code{@@vector->list}.
31386 @c JP
31387 これは@code{@@vector->list}の汎用バージョンで、
31388 ユニフォームベクタなら何であれ@var{uvec}に取ることができます。
31389 省略可能引数の意味は@code{@@vector->list}と同じです。
31390 @c COMMON
31391 @end defun
31392
31393
31394 @deffn {Function} @@vector->vector vec :optional start end
31395 @findex u8vector->vector
31396 @findex s8vector->vector
31397 @findex u16vector->vector
31398 @findex s16vector->vector
31399 @findex u32vector->vector
31400 @findex s32vector->vector
31401 @findex u64vector->vector
31402 @findex s64vector->vector
31403 @findex f16vector->vector
31404 @findex f32vector->vector
31405 @findex f64vector->vector
31406 @findex c32vector->vector
31407 @findex c64vector->vector
31408 @findex c128vector->vector
31409 [R7RS vector.@@]
31410 @c MOD gauche.uvector
31411 @c EN
31412 Converts @@vector @var{vec} to a vector.
31413 If @var{start} and/or @var{end} are given, they limit the range of
31414 @var{vec} to be copied.
31415
31416 Note that the generic function @code{coerce-to} can be used as well,
31417 if you import @code{gauche.collection}.
31418 @c JP
31419 @@vector @var{vec}をベクタに変換します。
31420 省略可能な引数@var{start}と@var{end}が与えられた場合、
31421 それらは取り出される要素の範囲を制限します。
31422
31423 モジュール@code{gauche.collection}をインポートしていれば、
31424 総称関数@code{coerce-to}を使うこともできます。
31425 @c COMMON
31426 @example
31427 (f32vector->vector '#f32(9.3 2.2 5.5)) @result{} #(9.3 2.2 5.5)
31428 (f32vector->vector '#f32(9.3 2.2 5.5) 2) @result{} #(5.5)
31429
31430 (use gauche.collection)
31431 (coerce-to <vector> '#f32(9.3 2.2 5.5)) @result{} #(9.3 2.2 5.5)
31432 @end example
31433 @end deffn
31434
31435 @defun uvector->vector uvec :optional start end
31436 @c MOD gauche.uvector
31437 @c EN
31438 This is a generic version of @code{@@vector->vector}.
31439 It can take any kind of uvector as @var{uvec}. The meaning of
31440 optional arguments are the same as @code{@@vector->vector}.
31441 @c JP
31442 これは@code{@@vector->vector}の汎用バージョンで、
31443 ユニフォームベクタなら何であれ@var{uvec}に取ることができます。
31444 省略可能引数の意味は@code{@@vector->vector}と同じです。
31445 @c COMMON
31446 @end defun
31447
31448 @deffn {Function} list->@@vector list :optional clamp
31449 @findex list->s8vector
31450 @findex list->u8vector
31451 @findex list->s16vector
31452 @findex list->u16vector
31453 @findex list->s32vector
31454 @findex list->u32vector
31455 @findex list->s64vector
31456 @findex list->u64vector
31457 @findex list->f16vector
31458 @findex list->f32vector
31459 @findex list->f64vector
31460 @findex list->c32vector
31461 @findex list->c64vector
31462 @findex list->c128vector
31463 [R7RS vector.@@]
31464 @c MOD gauche.uvector
31465 @c EN
31466 Converts a list @var{list} to a @@vector.
31467 Optional argument @var{clamp} specifies the behavior when
31468 the element of @var{list} is out of the valid range.
31469 (The @var{clamp} argument is Gauche's extension.)
31470
31471 Note that the generic function @code{coerce-to} can be used as well,
31472 if you import @code{gauche.collection}.
31473 @c JP
31474 リスト@var{list}を@@vectorに変換します。
31475 省略可能な引数@var{clamp}が、リスト内の要素が正しい範囲外の数であった場合の
31476 動作を指定します。
31477 (@var{clamp}引数はGauche独自拡張です。)
31478
31479 モジュール@code{gauche.collection}をインポートしていれば、
31480 総称関数@code{coerce-to}を使うこともできます。
31481 @c COMMON
31482 @example
31483 (list->s64vector '(9 2 5)) @result{} #s64(9 2 5)
31484
31485 (use gauche.collection)
31486 (coerce-to <s64vector> '(9 2 5)) @result{} #s64(9 2 5)
31487 @end example
31488 @end deffn
31489
31490 @deffn {Function} reverse-list->@@vector list :optional clamp
31491 @findex reverse-list->s8vector
31492 @findex reverse-list->u8vector
31493 @findex reverse-list->s16vector
31494 @findex reverse-list->u16vector
31495 @findex reverse-list->s32vector
31496 @findex reverse-list->u32vector
31497 @findex reverse-list->s64vector
31498 @findex reverse-list->u64vector
31499 @findex reverse-list->f16vector
31500 @findex reverse-list->f32vector
31501 @findex reverse-list->f64vector
31502 @findex reverse-list->c32vector
31503 @findex reverse-list->c64vector
31504 @findex reverse-list->c128vector
31505 [R7RS vector.@@]
31506 @c MOD gauche.uvector
31507 @c EN
31508 Create a new @code{@@vector} with the elements of @var{list} in
31509 reverse order.
31510 Optional argument @var{clamp} specifies the behavior when
31511 the element of @var{list} is out of the valid range.
31512 (The @var{clamp} argument is Gauche's extension.)
31513 @c JP
31514 @var{list}の要素を逆順に持つ新たな@code{@@vector}を作って返します。
31515 省略可能な引数@var{clamp}が、リスト内の要素が正しい範囲外の数であった場合の
31516 動作を指定します。
31517 (@var{clamp}引数はGauche独自拡張です。)
31518 @c COMMON
31519 @end deffn
31520
31521
31522 @deffn {Function} vector->@@vector vec :optional start end clamp
31523 @findex vector->s8vector
31524 @findex vector->u8vector
31525 @findex vector->s16vector
31526 @findex vector->u16vector
31527 @findex vector->s32vector
31528 @findex vector->u32vector
31529 @findex vector->s64vector
31530 @findex vector->u64vector
31531 @findex vector->f16vector
31532 @findex vector->f32vector
31533 @findex vector->f64vector
31534 @findex vector->c32vector
31535 @findex vector->c64vector
31536 @findex vector->c128vector
31537 [R7RS vector.@@]
31538 @c MOD gauche.uvector
31539 @c EN
31540 Converts a vector @var{vec} to a @@vector.
31541 If @var{start} and/or @var{end} are given, they limit the range of
31542 @var{vec} to be copied.
31543 Optional argument @var{clamp} specifies the behavior when
31544 the element of @var{vec} is out of the valid range.
31545 (The @var{clamp} argument is Gauche's extension.)
31546
31547 Note that the generic function @code{coerce-to} can be used as well,
31548 if you import @code{gauche.collection}.
31549 @c JP
31550 ベクタ@var{vec}を@@vectorに変換します。
31551 省略可能な引数@var{start}と@var{end}が与えられた場合、
31552 それらは取り出される要素の範囲を制限します。
31553 省略可能な引数@var{clamp}が、ベクタ内の要素が正しい範囲外の数であった場合の
31554 動作を指定します。
31555 (@var{clamp}引数はGauche独自拡張です。)
31556
31557 モジュール@code{gauche.collection}をインポートしていれば、
31558 総称関数@code{coerce-to}を使うこともできます。
31559 @c COMMON
31560 @example
31561 (vector->f64vector '#(3.1 5.4 3.2)) @result{} #f64(3.1 5.4 3.2)
31562
31563 (use gauche.collection)
31564 (coerce-to <f64vector> '#(3.1 5.4 3.2)) @result{} #f64(3.1 5.4 3.2)
31565 @end example
31566 @end deffn
31567
31568 @defun uvector-alias uvector-class vec :optional start end
31569 @c MOD gauche.uvector
31570 @c EN
31571 This procedure creates an uvector of class @var{uvector-class}
31572 that shares the storage of the given uniform vector @var{vec}.
31573 If optional @var{start} and @var{end} arguments are given,
31574 only the specified range of @var{vec} is used for the new vector.
31575 Since the storage is shared, modification of the original vector
31576 can be seen from the new vector, or vice versa.
31577 @c JP
31578 この手続きは、クラスが@var{uvector-class}であり、
31579 ユニフォームベクタ@var{vec}のメモリ領域を共有するような
31580 新しいユニフォームベクタを作成して返します。
31581 省略可能な引数@var{start}と@var{end}が与えられた場合は
31582 @var{vec}の内容のうちそれらのインデックスで指定される範囲のみが使われます。
31583 メモリ領域が共有されているので、@var{vec}に加える変更は
31584 新しいベクタから見えますし、その逆も可能です。
31585 @c COMMON
31586
31587 @c EN
31588 The class @var{uvector-class} must be either one of the uniform
31589 vector class, but is not necessary match the class of the
31590 source vector @var{vec}. In such case, the new vector looks at the same
31591 region of @var{vec}'s memory, but interprets it differently.
31592 For example, the following code determines whether Gauche
31593 is running on big-endian or little-endian machine:
31594 @c JP
31595 クラス@var{uvector-class}はユニフォームベクタのクラスでなければなりませんが、
31596 @var{vec}のクラスと一致している必要はありません。
31597 そのような場合は、新しいベクタは@var{vec}と同じメモリ領域の値を
31598 異なる値と解釈するかもしれません。
31599 例えば、次のコードはGaucheが走っているマシンが
31600 リトルエンディアンであるかビッグエンディアンであるかを判定します。
31601 @c COMMON
31602
31603 @example
31604 (let ((u8v (uvector-alias <u8vector> #u32(1))))
31605 (if (zero? (u8vector-ref u8v 0))
31606 'big-endian
31607 'little-endian))
31608 @end example
31609
31610 @c EN
31611 If the @var{uvector-class} is other than s8vector or u8vector,
31612 the region the new vector points has to meet the alignment
31613 requirement. You can assume the beginning of the source vector
31614 is aligned suitable for any uniform vectors. So, for example,
31615 if you're creating u32vector from u8vector, the @var{start} and
31616 @var{end} must be multiple of 4 (or, if they're omitted, the length
31617 of the original u8vector must be multiple of 4).
31618 An error is signaled when the given parameters doesn't satisfy
31619 alignment constraint.
31620 @c JP
31621 @var{uvector-class}がs8vectorかu8vector以外の場合、
31622 新しいベクタが指す領域は、そのベクタの要素のアラインメントの要請に
31623 したがっていなければなりません。
31624 ユニフォームベクタの開始点は常に全てのユニフォームベクタのアラインメント要請を
31625 満たします。したがって、例えばu8vectorからu32vectorを作成する場合、
31626 @var{start}および@var{end}は4の倍数でなければなりません
31627 (あるいは、@var{start}/@var{end}が省略された場合、@var{vec}の長さが
31628 4の倍数でなければなりません)。
31629 与えられたパラメータでアラインメントの要請が満たせない場合はエラーが通知されます。
31630 @c COMMON
31631 @end defun
31632
31633
31634
31635
31636 @node Uvector numeric operations, Uvector block I/O, Uvector conversion operations, Uniform vector library
31637 @subsection Uvector numeric operations
31638 @c NODE ユニフォームベクタの数値演算
31639
31640 @c EN
31641 These are Gauche extension that allows faster arithmetic over uniform
31642 vectors, than extracting and calculating element-wise values.
31643
31644 Most procedures comes with two flavors, a functional version (without @code{!}
31645 in the name) and a linear-update version (with @code{!} in the name).
31646
31647 A functional version assumes the caller treats the arguments and
31648 results immutable objects; mutating them later could have unexpected
31649 consequences. (Notably, the functional version may return one of its
31650 arguments as is, or returns a pre-computed value,
31651 so you shouldn't assume the return values are freshly
31652 allocated objects, unless it is noted so explicitly.)
31653
31654 A linear update version may reuse the storage of the designated
31655 argument to produce the return value. Gauche tries to reuse the
31656 argument as much as possible, but you should always use the return
31657 value and shouldn't assume the argument itself is modified in-place.
31658 In fact, after calling linear-updating procedure, you can't use
31659 the argument that may be modified, since you can't assume the state
31660 of the object after calling the procedure.
31661 @c JP
31662 ここに上げる手続きはGaucheの拡張で、
31663 ユニフォームベクタ全体に渡る演算を、要素ごとに計算するよりも速く行います。
31664
31665 ほとんどの手続きには関数型バージョン(名前に@code{!}の無いもの)と
31666 線形更新バージョン(名前に@code{!}のついたもの)の二つが用意されています。
31667
31668 関数型バージョンは、呼び出し元が引数と戻り値を変更不可なオブジェクトとして
31669 扱うことを期待します。後からそれらを変更することは予想外の結果を引き起こすかも
31670 しれません(特に、関数型バージョンでは引数に渡されたオブジェクトをそのまま
31671 返したり、既に計算済みの値を返したりする可能性もあるので、
31672 特に記述されてなければ、戻り値が常に新たにアロケートされたものであると考えてはいけません。)
31673
31674 線形更新バージョンは、結果を作るために特定の引数のメモリを再利用する可能性が
31675 あります。Gaucheではアロケーションを最小化するようにできるだけメモリの再利用をしますが、
31676 引数がその場で変更されていることをあてにしてはいけません。必ず戻り値を利用するように
31677 してください。
31678 変更され得る引数については、呼び出し後にそれがどういう状態になっているかは定義されません。
31679 @c COMMON
31680
31681 @deffn {Function} @@vector-add vec val :optional clamp
31682 @deffnx {Function} @@vector-add! vec val :optional clamp
31683 @deffnx {Function} @@vector-sub vec val :optional clamp
31684 @deffnx {Function} @@vector-sub! vec val :optional clamp
31685 @deffnx {Function} @@vector-mul vec val :optional clamp
31686 @deffnx {Function} @@vector-mul! vec val :optional clamp
31687 @findex s8vector-add
31688 @findex s8vector-add!
31689 @findex s8vector-sub
31690 @findex s8vector-sub!
31691 @findex s8vector-mul
31692 @findex s8vector-mul!
31693 @findex u8vector-add
31694 @findex u8vector-add!
31695 @findex u8vector-sub
31696 @findex u8vector-sub!
31697 @findex u8vector-mul
31698 @findex u8vector-mul!
31699 @findex s16vector-add
31700 @findex s16vector-add!
31701 @findex s16vector-sub
31702 @findex s16vector-sub!
31703 @findex s16vector-mul
31704 @findex s16vector-mul!
31705 @findex u16vector-add
31706 @findex u16vector-add!
31707 @findex u16vector-sub
31708 @findex u16vector-sub!
31709 @findex u16vector-mul
31710 @findex u16vector-mul!
31711 @findex s32vector-add
31712 @findex s32vector-add!
31713 @findex s32vector-sub
31714 @findex s32vector-sub!
31715 @findex s32vector-mul
31716 @findex s32vector-mul!
31717 @findex u32vector-add
31718 @findex u32vector-add!
31719 @findex u32vector-sub
31720 @findex u32vector-sub!
31721 @findex u32vector-mul
31722 @findex u32vector-mul!
31723 @findex s64vector-add
31724 @findex s64vector-add!
31725 @findex s64vector-sub
31726 @findex s64vector-sub!
31727 @findex s64vector-mul
31728 @findex s64vector-mul!
31729 @findex u64vector-add
31730 @findex u64vector-add!
31731 @findex u64vector-sub
31732 @findex u64vector-sub!
31733 @findex u64vector-mul
31734 @findex u64vector-mul!
31735 @findex f16vector-add
31736 @findex f16vector-add!
31737 @findex f16vector-sub
31738 @findex f16vector-sub!
31739 @findex f16vector-mul
31740 @findex f16vector-mul!
31741 @findex f32vector-add
31742 @findex f32vector-add!
31743 @findex f32vector-sub
31744 @findex f32vector-sub!
31745 @findex f32vector-mul
31746 @findex f32vector-mul!
31747 @findex f64vector-add
31748 @findex f64vector-add!
31749 @findex f64vector-sub
31750 @findex f64vector-sub!
31751 @findex f64vector-mul
31752 @findex f64vector-mul!
31753 @findex c32vector-add
31754 @findex c32vector-add!
31755 @findex c32vector-sub
31756 @findex c32vector-sub!
31757 @findex c32vector-mul
31758 @findex c32vector-mul!
31759 @findex c64vector-add
31760 @findex c64vector-add!
31761 @findex c64vector-sub
31762 @findex c64vector-sub!
31763 @findex c64vector-mul
31764 @findex c64vector-mul!
31765 @findex c128vector-add
31766 @findex c128vector-add!
31767 @findex c128vector-sub
31768 @findex c128vector-sub!
31769 @findex c128vector-mul
31770 @findex c128vector-mul!
31771 @c MOD gauche.uvector
31772 @c EN
31773 Element-wise arithmetic. @var{Vec} must be a @@vector,
31774 and @var{val} must be either a @@vector, a vector, or a list
31775 of the same length as @var{vec}, or a number
31776 (an exact integer for integer vectors,
31777 and a real number for f32- and f64-vectors).
31778 @c JP
31779 要素毎の計算手続きです。@var{vec}は@@vectorでなければなりません。
31780 また、@var{val}は@var{vec}と同じ長さの@@vectorかベクタかリスト、
31781 あるいは数値(整数ベクタに対しては正確な整数、実数ベクタに対しては実数)
31782 でなければなりません。
31783 @c COMMON
31784
31785 @c EN
31786 If @var{val} is a @@vector, its elements are
31787 added to, subtracted from, or multiplied by the corresponding
31788 elements of @var{vec}, respectively,
31789 and the results are gathered to a @@vector
31790 and returned. The linear-update version (those have bang `!' in the name)
31791 reuses @var{vec} to store the result, and also returns it.
31792 If the result of calculation goes out of the range of @@vector's
31793 element, the behavior is specified by @var{clamp} optional argument.
31794 (For f32vector and f64vector, @var{clamp} argument is ignored and
31795 the result may contain infinity).
31796 @c JP
31797 @var{val}が@@vectorの場合、
31798 @var{vec}と対応する要素毎に加算、減算、乗算が行われ、
31799 結果が@@vectorとして返されます。
31800 線形更新バージョン(名前に`!'がついているもの)では、@var{vec}が
31801 結果を格納するために再利用され、またそれが返されます。
31802 演算の結果が@@vectorの要素の値域外になった場合の動作は
31803 省略可能な引数@var{clamp}によって指定されます。
31804 (f32vectorとf64vectorでは、値域外になった要素にはinfinityが格納され、
31805 @var{clamp}の値は無視されます)。
31806 @c COMMON
31807
31808 @c EN
31809 If @var{val} is a number, it is added to, subtracted from, or
31810 multiplied by each element of @var{vec}, respectively.
31811 @c JP
31812 @var{val}が数値である場合、@var{vec}の各要素とその数値の間で演算が行われます。
31813 @c COMMON
31814
31815 @example
31816 (s8vector-add '#s8(1 2 3 4) '#s8(5 6 7 8)) @result{} #s8(6 8 10 12)
31817 (u8vector-sub '#u8(1 2 3 4) '#u8(2 2 2 2)) @result{} @r{error}
31818 (u8vector-sub '#u8(1 2 3 4) '#u8(2 2 2 2) 'both) @result{} #u8(0 0 1 2)
31819
31820 (f32vector-mul '#f32(3.0 2.0 1.0) 1.5) @result{} #f32(4.5 3.0 1.5)
31821 @end example
31822 @end deffn
31823
31824 @deffn {Function} @@vector-div vec val
31825 @deffnx {Function} @@vector-div! vec val
31826 @findex f16vector-div
31827 @findex f16vector-div!
31828 @findex f32vector-div
31829 @findex f32vector-div!
31830 @findex f64vector-div
31831 @findex f64vector-div!
31832 @findex c32vector-div
31833 @findex c32vector-div!
31834 @findex c64vector-div
31835 @findex c64vector-div!
31836 @findex c128vector-div
31837 @findex c128vector-div!
31838 @c MOD gauche.uvector
31839 @c EN
31840 Element-wise division of flonum vectors. These are only defined
31841 for f16, f32 and f64vector. @var{val} must be a @@vector,
31842 a vector or a list of the same length as @var{vec}, or a real number.
31843 @c JP
31844 要素毎の除算です。これらはf32vectorとf64vectorのみに対して定義されます。
31845 @var{val}は@var{vec}と同じ大きさの@@vectorかベクタかリスト、
31846 あるいは実数でなければなりません。
31847 @c COMMON
31848
31849 @example
31850 (f32vector-div '#f32(1.0 2.0 3.0) 2.0) @result{} #f32(0.5 1.0 1.5)
31851 @end example
31852 @end deffn
31853
31854
31855 @deffn {Function} @@vector-and vec val
31856 @deffnx {Function} @@vector-and! vec val
31857 @deffnx {Function} @@vector-ior vec val
31858 @deffnx {Function} @@vector-ior! vec val
31859 @deffnx {Function} @@vector-xor vec val
31860 @deffnx {Function} @@vector-xor! vec val
31861 @findex s8vector-and
31862 @findex s8vector-and!
31863 @findex s8vector-ior
31864 @findex s8vector-ior!
31865 @findex s8vector-xor
31866 @findex s8vector-xor!
31867 @findex u8vector-and
31868 @findex u8vector-and!
31869 @findex u8vector-ior
31870 @findex u8vector-ior!
31871 @findex u8vector-xor
31872 @findex u8vector-xor!
31873 @findex s16vector-and
31874 @findex s16vector-and!
31875 @findex s16vector-ior
31876 @findex s16vector-ior!
31877 @findex s16vector-xor
31878 @findex s16vector-xor!
31879 @findex u16vector-and
31880 @findex u16vector-and!
31881 @findex u16vector-ior
31882 @findex u16vector-ior!
31883 @findex u16vector-xor
31884 @findex u16vector-xor!
31885 @findex s32vector-and
31886 @findex s32vector-and!
31887 @findex s32vector-ior
31888 @findex s32vector-ior!
31889 @findex s32vector-xor
31890 @findex s32vector-xor!
31891 @findex u32vector-and
31892 @findex u32vector-and!
31893 @findex u32vector-ior
31894 @findex u32vector-ior!
31895 @findex u32vector-xor
31896 @findex u32vector-xor!
31897 @findex s64vector-and
31898 @findex s64vector-and!
31899 @findex s64vector-ior
31900 @findex s64vector-ior!
31901 @findex s64vector-xor
31902 @findex s64vector-xor!
31903 @findex u64vector-and
31904 @findex u64vector-and!
31905 @findex u64vector-ior
31906 @findex u64vector-ior!
31907 @findex u64vector-xor
31908 @findex u64vector-xor!
31909 @c MOD gauche.uvector
31910 @c EN
31911 Element-wise logical (bitwise) operation.
31912 These procedures are only defined for integral vectors.
31913 @var{val} must be a @@vector, a vector or a list
31914 of the same length as @var{vec},
31915 or an exact integer. Bitwise and, inclusive or or exclusive or
31916 is calculated between each element in @var{vec} and the corresponding
31917 element of @var{val} (when @var{val} is a non-scalar value),
31918 or @var{val} itself (when @var{val} is an integer).
31919 The result is returned in a @@vector.
31920 The linear-update version reuses @var{vec} to store the result,
31921 and also returns it.
31922 @c JP
31923 要素毎の論理(ビット)演算です。
31924 これらの手続きは整数ベクタに対してのみ定義されています。
31925 @var{val}は@var{vec}と同じ大きさの@@vectorかベクタかリスト、
31926 あるいは正確な整数でなければなりません。@var{vec}の各要素と、対応する@var{val}の要素
31927 (@var{val}が非スカラー値の場合)もしくは@var{val}自身
31928 (@var{val}が整数の場合)とのビット毎のand, inclusive orまたはexclusive or
31929 が計算され、結果が@@vectorで返されます。
31930 線形更新バージョン(名前に`!'がついているもの)では、@var{vec}が
31931 結果を格納するために再利用され、またそれが返されます。
31932 @c COMMON
31933 @end deffn
31934
31935 @deffn {Function} @@vector-dot vec0 vec1
31936 @findex s8vector-dot
31937 @findex s16vector-dot
31938 @findex s32vector-dot
31939 @findex s64vector-dot
31940 @findex u8vector-dot
31941 @findex u16vector-dot
31942 @findex u32vector-dot
31943 @findex u64vector-dot
31944 @findex f16vector-dot
31945 @findex f32vector-dot
31946 @findex f64vector-dot
31947 @findex c32vector-dot
31948 @findex c64vector-dot
31949 @findex c128vector-dot
31950 @c MOD gauche.uvector
31951 @c EN
31952 Calculates the dot product of two @@vectors.
31953 The length of @var{vec0} and @var{vec1} must be the same.
31954 @c JP
31955 ふたつの@@vectorの内積を計算します。
31956 @var{vec0}と@var{vec1}の長さは等しくなければなりません。
31957 @c COMMON
31958 @end deffn
31959
31960 @deffn {Function} @@vector-range-check vec min max
31961 @findex s8vector-range-check
31962 @findex s16vector-range-check
31963 @findex s32vector-range-check
31964 @findex s64vector-range-check
31965 @findex u8vector-range-check
31966 @findex u16vector-range-check
31967 @findex u32vector-range-check
31968 @findex u64vector-range-check
31969 @findex f16vector-range-check
31970 @findex f32vector-range-check
31971 @findex f64vector-range-check
31972 @c MOD gauche.uvector
31973 @c EN
31974 @var{Vec} must be a @@vector, and each of @var{min} and @var{max}
31975 must be either a @@vector, a vector or a list of the same length
31976 as @var{vec}, or a number, or @code{#f}.
31977
31978 For each element in @var{vec}, this procedure checks if the value
31979 is between @var{minval} and @var{maxval} inclusive, where
31980 @var{minval} and @var{maxval} are the corresponding values of
31981 @var{min} and @var{max} (when @var{min} and/or @var{max} is/are
31982 non-scalar value) or @var{min} and @var{max} themselves (when
31983 @var{min} and/or @var{max} is/are a number).
31984 When @var{min} is @code{#f}, negative infinity is assumed.
31985 When @var{max} is @code{#f}, positive infinity is assumed.
31986
31987 If all the elements in @var{vec} are within the range, @code{#f} is
31988 returned. Otherwise, the index of the leftmost element of @var{vec}
31989 that is out of range is returned.
31990 @c JP
31991 @var{vec}は@@vectorでなければなりません。
31992 @var{min}と@var{max}はそれぞれ、@var{vec}と同じ長さの@@vector、
31993 ベクタ、リストのいずれかか、実数もしくは@code{#f}でなければなりません。
31994
31995 @var{vec}の各要素に対して、この手続きはそれが対応する@var{minval}と@var{maxval}
31996 の間にあるかどうかを検査します。@var{minval}と@var{maxval}も範囲に含みます。
31997 ここで、@var{minval}と@var{maxval}は、@var{min}/@var{max}が非スカラー値
31998 であれば@var{vec}の要素に対応するそれぞれの要素、
31999 @var{min}/@var{max}が数値であればその数値そのものです。
32000 @var{min}が@code{#f}の場合、最小値はマイナス無限大と考えられます。
32001 @var{max}が@code{#f}の場合、最大値はプラス無限大と考えられます。
32002
32003 @var{vec}の全ての要素が範囲内であった場合は@code{#f}が返されます。
32004 そうでなければ、範囲を外れた要素のうちもっとも左のものの@var{vec}内での
32005 インデックスが返されます。
32006 @c COMMON
32007
32008 @example
32009 (u8vector-range-check '#u8(3 1 0 2) 0 3) @result{} #f
32010 (u8vector-range-check '#u8(3 1 0 2) 1 3) @result{} 2
32011
32012 (u8vector-range-check '#u8(4 32 64 98) 0 '#u8(10 40 70 90))
32013 @result{} 3
32014
32015 ;; Range check in a program
32016 (cond
32017 ((u8vector-range-check u8v 1 31)
32018 => (lambda (i)
32019 (errorf "~sth vector element is out of range: ~s"
32020 i (u8vector-ref u8v i))))
32021 (else (do-something u8v)))
32022 @end example
32023 @end deffn
32024
32025 @deffn {Function} @@vector-clamp vec min max
32026 @deffnx {Function} @@vector-clamp! vec min max
32027 @findex s8vector-clamp
32028 @findex s16vector-clamp
32029 @findex s32vector-clamp
32030 @findex s64vector-clamp
32031 @findex u8vector-clamp
32032 @findex u16vector-clamp
32033 @findex u32vector-clamp
32034 @findex u64vector-clamp
32035 @findex f32vector-clamp
32036 @findex f64vector-clamp
32037 @findex s8vector-clamp!
32038 @findex s16vector-clamp!
32039 @findex s32vector-clamp!
32040 @findex s64vector-clamp!
32041 @findex u8vector-clamp!
32042 @findex u16vector-clamp!
32043 @findex u32vector-clamp!
32044 @findex u64vector-clamp!
32045 @findex f16vector-clamp!
32046 @findex f32vector-clamp!
32047 @findex f64vector-clamp!
32048 @c MOD gauche.uvector
32049 @c EN
32050 @var{Vec} must be a @@vector, and each of @var{min} and @var{max}
32051 must be either a @@vector, a vector or a list of the same length
32052 as @var{vec}, or a number, or @code{#f}.
32053
32054 Like @@vector-range-check, these procedures check if
32055 each element of @var{vec} are within the range between @var{minval}
32056 and @var{maxval} inclusive, which are derived from @var{min} and @var{max}.
32057 If the value is less than @var{minval}, it is replaced by @var{minval}.
32058 If the value is grater than @var{maxval}, it is replaced by @var{maxval}.
32059
32060 @@vector-clamp creates a copy of @var{vec} and do clamp
32061 operation on it, while @@vector-clamp! modifies @var{vec}.
32062 Both return the clamped vector.
32063 @c JP
32064 @var{vec}は@@vectorでなければなりません。
32065 @var{min}と@var{max}はそれぞれ、@var{vec}と同じ長さの@@vector、
32066 ベクタ、リストのいずれかか、実数もしくは@code{#f}でなければなりません。
32067
32068 @@vector-range-checkと同じように、この手続きは@var{vec}の各要素が
32069 @var{min}および@var{max}で指定される最小値と最大値の間にあるかどうかを
32070 検査します。要素が最小値より小さかった場合はそれが最小値に置き換えられます。
32071 要素が最大値より大きかった場合はそれが最大値に置き換えられます。
32072
32073 @@vector-clampは@var{vec}のコピーを作ってそれに対して
32074 クランプ操作を行います。@@vector-clamp!は@var{vec}を直接
32075 変更します。どちらもクランプ操作が行われた後の@@vectorを返します。
32076 @c COMMON
32077
32078 @example
32079 (s8vector-clamp '#s8(8 14 -3 -22 0) -10 10) @result{} #s8(8 10 -3 -10 0)
32080 @end example
32081 @end deffn
32082
32083
32084 @node Uvector block I/O, Bytevector compatibility, Uvector numeric operations, Uniform vector library
32085 @subsection Uvector block I/O
32086 @c NODE ユニフォームベクタのブロック入出力
32087
32088 @c EN
32089 A uniform vector can be seen as an abstraction of a chunk of memory.
32090 So you might want to use it for binary I/O. Yes, you can do it.
32091 @c JP
32092 ユニフォームベクタは、メモリの固まりを抽象化しているものと考えることも
32093 できます。それなら、それをバイナリI/Oに使えないでしょうか。もちろんできます。
32094 @c COMMON
32095
32096 @defun read-uvector class size :optional iport endian
32097 @c MOD gauche.uvector
32098 @c EN
32099 Reads @var{size} elements of uvector of class @var{class} from
32100 @var{iport}, and returns fleshly created uvector. If @var{iport}
32101 is omitted, the curret input port is used.
32102 @c JP
32103 クラス@code{class}のユニフォームベクタの要素を@var{size}個、@var{iport}から
32104 読み込み、それを新たに作ったユニフォームベクタとして返します。
32105 @var{iport}が省略された場合は、現在の入力ポートが使われます。
32106 @c COMMON
32107
32108 @c EN
32109 For example, you can read input as an octet stream as follows:
32110 @c JP
32111 例えば次のようにして、入力をオクテットストリームとして読み込めます:
32112 @c COMMON
32113
32114 @example
32115 (with-input-from-string "abcde"
32116 (^[] (read-uvector <u8vector> 5)))
32117 @result{} #u8(97 98 99 100 101)
32118 @end example
32119
32120 @c EN
32121 If the input port has already reached EOF, an EOF object is
32122 returned. The returned uvector can be shorter than @var{size}
32123 if the input reaches EOF before @var{size} elements are read.
32124 @c JP
32125 入力ポートが既にEOFに達していた場合はEOFオブジェクトが返されます。
32126 @var{size}要素を読む前に入力がEOFに達した場合、返されるuvectorの長さは
32127 @var{size}より短いものとなります。
32128 @c COMMON
32129
32130 @c EN
32131 If the @var{iport} is a buffered port with `modest' or `none'
32132 buffering mode (@pxref{File ports}), @code{read-uvector} may return
32133 before @var{size} elements are read, even if @var{iport}
32134 hasn't reached EOF. The ports connected to a pipe or a network socket
32135 behave so by default.
32136 @c JP
32137 @var{iport}がバッファードポートであり、そのバッファリングモードが
32138 `modest' か `none' であった場合、@code{read-uvector}は@var{iport}が
32139 EOFに達していなくても、@var{size}要素を読む前に戻ることがあります
32140 (バッファリングモードについては@ref{File ports}を参照して下さい)。
32141 パイプやネットワークに接続されたポートはデフォルトでそのように振舞います。
32142 @c COMMON
32143
32144 @c EN
32145 The data is read as a byte stream, so if you give uniform vectors
32146 other than s8vector or u8vector, your result may affected by
32147 the endianness. If the optional argument @var{endian} is
32148 given, the input is interpreted in that endianness.
32149 When omitted, the value of the parameter @code{default-endian}
32150 is used. @xref{Endianness}, for more about endian handling.
32151 @c JP
32152 データはバイトストリームとして読まれるので、
32153 s8vectorとu8vector以外のユニフォームベクタを与えた場合は
32154 結果がエンディアンに影響を受けることに注意して下さい。
32155 省略可能引数@var{endian}によって、入力データのエンディアンを指定
32156 することができます。省略した場合はパラメータ@code{default-endian}の
32157 値が使われます。エンディアンの扱いについてより詳しくは@ref{Endianness}を参照して
32158 ください。
32159 @c COMMON
32160
32161 @c EN
32162 If the size of the input data is unknown and you need to read everything
32163 until EOF, use @code{port->uvector} below.
32164 @c JP
32165 入力データの大きさが不明で、EOFまで全てを読み込みたい場合は、下の
32166 @code{port->uvector}を使ってください。
32167 @c COMMON
32168 @end defun
32169
32170 @defun read-bytevector size :optional iport
32171 [R7RS base]
32172 @c MOD gauche.uvector
32173 @c EN
32174 Equivalent to @code{(read-uvector <u8vector> size iport)}.
32175 This is an R7RS base procedure.
32176 @c JP
32177 @code{(read-uvector <u8vector> size iport)}と等価です。
32178 R7RS baseにある手続きです。
32179 @c COMMON
32180 @end defun
32181
32182 @defun read-uvector! vec :optional iport start end endian
32183 @c MOD gauche.uvector
32184 @c EN
32185 Reads a chunk of data from the given input port @var{iport},
32186 and stores it to the uniform vector @var{vec}.
32187 You can give any uniform vector.
32188 If optional @var{start} and @var{end}
32189 arguments are given, they specify the index range in @var{vec}
32190 that is to be filled, and the rest of the vector remains untouched.
32191 Otherwise, entire vector is used. A special value -1 for @var{end}
32192 indicates the end of @var{vec}.
32193 If @var{iport} is omitted, the current input port is used.
32194 @c JP
32195 与えられた入力ポート@var{iport}からデータの固まりを読みだし、それを
32196 ユニフォームベクタ@var{vec}に格納します。
32197 どんな種類のユニフォームベクタでも与えることができます。
32198 省略可能な引数@var{start}と@var{end}が与えられた場合は、
32199 それらが@var{vec}中でデータが格納されるべき領域のインデックスの範囲を
32200 示します。@var{end}については-1で@var{vec}の最後を示すこともできます。
32201 その範囲外の@var{vec}の値は変更されません。
32202 @var{start}、@var{end}が与えられなかった場合は@var{vec}全体が使われます。
32203 @var{iport}が省略された場合はカレント入力ポートが使われます。
32204 @c COMMON
32205
32206 @c EN
32207 If the input reached EOF before the required region of @var{vec}
32208 is filled, the rest of the vector is untouched.
32209 @c JP
32210 要求された領域を埋め終る前に入力がEOFに達した場合は、ベクタの残りの部分は
32211 変更されません。
32212 @c COMMON
32213
32214 @c EN
32215 If @var{iport} is already reached EOF when @code{read-uvector!} is
32216 called, an EOF object is returned. Otherwise,
32217 the procedure returns the number of @emph{elements} read (not bytes).
32218 @c JP
32219 @code{read-uvector!}が呼ばれた時既に@var{iport}がEOFに達していた場合は
32220 EOFが、そうでなければ読まれた要素の数 (バイト数ではありません) が返されます。
32221 @c COMMON
32222
32223 @c EN
32224 If the @var{iport} is a buffered port with `modest' or `none'
32225 buffering mode (@pxref{File ports}), @code{read-uvector!} may return
32226 before all the elements in @var{vec} is filled, even if @var{iport}
32227 hasn't reached EOF. The ports connected to a pipe or a network socket
32228 behave so by default. If you know there will be enough data arriving and
32229 want to make sure @var{vec} is filled, change the buffering mode of
32230 @var{iport} to `full'.
32231 @c JP
32232 @var{iport}がバッファードポートであり、そのバッファリングモードが
32233 `modest' か `none' であった場合、@code{read-uvector!}は@var{iport}が
32234 EOFに達していなくても、@var{vec}を埋める前に戻ることがあります
32235 (バッファリングモードについては@ref{File ports}を参照して下さい)。
32236 パイプやネットワークに接続されたポートはデフォルトでそのように振舞います。
32237 もし、十分なデータが到着することがわかっており、@var{vec}を確実に埋めたい場合は
32238 ポートのバッファリングモードを`full'に変更して下さい。
32239 @c COMMON
32240
32241 @c EN
32242 The data is read as a byte stream, so if you give uniform vectors
32243 other than s8vector or u8vector, your result may affected by
32244 the endianness. If the optional argument @var{endian} is
32245 given, the input is interpreted in that endianness.
32246 When omitted, the value of the parameter @code{default-endian}
32247 is used. @xref{Endianness}, for more about endian handling.
32248 @c JP
32249 データはバイトストリームとして読まれるので、
32250 s8vectorとu8vector以外のユニフォームベクタを与えた場合は
32251 結果がエンディアンに影響を受けることに注意して下さい。
32252 省略可能引数@var{endian}によって、入力データのエンディアンを指定
32253 することができます。省略した場合はパラメータ@code{default-endian}の
32254 値が使われます。エンディアンの扱いについてより詳しくは@ref{Endianness}を参照して
32255 ください。
32256 @c COMMON
32257 @end defun
32258
32259 @defun read-block! vec :optional iport start end endian
32260 @c MOD gauche.uvector
32261 @c DEPRECATED
32262 @c EN
32263 An old name of @code{read-uvector!}. Supported for the backward
32264 compatibility, but new code should use @code{read-uvector!}.
32265 @c JP
32266 @code{read-uvector!}の古い名前です。互換性のためサポートされていますが、
32267 新しいコードでは@code{read-uvector!}を使ってください。
32268 @c COMMON
32269 @end defun
32270
32271 @defun port->uvector iport :optional class
32272 @c MOD gauche.uvector
32273 @c EN
32274 Read data from the input port @var{iport} until EOF and store them
32275 into a uvector of @var{class}. If @var{class} is omitted,
32276 @code{<u8vector>} is used.
32277
32278 If you specify a class of uvector whose element is more than an octet,
32279 the input data is packed with platform's native byteorder.
32280
32281 This procedure is parallel to @code{port->string} etc.
32282 (@pxref{Input utility functions}).
32283 @c JP
32284 入力ポート@var{iport}からEOFまでデータを読み込み、@var{class}クラスの
32285 ユニフォームベクタに格納して返します。@var{class}が省略された場合は
32286 @code{<u8vector>}が使われます。
32287
32288 要素が1オクテット以上のユニフォームベクタのクラスを指定した場合、
32289 各要素はプラットフォームのネイティブバイトオーダーで埋められます。
32290
32291 この手続きは組み込みの@code{port->string}等と対応しています
32292 (@ref{Input utility functions}参照)。
32293 @c COMMON
32294 @end defun
32295
32296 @defun read-bytevector! bv :optional iport start end
32297 [R7RS base]
32298 @c MOD gauche.uvector.
32299 @c EN
32300 Similar to @code{read-uvector!}, but @var{bv} must be a u8vector.
32301 This is an R7RS base procedure.
32302 @c JP
32303 @code{read-uvector!}と似ていますが、@var{bv}はu8vectorでなければなりません。
32304 これはR7RS baseにある手続きです。
32305 @c COMMON
32306 @end defun
32307
32308
32309 @defun write-uvector vec :optional oport start end endian
32310 @c MOD gauche.uvector
32311 @c EN
32312 Writes out the content of the uniform vector @var{vec} 'as is'
32313 to the output port @var{oport}. If @var{oport} is omitted,
32314 the current output port is used.
32315 If optional @var{start} and @var{end} arguments are given,
32316 they specify the index range in @var{vec} to be written out.
32317 A special value -1 for @var{end} indicates the end of @var{vec}.
32318 This procedure returns an unspecified value.
32319 @c JP
32320 ユニフォームベクタ@var{vec}の内容を「そのまま」@var{oport}に書き出します。
32321 @var{oport}が省略された場合はカレント出力ポートが使われます。
32322 省略可能な引数@var{start}と@var{end}が与えられた場合は、
32323 それらのインデックスの範囲が示す@var{vec}の内容のみが出力されます。
32324 @var{end}に-1を渡して@var{vec}の最後を示すこともできます。
32325 この手続きの返す値は未定義です。
32326 @c COMMON
32327
32328 @c EN
32329 If you write out a uniform vector except s8vector and u8vector, the
32330 care should be taken about the endianness, as in @code{read-uvector}.
32331 The optional argument @var{endian} specifies the output endian.
32332 When it is omitted, the value of the parameter @code{default-endian}
32333 is used (@pxref{Endianness}).
32334 @c JP
32335 @code{s8vector}と@code{u8vector}以外のユニフォームベクタを与えた場合、
32336 @code{read-uvector}と同じようにエンディアンの影響を受けることに注意して
32337 下さい。省略可能引数@var{endian}によって出力のエンディアンを
32338 指定できます。省略した場合はパラメータ@code{default-endian}の値が
32339 使われます (@ref{Endianness}参照)。
32340 @c COMMON
32341 @end defun
32342
32343 @deffn {Function} write-@@vector vec :optional port
32344 @findex write-u8vector
32345 @findex s8ite-u8vector
32346 @findex u16ite-u8vector
32347 @findex s16ite-u8vector
32348 @findex u32ite-u8vector
32349 @findex s32ite-u8vector
32350 @findex u64ite-u8vector
32351 @findex s64ite-u8vector
32352 @findex f16ite-u8vector
32353 @findex f32ite-u8vector
32354 @findex f64ite-u8vector
32355 @findex c32ite-u8vector
32356 @findex c64ite-u8vector
32357 @findex c128ite-u8vector
32358 [R7RS vector.@@]
32359 @c MOD gauche.uvector
32360 @c EN
32361 @c JP
32362 @c COMMON
32363 @end deffn
32364
32365 @defun write-bytevector bv :optional oport start end
32366 [R7RS base]
32367 @c MOD gauche.uvector
32368 @c EN
32369 Similar to @code{write-uvector}, but @var{bv} must be a u8vector.
32370 This is an R7RS base procedure.
32371 @c JP
32372 @code{write-uvector}と似ていますが、@var{bv}はu8vectorでなければなりません。
32373 R7RS baseの手続きです。
32374 @c COMMON
32375 @end defun
32376
32377 @defun write-block vec :optional oport start end endian
32378 @c MOD gauche.uvector
32379 @c DEPRECATED
32380 @c EN
32381 An old name of @code{write-uvector}. Supported for the backward
32382 compatibility, but new code should use @code{write-uvector}.
32383 @c JP
32384 @code{write-uvector}の古い名前です。互換性のためサポートされていますが、
32385 新しいコードでは@code{write-uvector}を使ってください。
32386 @c COMMON
32387 @end defun
32388
32389
32390
32391 @node Bytevector compatibility, , Uvector block I/O, Uniform vector library
32392 @subsection Bytevector compatibility
32393 @c NODE バイトベクタ互換性
32394
32395 @c EN
32396 R7RS-small includes bytevectors in its core (@code{scheme.base}).
32397 In Gauche, bytevectors are the same as u8vectors.
32398
32399 The basic R7RS bytevector procedures are provided in this module.
32400 Conversion between bytevectors and strings are provided in
32401 @code{gauche.unicode} (@pxref{Unicode transfer encodings})
32402 and @code{srfi.181} (@pxref{Transcoded ports}).
32403 @c JP
32404 R7RS-smallはコア(@code{scheme.base})にバイトベクタを含んでいます。
32405 Gaucheでは、バイトベクタはu8vectorと同じです。
32406
32407 R7RSのバイトベクタの基本的な手続きはこのモジュールで提供されます。
32408 ただし、文字列とバイトベクタの変換手続きは
32409 @code{gauche.unicode}(@ref{Unicode transfer encodings}参照)および
32410 @code{srfi.181}(@ref{Transcoded ports}参照)にあります。
32411 @c COMMON
32412
32413 @defun bytevector byte @dots{}
32414 @c MOD gauche.uvector
32415 [R7RS base]
32416 @c EN
32417 Alias of @code{u8vector}. Returns a fresh bytevector (u8vector) with
32418 @var{byte} @dots{} as its elements.
32419 @c JP
32420 @code{u8vector}の別名です。@var{byte} @dots{}を要素とするバイトベクタ(u8vector)を
32421 新たに作って返します。
32422 @c COMMON
32423 @end defun
32424
32425 @defun bytevector? obj
32426 @c MOD gauche.uvector
32427 [R7RS base]
32428 @c EN
32429 Alias of @code{u8vector?}. Returns true iff @var{obj} is
32430 a bytevector (u8vector).
32431 @c JP
32432 @code{u8vector?}の別名です。@var{obj}がバイトベクタ(u8vector)なら
32433 @code{#t}を、そうでなければ@code{#f}を返します。
32434 @c COMMON
32435 @end defun
32436
32437 @defun make-bytevector len :optional byte
32438 @c MOD gauche.uvector
32439 [R7RS base][R7RS bytevector]
32440 @c EN
32441 Returns a fresh bytevector (u8vector)
32442 of length @var{len}. All elements are initialized by @var{byte}
32443 if given.
32444
32445 R7RS base accepts an exact integer between 0 and 255 inclusive as
32446 @var{byte}. R7RS bytevector extends the range to -128 to 255 inclusive,
32447 while the negative value is wrapped-around by modulo 255.
32448 This procedure supports the extended range.
32449 @c JP
32450 長さ@var{len}の新たなバイトベクタ(u8vector)を作って返します。
32451 @var{byte}が与えられていれば、全ての要素をそれで初期化します。
32452
32453 R7RS baseでは@var{byte}の範囲を0から255(両端含む)としていますが、
32454 R7RS bytevectorではそれを-128から255(両端含む)に拡張しています。
32455 負の場合は256を法としてラップアラウンドします。この手続きは拡張範囲をサポートします。
32456 @c COMMON
32457 @end defun
32458
32459 @defun bytevector-length bv
32460 @c MOD gauche.uvector
32461 [R7RS base]
32462 @c EN
32463 Alias of @code{u8vector-length}. Returns the length of the
32464 bytevector (u8vector) @var{bv}.
32465 @c JP
32466 @code{u8vector-length}の別名です。バイトベクタ(u8vector) @var{bv}の長さを返します。
32467 @c COMMON
32468 @end defun
32469
32470 @defun bytevector-u8-ref bv k
32471 @defunx bytevector-u8-set! bv k byte
32472 @c MOD gauche.uvector
32473 [R7RS base]
32474 @c EN
32475 Alias of @code{u8vector-ref} and @code{u8vector-set!}.
32476 Read and write @var{k}-th element of a bytevector (u8vector) @var{bv}.
32477
32478 It is an error to give out-of-bound index.
32479
32480 The return value of @code{bytevector-u8-set!} is unspecified.
32481
32482 As Gauche's extension, @code{(setter bytevector-u8-ref)} is
32483 @code{bytevector-u8-set!}.
32484 @c JP
32485 @code{u8vector-ref}と@code{u8vector-set!}の別名です。
32486 バイトベクタ(u8vector) @var{bv} の@var{k}番目の要素を返す/セットします。
32487
32488 @var{k}が領域外ならエラーが投げられます。
32489
32490 @code{bytevector-u8-set!}の戻り値は規定されていません。
32491
32492 Gaucheの拡張として、@code{(setter bytevector-u8-ref)} は
32493 @code{bytevector-u8-set!}になっています。
32494 @c COMMON
32495 @end defun
32496
32497 @defun bytevector-s8-ref bv k
32498 @defunx bytevector-s8-set! bv k signed-byte
32499 @c MOD gauche.uvector
32500 [R7RS bytevector]
32501 @c EN
32502 Like @code{bytevector-u8-ref} and @code{bytevector-u8-set!}, but
32503 treates octets as a signed byte, ranging from -128 to 127, inclusive.
32504
32505 As Gauche's extension, @code{(setter bytevector-s8-ref)} is
32506 @code{bytevector-s8-set!}.
32507 @c JP
32508 オクテットを-128から127までの符号つきバイトと扱うことを除き、
32509 それぞれ@code{bytevector-u8-ref}および@code{bytevector-u8-set!}と同じです。
32510
32511 Gaucheの拡張として、@code{(setter bytevector-s8-ref)} は
32512 @code{bytevector-s8-set!}になっています。
32513 @c COMMON
32514 @end defun
32515
32516 @defun bytevector-copy bv :optional start end
32517 @c MOD gauche.uvector
32518 [R7RS base]
32519 @c EN
32520 Alias of @code{u8vector-copy}. Returns a fresh copy of a
32521 bytevector (u8vector) @var{bv}. Optionally you can restrict the
32522 range of the source vector by indices @var{start} (inclusive)
32523 and @var{end} (exclusive).
32524 @c JP
32525 @code{u8vector-copy}の別名です。
32526 バイトベクタ(u8vector) @var{bv} の新たなコピーを作って返します。
32527 インデックス@var{start}と@var{end}でコピーする範囲を限定することができます
32528 (@var{start}は含まれ、@var{end}は含まれない)。
32529 @c COMMON
32530 @end defun
32531
32532 @defun bytevector-copy! target tstart source :optional sstart send
32533 @c MOD gauche.uvector
32534 [R7RS base]
32535 @c EN
32536 Alias of @code{u8vector-copy!}. Both @var{target} and @var{source}
32537 muse be bytevectors (u8vectors), and @var{target} must be mutable.
32538 Copy the content of @var{source} (optionally restricting the range
32539 between indices @var{start} (inclusive) and @var{end} (exclusive))
32540 into @var{target} starting at the index @var{tstart}.
32541 @c JP
32542 @code{u8vector-copy!}の別名です。
32543 @var{target}と@var{source}はバイトベクタ(u8vector)で、@var{target}は
32544 変更可能でなければなりません。@var{source}の内容 (@var{start}と@var{end}で
32545 範囲を限定することもできます) を@var{target}の@var{tstart}以降へとコピーします。
32546 @c COMMON
32547 @end defun
32548
32549 @defun bytevector-copy!-r6 src sstart target tstart len
32550 @c MOD gauche.uvector
32551 @c EN
32552 This is a compatibility procedure for R6RS @code{bytevector-copy!}
32553 (hence the suffix @code{-r6}). When R6RS bytevectors are
32554 adpoted as R7RS-large @code{scheme.bytevector}, the R6RS version
32555 of @code{bytevector-copy!} comes into R7RS as well
32556 (hence R7RS has two different @code{bytevector-copy!}, one in
32557 @code{scheme.base} and one in @code{scheme.bytevector}).
32558
32559 It's unfortunate
32560 that R6RS tends to break tradition and invent a new API; here, the
32561 arguments differ from other @code{*-copy!} procedures:
32562 This procedure copies from @var{src}, starting from
32563 @var{sstart} and length @var{len}, to @var{target} starting @var{tstart}.
32564 @c JP
32565 これはR6RSの@code{bytevector-copy!}との互換ルーチンです
32566 (なので@code{-r6}サフィックスがついています)。
32567 R6RSバイトベクタライブラリがR7RS-largeにも@code{scheme.bytevector}として
32568 採り入れられたので、R6RSバージョンの@code{bytevector-copy!}もR7RSに入ってきました。
32569 (なのでR7RSには二つの異なる@code{bytevector-copy!}があります。
32570 ひとつは@code{scheme.base}に、もうひとつは@code{scheme.bytevector}に。)
32571
32572 残念なことに、R6RSはしばしば伝統を破って新しいAPIを発明することがあり、
32573 この手続きもそのひとつで、他の@code{*-copy!}系の手続きと引数が異なります。
32574 この手続きでは、バイトベクタ@var{src}の@var{sstart}から@var{len}の長さのデータを
32575 @var{target}の@var{tstart}からの領域にコピーします。
32576 @c COMMON
32577 @end defun
32578
32579 @defun bytevector-append bv @dots{}
32580 @c MOD gauche.uvector
32581 [R7RS base]
32582 @c EN
32583 Alias of @code{u8vector-append}. All arguments must be bytevectors
32584 (u8vectors). Returns a fresh bytevector whose elements are
32585 the concatenation of elements of @var{bv} @dots{}.
32586 @c JP
32587 @code{u8vector-append}の別名です。
32588 全ての引数はバイトベクタ(u8vector)でなければなりません。
32589 引数の全ての要素をつなげた新たなバイトベクタを作って返します。
32590 @c COMMON
32591 @end defun
32592
32593 @defun bytevector=? bv1 bv2
32594 @c MOD gauche.uvector
32595 [R7RS bytevector]
32596 @c EN
32597 Alias of @code{u8vector=?}. All arguments must be bytevectors
32598 (u8vectors). Returns @code{#t} iff all bytevectors are of the same
32599 size and content.
32600 @c JP
32601 @code{u8vector=?}の別名です。全ての引数はバイトベクタ(u8vector)でなければなりません。
32602 引数の大きさと内容が一致している時に限り@code{#t}を返します。
32603 @c COMMON
32604 @end defun
32605
32606 @defun bytevector->u8-list bv
32607 @defunx u8-list->bytevector list
32608 [R7RS bytevector]
32609 @c EN
32610 Convert a u8vector to a list of bytes, and vice versa.
32611 Same as @code{u8vector->list} and @code{list->u8vector}, except to not
32612 taking optional @var{start}/@var{end} arguments.
32613 @c JP
32614 それぞれ、u8vectorをバイトのリストへ変換、およびその逆を行う手続きです。
32615 省略可能な@var{start}/@var{end}引数を取らないことを除き、
32616 @var{u8vector->list}およぎ@code{list->u8vector}と同じです。
32617 @c COMMON
32618 @end defun
32619
32620
32621 @c ----------------------------------------------------------------------
32622 @node Comparing version numbers, Virtual ports, Uniform vector library, Library modules - Gauche extensions
32623 @section @code{gauche.version} - Comparing version numbers
32624 @c NODE バージョン番号の比較, @code{gauche.version} - バージョン番号の比較
32625
32626 @deftp {Module} gauche.version
32627 @mdindex gauche.version
32628 @c EN
32629 This module provides a convenient procedure to compare
32630 @emph{version numbers} or @emph{revision numbers},
32631 such as "@code{0.5.1}", "@code{3.2-3}" or "@code{8.2pl1}".
32632 Usually each release of software component has
32633 a version number, and you can define order between them.
32634 For example, version "1.2.3" is newer than "1.2" and
32635 older than "2.1". You can compare those version numbers like this:
32636 @c JP
32637 このモジュールは、バージョン番号(リリース番号)を比較する便利な手続きを提供します。
32638 ここでのバージョン番号とはソフトウェアのリリースにつけられる
32639 "@code{0.5.1}"、"@code{3.2-3}"、"@code{8.2pl1}"といった文字列で、
32640 通常これらの番号間には順序関係が定義できます。
32641 例えば "1.2.3" は "1.2" より新しいが "2.1" より古い、といった具合です。
32642 以下のようにこれらの文字列の順序を比較することができるようになります。
32643 @c COMMON
32644
32645 @example
32646 (version<? "2.2.3" "2.2.11") @result{} #t
32647 (version<? "2.3.1" "2.3") @result{} #f
32648 (version<? "2.3.1-1" "2.3.1-10") @result{} #t
32649 (version<? "13a" "5b") @result{} #f
32650 @end example
32651
32652 @c EN
32653 There are no standard way to name versions, so I chose
32654 one convention. This won't work for all possible
32655 variations, but I think it covers typical cases.
32656 @c JP
32657 バージョン番号の付け方には特に標準というものはありませんが、
32658 よく使われている方法を採用しました。全ての場合に使えるとはいきませんが、
32659 大抵の場合はカバーできるのではないかと思います。
32660 @c COMMON
32661
32662 @c EN
32663 Strictly speaking, you can only define partial order between
32664 version numbers, for there can be branches. This module
32665 uses simple measure and just assumes the version numbers
32666 can be fully ordered.
32667 @c JP
32668 厳密に言えば、分岐などの場合があるのでバージョン番号間の関係は半順序関係にしかなりません。
32669 このモジュールでは単純な定義を使って、全順序関係があるものとして扱います。
32670 @c COMMON
32671
32672 @c EN
32673 The version number here is defined by the following syntax.
32674 @c JP
32675 まず、ここでのバージョン番号は以下の構文に従うものとします。
32676 @c COMMON
32677 @example
32678 <version> : <principal-release>
32679 | <version> <post-subrelease>
32680 | <version> <pre-subrelease>
32681 <principal-release> : <relnum>
32682 <post-subrelease> : [.-] <relnum>
32683 <pre-subrelease> : _ <relnum>?
32684 <relnum> : [^._-]+
32685 @end example
32686
32687 @c EN
32688 Typically @code{<relnum>} is composed by numeric part and extension part.
32689 For example, "23a" is composed by an integer 23 and extension "a".
32690 If @code{<relnum>} doesn't begins with digits, we assume its
32691 numeric part is -1.
32692 @c JP
32693 通常@code{<relnum>}は数字部分と、それに続く省略可能な拡張部分とからなります。
32694 例えば "@code{23a}" は数字部分23と拡張部分"@code{a}"からなります。
32695 もし@code{<relnum>}が数字で始まらない場合、その数字部分は-1であると考えることにします。
32696 @c COMMON
32697
32698 @c EN
32699 Then, the order of @code{<relnum>} is defined as follows:
32700 @c JP
32701 @code{<relnum>}の順序関係を次のように定義します。
32702 @c COMMON
32703 @enumerate
32704 @item
32705 @c EN
32706 If relnum A and relnum B have different numeric part, we ignore the
32707 extension and order them numerically, e.g. "@code{3b}" < "@code{4a}".
32708 @c JP
32709 relnum Aとrelnum Bが異なる数字部分を持っている場合、拡張部分を無視して
32710 数字部分を数値として比較します。例:"@code{3b}" < "@code{4a}"。
32711 @c COMMON
32712 @item
32713 @c EN
32714 If relnum A and relnum B have the same numeric part, we compare
32715 extension by alphabetically, e.g. "@code{4c}" < "@code{4d}"
32716 and "@code{5}" < "@code{5a}".
32717 @c JP
32718 relnum Aとrelnum Bの数字部分が等しい場合、拡張部分を辞書順に比較します。
32719 例:"@code{4c}" < "@code{4d}"、"@code{5}" < "@code{5a}"。
32720 @c COMMON
32721 @end enumerate
32722
32723 @c EN
32724 Given the order of @code{<relnum>}, the order of version numbers
32725 are defined as follows:
32726 @c JP
32727 @code{<relnum>}間の順序が定義できたところで、バージョン番号の順序を次のように定義します。
32728 @c EN
32729 @enumerate
32730 @item
32731 Decompose each version number into a list of @code{<principal-release>} and
32732 subsequence subrelease components. We call each element of
32733 the list "release components".
32734 @item
32735 If the first release component of both lists are the same,
32736 remove it from both. Repeat this until the head of the lists differ.
32737 @item
32738 Now we have the following cases.
32739 @enumerate
32740 @item
32741 Both lists are empty: versions are the same.
32742 @item
32743 One list (A) is empty and the other list (B) has post-subrelease
32744 at head: A is prior to B
32745 @item
32746 One list (A) is empty and the other list (B) has pre-subrelease
32747 at head: B is prior to A
32748 @item
32749 List A's head is post-subrelease and list B's head is
32750 pre-subrelease: B is prior to A
32751 @item
32752 Both lists have post-subrelease or pre-subrelease at head:
32753 compare their relnums.
32754 @end enumerate
32755 @end enumerate
32756 Here are some examples:
32757 @c JP
32758 @enumerate
32759 @item
32760 各々のバージョン番号を分解して @code{<principal-release>} とそれに続く
32761 サブリリース部品のリストに入れる。このリストの各要素のことを「リリース部品」
32762 と呼びます。
32763 @item
32764 もし両方のリストの最初のリリース部品が同じなら、それを両方のリストから
32765 取り除きます。これをリストの先頭が異るまでくりかえします。
32766 @item
32767 そうすると次のような場合に分られます。
32768 @enumerate
32769 @item
32770 両方のリストが空: バージョンは同じ。
32771 @item
32772 一方のリスト (A) が空で、他方のリスト (B) の先頭がポストサブリリース:
32773 A が B より前のバージョン。
32774 @item
32775 一方のリスト (A) が空で、他方のリスト (B) の先頭がプリサブリリース:
32776 B が A より前のバージョン
32777 @item
32778 リスト A の先頭がポストサブリリースで、リスト B の先頭がプリサブリリース:
32779 B が A より前のバージョン
32780 @item
32781 両方のリストとも先頭がポストサブリリースであるかプリサブリリース:
32782 relnum を比較する。
32783 @end enumerate
32784 @end enumerate
32785
32786 以下はいくつかの例です。
32787 @c COMMON
32788 @example
32789 "1" < "1.0" < "1.1" < "1.1.1" < "1.1.2" < "1.2" < "1.11"
32790 "1.2.3" < "1.2.3-1" < "1.2.4"
32791 "1.2.3" < "1.2.3a" < "1.2.3b"
32792 "1.2_" < "1.2_rc0" < "1.2_rc1" < "1.2" < "1.2-pl1" < "1.2-pl2"
32793 "1.1-patch112" < "1.2_alpha"
32794 @end example
32795
32796 @c EN
32797 The reason of having @code{<pre-subrelease>} is to allow
32798 "release candidate" or "pre-release" version.
32799
32800 A trick: If you want ``version 1.2 release or later'', you
32801 can say @code{(version<=? "1.2" v)}. This excludes prerelease
32802 versions such as @code{1.2_pre3}.
32803 If you want ``version 1.2 release or later'',
32804 you can say @code{(version<=? "1.2_" v)}, which includes
32805 @code{1.2_pre1} etc., but excludes anything below, such as
32806 @code{1.1.99999}.
32807 @c JP
32808 @code{<pre-subrelease>} があるのは、「リリース候補」あるいは
32809 「プリリリース」のバージョンをつかえるようにするためです。
32810
32811 ヒント: 「1.2正式リリースもしくはそれ以降」をチェックした場合は
32812 @code{(version<=? "1.2" v)} とします。これは、
32813 @code{1.2_pre3}といったプレリリース版を除外します。一方、
32814 「プレリリース版も含めて1.2もしくはそれ以降」としたい場合は
32815 @code{(version<=? "1.2_" v)}と書けます。これは、
32816 @code{1.2_pre1}等は含み、それ以前の例えば@code{1.1.99999}等は除外します。
32817 @c COMMON
32818
32819 @c EN
32820 It is common if you want to specify acceptable versions with
32821 combination of conditions, e.g. ``version 1.3 or later, except
32822 version 1.4.1'' or ``greater than version 1.1 and below 1.5''.
32823 A @emph{version spec} is an S-expression to represent that condition.
32824 You can use @code{version-satisfy?} to check if given version
32825 satisfies the spec.
32826 @c JP
32827 許容できるバージョンを条件の組み合わせで指定したいことはよくあります。
32828 例えば「バージョン1.3以降、ただし1.4.1を除く」とか、
32829 「バージョン1.1以上で、1.5より前」等。
32830 バージョン指定 (version spec) は、S式でバージョンに関する条件を表現する手段です。
32831 @code{version-satisfy?}手続きで、バージョンがバージョン指定を満たしている
32832 かどうかチェックできます。
32833 @c COMMON
32834
32835 @c EN
32836 The syntax of version spec is as follows.
32837 @c JP
32838 バージョン指定の構文は以下の通りです。
32839 @c COMMON
32840
32841 @example
32842 <version-spec> : <version>
32843 | (<op> <version>)
32844 | (and <version-spec> ...)
32845 | (or <version-spec> ...)
32846 | (not <version-spec>)
32847
32848 <version> : version string
32849 <op> : = | < | <= | > | >=
32850 @end example
32851
32852 @end deftp
32853
32854 @defun version=? ver1 ver2
32855 @defunx version<? ver1 ver2
32856 @defunx version<=? ver1 ver2
32857 @defunx version>? ver1 ver2
32858 @defunx version>=? ver1 ver2
32859 @c MOD gauche.version
32860 @c EN
32861 Returns a boolean value depending on the order of two version number
32862 string @var{ver1} and @var{ver2}. If the arguments contain invalid
32863 strings as the defined version number, an error is signaled.
32864 @c JP
32865 ふたつのバージョン番号文字列 @var{ver1} と @var{ver2} の順序関係によって
32866 真偽値を返します。もし引数が、バージョン番号を定義するのに不正な文字列を
32867 含んでいた場合、エラーが上ります。
32868 @c COMMON
32869 @end defun
32870
32871 @defun version-compare ver1 ver2
32872 @c MOD gauche.version
32873 @c EN
32874 Compares two version number strings @var{ver1} and @var{ver2},
32875 and returns either -1, 0, or 1, depending whether @var{ver1} is
32876 prior to @var{ver2}, @var{ver1} is the same as @var{ver2}, or
32877 @var{ver1} is after @var{ver2}, respectively.
32878 @c JP
32879 ふたつのバージョン番号文字列 @var{ver1} と @var{ver2} を比較し、
32880 @var{ver1} のほうが @var{ver2} より前、@var{ver1} と @var{ver2} は同じ、
32881 @var{ver1} が @var{ver2} の後、の3つの場合によって、それぞれ、
32882 -1、0、1 を返します。
32883 @c COMMON
32884 @end defun
32885
32886 @defun relnum-compare rel1 rel2
32887 @c MOD gauche.version
32888 @c EN
32889 This is lower-level procedure of @code{version-compare}. Compares
32890 two release numbers (relnums) @var{rel1} and @var{rel2},
32891 and returns either -1, 0, or 1 depending whether @var{rel1} is
32892 prior to @var{rel2}, @var{rel1} is the same as @var{rel2}, or
32893 @var{rel1} is after @var{rel2}, respectively.
32894 @c JP
32895 これは @code{version-compare}の下位レベルの手続きです。
32896 ふたつのリリース番号 (relnum) @var{rel1} と @var{rel2} を比較し、
32897 @var{rel1} が @var{rel2} より前、@var{rel1} と @var{rel2} が同じ、
32898 @var{rel1} が @var{rel2} より後、の3つの場合によって、それぞれ、
32899 -1、0、1 を返します。
32900 @c COMMON
32901 @end defun
32902
32903 @c EN
32904 The following procedures are to check if a given version
32905 satisfies a version specification.
32906 @c JP
32907 以下の手続きは、与えられたバージョンがバージョン指定を満たすかどうかを
32908 検査するためのものです。
32909 @c COMMON
32910
32911 @defun valid-version-spec? spec
32912 @c MOD gauche.version
32913 @c EN
32914 This is a syntax checker. Returns @code{#t} if @var{spec} is
32915 a valid version specification, @code{#f} otherwise.
32916 See @code{gauche.version} module description for the definition of
32917 version specification.
32918 @c JP
32919 構文チェッカです。@var{spec}がバージョン指定として正当なフォームであれば
32920 @code{#t}を、そうでなければ@code{#f}を返します。
32921 バージョン指定フォームについてはモジュール@code{gauche.version}の記述を参照してください。
32922 @c COMMON
32923 @end defun
32924
32925 @defun version-satisfy? spec version
32926 @c MOD gauche.version
32927 @c EN
32928 Returns @code{#t} if @var{version} satisfies
32929 a version specification @var{spec}, @code{#f} otherwise.
32930 See @code{gauche.version} module description for the definition of
32931 version specification.
32932 @c JP
32933 バージョン番号@var{version}がバージョン指定@var{spec}を満たせば@code{#t}を、
32934 そうでなければ@code{#f}を返します。
32935 バージョン指定フォームについてはモジュール@code{gauche.version}の記述を参照してください。
32936 @c COMMON
32937 @end defun
32938
32939
32940
32941 @c ----------------------------------------------------------------------
32942 @node Virtual ports, , Comparing version numbers, Library modules - Gauche extensions
32943 @section @code{gauche.vport} - Virtual ports
32944 @c NODE 仮想ポート, @code{gauche.vport} - 仮想ポート
32945
32946 @deftp {Module} gauche.vport
32947 @mdindex gauche.vport
32948 @c EN
32949 @emph{Virtual ports}, or procedural ports, are the ports
32950 whose behavior can be programmed in Scheme.
32951 @c JP
32952 @emph{仮想ポート}あるいは手続き的ポートとは、その振舞いを
32953 Scheme でプログラム可能なポートです。
32954 @c COMMON
32955
32956 @c EN
32957 This module provides two kinds of virtual ports:
32958 Fully virtual ports, in which every I/O operation invokes
32959 user-provided procedures, and virtual buffered ports,
32960 in which I/O operations are done on an internal buffer and
32961 user-provided procedures are called only when the buffer
32962 needs to be filled or flushed.
32963 @c JP
32964 このモジュールは 2 種類の仮想ポートを提供します。ひとつは、
32965 完全仮想ポートで、すべての I/O 操作でユーザが提供する手続きが
32966 呼出されるものです。もうひとつは、仮想バッファポートで、
32967 I/O 操作は内部バッファ上で行われ、ユーザが提供する手続きは
32968 バッファを一杯にするかフラッシュする必要がある場合にのみ
32969 呼出されます。
32970 @c COMMON
32971
32972 @c EN
32973 This module also provides virtual buffered ports backed up
32974 by a uniform vector, as an example of the feature.
32975 @c JP
32976 このモジュールはさらに、ユニフォームベクタにより
32977 バックアップされる仮想バッファポートも提供します。
32978 これは仮想ポートの使用例でもあります。
32979 @c COMMON
32980 @end deftp
32981
32982 @c EN
32983 @subsubheading Fully virtual ports
32984 @c JP
32985 @subsubheading 完全仮想ポート
32986 @c COMMON
32987
32988 @c EN
32989 This type of virtual ports are realized by classes
32990 @code{<virtual-input-port>} and @code{<virtual-output-port>}.
32991 You can customize the port behavior by setting
32992 appropriate slots with procedures.
32993 @c JP
32994 このタイプの仮想ポートは、@code{<virtual-input-port>} クラス
32995 および @code{<virtual-output-port>} クラスで実現されています。
32996 適切なスロットに手続きをセットすることでポートの振舞いをカスタマイズ
32997 可能です。
32998 @c COMMON
32999
33000 @deftp {Class} <virtual-input-port>
33001 @clindex virtual-input-port
33002 @c MOD gauche.vport
33003 @c EN
33004 An instance of this class can be used as an input port.
33005 The behavior of the port depends on the settings of the
33006 instance slot values.
33007 @c JP
33008 このクラスのインスタンスは入力ポートとして使えます。
33009 このポートの振舞いはインスタンスのスロットに設定された値に依存します。
33010 @c COMMON
33011
33012 @c EN
33013 To work as a meaningful input port, at least either one of
33014 @code{getb} or @code{getc} slot must be set. Otherwise,
33015 the port returns EOF for all input requests.
33016 @c JP
33017 まともな入力ポートとして動かすためには、少くとも、@code{getb} スロット
33018 あるいは @code{getc} スロットのどちらか一方は設定しなければなりません。
33019 さもなければ、このポートはすべての入力要求に対して EOF を返します。
33020 @c COMMON
33021
33022 @defivar {<virtual-input-port>} getb
33023 @c EN
33024 If set, the value must be a procedure that takes no arguments.
33025 Every time binary input is required, the procedure is called.
33026 @c JP
33027 設定されているのなら、その値は、引数を取らない手続きでなければなりません。
33028 バイナリ入力の要求のたびに、この手続きが呼ばれます。
33029 @c COMMON
33030
33031 @c EN
33032 The procedure must return an exact integer between 0 and 255
33033 inclusive, or @code{#f} or an EOF object. If it returns an
33034 integer, it becomes the value read from the port. If it returns
33035 other values, the port returns EOF.
33036 @c JP
33037 この手続きは、0 から 255 までの正確な整数を返すか、@code{#f}あるいは
33038 EOF オブジェクトを返さなければなりません。整数を返す場合には、
33039 それがこのポートから読みとられる値となります。それ以外の値を返す
33040 場合は、このポートは EOF を返します。
33041 @c COMMON
33042
33043 @c EN
33044 If the port is requested a character input and it doesn't have
33045 the @code{getc} procedure, the port calls this procedure, possibly
33046 multiple times, to construct a whole character.
33047 @c JP
33048 このポートが文字入力を要求され、かつ、@code{getc} 手続きを持たない場合、
33049 このポートはこの手続きを呼び(複数回の可能性もある)文字全体を構築します。
33050 @c COMMON
33051 @end defivar
33052
33053 @defivar {<virtual-input-port>} getc
33054 @c EN
33055 If set, the value must be a procedure that takes no arguments.
33056 Every time character input is required, the procedure is called.
33057 @c JP
33058 設定されているのなら、その値は、引数を取らない手続きでなければなりません。
33059 文字入力の要求のたびに、この手続きが呼ばれます。
33060 @c COMMON
33061
33062 @c EN
33063 The procedure must return a character,
33064 @code{#f} or an EOF object. If it returns a character,
33065 it becomes the value read from the port. If it returns
33066 other values, the port returns EOF.
33067 @c JP
33068 この手続きは文字を返すか、または@code{#f}あるいはEOFオブジェクトを返さなければ
33069 なりません。文字を返した場合には、それがこのポートから読みとられる値と
33070 なります。それ以外の値を返す場合は、このポートは EOF を返します。
33071 @c COMMON
33072
33073 @c EN
33074 If the port is requested a binary input and it doesn't have
33075 the @code{getb} procedure, the port calls this procedure, then converts
33076 a character into a byte sequence, and use it as the binary
33077 value(s) read from the port.
33078 @c JP
33079 このポートがバイナリ入力を要求され、かつ、@code{getb} 手続きを持たない場合、
33080 このポートはこの手続きを呼び、文字をバイト列に変換し、それをこのポートから
33081 読みだされる値として使います。
33082 @c COMMON
33083 @end defivar
33084
33085 @defivar {<virtual-input-port>} gets
33086 @c EN
33087 If set, the value must be a procedure that takes one argument,
33088 a positive exact integer. It is called when the block binary
33089 input, such as @code{read-uvector}, is requested.
33090 @c JP
33091 設定されているなら、その値は、正の正確な整数の引数をひとつだけとる手続き
33092 でなければなりません。ブロックバイナリ入力、たとえば、
33093 @code{read-uvector}などが要求された場合に、呼出されます。
33094
33095 @c EN
33096 It must return a (maybe incomplete) string up to the specified size,
33097 or @code{#f} or EOF object. If it returns a null string, @code{#f}
33098 or EOF object,
33099 the port thinks it reached EOF. If it returns other string,
33100 it is used as the result of block read.
33101 It shouldn't return a string larger than the given size
33102 (Note: you must count size (bytes), not the number of characters).
33103 @c JP
33104 そしてそれは文字列、 不完全文字列、 @code{#f}、 EOF オブジェクトを
33105 返さなくてはなりません. 文字列を返す場合は上記正の正確な整数によって
33106 指定された大きさを越えてはなりません。空文字列、 @code{#f}、EOF を
33107 返した場合はポートの終端にたどり着いたものとみなされます。
33108 (注意: 文字列大きさは文字数でなく文字列が占めるバイト数で指定されます。)
33109
33110 @c EN
33111 The reason of this procedure is efficiency; if this procedure
33112 is not provided, the port calls @code{getb} procedure repeatedly
33113 to prepare the block of data. In some cases, providing block input
33114 can be much more efficient (e.g. suppose you're reading from
33115 a block of memory chunk).
33116 @c JP
33117 この手続きは効率のためにあります。もし、この手続きが用意されて
33118 いなければ、このポートは、データブロックを準備するのに @code{getb}を
33119 繰り返し呼びます。場合によっては、ブロック入力を用意するほうが
33120 はるかに効率的です。(たとえば、メモリチャンクのブロックからの読みだし
33121 を行なうような場合です。)
33122 @c COMMON
33123
33124 @c EN
33125 You can leave this slot unset if you don't need to take such
33126 advantage.
33127 @c JP
33128 こうした利点を必要としないのなら、このスロットは未設定のままにして
33129 おいてもかまいません。
33130 @c COMMON
33131 @end defivar
33132
33133 @defivar {<virtual-input-port>} ready
33134 @c EN
33135 If set, the value must be a procedure that takes one boolean argument.
33136 It is called when @code{char-ready?} or @code{byte-ready?} is
33137 called on the port. The value returned from your procedure will
33138 be the result of these procedures.
33139 @c JP
33140 設定されているなら、その値は、真偽値をひとつだけとる手続きでなければ
33141 なりません。この手続きは、このポートに対して、@code{char-ready?}
33142 あるいは @code{byte-ready?} が呼ばれたときに呼出されます。設定した手続き
33143 が返す値が、これらの手続きの結果になります。
33144 @c COMMON
33145
33146 @c EN
33147 The boolean argument is @code{#t} if
33148 @code{char-ready?} is called, or @code{#f} if @code{byte-ready?} is called.
33149 @c JP
33150 @code{char-ready?} が呼ばれたのなら、真偽値引数は @code{#t} です。
33151 @code{byte-ready?} が呼ばれたのなら、真偽値引数は @code{#f} になります。
33152 @c COMMON
33153
33154 @c EN
33155 If unset, @code{char-ready?} and @code{byte-ready?}
33156 always return @code{#t} on the port
33157 @c JP
33158 未設定なら、@code{char-ready?} および @code{byte-ready?} は
33159 このポートに対して常に、@code{#t} を返します。
33160 @c COMMON
33161 @end defivar
33162
33163 @defivar {<virtual-input-port>} close
33164 @c EN
33165 If set, the value must be a procedure that takes no arguments.
33166 It is called when the port is closed. Return value is discarded.
33167 You can leave this unset
33168 if you don't need to take an action when the port is closed.
33169 @c JP
33170 設定されているのなら、その値は引数を取らない手続きでなければなりません。
33171 その手続きはこのポートがクローズされるときに呼びだされ、返り値は
33172 捨てられます。このポートをクローズするときになんらかのアクションが
33173 必要でないのなら、未設定にしておけます。
33174 @c COMMON
33175
33176 @c EN
33177 This procedure may be called from a finalizer, so you have to be
33178 careful to write it. See the note on finalization below.
33179 @c JP
33180 この手続きはファイナライザから呼ばれることもあり得ます。したがって、
33181 この手続きは慎重に書く必要があります。後述のファイナライズに
33182 関する注意を参照してください。
33183 @c COMMON
33184 @end defivar
33185
33186 @defivar {<virtual-input-port>} seek
33187 @c EN
33188 If set, the value must be a procedure that takes two arguments,
33189 offset and whence. The meaning of them is the same as the arguments
33190 to @code{port-seek} (@pxref{Common port operations}).
33191 The procedure must adjust the port's internal read pointer
33192 so that the next read begins from the new pointer.
33193 It should return the updated pointer (the byte offset from the
33194 beginning of the port).
33195 @c JP
33196 設定されているのなら、その値は、オフセット引数とそれがどこからかを示す引数
33197 の 2つの引数をとる手続きでなければなりません。これらの引数の意味は、
33198 @code{port-seek} (@ref{Common port operations} 参照) のそれと同じです。
33199 この手続きは、次の読み出しが新しい位置から始められるように
33200 内部のリードポインタを調整しなければなりません。そして
33201 更新されたポインタ(ポート先頭からのバイトオフセット)
33202 を返さなければなりません。
33203 @c COMMON
33204
33205 @c EN
33206 If unset, call of @code{port-seek} and @code{port-tell} on this
33207 port will return @code{#f}.
33208 @c JP
33209 未設定なら、このポートに対する @code{port-seek} および @code{port-tell}
33210 の呼び出しは @code{#f} になります。
33211 @c COMMON
33212
33213 @c EN
33214 Note that this procedure may be called for the purpose of merely
33215 querying the current position, with 0 as @code{offset} and @code{SEEK_CUR}
33216 as @code{whence}. If your port knows the read pointer but cannot move it,
33217 you can still provide this procedure, which returns the current pointer
33218 position for such queries and returns @code{#f} for other arguments.
33219 @c JP
33220 この手続きは単に現在の位置を問合せるために、
33221 @code{offset} として 0 を、@code{whence} として @code{SEEK_CUR} を与えて
33222 呼び出すこともあることに注意してください。リードポインタの位置は知って
33223 いるが、動かすことができないという場合にも、この手続きを提供することが
33224 できます。上のような問合せには、現在位置を返し、そうでない場合には、
33225 @code{#f} を返します。
33226 @c COMMON
33227 @end defivar
33228
33229 @end deftp
33230
33231
33232 @deftp {Class} <virtual-output-port>
33233 @clindex virtual-output-port
33234 @c MOD gauche.vport
33235 @c EN
33236 An instance of this class can be used as an output port.
33237 The behavior of the port depends on the settings of the
33238 instance slot values.
33239 @c JP
33240 このクラスのインスタンスは出力ポートとして使えます。
33241 このポートの振舞いはインスタンスのスロットに設定された値に依存します。
33242 @c COMMON
33243
33244 @c EN
33245 To work as an output port, at least either one of @code{putb} or
33246 @code{putc} slot has to be set.
33247 @c JP
33248 まともな出力ポートとして動かすためには、少くとも、@code{putb} スロット
33249 あるいは @code{putc} スロットのどちらか一方は設定しなければなりません。
33250 @c COMMON
33251
33252 @defivar {<virtual-output-port>} putb
33253 @c EN
33254 If set, the value must be a procedure that takes one argument,
33255 a byte value (exact integer between 0 and 255, inclusive).
33256 Every time binary output is required, the procedure is called.
33257 The return value of the procedure is ignored.
33258 @c JP
33259 設定されているなら、その値は、バイト値(0 から 255までの正確な整数)を
33260 ひとつだけ引数としてとる手続きでなければなりません。バイナリ出力
33261 の要求のたびに、この手続きが呼ばれます。この手続きの返り値は無視
33262 されます。
33263 @c COMMON
33264
33265 @c EN
33266 If this slot is not set and binary output is requested,
33267 the port may signal an @code{<io-unit-error>} error.
33268 @c JP
33269 このスロットが未設定の場合、バイナリ出力を要求されると、このポートは
33270 @code{<io-unit-error>} エラーを発生させることがあります。
33271 @c COMMON
33272 @end defivar
33273
33274 @defivar {<virtual-output-port>} putc
33275 @c EN
33276 If set, the value must be a procedure that takes one argument,
33277 a character.
33278 Every time character output is required, the procedure is called.
33279 The return value of the procedure is ignored.
33280 @c JP
33281 設定されているなら、それは文字をひとつ引数にとる手続きでなければなりません。
33282 文字出力の要求があるたびにこの手続きがよばれます。この手続きの返り値は
33283 無視されます。
33284 @c COMMON
33285
33286 @c EN
33287 If this slot is not set but @code{putb} slot is set,
33288 the virtual port decomposes the character into a sequence of bytes
33289 then calls @code{putb} procedures.
33290 @c JP
33291 このスロットが未設定であっても、@code{putb} スロットが設定されていれば、
33292 この仮想ポートは文字をバイト列に展開してから、@code{putb} を呼びだします。
33293 @c COMMON
33294 @end defivar
33295
33296 @defivar {<virtual-output-port>} puts
33297 @c EN
33298 If set, the value must be a procedure that takes a
33299 (possibly incomplete) string.
33300 The return value of the procedure is ignored.
33301 @c JP
33302 設定されていれば、その値は、文字列(不完全なものである可能性もある)を
33303 ひとつ引数としてとる手続きでなければなりません。この手続きの返り値は
33304 無視されます。
33305 @c COMMON
33306
33307 @c EN
33308 This is for efficiency. If this slot is not set, the virtual port
33309 calls @code{putb} or @code{putc} repeatedly to output a chunk of data.
33310 But if your code can perform chunked output efficiently,
33311 you can provide this procedure.
33312 @c JP
33313 これは、効率のためにあります。このスロットが未設定であれば、この
33314 仮想ポートは、データのかたまりを出力するために、@code{putb}
33315 あるいは @code{putc} を繰り返し呼びます。もし、ひとかたまりの
33316 出力を効率的に実行可能なコードであれば、この手続きを提供できます。
33317 @c COMMON
33318 @end defivar
33319
33320 @defivar {<virtual-output-port>} flush
33321 @c EN
33322 If set, the value must be a procedure that takes no arguments.
33323 It is called when flushing a port is required (e.g. @code{flush}
33324 is called on the port, or the port is being closed).
33325 @c JP
33326 設定されていれば、その値は引数をとらない手続きでなければなりません。
33327 ポートのフラッシュを要求されたときに呼ばれます(たとえば、@code{flush}
33328 がこのポートに対して呼ばれたとき、あるいは、このポートがクローズ
33329 されるとき)。
33330 @c COMMON
33331
33332 @c EN
33333 This procedure is useful that your port does some sort of buffering,
33334 or needs to keep some state. If your port doesn't do stateful operation,
33335 you can leave this unset.
33336 @c JP
33337 この手続きは、ポートが何らかのバッファリングをおこなうか、なんらかの
33338 状態を持つような場合に便利です。ポートが状態をともなう操作を行わない
33339 のなら、これは未設定にしておけます。
33340 @c COMMON
33341
33342 @c EN
33343 This procedure may be called from a finalizer, and needs a special
33344 care. See notes on finalizers below.
33345 @c JP
33346 この手続きはファイナライザから呼ばれることがあります。したがって、
33347 特別な注意が必要です。後述のファイナライザに関する注意を
33348 参照してください。
33349 @c COMMON
33350
33351 @end defivar
33352
33353 @defivar {<virtual-output-port>} close
33354 @c EN
33355 The same as @code{<virtual-input-port>}'s @code{close} slot.
33356 @c JP
33357 @code{<virtual-input-port>} の @code{close} スロットと同様です。
33358 @c COMMON
33359 @end defivar
33360
33361 @defivar {<virtual-output-port>} seek
33362 @c EN
33363 The same as @code{<virtual-input-port>}'s @code{seek} slot.
33364 @c JP
33365 @code{<virtual-input-port>} の @code{seek} スロットと同様です。
33366 @c COMMON
33367 @end defivar
33368
33369 @end deftp
33370
33371 @c EN
33372 @subsubheading Virtual buffered ports
33373 @c JP
33374 @subsubheading 仮想バッファポート
33375 @c COMMON
33376
33377 @c EN
33378 This type of virtual ports are realized by classes
33379 @code{<buffered-input-port>} and @code{<buffered-output-port>}.
33380 You can customize the port behavior by setting
33381 appropriate slots with procedures.
33382 @c JP
33383 このタイプの仮想ポートは @code{<buffered-input-port>} クラス
33384 および @code{<buffered-output-port>} クラスで実現されています。
33385 適切なスロットに手続きを設定するこでポートの振舞いをカスタマイズ
33386 することができます。
33387 @c COMMON
33388
33389 @c EN
33390 Those ports have internal buffer and only calls Scheme procedures
33391 when the buffer needs to be filled or flushed. Generally it is
33392 far more efficient than calling Scheme procedures for every
33393 I/O operation. Actually, the internal buffering mechanism is
33394 the same as Gauche's file I/O ports.
33395 @c JP
33396 これらのポートは、内部バッファを持っており、そのバッファを満たすか
33397 フラッシュするかの必要があるときにのみ、Scheme の手続きが呼ばれます。
33398 通常、I/O毎に Scheme の手続きを呼ぶよりも遥かに効率がいいものです。
33399 実際の内部バッファリング機構は、GaucheのファイルI/Oポートと同じです。
33400 @c COMMON
33401
33402 @c EN
33403 These ports uses @code{u8vector} as a buffer. See @ref{Uniform vectors}
33404 for the details.
33405 @c JP
33406 これらのポートはバッファとして @code{u8vector} を使います。詳細は、
33407 @ref{Uniform vectors} を参照してください。
33408 @c COMMON
33409
33410 @deftp {Class} <buffered-input-port>
33411 @clindex buffered-input-port
33412 @c MOD gauche.vport
33413 @c EN
33414 An instance of this class behaves as an input port.
33415 It has the following instance slots. For a meaningful input
33416 port, you have to set at least @code{fill} slot.
33417 @c JP
33418 このクラスのインスタンスは、入力ポートとして振舞います。
33419 これは以下のようなインスタンススロットを持ちます。
33420 意味のある入力ポートとして使うには少くとも、@code{fill} スロットを
33421 設定しなければなりません。
33422 @c COMMON
33423
33424 @defivar {<buffered-input-port>} fill
33425 @c EN
33426 If set, it must be a procedure that takes one argument,
33427 a @code{u8vector}. It must fill the data from the
33428 beginning of the vector. It doesn't need to fill the entire
33429 vector if there's not so many data. However, if there are remaining
33430 data, it must fill at least one byte; if the data isn't readily
33431 available, it has to wait until some data becomes available.
33432 @c JP
33433 設定されているなら、@code{u8vector} の引数を一つとる手続きでなければ
33434 なりません。そのベクタの最初からデータを満たさなければなりません。
33435 要求されたものよりデータの残りが少ない場合には、
33436 ベクタ全体を満たす必要はありません。しかしながら、
33437 データが残っている場合には少くとも1バイトは満たさなければなりません。
33438 もしデータがまだ利用可能になっていなければ、なにがしかのデータが利用可能に
33439 なるまで待たなければなりません。
33440 @c COMMON
33441
33442 @c EN
33443 The procedure must return a number of bytes it actually filled.
33444 It may return 0 or an EOF object to indicate the port has reached EOF.
33445 @c JP
33446 この手続きは実際に満されたバイト数を返さなければなりません。ポートが
33447 EOFに達したことを示すために、0 または EOFオブジェクトを返すこともできます。
33448 @c COMMON
33449 @end defivar
33450
33451 @defivar {<buffered-input-port>} ready
33452 @c EN
33453 If set, it must be a procedure that takes no arguments.
33454 The procedure must return a true value if there are some data
33455 readily available to read, or @code{#f} otherwise.
33456 Unlike fully virtual ports, you don't need to distinguish
33457 binary and character I/O.
33458 @c JP
33459 設定されているなら、引数をとらない手続きでなければなりません。
33460 この手続きは、なにがしかの読み込み用データが利用可能になっていれば
33461 真の値を返し、そうでなければ、@code{#f}を返します。完全仮想ポートとはちがい、
33462 バイナリI/Oと文字I/Oを区別する必要はありません。
33463 @c COMMON
33464
33465 @c EN
33466 If this slot is not set, the port is regarded as it always has data ready.
33467 @c JP
33468 このスロットが未定義の場合、このポートは常にデータが利用可能になっている
33469 とみなされます。
33470 @c COMMON
33471 @end defivar
33472
33473 @defivar {<buffered-input-port>} close
33474 @c EN
33475 If set, it must be a procedure that takes no arguments.
33476 The procedure is called when the virtual buffered port is closed.
33477 You don't need to set this slot unless you need some cleaning up
33478 when the port is closed.
33479 @c JP
33480 設定されていれば、引数をとらない手続きでなければなりません。この手続きは
33481 仮想バッファポートがクローズされるときに呼出されます。ポートがクローズ
33482 されるときに、なにがしかのクリーンアップを行うのでなければ、設定する必要
33483 はありません。
33484 @c COMMON
33485
33486 @c EN
33487 This procedure may be called from a finalizer, and
33488 needs special care. See the note on finalization below.
33489 @c JP
33490 この手続きは、ファイナライザから呼ばれる可能性がありますので、特別な
33491 注意が必要です。後述のファイナライズに関する注意書きを参照してください。
33492 @c COMMON
33493 @end defivar
33494
33495 @defivar {<buffered-input-port>} filenum
33496 @c EN
33497 If set, it must be a procedure that returns underlying
33498 file descriptor number (exact nonnegative integer).
33499 The procedure is called when @code{port-file-number} is called
33500 on the port.
33501 @c JP
33502 設定されているなら、このポートの使っているファイルディスクリプタ番号(正確な非負整数)
33503 を返す手続きでなければなりません。この手続きは @code{port-file-number}
33504 をこのポートに対して呼出したときに呼ばれます。
33505 @c COMMON
33506
33507 @c EN
33508 If there's no such underlying file descriptor, you can
33509 return @code{#f}, or you can leave this slot unset.
33510 @c JP
33511 そのようなファイルディスクリプタが存在していなければ、
33512 @code{#f} を返すことができます。
33513 あるいは、このスロットを未設定にしておくこともできます。
33514 @c COMMON
33515 @end defivar
33516
33517 @defivar {<buffered-input-port>} seek
33518 @c EN
33519 If set, it must be a procedure that takes two arguments,
33520 @var{offset} and @var{whence}.
33521 It works the same way as @code{<virtual-input-port>}'s seek procedure;
33522 see above.
33523 @c JP
33524 設定されているなら、オフセット引数とどこからかを示す引数の2つをとる
33525 手続きでなければなりません。これは、前述の
33526 @code{<virtual-input-port>}のseek 手続きと同じように動作します。
33527 @c COMMON
33528
33529 @c EN
33530 This procedure may be called from a finalizer, and
33531 needs special care. See the note on finalization below.
33532 @c JP
33533 この手続きはファイナライザから呼ばれる可能性があり、特別な注意が
33534 必要です。後述のファイナライズに関する注意を参照してください。
33535 @c COMMON
33536 @end defivar
33537
33538 @c EN
33539 Besides those slot values, you can pass an exact nonnegative integer
33540 as the @code{:buffer-size} keyword argument to the @var{make} method
33541 to set the size of the port's internal buffer. If @code{:buffer-size}
33542 is omitted, or zero is passed, the system's default buffer size
33543 (something like 8K) is used. @code{:buffer-size} is not an instance
33544 slot and you cannot set it after the instance of the buffered port
33545 is created. The following example specifies the buffered port
33546 to use a buffer of size 64K:
33547 @c JP
33548 これらのスロットの値以外に、当該ポートの内部バッファのサイズを設定する
33549 のには@var{make}メソッドに@code{:buffer-size}というキーワード引数で非
33550 負の正確な整数を渡します。@code{:buffer-size}が省略されるか、0 が渡さ
33551 れた場合にはシステムのデフォルトのバッファサイズ(たとえば、8kとか)が使
33552 われます。@code{:buffer-size}はインスタンススロットではないので、バッ
33553 ファポートのインスタンスを生成したあとで設定することはできません。以下
33554 は 64K のバッファを使うバッファの作り方の例です。
33555 @c COMMON
33556
33557 @example
33558 (make <buffered-input-port> :buffer-size 65536 :fill my-filler)
33559 @end example
33560 @end deftp
33561
33562 @deftp {Class} <buffered-output-port>
33563 @clindex buffered-output-port
33564 @c MOD gauche.vport
33565 @c EN
33566 An instance of this class behaves as an output port.
33567 It has the following instance slots.
33568 You have to set at least @code{flush} slot.
33569 @c JP
33570 このクラスのインスタンスは出力ポートとして振舞います。これは、以下のような
33571 インスタンススロットを持ちます。少くとも @code{flush} は設定しなければ
33572 なりません。
33573 @c COMMON
33574
33575 @defivar {<buffered-output-port>} flush
33576 @c EN
33577 If set, it must be a procedure that takes two arguments,
33578 an @code{u8vector} buffer and a flag.
33579 The procedure must output data in the buffer to somewhere,
33580 and returns the number of bytes actually output.
33581 @c JP
33582 設定されているなら、@code{u8vector}のバッファとフラグという2つの
33583 引数をとる手続きでなければなりません。手続きはバッファ内のデータを
33584 どこかへ出力しなければならず、実際に出力したバイト数を返します。
33585 @c COMMON
33586
33587 @c EN
33588 If the flag is false, the procedure may output less
33589 than entire buffer (but at least one byte). If the flag
33590 is true, the procedure must output entire buffer.
33591 @c JP
33592 フラグが偽なら、この手続きはバッファ全体よりも少い(ただし、最低でも
33593 1バイト)の出力を行ってもかまいません。もしフラグが真ならば、この手続きは、
33594 バッファの内容をすべて出力しなければなりません。
33595 @c COMMON
33596 @end defivar
33597
33598 @defivar {<buffered-output-port>} close
33599 @c EN
33600 Same as @code{<buffered-input-port>}'s @code{close} slot.
33601 @c JP
33602 @code{<buffered-input-port>} の @code{close} スロットと同様です。
33603 @c COMMON
33604 @end defivar
33605
33606 @defivar {<buffered-output-port>} filenum
33607 @c EN
33608 Same as @code{<buffered-input-port>}'s @code{filenum} slot.
33609 @c JP
33610 @code{<buffered-input-port>} の @code{filenum} スロットと同様です。
33611 @c COMMON
33612 @end defivar
33613
33614 @defivar {<buffered-output-port>} seek
33615 @c EN
33616 Same as @code{<buffered-input-port>}'s @code{seek} slot.
33617 @c JP
33618 @code{<buffered-input-port>} の @code{seek} スロットと同様です。
33619 @c COMMON
33620 @end defivar
33621
33622 @c EN
33623 Besides those slot values, you can pass an exact nonnegative integer
33624 as the @code{:buffer-size} keyword argument to the @var{make} method
33625 to set the size of the port's internal buffer. See the description
33626 of @code{<buffered-input-port>} above for the details.
33627 @c JP
33628 これらのスロットの値以外に、当該ポートの内部バッファのサイズを設定する
33629 のには@var{make}メソッドに@code{:buffer-size}というキーワード引数で非
33630 負の正確な整数を渡します。詳しくは前述 @code{<buffered-input-port>}
33631 の項を見てください。
33632 @c COMMON
33633
33634 @end deftp
33635
33636 @c EN
33637 @subsubheading Uniform vector ports
33638 @c JP
33639 @subsubheading ユニフォームベクタポート
33640 @c COMMON
33641
33642 @c EN
33643 The following two procedures return a buffered input/output port
33644 backed up by a uniform vector. The source or destination vector
33645 can be any type of uniform vector, but they will be aliased
33646 to @code{u8vector} (see @code{uvector-alias} in
33647 @ref{Uvector conversion operations}).
33648 @c JP
33649 以下の 2つの手続きは、ユニフォームベクタでバックアップされた、
33650 バッファ入/出力ポートを返します。読み込み元のベクタあるいは
33651 書き出し相手のベクタはどのようなユニフォームベクタであってもかまいませんが、
33652 実際の入出力時には@code{u8vector} にaliasされます
33653 (@ref{Uvector conversion operations} の @code{uvector-alias} 参照)。
33654 @c COMMON
33655
33656 @c EN
33657 If used together with @code{pack}/@code{unpack}
33658 (see @ref{Packing binary data}), it is useful to parse
33659 or construct binary data structure. It is also an
33660 example of using virtual ports; read @file{gauche/vport.scm}
33661 (or @file{ext/vport/vport.scm} in the source tree) if you're
33662 curious about the implementation.
33663 @c JP
33664 @code{pack}/@code{unpack}(@ref{Packing binary data}参照) と一緒に使うと
33665 バイナリのデータ構造をパースしたり、構築したりするのに便利です。
33666 また、仮想ポートの使い方の例でもあります。実装法に興味があれば、
33667 ソースツリーの @file{gauche/vport.scm}(あるいは @file{ext/vport/vport.scm})
33668 を読んでください。
33669 @c COMMON
33670
33671 @defun open-input-uvector uvector
33672 @c MOD gauche.vport
33673 @c EN
33674 Returns an input port that reads the content of the given
33675 uniform vector @var{uvector} from its beginning. If reading
33676 operation reaches the end of @var{uvector}, EOF is returned.
33677 Seek operation is also implemented.
33678 @c JP
33679 与えられたユニフォームベクタ @var{uvector}の最初からその内容を読む
33680 入力ポートを返します。読み込み動作が、@var{uvector}の終端に到達したら
33681 EOFが返されます。シーク操作も実装されています。
33682 @c COMMON
33683 @end defun
33684
33685 @defun open-input-bytevector u8vector
33686 [R7RS base]
33687 @c MOD gauche.vport
33688 @c EN
33689 Similar to @code{open-input-uvector},
33690 but the argument must be an u8vector.
33691 This is an R7RS base procedure.
33692 @c JP
33693 @code{open-input-uvector}と似ていますが、引数はu8vectorでなければなりません。
33694 R7RS baseの手続きです。
33695 @c COMMON
33696 @end defun
33697
33698 @defun open-output-uvector :optional uvector :key extendable
33699 @c MOD gauche.vport
33700 @c EN
33701 Returns an output port that uses the given uvector as the
33702 storage for the data output to the port.
33703
33704 If @var{uvector} is completely filled, what happens after that
33705 depends on @var{extendable} - if it is false (default), the rest
33706 of data is discarded silently. If it is true, the storage is
33707 extended automatically to accommodate more data.
33708
33709 If you give true value to @var{extendable}, you have to retrieve
33710 the result by @code{get-output-uvector} below, since the uvector
33711 you passed in won't contain spilled data.
33712
33713 As a special case, you can omit @var{uvector} argument; then
33714 @code{u8vector} is used as the storage. In that case
33715 you can't specify @var{extendable} keyword argument, but it is
33716 assumed true, since it won't make sense otherwise. Use
33717 @code{get-output-uvector} to retrieve the stored result.
33718
33719 Seek operation is also implemented. Note that the meaning
33720 of @code{SEEK_END} whence differ between extendable and
33721 fixed-size uvector ports. For extendable ports,
33722 the end whence placed next to the biggest offset of
33723 the data ever written; if you open a port and just write
33724 one byte, the end whence is the second byte, no matter
33725 how big the existing buffer is. On the other hand,
33726 for fixed-size uvector ports, end whence is fixed to
33727 the next to the end of the given buffer, no matter
33728 how much data you've written to it. In the latter case,
33729 you can't seek on or past the end (you need to pass negative
33730 number along @code{SEEK_END} to @code{port-seek}).
33731 @c JP
33732 与えられた uvector をデータの格納に使うような出力ポートを返します。
33733
33734 @var{uvector}が全て埋まった後、何が起きるかは、@var{extendable}引数によって
33735 変わります。もし偽の値(デフォルト)では、更に送られてきたデータは黙って捨てられます。
33736 @var{extendable}が真の値であった場合、追加のデータを保持するため
33737 格納領域は自動的に拡張されます。
33738
33739 @var{extendable}に真の値を与えた場合、貯められたデータを取り出すには、
33740 下で説明する@code{get-output-uvector}を使ってください。渡した@var{uvector}
33741 引数には溢れたデータは格納されないので。
33742
33743 特別な場合として、@var{uvector}引数を省略することができます。
33744 この場合、データストレージとして@code{u8vector}が使われます。
33745 @var{uvector}引数を省略した場合、@var{extendable}引数を
33746 与えることはできませんが、これは真の値を与えたものとみなされます。
33747 でないと意味がないからです。@code{get-output-uvector}で
33748 貯められたデータを取り出すことができます。
33749
33750 ポートに対してシーク操作も使うことができます。
33751 ただし、whenceに@code{SEEK_END}を与えた場合の解釈が、@var{extendable}かどうかで
33752 変わることに注意してください。@var{extendable}なポートでは、
33753 末尾は「それまでに書き込まれたデータのうちもっとも大きなオフセット」の次に
33754 設定されます。uvectorポートを開いてすぐに1バイト書き込んだ状態では、
33755 @var{uvector}引数にどんなに大きなベクタを渡していたとしても、@code{SEEK_END}
33756 の基準点は2バイト目です。一方、@var{extendable}でないポートでは、
33757 末尾はそれまでに書き込んだデータによらず、常に与えた@var{uvector}の
33758 末尾の次になります。その場合は、末尾やそれ以降にシークすることはできません
33759 (@code{port-seek}に@code{SEEK_END}を渡す時、オフセットは必ず負数でなければ
33760 なりません)。
33761 @c COMMON
33762 @end defun
33763
33764 @defun open-output-bytevector
33765 [R7RS base]
33766 @c MOD gauche.vport
33767 @c EN
33768 Same as @code{open-output-uvector} without arguments.
33769 Uses extenable u8vector as the buffer.
33770 This is an R7RS base procedure.
33771 @c JP
33772 @code{open-output-uvector}を引数なしで呼ぶのと同じです。
33773 必要に応じて伸長するu8vectorをバッファに使います。
33774 R7RS baseの手続きです。
33775 @c COMMON
33776 @end defun
33777
33778 @defun get-output-uvector port :key shared
33779 @c MOD gauche.vport
33780 @c EN
33781 If @var{port} is a port created by @code{open-output-uvector}, returns
33782 a @var{uvector} that contains accumulated data.
33783 If @var{port} is not a port created by @code{open-output-uvector},
33784 @code{#f} is returned.
33785
33786 The returned uvector is the same type as the one passed to
33787 @code{open-output-uvector}, containing up to actually written data; it may
33788 be smaller than the @var{uvector} passed to @code{open-output-uvector};
33789 it can be larger if the port is extendable.
33790
33791 If the type of uvector is other than @code{s8vector} and @code{u8vector},
33792 and the written data doesn't fill up the whole element won't be
33793 in the result.
33794 For example, if you use @code{s32vector} to create the port,
33795 then write 7 bytes to it, @code{get-output-uvector} returns a
33796 single element @code{s32vector}, for the last 3 bytes does not
33797 consist a whole 32bit integer.
33798
33799 By default, the returned vector is a fresh copy of the contents.
33800 Passing true value to @var{shared} may avoid copying and allow
33801 sharing storage for the one being used by @var{port}. If you do so,
33802 keep in mind that if you seek back and write to @var{port} subsequently,
33803 the content of returned vector may be changed.
33804 @c JP
33805 @var{port}が@code{open-output-uvector}で作られたポートであるなら、
33806 これまでに蓄えられたデータを@var{uvector}として返します。
33807 @var{port}がそうでない場合は@code{#f}が返されます。
33808
33809 返り値のベクタは、@code{open-output-uvector}に渡したuvector
33810 と同じ型で、実際に書き込まれたデータの最後尾までの範囲になります。
33811 それは@code{open-output-uvector}に渡された@var{uvector}より小さいかも
33812 しれませんし、ポート作成時に@var{extendable}に真の値が渡されていた場合は
33813 元の@var{uvector}よりも大きいかもしれません。
33814
33815 uvectorの型が@code{s8vector}や@code{u8vector}以外である場合、
33816 書き込まれたデータのうち完全な要素に足りない部分は結果に含まれません。
33817 例えば、@code{s32vector}でポートを作り7バイト書き込んでから
33818 @code{get-output-uvector}を呼ぶと、返される@code{s32vector}は
33819 1要素になります。最後の3バイトは完全な32bit整数を構成しないからです。
33820
33821 デフォルトでは、返り値のベクタは新たにアロケートされたものです。
33822 しかし@var{shared}キーワード引数に真の値を渡すと、可能ならば、
33823 @var{port}が使っている格納領域をそのまま参照するベクタが返されます。
33824 このオプションによってコピーを減らすことができますが、
33825 後で@var{port}をシークして前に戻って再書き込みすると、
33826 返されたベクタの内容が書き換わってしまう可能性があることに注意してください。
33827 @c COMMON
33828 @end defun
33829
33830 @defun get-output-bytevector port
33831 [R7RS base]
33832 @c MOD gauche.vport
33833 @c EN
33834 Extract the data put to an bytevector output port as an u8vector.
33835 The port must be created by @code{open-output-bytevector} or
33836 @code{open-output-uvector}.
33837 This is an R7RS base procedure.
33838 @c JP
33839 バイトベクタ出力ポートに出力されたデータをu8vectorとして取り出して返します。
33840 @var{port}は@code{open-output-bytevector}か
33841 @code{open-output-uvector}で作られたものでなければなりません。
33842 R7RS baseの手続きです。
33843 @c COMMON
33844 @end defun
33845
33846
33847 @c EN
33848 @subsubheading List ports
33849 @c JP
33850 @subsubheading リストポート
33851 @c COMMON
33852
33853 @c EN
33854 The following procedures allow you to use list of characters
33855 or octets as a source of an input port. These are (a kind of)
33856 opposite of @code{port->list} family
33857 (@pxref{Input utility functions}) or @code{port->char-lseq} family
33858 (@pxref{Lazy sequences}).
33859 @c JP
33860 以下の手続きは、文字またはオクテットのリストを入力ポートのソースとして利用するものです。
33861 ある意味、@code{port->list}系の手続き(@ref{Input utility functions}参照)や
33862 @code{port->char-lseq}系の手続き(@ref{Lazy sequences}参照)の逆であると
33863 言えます。
33864 @c COMMON
33865
33866 @defun open-input-char-list char-list
33867 @defunx open-input-byte-list byte-list
33868 @c MOD gauche.vport
33869 @c EN
33870 Creates and returns an input port that uses
33871 the given list of characters and bytes as the source.
33872 @c JP
33873 与えられた文字もしくはオクテットのリストをデータ源とする
33874 入力ポートを作って返します。
33875 @c COMMON
33876
33877 @example
33878 (read (open-input-char-list '(#\a #\b)))
33879 @result{} ab
33880 @end example
33881 @end defun
33882
33883 @defun get-remaining-input-list port
33884 @c MOD gauche.vport
33885 @c EN
33886 If @var{port} is the one created by @code{open-input-char-list}
33887 or @code{open-input-byte-list}, returns a list of remaining data
33888 that hasn't been read yet. If the port already read everything,
33889 or the port is not the one created by @code{open-input-char-list}
33890 or @code{open-input-byte-list}, an empty list is returned.
33891
33892 A caveat: Gauche allows mixing binary input and textual input from
33893 the same port. If you read or even peek a byte from a port
33894 created from a character list, the port buffers a character
33895 and disassembles it to bytes; the disassembled character
33896 may not be included in the remaining input list.
33897 @c JP
33898 @var{port}が@code{open-input-char-list}か@code{open-input-byte-list}で
33899 作られたものであった場合、ポート中のまだ読まれていない部分のリストを返します。
33900 既に全てのデータが読まれていたり、ポートが
33901 @code{open-input-char-list}か@code{open-input-byte-list}で作られたもので
33902 なかった場合は、空リストが返されます。
33903
33904 注意: Gaucheは一つのポートからのバイナリ読み出しと文字読み出しを混ぜて使うことを
33905 許しています。文字のリストで作られたリストポートからバイトを読み出したり、
33906 あるいは@code{peek-byte}した場合、ひとつ文字がデータ源から取り出され、
33907 バイト列に分解されてポート内部の一時バッファに置かれます。
33908 その状態でこの手続きを呼び出した場合、バッファ内のバイト列は戻り値には含まれません。
33909 @c COMMON
33910 @end defun
33911
33912 @c EN
33913 @subsubheading Generator ports
33914 @c JP
33915 @subsubheading ジェネレータポート
33916 @c COMMON
33917
33918 @c EN
33919 The following procedures allow you to use character generators
33920 or byte generators as a source of an input port. These are (a kind of)
33921 opposite of @code{port->char-generator} family
33922 (@pxref{Generator constructors}).
33923 @c JP
33924 以下の手続きは、文字あるいはオクテットのジェネレータ
33925 入力ポートのソースとして利用するものです。
33926 ある意味、@code{port->char-generator}系の手続き
33927 (@ref{Generator constructors}参照)の逆であると言えます。
33928 @c COMMON
33929
33930 @defun open-input-char-generator cgen
33931 @defunx open-input-byte-generator bgen
33932 @c MOD gauche.vport
33933 @c EN
33934 Creates and returns an input port that uses
33935 the given generators as the source. The @var{cgen} argument
33936 must be a generator that yields characters. The @var{bgen} argument
33937 must be a generator that yields bytes (exact integers between 0 and
33938 255, inclusive).
33939 An error will be raised if the given generator yields
33940 incorrect type of objects.
33941 @c JP
33942 与えられたジェネレータをデータ源とする入力ポートを作って
33943 返します。@var{cgen}は文字を生成するジェネレータ、
33944 @var{bgen}はバイト(オクテット、0から255の間の正確な整数)を
33945 生成するジェネレータでなけばなりません。
33946 ジェネレータが想定される値以外のものを返した場合はエラーが通知されます。
33947 @c COMMON
33948
33949 @example
33950 (read (open-input-char-generator (string->generator "foo")))
33951 @result{} foo
33952 @end example
33953
33954 @c EN
33955 Since the generators are objects relying on side effects,
33956 you shouldn't use @var{cgen} or @var{bgen} after you pass them
33957 to those procedures; if you use them afterwards, the result
33958 is undefined.
33959 @c JP
33960 ジェネレータは本質的に副作用に依存しているオブジェクトなので、
33961 この手続きに@var{cgen}や@var{bgen}を渡したら、その後で
33962 それらのジェネレータに触ってはなりません。
33963 もしそれらのジェネレータを使ってしまった場合、以降の動作は未定義となります。
33964 @c COMMON
33965 @end defun
33966
33967 @defun get-remaining-input-generator port
33968 @c MOD gauche.vport
33969 @c EN
33970 If @var{port} is the one created by @code{open-input-char-generator}
33971 or @code{open-input-byte-generator}, returns a generator that
33972 yields the characters or bytes that haven't been read yet.
33973 If the port already read everything, an empty generator
33974 is returned.
33975
33976 Once you take the remaining input generator, you should no longer
33977 read from the input generator ports; they share internal states and
33978 mixing them will likely to cause unexpected behaviors.
33979 If side-effects safe behavior is desired, use lazy sequence and
33980 input list ports.
33981 @c JP
33982 @var{port}が@code{open-input-char-generator}か
33983 @code{open-input-byte-generator}で作られたものであった場合、
33984 残りのデータを生成するジェネレータを返します。
33985 ポートが既にデータを全て消費していた場合は、空のジェネレータが返されます。
33986
33987 残りのデータを生成するジェネレータを取り出したら、
33988 ジェネレータポートからはも読み出してはなりません。
33989 内部状態を共有しているため、予期せぬ結果がもたらされることになるでしょう。
33990 副作用に頼らず安全な振る舞いが必要な場合は、遅延シーケンスと
33991 リストポートを使うのが良いでしょう。
33992 @c COMMON
33993 @end defun
33994
33995 @c EN
33996 @subsubheading Accumulator ports
33997 @c JP
33998 @subsubheading アキュムレータポート
33999 @c COMMON
34000
34001 @c EN
34002 Accumulators are dual to generators; it's a procedure that accepts a value
34003 at a time, and the end of the value is indicated by EOF.
34004 @xref{R7RS generators}, for the basic operations of accumulators.
34005
34006 The following procedures turns an accumulator that accepts characters
34007 or octets into an output port.
34008 @c JP
34009 アキュムレータはジェネレータの双対です。値を一回にひとつづつ受け取る手続きで、
34010 値の末端はEOFで示されます。
34011 アキュムレータの操作については@ref{R7RS generators}を参照してください。
34012
34013 以下の手続きは、文字またはバイトを受け取るアキュムレータを出力ポートに変換します。
34014 @c COMMON
34015
34016 @defun open-output-char-accumulator acc
34017 @c MOD gauche.vport
34018 @c EN
34019 Returns an output port that sends the output characters to an
34020 accumulator @code{acc}, which takes a character as the argument.
34021 When the returned output port is closed, EOF is passed to @var{acc}.
34022
34023 Note: The behavior is undefined if you try to perform binary output
34024 to the returned output port.
34025 @c JP
34026 @var{acc}は文字を受け取るアキュムレータです。
34027 出力される文字を@var{acc}に送る出力ポートを返します。
34028 出力ポートがクローズされると、@var{acc}にEOFが渡されます。
34029
34030 註: 返される出力ポートにバイナリ出力を行った場合の動作は未定義です。
34031 @c COMMON
34032 @end defun
34033
34034 @defun open-output-char-accumulator acc
34035 @c MOD gauche.vport
34036 @c EN
34037 Returns an output port that sends the output bytes to an
34038 accumulator @code{acc}, which takes a byte as the argument.
34039 When the returned output port is closed, EOF is passed to @var{acc}.
34040
34041 A character sent to the output port is converted to octets in
34042 the Gauche's native encoding.
34043 @c JP
34044 @var{acc}はバイト(オクテット)を受け取るアキュムレータです。
34045 出力されるバイトを@var{acc}に送る出力ポートを返します。
34046 出力ポートがクローズされると、@var{acc}にEOFが渡されます。
34047
34048 文字が出力された場合は、Gaucheの内部エンコーディングにしたがってオクテット列に
34049 変換されて@var{acc}に送られます。
34050 @c COMMON
34051 @end defun
34052
34053 @defun open-output-accumulator acc
34054 @c MOD gauche.vport
34055 @c EN
34056 The accumulator @var{acc} must accept a byte, a character or a string.
34057 Returns an output port that sends the output data to the @var{acc}.
34058 When the returned output port is closed, EOF is passed to @var{acc}.
34059 @c JP
34060 @var{acc}はバイト(オクテット)、文字、文字列を受け取るアキュムレータです。
34061 出力データを@var{acc}に送る出力ポートを返します。
34062 出力ポートがクローズされると、@var{acc}にEOFが渡されます。
34063 @c COMMON
34064 @end defun
34065
34066 @c EN
34067 @subsubheading Note on finalization
34068 @c JP
34069 @subsubheading ファイナライズに関する注意
34070 @c COMMON
34071
34072 @c EN
34073 If an unclosed virtual port is garbage collected, its close procedure
34074 is called (in case of virtual buffered ports, its flush procedure
34075 may also be called before close procedure). It is done by
34076 a finalizer of the port. Since it is a part of garbage-collection
34077 process (although the Scheme procedure itself is called outside of
34078 the garbage collector main part), it requires special care.
34079 @c JP
34080 クローズされていない仮想ポートがガベージ・コレクションされると、
34081 クローズ手続きが呼ばれます(仮想バッファポートの場合は、
34082 フラッシュ手続きがクローズ手続きの前に呼ばれます)。これは、
34083 そのポートのファイナライザによって行われます。これはガベージ・コレクション
34084 処理の一部ですから(Scheme 手続きそのものはガーベッジ・コレクタの
34085 メインパートの外側で呼ばれているのですが、それでも)特別な注意が必要です。
34086 @c COMMON
34087
34088 @itemize @bullet
34089 @item
34090 @c EN
34091 It is possible that the object the virtual port has a reference
34092 may already be finalized. For example, if a virtual port @var{X}
34093 holds the only reference to a @emph{sink} port @var{Y}, to which
34094 the output goes. @var{X}'s @code{flush} procedure sends its output to
34095 @var{Y}. However, if @code{flush} procedure can be called from a
34096 finalizer, it may be possible that @var{Y}'s finalizer has already been
34097 called and @var{Y} is closed. So @var{X}'s @code{flush} procedure
34098 has to check if @var{Y} has not been closed.
34099 @c JP
34100 仮想ポートが参照しているオブジェクトが既にファイナライズされて
34101 しまっているということがあり得ます。たとえば、仮想ポート @var{X}
34102 は、@emph{流し込み用}のポート @var{Y} への唯一の参照を保持しており、それに
34103 出力するものとします。@var{X}の @code{flush} 手続きは、その出力を
34104 @var{Y}へ送ります。もし@code{flush} 手続きがファイナライザから
34105 呼ばれた場合、@var{Y} のファイナライザが既に
34106 呼ばれていて、@var{Y} がクローズしてしまっていることがあるのです。
34107 従って @var{X} の @code{flush} 手続きは、@var{Y} が既にクローズして
34108 いるかどうかをチェックする必要があります。
34109 @c COMMON
34110
34111 @item
34112 @c EN
34113 You cannot know when and in which thread the finalizer runs.
34114 So if the procedure like @code{close} or @code{flush} of virtual ports
34115 need to lock or access the global resource, it needs to take
34116 extra care of avoiding dead lock or conflict of access.
34117 @c JP
34118 いつ、どのスレッドでファイナライザが走るかを知ることはできません。
34119 それゆえ、仮想ポートの @code{close} あるいは @code{flush} などの
34120 手続きが、グローバルなリソースをロックしたり、アクセスしたりする
34121 必要のある場合には、デッドロックやアクセスの衝突を回避するために
34122 特に注意する必要があります。
34123 @c COMMON
34124
34125 @c EN
34126 Even in single thread programs, the finalizer can run anywhere
34127 in Scheme programs, so effectively it should be considered as
34128 running in a different thread.
34129 @c JP
34130 単一スレッドのプログラムにおいても、ファイナライザは、Schemeの
34131 プログラムのいたるところで走る可能性があります。したがって、実質的に
34132 それは別のスレッドで走っていると考えておくべきです。
34133 @c COMMON
34134 @end itemize
34135
34136 @c Local variables:
34137 @c mode: texinfo
34138 @c coding: utf-8
34139 @c end: