Debian Codegraph @

doc/macro.texi

raw
1 @node Macros, Core library, Core syntax, Top
2 @chapter Macros
3 @c NODE マクロ
4
5 @c EN
6 Macro of Lisp-family language is very different feature from
7 ones of other languages, such as C preprocessor macros.
8 It allows you to extend the original language syntax.
9 You can use macros to change Gauche syntax
10 so that you can run a Scheme program written to other Scheme
11 implementations, and you can even design your own mini-language
12 to solve your problem easily.
13 @c JP
14 Lisp系言語のマクロは、他の言語に見られるマクロ(例えばCプリプロセッサマクロ)とは
15 大きく異なります。Lispのマクロは元の言語の構文を拡張する手段なのです。
16 例えば、Gaucheの構文を若干変えることで他のScheme実装用に書かれたSchemeプログラムを
17 走らせたり、あるいは自分の問題解決に適した「ミニ言語」をデザインすることさえできます。
18 @c COMMON
19
20 @c EN
21 Gauche supports hygienic macros, which allows to write safe macros
22 by avoiding name collisions. If you know traditional Lisp macros
23 but new to hygienic macros, they might seem confusing at first.
24 We have an introductory section (@ref{Why hygienic?}) for those who
25 are not familiar with hygienic macros; if you know what they are,
26 you can skip the section.
27 @c JP
28 Gaucheは、名前の衝突を避ける安全なマクロを簡単に書ける、「衛生的な(hygienic)」
29 マクロをサポートします。これは、従来のLispマクロは知っていても衛生的なマクロを
30 初めて見る人には、やや難解に見えるかもしれません。
31 衛生的マクロに馴染みが無い読者向けに、紹介の節を用意しました(@ref{Why hygienic?})。
32 既に衛生的マクロを知っている読者はその節は読み飛ばして構いません。
33 @c COMMON
34
35 @menu
36 * Why hygienic?::
37 * Hygienic macros::
38 * Traditional macros::
39 * Hybrid macros::
40 * Syntax parameters::
41 * Identifiers::
42 * Debugging macros::
43 * Macro utilities::
44 @end menu
45
46 @node Why hygienic?, Hygienic macros, Macros, Macros
47 @section Why hygienic?
48 @c NODE なぜ衛生的マクロか
49
50 @c EN
51 Lisp macro is a programmatic transformation of source code.
52 A @emph{macro transformer} is a procedure that takes a subtree of
53 source code, and returns a reconstructed tree of source code.
54 @c JP
55 Lispのマクロは、ソースコードをプログラムによって変換するものです。
56 @emph{マクロ変換器(macro transformer)}が、ソースコードの部分木を受け取り、
57 加工したソースコードの部分木を返します。
58 @c COMMON
59
60 @c EN
61 The traditional Lisp macros take the input source code as
62 an S-expression, and returns the output as another S-expression.
63 Gauche supports that type of macro, too, with @code{define-macro} form.
64 Here's the simple definition of @code{when} with the traditional macro.
65 @c JP
66 伝統的なLispマクロでは、入力となるソースコードも、出力されるコードも、単なるS式でした。
67 Gaucheはそのタイプのマクロも@code{define-macro}形式でサポートしています。
68 例えば、@code{when}は伝統的マクロで次のとおり書けます。
69 @c COMMON
70
71 @example
72 (define-macro (when test . body)
73 `(if ,test (begin ,@@body)))
74 @end example
75
76 @c EN
77 For example,
78 if the macro is used as @code{(when (zero? x) (print "zero") 'zero)},
79 the above macro transformer rewrites it to
80 @code{(if (zero? x) (begin (print "zero") 'zero))}. So far, so good.
81 @c JP
82 このマクロが@code{(when (zero? x) (print "zero") 'zero)}のように使われたとすれば、
83 上記の変換器はそれを@code{(if (zero? x) (begin (print "zero") 'zero))}と
84 書き換えます。一見問題なさそうですね。
85 @c COMMON
86
87 @c EN
88 But what if the @code{when} macro is used in an environment
89 where the names @code{begin} or @code{if} is bound to nonstandard values?
90 @c JP
91 けれども、@code{begin}や@code{if}が通常とは違う意味で束縛されている環境で
92 @code{when}が使われたらどうなるでしょう。
93 @c COMMON
94
95 @example
96 (let ([begin list])
97 (when (zero? x) (print "zero") 'zero))
98 @end example
99
100 @c EN
101 The expanded result would be as follows:
102 @c JP
103 展開結果は次の通りになります。
104 @c COMMON
105
106 @example
107 (let ([begin list])
108 (if (zero? x) (begin (print "zero") 'zero)))
109 @end example
110
111 @c EN
112 This obviously won't work as the macro writer intended, since
113 @code{begin} in the expanded code refers to the locally bound name.
114 @c JP
115 これでは意図した通りには動きません。展開された結果の中の@code{begin}が
116 ローカル変数と解釈されてしまいます。
117 @c COMMON
118
119 @c EN
120 This is a form of @emph{variable capture}. Note that, when Lisp
121 people talk about variable capture of macros, it often means
122 another form of capture, where the temporary variables inserted
123 by a macro would unintentionally capture the variables passed to
124 the macro. That kind of variable capture can be avoided easily
125 by naming the temporary variables something that never conflict,
126 using @code{gensym}.
127 @c JP
128 これは@emph{変数捕捉}の一形態です。Lispのマクロによる変数捕捉というと、
129 別の形態、すなわちマクロにより導入される一時変数がマクロに渡された式内の
130 変数を意図せずに捕捉してしまうことが話題に上ることが多いのですが、
131 そちらは@code{gensym}を使って一時変数を決して衝突しない名前にすることで
132 簡単に回避できます。
133 @c COMMON
134
135 @c EN
136 On the other hand, the kind of variable capture in the above example
137 can't be avoided by @code{gensym}, because @code{(let ([begin list]) ...)}
138 part isn't under macro writer's control. As a macro writer, you can
139 do nothing to prevent the conflict, just hoping the
140 macro user won't do such a thing. Sure, rebinding @code{begin} is
141 a crazy idea that nobody perhaps wants to do, but it can happen on
142 @emph{any} global variable, even the ones you define for your library.
143 @c JP
144 しかし上の例のような変数捕捉は@code{gensym}では回避できません。外側の
145 @code{(let ([begin list]) ...)}の部分はマクロを書く人には制御できない
146 からです。マクロ作成者が、この衝突を避けるために出来ることは何もありません。
147 せいぜい、マクロ使用者がそんな使い方をしないように祈るだけです。
148 もちろん、@code{begin}を再束縛するなんて誰もやろうとは思わないかもしれませんが、
149 同様の衝突はあなたのライブラリが提供するものも含めあらゆるグローバル変数について
150 起こり得るのです。
151 @c COMMON
152
153 @c EN
154 Various Lisp dialects have tried to address this issue in different
155 ways. Common Lisp somewhat relies on the common sense of the
156 programmer---you can use separate packages to reduce the chance
157 of accidental conflict but can't prevent the user from binding
158 the name in the same package.
159 (The Common Lisp spec says it is undefined if you locally rebind
160 names of CL standard symbols; but it doesn't prevent you from locally
161 rebinding symbols that are provided by user libraries.)
162 @c JP
163 異なるLisp方言はそれぞれ異なる方法でこの問題に対処してきました。
164 Common Lispは、ある意味プログラマの常識に頼ります。マクロ作成者は
165 ライブラリのパッケージを分けることで、偶然名前が衝突してしまう危険性を
166 減らせますが、マクロ使用者が同じパッケージの名前を再束縛することを防げるわけではありません。
167 (Common Lispの仕様ではCL標準のシンボルをローカルに再束縛した場合の
168 動作は未定義とされていますが、ユーザが提供するライブラリについては
169 何も決められていません。)
170 @c COMMON
171
172 @c EN
173 Clojure introduced a way to directly refer to the toplevel variables
174 by a namespace prefix, so it can bypass whatever local bindings of
175 the same name (also, it has a sophisticated quasiquote form that
176 automatically renames free variables to refer to the toplevel ones).
177 It works, as far as there are no local macros. With
178 local macros, you need a way to distinguish different local bindings
179 of the same name, as we see in the later examples. Clojure's way
180 can only distinguish between local and toplevel bindings.
181 It's ok for Clojure which doesn't have local macros,
182 but in Scheme, we prefer uniform and orthogonal axioms---if functions
183 can be defined locally with lexical scope, why not macros?
184 @c JP
185 Clojureは、名前空間プレフィクスによって直接トップレベル変数を参照する方法を
186 導入したので、同名のローカル変数束縛をバイパスして意図するトップレベル変数を確実に
187 参照できます (また、Clojureのquasiquoteは高機能で、自由変数を自動的に
188 プレフィクスつきのトップレベル変数へと変換してくれます。)
189 この方法はローカルマクロが存在しない限りはうまくいきます。
190 ローカルマクロがあると、後の例で見るように、複数の同名のローカル変数束縛を
191 区別する必要が出てきます。Clojureの方法はローカル変数束縛とトップレベル変数束縛を
192 区別できるだけです。Clojureにはローカルマクロが無いのでそれでよいのですが、
193 Schemeは一様で直交する定理を重視するので、レキシカルスコープを持つローカル関数があるなら、
194 レキシカルスコープを持つローカルマクロもやっぱり欲しいわけです。
195 @c COMMON
196
197 @c EN
198 Let's look at the local macro with lexical scope. For the sake of
199 explanation, suppose we have
200 @emph{hypothetical} local macro binding form, @code{let-macro},
201 that binds a local identifiers to a macro transformer.
202 (We don't actually have @code{let-macro}; what we have is
203 @code{let-syntax} and @code{letrec-syntax}, which have slightly
204 different way to call macro transformers. But here @code{let-macro} may
205 be easier to understand as it is similar to @code{define-macro}.)
206 @c JP
207 レキシカルスコープを持つローカルマクロを見てみましょう。説明のために、
208 ローカルなマクロ束縛を書ける@code{let-macro}という形式があると仮定します。
209 (実際には@code{let-macro}形式はありません。マクロ変換器の指定方法が
210 やや異なる@code{let-syntax}と@code{letrec-syntax}という形式があります。
211 ただ、ここでは@code{define-macro}と似たような形で例を示す方がわかりやすいので、
212 そのような@code{let-macro}があるものとして説明します。)
213 @c COMMON
214
215 @example
216 (let ([f (^x (* x x))])
217 (let-macro ([m (^[expr1 expr2] `(+ (f ,expr1) (f ,expr2)))])
218 (let ([f (^x (+ x x))])
219 (m 3 4)))) ; [1]
220 @end example
221
222 @c EN
223 The local identifier @var{m} is bound to a macro transformer
224 that takes two expressions, and returns an S-expression.
225 So, the @code{(m 3 4)} form [1] would be expanded into
226 @code{(+ (f 3) (f 4))}. Let's rewrite the above expression
227 with the expanded form. (After expansion, we no longer
228 need @code{let-macro} form, so we don't include it.)
229 @c JP
230 ローカルな識別子@var{m}は、二つの式を引数として取り、S式を返すマクロ変換器に
231 束縛されます。従って、[1]の@code{(m 3 4)}は
232 @code{(+ (f 3) (f 4))}へと展開されます。上の式を展開結果を使って
233 書き直してみます (展開後は@code{let-macro}フォームはもはや必要ないので
234 展開結果には含めていません)。
235 @c COMMON
236
237 @example
238 (let ([f (^x (* x x))])
239 (let ([f (^x (+ x x))])
240 (+ (f 3) (f 4)))) ; [2]
241 @end example
242
243 @c EN
244 Now, the question. Which binding @code{f} in the expanded form [2]
245 should refer? If we literally interpret the expansion,
246 it would refer to the inner binding @code{(^x (+ x x))}.
247 However, following the Scheme's scoping principle, the outer
248 code should be fully understood regardless of inner code:
249 @c JP
250 さてここで問題です。展開結果に現れた[2]のフォーム内の@code{f}は、どちらの
251 @code{f}を参照すべきでしょう。上の式を文字通り解釈するなら、
252 より内側にある@code{(^x (+ x x))}への束縛となります。
253 けれども、Schemeのスコープ規則にしたがえば、
254 外側のコードは、内側にどんなコードが来るかに関わらず意味が決まって欲しいわけです。
255 @c COMMON
256
257 @example
258 (let ([f (^x (* x x))])
259 (let-macro ([m (^[expr1 expr2] `(+ (f ,expr1) (f ,expr2)))])
260 @c EN
261 ;; The code here isn't expected to accidentally alter
262 ;; the behavior defined outside.
263 @c JP
264 ;; ここに書かれたコードがうっかり外側のコードに影響を与えてしまう
265 ;; のは避けたい。
266 @c COMMON
267 ))
268 @end example
269
270 @c EN
271 The macro writer may not know the inner @code{let} shadows
272 the binding of @code{f} (the inner forms may be @code{include}d,
273 or may be changed by other person who didn't fully realize
274 the macro expansion needs to refer outer @code{f}).
275 @c JP
276 マクロ作成者は内側の@code{let}が@code{f}をシャドウしてしまうことを
277 知らないかもしれません(内側のフォームは他のコードを@code{include}している
278 かもしれませんし、また他の人が、ローカルマクロが外側の@code{f}を参照することに
279 気づかずに内側のコードを変更してしまうかもしれません。)
280 @c COMMON
281
282 @c EN
283 To ensure the local macro to work regardless of what's placed
284 inside @code{let-macro}, we need a sure way to refer the outer
285 @code{f} in the result of macro expansion. The basic idea is
286 to ``mark''
287 the names inserted by the macro transformer @code{m}---which are
288 @code{f} and @code{+}---so that we can distinguish two @code{f}'s.
289 @c JP
290 @code{let-macro}の中に置かれるコードが何であれローカルマクロが動作するためには、
291 マクロの展開結果から「外側の@code{f}」を確実に参照する方法が必要です。
292 基本的なアイディアは、
293 マクロ変換器@code{m}により挿入される名前(@code{f}と@code{+})に
294 「印」をつけて、二つの@code{f}を区別するというものです。
295 @c COMMON
296
297 @c EN
298 For example, if we would rewrite the entire form and @emph{renames}
299 corresponding local identifiers as follows:
300 @c JP
301 例えば、フォーム全体を書き直して、対応するローカル変数がユニークな名前を持つように
302 @emph{リネーム}したらどうでしょう:
303 @c COMMON
304
305 @example
306 (let ([f_1 (^x (* x x))])
307 (let-macro ([m (^[expr1 expr2] `(+ (f_1 ,expr1) (f_1 ,expr2)))])
308 (let ([f_2 (^x (+ x x))])
309 (m 3 4))))
310 @end example
311
312 @c EN
313 Then the naive expansion would correctly preserve scopes; that is,
314 expansion of @code{m} refers @code{f_1}, which wouldn't conflict
315 with inner name @code{f_2}:
316 @c JP
317 こうしておけばナイーブな展開でもスコープが正しく保たれます。つまり、
318 @code{m}の展開結果に現れる@code{f_1}は内側の@code{f_2}と衝突しません。
319 @c COMMON
320
321 @example
322 (let ([f_1 (^x (* x x))])
323 (let ([f_2 (^x (+ x x))])
324 (+ (f_1 3) (f_1 4))))
325 @end example
326
327 @c EN
328 (You may notice that this is similar to lambda calculus treating
329 lexical bindings with higher order functions.)
330 @c JP
331 (ラムダ計算において、レキシカルスコープを保ったまま高階関数を扱う際に
332 似たようなリネーム戦略を見たことがあるかもしれません)
333 @c COMMON
334
335 @c EN
336 The above example deal with avoiding @code{f} referred from the
337 macro @emph{definition} (which is, in fact, @code{f_1}) from being
338 shadowed
339 by the binding of @code{f} at the macro @emph{use} (which is @code{f_2}).
340 @c JP
341 上の例ではマクロの@emph{定義時}に現れる@code{f}(リネーム後は@code{f_1})が
342 マクロの@emph{使用時}に現れる@code{f} (リネーム後は@code{f_2}) によって
343 シャドウされることを避ける話でした。
344 @c COMMON
345
346 @c EN
347 Another type of variable capture (the one most often talked about,
348 and can be avoided by @code{gensym})
349 is that a variable in macro use site is shadowed by the binding introduced
350 by a macro definition. We can apply the same renaming strategy to
351 avoid that type of capture, too. Let's see the following example:
352 @c JP
353 一方、もう一つのタイプの変数捕捉 (より頻繁に話題に上る、@code{gensym}で回避できる捕捉)
354 は、マクロ使用時の変数がマクロ定義時に導入される束縛によりシャドウされてしまう
355 という問題です。これについても、同じリネーム戦略が使えます。
356 次の例を見てみましょう。
357 @c COMMON
358
359 @example
360 (let ([f (^x (* x x))])
361 (let-macro ([m (^[expr1] `(let ([f (^x (+ x x))]) (f ,expr1)))])
362 (m (f 3))))
363 @end example
364
365 @c EN
366 The local macro inserts binding of @code{f} into the expansion.
367 The macro use @code{(m (f 3))} also contains a reference to @code{f},
368 which should be the outer @code{f},
369 since the macro use is lexically outside of the @code{let} inserted
370 by the macro.
371 @c JP
372 ローカルマクロは@code{f}の束縛を導入しています。
373 一方、マクロの使用時@code{(m (f 3))}に、@code{f}への参照が含まれています。
374 後者の@code{f}は外側の@code{f}を指すべきです。なぜならマクロを使っている
375 フォームは字句上、マクロ定義の@code{let}の外側にあるからです。
376 @c COMMON
377
378 @c EN
379 We could rename @code{f}'s according to its lexical scope:
380 @c JP
381 @code{f}をレキシカルスコープによってリネームすれば次のようになるでしょう。
382 @c COMMON
383
384 @example
385 (let ([f_1 (^x (* x x))])
386 (let-macro ([m (^[expr1] `(let ([f_2 (^x (+ x x))]) (f_2 ,expr1)))])
387 (m (f_1 3))))
388 @end example
389
390 @c EN
391 Then expansion unambiguously distinguish two @code{f}'s.
392 @c JP
393 これだと展開しても二つの@code{f}はきちんと区別されます。
394 @c COMMON
395
396 @example
397 (let ([f_1 (^x (* x x))])
398 (let ([f_2 (^x (+ x x))])
399 (f_2 (f_1 3))))
400 @end example
401
402 @c EN
403 This is, in principle, what hygienic macro is about (well, almost).
404 In reality, we don't rename everything in batch.
405 One caveat is in the latter example---we statically renamed
406 @code{f} to @code{f_2}, but it is possible that the macro
407 recursively calls itself, and we have to distinguish @code{f}'s
408 introduced in every individual expansion of @code{m}.
409 So macro expansion and renaming should work together.
410 @c JP
411 以上が、衛生的マクロの原理です (まあ、だいたいは)。
412 ただし、実際の実装では、すべてを一気にリネームすることはありません。
413 後者の例のようなケースで注意すべき点があります。後者の例では静的に
414 @code{f}を@code{f_2}にリネームしましたが、より複雑な場合にマクロ展開器が
415 再帰的に自分を呼ぶことがあり、その場合にはマクロの展開ごとに挿入される@code{f}を
416 別のものとして扱う必要があります。
417 従って、マクロの展開とリネームは協調して動作しなければなりません。
418 @c COMMON
419
420 @c EN
421 There are multiple strategies to implement it, and the
422 Scheme standard doesn't want to bind implementations to single
423 specific strategy. The standard only states the properties
424 the macro system should satisfy, in two concise sentences:
425 @c JP
426 それを実装する戦略はいくつか考えられます。そして、Scheme標準は実装を
427 どれかひとつの戦略に縛ってしまうことを良しとしません。
428 結果的に、標準はマクロシステムが満たすべき性質を、二つの簡潔な
429 文で示すに止まります:
430 @c COMMON
431
432 @quotation
433 @c EN
434 If a macro transformer inserts a binding for an
435 identifier (variable or keyword), the identifier will in effect be
436 renamed throughout its scope to avoid conflicts with
437 other identifiers.
438 @c JP
439 マクロ展開器が識別子(変数かキーワード)の束縛を挿入した場合、
440 識別子はそのスコープ内で実効的にリネームされ、
441 他の識別子との衝突を避けられる。
442 @c COMMON
443
444 @c EN
445 If a macro transformer inserts a free reference to an
446 identifier, the reference refers to the binding that was
447 visible where the transformer was specified,
448 regardless of any local bindings that surround the use of the macro.
449 @c JP
450 マクロ展開器が識別子の自由参照を挿入した場合、その識別子は展開器が定義された場所から
451 見える束縛を参照し、マクロが使われる場所を囲むローカル束縛には影響されない。
452 @c COMMON
453 @end quotation
454
455 @c EN
456 Just from reading this,
457 it may not be obvious @emph{how} to realize those properties, and
458 the existing hygienic macro mechanisms (e.g. @code{syntax-rules}) hide
459 the ``how'' part. That's probably one of the reason some people
460 feel hygienic macros are difficult to grasp. It's like
461 continuations---its description is concise but at first
462 you have no idea how it works; then, through experience,
463 you become familiarized yourself to it, and then you reread
464 the original description and understand it says exactly what it is.
465 @c JP
466 これを読んだだけでは、これらの性質を@emph{いかにして}実現するかは
467 すぐにはわからないかもしれません。そして既存の衛生的マクロ(@code{syntax-rules}など)は
468 この@emph{いかにして}の部分を隠しています。それが、
469 衛生的マクロをとっつきにくく思う理由の一つかもしれません。
470 これはある意味、継続に似ています。継続の仕様はごく簡潔に述べられていて、
471 最初に読んだときにはどう動くかさっぱりわからないかもしれません。
472 しかし経験を積んで使うのに慣れた後でもう一度元の説明を読むと、
473 必要十分なことが書いてあるとわかるのです。
474 @c COMMON
475
476 @c EN
477 This introduction may not answer @emph{how} the hygienic macro
478 realizes those properties, but I hope it showed @emph{what} it does
479 and @emph{why} it is needed. In the following chapters we introduce
480 a couple of hygienic macro mechanisms Gauche supports, with examples,
481 so that you can familiarize yourself to the concept.
482 @c JP
483 この節では@emph{いかにして}衛生的マクロがこれらの性質を
484 実現しているかについての詳細には触れませんでしたが、
485 衛生的マクロが@emph{何を}して、@emph{何のために}必要かについて
486 ある程度示せたのではないかと思います。
487 以降の節では、Gaucheがサポートする衛生的マクロシステムについて
488 例を交え紹介してゆきます。
489 @c COMMON
490
491
492 @node Hygienic macros, Traditional macros, Why hygienic?, Macros
493 @section Hygienic macros
494 @c NODE 衛生的マクロ
495
496 @c EN
497 @subheading Macro bindings
498 @c JP
499 @subheading マクロ束縛
500 @c COMMON
501
502 @c EN
503 The following forms establish bindings of @var{name} and
504 a macro transformer created by @var{transformer-spec}. The
505 binding introduced by these forms shadows
506 a binding of @var{name} established in outer scope, if there's any.
507 @c JP
508 以下のフォームは@var{transformer-spec}で作られるマクロ変換器と
509 @var{name}の束縛を作ります。外側のスコープに@var{name}の束縛があれば、
510 それはシャドウされます。
511 @c COMMON
512
513 @c EN
514 For toplevel bindings, it will shadow bindings of @var{name} imported
515 or inherited from other modules (@pxref{Modules}).
516 (Note: This toplevel shadowing behavior is Gauche's extension;
517 in R7RS, you shouldn't redefine imported bindings, so the portable
518 code should avoid it.)
519 @c JP
520 トップレベル束縛の場合、@var{name}に他のモジュールからインポートされたり
521 継承されている束縛があれば、それをシャドウすることになります
522 (@ref{Modules}参照)。
523 (註:モジュール内でのトップレベル束縛がインポートした束縛をシャドウするのは
524 Gaucheの拡張です。R7RSではインポートした束縛の再定義はしてはいけないことに
525 なっているので、ポータブルなコードでは避けて下さい)。
526 @c COMMON
527
528 @c EN
529 The effect is undefined if you bind the same name more than once
530 in the same scope.
531 @c JP
532 同じスコープで同じ名前を複数回束縛した場合の動作は未定義です。
533 @c COMMON
534
535 @c EN
536 The @var{transformer-spec} can be either one of @code{syntax-rules}
537 form, @code{er-macro-transformer} form, or another macro keyword
538 or syntactic keyword. We'll explain them later.
539 @c JP
540 @var{transformer-spec}は@code{syntax-rules}フォーム、
541 @code{er-macro-transformer}フォーム、あるいは他のマクロキーワードか
542 構文キーワードです。これについては後述します。
543 @c COMMON
544
545 @defspec define-syntax name transformer-spec
546 [R7RS base]
547 @c EN
548 If this form appears in toplevel, it binds toplevel @var{name} to
549 a macro transformer defined by @var{transformer-spec}.
550
551 If this form appears in the @emph{declaration} part of
552 body of @code{lambda} (internal define-syntax), @code{let} and
553 other similar forms, it binds @var{name} locally within that body.
554 Conceptually, internal @code{define-syntax}es on the same level
555 are treated like @code{letrec-syntax}. However, mere appearance of
556 @code{define-syntax} does not create another scope; for example,
557 you can interleave internal @code{define} and internal @code{define-syntax}
558 within the same scope. It is important, though, that the local macros
559 defined by internal @code{define-syntax} should not be required
560 to expand macro uses before the definition.
561 @c JP
562 トップレベルで使われた場合、このフォームはトップレベルの@var{name}を
563 @var{transformer-spec}で定義されるマクロ変換器に束縛します。
564
565 @code{lambda}、@code{let}等の本体の宣言部分に使われた場合 (内部@code{define-syntax})、
566 その本体内のスコープで@var{name}を束縛します。
567 概念的には、同一階層にある内部@code{define-syntax}はまとめられて
568 @code{letrec-syntax}のように振る舞います。ただし、@code{define-syntax}が出てきたところで
569 新たなスコープが作られるわけではありません。
570 例えば内部@code{define}と内部@code{define-syntax}を一つのスコープ内で混ぜこせに
571 並べることができます。重要なのは、内部@code{define-syntax}で定義されるローカルマクロは、
572 その定義前にマクロ展開に必要とされてはならない、ということです。
573 @c COMMON
574 @end defspec
575
576 @defspec let-syntax ((name transformer-spec) @dots{}) body
577 @defspecx letrec-syntax ((name transformer-spec) @dots{}) body
578 [R7RS base]
579 @c EN
580 Defines local macros. Each @var{name} is bound to a macro
581 transformer as specified by the corresponding @var{transformer-spec},
582 then @code{body} is expanded. With @code{let-syntax},
583 @var{transformer-spec} is evaluated with the scope
584 surrounding @code{let-syntax}, while with @code{letrec-syntax}
585 the bindings of @var{name}s are included in the scope where
586 @var{transformer-spec} is evaluated. Thus @code{letrec-syntax}
587 allows mutually recursive macros.
588 @c JP
589 ローカルマクロを定義します。各@var{name}が
590 対応する@var{transformer-spec}で定義されるマクロ変換器へと束縛された
591 環境を作り@var{body}を評価します。
592 @code{let-syntax}では、@var{transformer-spec}は@code{let-syntax}を
593 囲むスコープ内で@var{transformer-spec}を評価するのに対し、
594 @code{letrec-syntax}では@var{name}の束縛がなされた環境で
595 @var{transformer-spec}を評価します。つまり@code{letrec-syntax}は
596 相互再帰的なマクロを定義できます。
597 @c COMMON
598 @end defspec
599
600 @subheading Transformer specs
601
602 @c EN
603 The @var{transformer-spec} is a special expression that evaluates
604 to a macro transformer. It is evaluated in a different phase
605 than the other expressions, since macro transformers must be
606 executed during compiling. So there are some restrictions.
607
608 At this moment, only one of the following expressions are allowed:
609 @c JP
610 @var{transformer-spec}は、マクロ展開器へと評価される特別な式です。
611 マクロ変換器はコンパイル時に実行されるため、他の式とは異なった段階で評価されます。
612 そのためにいくらか制限があります。
613
614 現在のところ、以下に挙げる式しか許されていません。
615 @c COMMON
616
617 @enumerate
618 @item
619 @c EN
620 A @code{syntax-rules} form. This is called ``high-level'' macro,
621 for it uses pattern matching entirely, which is basically a
622 different declarative language from Scheme, thus putting the
623 complication of the phasing and hygiene issues completely under the hood.
624 Some kind of macros are easier to write in @code{syntax-rules}.
625 @xref{Syntax-rules macro transformer}, for further description.
626 @c JP
627 @code{syntax-rules}フォーム。これは「高レベル」マクロと呼ばれ、
628 パターンマッチングのみによってマクロを定義します。
629 これはSchemeとは異なる一種の宣言的言語で、
630 マクロの段階や衛生の問題をボンネットの下に隠してしまいます。
631 ある種のマクロは@code{syntax-rules}でより簡単に書けます。
632 詳しくは@ref{Syntax-rules macro transformer}を参照してください。
633 @c COMMON
634
635 @item
636 @c EN
637 An @code{er-macro-transformer} form. This employs @emph{explicit-renaming}
638 (ER) macro, where you can use arbitrary Scheme code to transform
639 the program, with required renaming to keep hygienity. The legacy
640 Lisp macro can also be written with ER macro if you don't use
641 renaming. @xref{Explicit-renaming macro transformer}, for the details.
642 @c JP
643 @code{er-macro-transfomer}フォーム。
644 これは@emph{explicit renaming}(ER)マクロを定義します。
645 ERマクロでは、必要な衛生を保ちながら、任意のSchemeコードを使って変換を書けます。
646 伝統的なLispのマクロは、ERマクロでリネームを使わない特別な場合と考えられます。
647 詳しくは@ref{Explicit-renaming macro transformer}を参照してください。
648 @c COMMON
649
650 @item
651 @c EN
652 A @code{make-id-transformer} form. This creates an @emph{identifier macro},
653 Unlike an ordinary macro, an identifier macro expands without
654 being at the head of a list; it looks like a variable in the source.
655 @xref{Identifier transformer}, for the details.
656 @c JP
657 @code{make-id-transformer}フォーム。
658 これは@emph{識別子マクロ}を定義します。
659 通常のマクロと異なり、識別子マクロはリストの最初の位置に置かれないでも展開されます。
660 ソース上では通常の変数のように見えます。
661 詳しくは@ref{Identifier transformer}を参照してください。
662 @c COMMON
663
664 @item
665 @c EN
666 Macro or syntax keyword. This is Gauche's extension, and can be
667 used to define alias of existing macro or syntax keyword.
668 @c JP
669 マクロキーワードか構文キーワード。これはGauche独自の拡張で、
670 既存のマクロキーワードや構文キーワードの別名を定義するものです。
671 @c COMMON
672 @example
673 (define-syntax si if)
674 (define écrivez write)
675
676 (si (< 2 3) (écrivez "oui"))
677 @end example
678 @end enumerate
679
680
681
682 @menu
683 * Syntax-rules macro transformer::
684 * Explicit-renaming macro transformer::
685 * Identifier transformer::
686 @end menu
687
688 @node Syntax-rules macro transformer, Explicit-renaming macro transformer, Hygienic macros, Hygienic macros
689 @subsection Syntax-rules macro transformer
690 @c NODE Syntax-rulesマクロ変換器
691
692 @defspec syntax-rules (literal @dots{}) clause clause2 @dots{}
693 @defspecx syntax-rules ellipsis (literal @dots{}) clause clause2 @dots{}
694 [R7RS base]
695 @c EN
696 This form creates a macro transformer by pattern matching.
697
698 Each @var{clause} has the following form:
699 @c JP
700 パターンマッチングによるマクロ変換器を作ります。
701
702 各@var{clause}は次の形式です。
703 @c COMMON
704
705 @example
706 (@var{pattern} @var{template})
707 @end example
708
709 @c EN
710 A @var{pattern} denotes a pattern to be matched to the macro call.
711 It is an S-expression that matches if the macro call has the same
712 structure, except that symbols in @var{pattern} can match a whole subtree
713 of the input; the matched symbol is called a @emph{pattern variable},
714 and can be referenced in the @var{template}.
715 @c JP
716 @var{pattern}はマクロ呼び出しにマッチすべきパターンを記述します。
717 パターンはS式で、マクロ呼び出しの式と同じ構造を持っている場合にマッチします。
718 但し、パターン中のシンボルは@emph{パターン変数}と呼ばれ、
719 マクロ呼び出し式の対応する任意の部分木とマッチし、
720 @var{template}の中でマッチした部分木を参照するのに使えます。
721 @c COMMON
722
723 @c EN
724 For example, if a pattern is @code{(_ "foo" (a b))}, it can match the
725 macro call @code{(x "foo" (1 2))}, or @code{(x "foo" (1 (2 3)))}, but does
726 not match @code{(x "bar" (1 2))}, @code{(x "foo" (1))} or
727 @code{(x "foo" (1 2) 3)}. You can also match repeating structure or
728 literal symbols; we'll discuss it fully later.
729 @c JP
730 例えば、パターンが@code{(_ "foo" (a b))}であったとすると、それは
731 @code{(x "foo" (1 2))}や@code{(x "foo" (1 (2 3)))}といったマクロ呼び出しとマッチしますが、
732 @code{(x "bar" (1 2))}、@code{(x "foo" (1))}、@code{(x "foo" (1 2) 3)}とは
733 マッチしません。
734 さらに、後で説明するように、繰り返しのある構造やリテラルシンボルとマッチするような記述も可能です。
735 @c COMMON
736
737 @c EN
738 Clauses are examined in order to see if the macro call form matches
739 its pattern. If matching pattern is found, the corresponding @var{template}
740 replaces the macro call form. A pattern variable in the template is
741 replaced with the subtree of input that is bound to the pattern variable.
742 @c JP
743 @var{clause}は順番に、そのパターンにマクロ呼び出しとマッチするかが検査されます。
744 マッチするパターンが見つかれば、対応する@var{template}でマクロ呼び出しの式が
745 置き換えられます。@var{template}中のパターン変数は、
746 マクロ呼び出し式のその変数にマッチした部分木で置き換えられます。
747 @c COMMON
748
749 @c EN
750 Here's a definition of @code{when} macro in @ref{Why hygienic?},
751 using @code{syntax-rules}:
752 @c JP
753 これは@ref{Why hygienic?}で例に出した@code{when}マクロを
754 @code{syntax-rules}で書いたものです:
755 @c COMMON
756
757 @example
758 (define-syntax when
759 (syntax-rules ()
760 [(_ test body ...) (if test (begin body ...))]))
761 @end example
762
763 @c EN
764 The pattern is @code{(_ test body ...)}, and the template is
765 @code{(if test (begin body ...))}.
766 The ellipsis @code{...} is a symbol; we're not omitting code here.
767 It denotes that the previous pattern (@code{body}) may
768 repeat zero or more times.
769 @c JP
770 パターンが@code{(_ test body ...)}で、
771 テンプレートが@code{(if test (begin body ...))}です。
772 @code{...} (エリプシス) は、記述を省略しているわけではなく、
773 ピリオド3つからなる名前を持つシンボルです。
774 これは直前のパターン(@code{body})がゼロ個以上繰り替えされるということを示します。
775 @c COMMON
776
777 @c EN
778 So, if the @code{when} macro is called as
779 @code{(when (zero? x) (print "huh?") (print "we got zero!"))},
780 the macro expander first check if the input matches the pattern.
781 @c JP
782 @code{when}マクロが
783 @code{(when (zero? x) (print "huh?") (print "we got zero!"))}
784 という形で呼び出されたとしましょう。
785 マクロ展開器はまず、この入力がパターンとマッチするかどうかを調べます。
786 @c COMMON
787
788 @itemize @bullet
789 @item
790 @c EN
791 The @var{test} in pattern matches the input @code{(zero? x)}.
792 @c JP
793 パターン中の@var{test}は入力の@code{(zero? x)}とマッチ。
794 @c COMMON
795 @item
796 @c EN
797 The @var{body} in pattern matches the input @code{(print "huh?")}
798 @emph{and} @code{(print "we got zero!")}.
799 @c JP
800 パターン中の@var{body}は入力の@code{(print "huh?")}および@code{(print "we got zero!")}とマッチ
801 @c COMMON
802 @end itemize
803
804 @c EN
805 The matching of @var{body} is a bit tricky; as a pattern variable,
806 you may think that @var{body} works like an array variable, each element
807 holds each match---and you can use them in similarly
808 repeating substructures in template.
809 Let's see the template, now that the input fully matched the pattern.
810 @c JP
811 @var{body}とのマッチングはちょっとややこしいです。
812 パターン変数@var{body}は配列のようなものだと考えても良いでしょう。
813 配列の各要素がマッチする入力の部分木を保持します。
814 その値は、テンプレート中の似たような繰り返し部分構造の中で使うことができます。
815 ここまでで入力がパターンにマッチしたので、テンプレートの方を見てみましょう。
816 @c COMMON
817
818 @itemize @bullet
819 @item
820 @c EN
821 In the template, @code{if} and @code{begin} are not pattern variable,
822 since they are not appeared in the pattern.
823 So they are inserted as identifiers---that is, hygienic symbols effectively
824 renamed to make sure to refer to the global @code{if} and @code{begin},
825 and will be unaffected by the macro use environment.
826 @c JP
827 テンプレート中の@code{if}と@code{begin}はパターン中に現れていないので
828 パターン変数ではありません。従って、識別子として出力に挿入されます。
829 ここで、識別子@code{if}や@code{begin}はこのマクロのスコープから見えるグローバルな
830 @code{if}や@code{begin}を常に参照できるように、衛生的に扱われます。
831 マクロが使われた場所で@code{if}や@code{begin}がシャドウされていたとしても影響を受けません。
832 @c COMMON
833 @item
834 @c EN
835 The @var{test} in the template is a pattern variable, so it is replaced
836 for the matched value, @code{(zero? x)}.
837 @c JP
838 テンプレート中の@var{test}はパターン変数なので、マッチした値である@code{(zero? x)}へと
839 置き換えられます。
840 @c COMMON
841 @item
842 @c EN
843 The @var{body} is also a pattern variable. The important point is
844 that it is also followed by ellipsis. So we repeat @var{body} as many
845 times as the number of matched values.
846 The first value, @code{(print "huh?")}, and the second value,
847 @code{(print "we got zero!")}, are expanded here.
848 @c JP
849 @var{body}もパターン変数です。重要な点はここでも@var{body}の後にエリプシスがあることで、
850 @var{body}はパターン変数にマッチした値のぶんだけ繰り返されます。
851 最初のマッチした値である@code{(print "huh?")}と、次の
852 @code{(print "we got zero!")}とがここに展開されます。
853 @c COMMON
854 @item
855 @c EN
856 Hence, we get
857 @code{(if (zero? x) (begin (print "huh?") (print "we got zero!")))}
858 as the result of expansion. (With the note that @code{if} and @code{begin}
859 refers to the identifiers visible from the macro definition environment.)
860 @c JP
861 以上から、最終的な展開結果として
862 @code{(if (zero? x) (begin (print "huh?") (print "we got zero!")))}
863 が得られます (このうち、@code{if}と@code{begin}は
864 マクロ定義環境から見える識別子を指すようになっています)。
865 @c COMMON
866 @end itemize
867
868 @c EN
869 The expansion of ellipses is quite powerful. In the template,
870 the ellipses don't need to follow the sequence-valued pattern variable
871 immediately; the variable can be in a substructure, as long as the
872 substructure itself is followed by an ellipsis.
873 See the following example:
874 @c JP
875 エリプシスを使った展開はかなり強力です。
876 テンプレート中で、エリプシスは複数の値を持つパターン変数の直後にある必要はありません。
877 そういった変数を中に含む部分構造をエリプシスで繰り返すことも可能です。
878 次の例を見てください。
879 @c COMMON
880
881 @example
882 (define-syntax show
883 (syntax-rules ()
884 [(_ expr ...)
885 (begin
886 (begin (write 'expr) (display "=") (write expr) (newline))
887 ...)]))
888 @end example
889
890 @c EN
891 If you call this macro as follows:
892 @c JP
893 このマクロを次のように呼ぶと:
894 @c COMMON
895
896 @example
897 (show (+ 1 2) (/ 3 4))
898 @end example
899
900 @c EN
901 It is expanded to the following form, modulo hygienity:
902 @c JP
903 以下のとおりに展開されます (シンボルの衛生性は保たれているとします)。
904 @c COMMON
905
906 @example
907 (begin
908 (begin (write '(+ 1 2)) (display "=") (write (+ 1 2)) (newline))
909 (begin (write '(/ 3 4)) (display "=") (write (/ 3 4)) (newline)))
910 @end example
911
912 @c EN
913 So you'll get this output.
914 @c JP
915 これを実行すれば、以下の出力が得られるでしょう。
916 @c COMMON
917
918 @example
919 (+ 1 2)=3
920 (/ 3 4)=3/4
921 @end example
922
923 @c EN
924 You can also match with a repetition of substructures in the pattern.
925 The following example is a simplified @code{let} that expands to
926 @code{lambda}:
927 @c JP
928 また、パターン中の部分構造を繰り返しマッチするのにも使えます。
929 次の例は@code{let}を@code{lambda}に展開する、簡略化した例です:
930 @c COMMON
931
932 @example
933 (define-syntax my-let
934 (syntax-rules ()
935 [(_ ((var init) ...) body ...)
936 ((lambda (var ...) body ...) init ...)]))
937 @end example
938
939 @c EN
940 If you call it as @code{(my-let ((a expr1) (b expr2)) foo)},
941 then @var{var} is matched to @code{a} and @code{b},
942 while @var{init} is matched to @code{expr1} and @code{expr2}, respectively.
943 They can be used separately in the template.
944 @c JP
945 このマクロを@code{(my-let ((a expr1) (b expr2)) foo)}のように呼び出すと、
946 @var{var}は@code{a}および@code{b}に、
947 @var{init}は@code{expr1}および@code{expr2}にそれぞれマッチします。
948 @var{var}と@var{init}はテンプレート中でばらばらに使うことができます。
949 @c COMMON
950
951 @c EN
952 Suppose ``level'' of a pattern variable
953 means the number of nested ellipses that designate repetition of the pattern
954 variable.
955 A subtemplate can be followed as many ellipses as the maximum level of
956 pattern variables in the subtemplate.
957 In the following example, the level of pattern variable @code{a} is 1
958 (it is repeated by the last ellipsis in the pattern),
959 while the level of @code{b} is 2 (repeated by the last two ellipses),
960 and the level of @code{c} is 3 (repeated by all the ellipses).
961 @c JP
962 パターン変数の繰り返しを示すエリプシスの入れ子の数を、
963 そのパターン変数のレベルと呼ぶことにします。
964 サブテンプレートは、その中に含まれるパターン変数のレベルの最大値と同じだけの
965 エリプシスの入れ子に中になければなりません。
966 次の例では、パターン変数@code{a}のレベルは1 (最後のエリプシスによって繰り返される)、
967 @code{b}は2 (後ろの2つのエリプシスで繰り返される)、
968 @code{c}は3 (全てのエリプシスで繰り返される) です。
969 @c COMMON
970
971 @example
972 (define-syntax ellipsis-test
973 (syntax-rules ()
974 [(_ (a (b c ...) ...) ...)
975 '((a ...)
976 (((a b) ...) ...)
977 ((((a b c) ...) ...) ...))]))
978 @end example
979
980 @c EN
981 In this case, the subtemplate @code{a} must be repeated by one level
982 of ellipsis, @code{(a b)} must be repeated by two,
983 and @code{(a b c)} must be repeated by three.
984 @c JP
985 したがって、サブテンプレート @code{a} は1重、
986 サブテンプレート @code{(a b)}は2重、
987 @code{(a b c)}は3重のエリプシスで繰り返されることになります。
988 @c COMMON
989
990 @example
991 (ellipsis-test (1 (2 3 4) (5 6)) (7 (8 9 10 11)))
992 @result{} ((1 7)
993 (((1 2) (1 5)) ((7 8)))
994 ((((1 2 3) (1 2 4)) ((1 5 6))) (((7 8 9) (7 8 10) (7 8 11)))))
995 @end example
996
997 @c EN
998 In the template, more than one ellipsis directly follow a subtemplate,
999 splicing the leaves into the surrounding list:
1000 @c JP
1001 また、サブテンプレートの後ろには複数のエリプシスを直接置くことができ、
1002 繰り返しの「葉」の部分がそこにスプライスされます。
1003 @c COMMON
1004
1005 @example
1006 (define-syntax my-append
1007 (syntax-rules ()
1008 [(_ (a ...) ...)
1009 '(a ... ...)]))
1010
1011 (my-append (1 2 3) (4) (5 6))
1012 @result{} (1 2 3 4 5 6)
1013
1014 (define-syntax my-append2
1015 (syntax-rules ()
1016 [(_ ((a ...) ...) ...)
1017 '(a ... ... ...)]))
1018
1019 (my-append2 ((1 2) (3 4)) ((5) (6 7 8)))
1020 @result{} (1 2 3 4 5 6 7 8)
1021 @end example
1022
1023 @c EN
1024 Note: Allowing multiple ellipses to directly follow a subtemplate,
1025 and a pattern variable in a subtemplate to be enclosed within more
1026 than the variable's level of nesting of ellipses, are extension to
1027 R7RS, and defined in SRFI-149. In the above examples,
1028 @code{ellipsis-test}, @code{my-append} and @code{my-append2} are
1029 outside of R7RS.
1030 @c JP
1031 註:サブテンプレートの直後に複数のエリプシスを置くこと、
1032 及びパターン変数をそのレベルよりもエリプシスのネストが深いテンプレート中に置けることは、
1033 R7RSに対する拡張で、SRFI-149で定義されています。上記の例では、
1034 @code{ellipsis-test}、@code{my-append}、@code{my-append2}が
1035 R7RSの範囲外になります。
1036 @c COMMON
1037
1038 @c EN
1039 Identifiers in a pattern is treated as pattern variables. But sometimes
1040 you want to match a specific identifier in the input. For example,
1041 the built-in @code{cond} and @code{case} detects an identifier @code{else}
1042 as a special identifier. You can use @var{literal} @dots{} for that.
1043 See the following example.
1044 @c JP
1045 パターン中に現れる識別子はパターン変数として扱われますが、
1046 特定の識別子そのものにマッチさせたい場合もあります。例えば組み込みの@code{cond}や
1047 @code{case}は、@code{else}という識別子を特別に認識します。
1048 @var{literal} @dots{}がその目的に使えます。次の例を見てください。
1049 @c COMMON
1050
1051 @example
1052 (define-syntax if+
1053 (syntax-rules (then else)
1054 [(_ test then expr1 else expr2) (if test expr1 expr2)]))
1055 @end example
1056
1057 @c EN
1058 The identifiers listed as the literals don't become pattern variables,
1059 but literally match the input. If the input doesn't have the same identifier
1060 in the position, match fails.
1061 @c JP
1062 リテラルとして列挙された識別子はパターン変数にはならず、入力の識別子とそのままマッチします。
1063 もし入力の該当する位置に同じ識別子が置かれていなければ、マッチは失敗します。
1064 @c COMMON
1065
1066 @example
1067 (if+ (even? x) then (/ x 2) else (/ (+ x 1) 2))
1068 @r{expands into} (if (even? x) (/ x 2) (/ (+ x 1) 2))
1069
1070 (if+ (even? x) foo (/ x 2) bar (/ (+ x 1) 2))
1071 @result{} ERROR: malformed if+
1072 @end example
1073
1074 @c EN
1075 We've been saying identifiers instead of symbols. Roughly speaking,
1076 an identifier is a symbol with the surrounding syntactic environment,
1077 so that they can keep identity under renaming of hygiene macro.
1078 @c JP
1079 これまで、シンボルと呼ばずに識別子という言葉を使っていました。大まかに言うと、
1080 識別子とはシンボルに周囲の構文的環境をくっつけたもので、
1081 衛生的マクロによるリネームによっても同一性を失わないようになっています。
1082 @c COMMON
1083
1084 @c EN
1085 The following example fails, because the @code{else} passed to the
1086 @code{if+} macro is the one locally bound by @code{let}, which is
1087 different from the global @code{else} when @code{if+} was defined,
1088 hence they don't match.
1089 @c JP
1090 次の例は失敗します。@code{if+}に渡されている@code{else}は@code{let}でローカルに
1091 束縛されており、それは@code{if+}が定義された時点でのグローバルな@code{else}とは
1092 違うもので、したがってマッチしないからです。
1093 @c COMMON
1094
1095 @example
1096 (let ((else #f))
1097 (if+ (even? x) then (/ x 2) else (/ (+ x 1) 2))
1098 @result{} ERROR: malformed if+
1099 @end example
1100 @end defspec
1101
1102 @node Explicit-renaming macro transformer, Identifier transformer, Syntax-rules macro transformer, Hygienic macros
1103 @subsection Explicit-renaming macro transformer
1104 @c NODE Explicit-renamingマクロ変換器
1105
1106 @defspec er-macro-transformer procedure-expr
1107 @c EN
1108 Creates a macro transformer from the given @var{procedure-expr}.
1109 The created macro transformer has to be bound to the syntactic keyword
1110 by @code{define-syntax}, @code{let-syntax} or @code{letrec-syntax}.
1111 Other use of macro transformers is undefined.
1112
1113 The @var{procedure-expr} must evaluate to a procedure that takes
1114 three arguments; @var{form}, @var{rename} and @var{id=?}.
1115
1116 The @var{form} argument receives the S-expression of
1117 the macro call. The @var{procedure-expr} must return an
1118 S-expression as the result of macro expansion. This part is pretty much
1119 like the traditional lisp macro. In fact, if you ignore @var{rename}
1120 and @var{id=?}, the semantics is the same as the traditional
1121 (unhygienic) macro. See the following example
1122 (Note the use of @code{match}; it is a good
1123 tool to decompose macro input):
1124 @c JP
1125 @var{procedure-expr}からマクロ変換器を作ります。
1126 作られたマクロ変換器は、@code{define-syntax}、@code{let-syntax}、
1127 @code{letrec-syntax}により構文キーワードに束縛されなければなりません。
1128 マクロ変換器の他の用途は定義されていません。
1129
1130 @var{procedure-expr}は3つの引数、@var{form}、@var{rename}、@var{id=?}を
1131 取る手続きへと評価される式です。
1132
1133 @var{form}引数には、マクロ呼び出しのS式そのものが渡されます。
1134 @var{procedure-expr}はマクロ展開の結果をS式として返します。
1135 この点は、伝統的なマクロとよく似ています。実のところ、
1136 @var{rename}と@var{id=?}を無視すれば、セマンティクスは伝統的な(非衛生な)マクロと
1137 同じになります。次の例を見てください
1138 (この例では@code{match}を使っています。マクロの入力を分解するのにも
1139 手軽なツールです。)
1140 @c COMMON
1141
1142 @example
1143 (use util.match)
1144
1145 ;; Unhygienic 'when-not' macro
1146 (define-syntax when-not
1147 (er-macro-transformer
1148 (^[form rename id=?]
1149 (match form
1150 [(_ test expr1 expr ...)
1151 `(if (not ,test) (begin ,expr1 ,@@expr))]
1152 [_ (error "malformed when-not:" form)]))))
1153
1154 (macroexpand '(when-not (foo) (print "a") 'boo))
1155 @result{} (if (not (foo)) (begin (print "a") 'boo))
1156 @end example
1157
1158 @c EN
1159 This is ok as long as you know you don't need hygiene---e.g. when
1160 you only use this macro locally in your code, knowing all the
1161 macro call site won't contain name conflicts. However, if you
1162 provide your @code{when-not} macro for general use,
1163 you have to protect namespace pollution around the macro use.
1164 For example, you want to make sure your macro work even if it is
1165 used as follows:
1166 @c JP
1167 衛生を気にする必要がない場合は、これでも十分です。
1168 例えばマクロを自分で書いたコードの中だけで使い、
1169 すべてのマクロ呼び出しを把握していて名前の衝突が起きないことを知っている場合です。
1170 けれども、この@code{when-not}マクロを広く使えるようにするなら、
1171 マクロの使われる場所での名前の衝突からの防御が必要です。
1172 たとえば、次のとおり呼び出されたとしてもちゃんと動くようにしたい場合です。
1173 @c COMMON
1174
1175 @example
1176 (let ((not values))
1177 (when-not #t (print "This shouldn't be printed")))
1178 @end example
1179
1180 @c EN
1181 The @var{rename} argument passed to @var{procedure-expr} is
1182 a procedure that takes a symbol (or, to be precise, a symbol or
1183 an identifier) and @emph{effectively renames} it to a unique
1184 identifier that keeps identity within the macro definition environment and
1185 won't be affected in the macro use environment.
1186 @c JP
1187 @var{procedure-expr}に渡される@var{rename}引数は、
1188 シンボル(正確には、シンボルか識別子)を取り、それをマクロ定義時の環境を保持する
1189 ユニークな識別子へと@emph{実質的にリネームする}手続きです。
1190 リネームされた識別子はマクロ使用時の環境には影響を受けません。
1191 @c COMMON
1192
1193 @c EN
1194 As a rule of thumb, you have to pass
1195 @emph{all new identifiers you insert into macro output} to the
1196 @var{rename} procedure to keep hygiene. In our @code{when-not} macro,
1197 we insert @code{if}, @code{not} and @code{begin} into the macro output,
1198 so our hygienic macro would look like this:
1199 @c JP
1200 大雑把なルールとして、マクロの出力に挿入する識別子はすべて@var{rename}を通すことを
1201 徹底すれば、衛生は保たれます。@code{when-not}マクロの例では、
1202 マクロの出力に@code{if}、@code{not}、@code{begin}を挿入していますから、
1203 衛生的なバージョンは次のとおり書けます。
1204 @c COMMON
1205
1206 @example
1207 (define-syntax when-not
1208 (er-macro-transformer
1209 (^[form rename id=?]
1210 (match form
1211 [(_ test expr1 expr ...)
1212 `(,(rename 'if) (,(rename 'not) ,test)
1213 (,(rename 'begin) ,expr1 ,@@expr))]
1214 [_ (error "malformed when-not:" form)]))))
1215 @end example
1216
1217 @c EN
1218 This is cumbersome and makes it hard to read the macro, so Gauche
1219 provides an auxiliary macro @code{quasirename}, which works like
1220 @code{quasiquote} but renaming identifiers in the form. See the
1221 entry of @code{quasirename} below for the details. You can write
1222 the hygienic @code{when-not} as follows:
1223 @c JP
1224 でもこれは面倒ですし読みづらいですね。そこでGaucheでは、
1225 補助マクロ@code{quasirename}を用意しています。これは@code{quasiquote}のように
1226 動作しますが、フォーム中の識別子をリネームしてゆきます。詳しくは後述の
1227 @code{quasirename}のエントリを参照してください。@code{quasirename}を使うと
1228 衛生的な@code{when-not}はこうなります:
1229 @c COMMON
1230
1231 @example
1232 (define-syntax when-not
1233 (er-macro-transformer
1234 (^[form rename id=?]
1235 (match form
1236 [(_ test expr1 expr ...)
1237 (quasirename rename
1238 `(if (not ,test) (begin ,expr1 ,@@expr)))]
1239 [_ (error "malformed when-not:" form)]))))
1240 @end example
1241
1242 @c EN
1243 You can intentionally break hygiene by inserting a symbol
1244 without renaming. The following code implements
1245 @emph{anaphoric} @code{when}, meaning the result of the
1246 test expression is available in the @var{expr1} @var{exprs} @dots{}
1247 with the name @code{it}. Since the binding of the identifier @code{it}
1248 does not exist in the macro use site, but rather injected into
1249 the macro use site by the macro expander, it is unhygienic.
1250 @c JP
1251 シンボルをリネームせずに挿入すれば、意図的に衛生を破ることができます。
1252 次のコードは@emph{アナフォリック(前方照応的)な}@code{when}を定義しています。
1253 つまり、テスト式の結果が、@var{expr1} @var{exprs} @dots{} から@code{it}という
1254 変数で参照できるということです。
1255 @code{it}の束縛はマクロ呼び出し箇所には無かったもので、
1256 マクロ展開器により挿入されるので、これは非衛生マクロになります。
1257 @c COMMON
1258
1259 @example
1260 (define-syntax awhen
1261 (er-macro-transformer
1262 (^[form rename id=?]
1263 (match form
1264 [(_ test expr1 expr ...)
1265 `(,(rename 'let1) it ,test ; 'it' is not renamed
1266 (,(rename 'begin) ,expr1 ,@@expr))]))))
1267 @end example
1268
1269 @c EN
1270 If you use @code{quasirename}, you can write @code{,'it} to prevent
1271 @code{it} from being renamed:
1272 @c JP
1273 @code{quasirename}を使う場合、@code{it}がリネームされないようにするには
1274 @code{,'it}と書きます。
1275 @c COMMON
1276
1277 @example
1278 (define-syntax awhen
1279 (er-macro-transformer
1280 (^[form rename id=?]
1281 (match form
1282 [(_ test expr1 expr ...)
1283 (quasirename rename
1284 `(let1 ,'it ,test
1285 (begin ,expr1 ,@@expr)))]))))
1286 @end example
1287
1288 @c EN
1289 Here's an example:
1290 @c JP
1291 使用例を見てみましょう。
1292 @c COMMON
1293
1294 @example
1295 (awhen (find odd? '(0 2 8 7 4))
1296 (print "Found odd number:" it))
1297 @result{} @r{prints} Found odd number:7
1298 @end example
1299
1300 @c EN
1301 Finally, the @var{id=?} argument to the @var{procedure-expr} is
1302 a procedure that takes two arguments, and returns @code{#t} iff
1303 both are identifiers and either both are referring to the same binding
1304 or both are free. It can be used to compare literal syntactic keyword
1305 (e.g. @code{else} in @code{cond} and @code{case} forms) hygienically.
1306
1307 The following @code{if=>} macro behaves like @code{if}, except that
1308 it accepts @code{(if=> test => procedure)} syntax,
1309 in which @code{procedure} is called with the value of @code{test}
1310 if it is not false (similar to @code{(cond [test => procedure])} syntax).
1311 The symbol @code{=>} must match hygienically,
1312 that is, it must refer to the same binding as in the macro definition.
1313 @c JP
1314 最後に、@var{procedure-expr}の@var{id=?}引数はふたつの引数を取り、
1315 それらがともに識別子であって、しかも同じ束縛を参照するか束縛されていないか、という
1316 場合に限り@code{#t}を返します。
1317 これはリテラル構文キーワード(@code{cond}や@code{case}フォームの@code{else}等)
1318 を比較するのに使えます。
1319
1320 下の@code{if=>}マクロは@code{if}と同じように動作しますが、
1321 @code{(if=> test => procedure)}のように呼ばれた場合、
1322 @code{(cond [test => procedure])}構文と同じように、
1323 @code{test}が真の値を返した際には結果を引数にして@code{procedure}を呼び出します。
1324 シンボル@code{=>}は衛生的に比較されます。つまり、マクロ定義時と同じ束縛を
1325 参照している場合にのみ有効となります。
1326 @c COMMON
1327
1328 @example
1329 (define-syntax if=>
1330 (er-macro-transformer
1331 (^[form rename id=?]
1332 (match form
1333 [(_ test a b)
1334 (if (id=? (rename '=>) a)
1335 (quasirename rename
1336 `(let ((t ,test))
1337 (if t (,b t))))
1338 (quasirename rename
1339 `(if ,test ,a ,b)))]))))
1340 @end example
1341
1342 @c EN
1343 The call @code{(rename '=>)} returns an identifier that captures
1344 the binding of @code{=>} in the macro definition, and using
1345 @code{id=?} with the thing passed to the macro argument
1346 checks if both refer to the same binding.
1347 @c JP
1348 @code{(rename '=>)}とすることで、マクロ定義時における@code{=>}の束縛を
1349 参照する識別子を手に入れ、@code{id=?}でそれをマクロ引数から渡された式と
1350 比較しています。
1351 @c COMMON
1352
1353 @example
1354 (if=> 3 => list) @result{} (3)
1355 (if=> #f => list) @result{} #<undef>
1356
1357 @c EN
1358 ;; If the second argument isn't =>, if=> behaves like ordinary if:
1359 @c JP
1360 ;; 第二引数が=>でなければ、if=>は通常のifと同じ:
1361 @c COMMON
1362 (if=> #t 1 2) @result{} 1
1363
1364 @c EN
1365 ;; The binding of => in macro use environment differs from
1366 ;; the macro definition environment, so this if=> behaves like
1367 ;; ordinary if, instead of recognizing literal =>.
1368 @c JP
1369 ;; 下の例ではマクロ使用時の=>の束縛がマクロ定義時の束縛と違っているため、
1370 ;; => はリテラルと認識されず、if=> は通常のifとして振る舞う。
1371 @c COMMON
1372 (let ((=> 'oof)) (if=> 3 => list)) @result{} oof
1373 @end example
1374 @end defspec
1375
1376 @defmac quasirename renamer quasiquoted-form
1377 @c EN
1378 It works like quasiquote, except that the symbols and identifiers
1379 that appear in the ``literal'' portion of @var{form} (i.e. outside
1380 of @code{unquote} and @code{unquote-splicing}) are replaced
1381 by the result of applying @var{rename} on themselves.
1382 @c JP
1383 @var{form}中の「リテラル」な部分 (@code{unquote}や@code{unquote-splicing}の外側)
1384 に現れるシンボルや識別子が@var{rename}によってリネームされることを除いて、
1385 準クオートのように動作します。
1386 @c COMMON
1387
1388 @c EN
1389 The @var{quasiquote-form} argument must be a quasiquoted form.
1390 The outermost quasiquote @code{`} is consumed by @code{quasirename} and
1391 won't appear in the output.
1392 The reason we require it is to make nested quasiquotes/quasirenames work.
1393 @c JP
1394 @var{quasiquote-form}引数は、準クオートされたフォームです。
1395 最も外側の準クオート@code{`} 自体は@code{quasirename}によって消費され、
1396 出力には現れません。
1397 この形にしたのは、ネストした@code{quasiquote}/@code{quasirename}を
1398 正しく扱うためです。
1399 @c COMMON
1400
1401 @c EN
1402 For example, a form:
1403 @example
1404 (quasirename r `(a ,b c "d"))
1405 @end example
1406 would be equivalent to write:
1407 @example
1408 (list (r 'a) b (r 'c) "d")
1409 @end example
1410 @c JP
1411 例えば次のフォームは:
1412 @example
1413 (quasirename r `(a ,b c "d"))
1414 @end example
1415 次のとおり書くのと同じです:
1416 @example
1417 (list (r 'a) b (r 'c) "d")
1418 @end example
1419 @c COMMON
1420
1421 @c EN
1422 This is not specifically tied to macros; the @var{renamer} can
1423 be any procedure that takes one symbol or identifier argument:
1424 @c JP
1425 この手続きはマクロ専用というわけではありません。
1426 @var{renamer}はシンボルか識別子を取る手続きであれば何でも構いません。
1427 @c COMMON
1428
1429 @example
1430 (quasirename (^[x] (symbol-append 'x: x)) `(+ a ,(+ 1 2) 5))
1431 @result{} (x:+ x:a 3 5)
1432 @end example
1433
1434 @c EN
1435 However, it comes pretty handy to construct the result form
1436 in ER macros. Compare the following two:
1437 @c JP
1438 ただ、ERマクロを書く際にとても便利なのは確かです。次の2つを比べてみてください。
1439 @c COMMON
1440
1441 @example
1442 (use util.match)
1443
1444 ;; using quasirename
1445 (define-syntax swap
1446 (er-macro-transformer
1447 (^[f r c]
1448 (match f
1449 [(_ a b) (quasirename r
1450 `(let ((tmp ,a))
1451 (set! ,a ,b)
1452 (set! ,b tmp)))]))))
1453
1454 ;; not using quasirename
1455 (define-syntax swap
1456 (er-macro-transformer
1457 (^[f r c]
1458 (match f
1459 [(_ a b) `((r'let) (((r'tmp) ,a))
1460 ((r'set!) ,a ,b)
1461 ((r'set!) ,b (r'tmp)))]))))
1462 @end example
1463
1464 @c EN
1465 Note: In Gauche 0.9.7 and before, @code{quasirename} didn't use
1466 quasiquoted form as the second argument; you can write
1467 @code{(quasirename r form)} instead of
1468 @code{(quasirename r `form)}.
1469
1470 For the backward compatibility,
1471 we support the form without quasiquote by default for a while.
1472
1473 If you already have a quasirename form that does intend to produce
1474 a quasiquoted form, you have to rewrite it with double quasiquote:
1475 @code{(quasirename r ``form)}.
1476
1477 To help transition, the handling of quasiquote in of @code{quasirename}
1478 can be customized with the environment variable
1479 @code{GAUCHE_QUASIRENAME_MODE}. It can have one of the following
1480 values:
1481
1482 @table @code
1483 @item legacy
1484 @code{Quasirename} behaves the same way as
1485 0.9.7 and before; use this to run code for 0.9.7 without any change.
1486 @item compatible
1487 @code{Quasirename} behaves as described in this entry; if
1488 @var{form} lacks a quasiquote, it silently assumes one.
1489 Existing code should work, except the rare case when you intend
1490 to return a quasiquoted form.
1491 @item warn
1492 @code{Quasirename} behaves as described in this entry, but
1493 warns if @var{form} lacks a quasiquote.
1494 @item strict
1495 @code{Quasirename} raises an error if @var{form} lacks a quasiquote.
1496 This will be the default behavior in future.
1497 @end table
1498 @c JP
1499 註: Gauche 0.9.7とそれ以前には、@code{quasirename}は第二引数に
1500 準クオートを必要としませんでした。つまり@code{(quasirename r `form)}
1501 と書くかわりに@code{(quasirename r form)}で良かったのです。
1502
1503 互換性のため、しばらくは準クオート無しのフォームも受け付けられます。
1504
1505 準クオートされたフォームを返すことを意図していた既存のコードについては、
1506 準クオートを@code{(quasirename r ``form)}のように重ねる必要があります。
1507
1508 移行を容易にするため、@code{quasirename}中の準クオートの扱いを、
1509 環境変数@code{GAUCHE_QUASIRENAME_MODE}でカスタマイズできます。
1510 次に挙げる値を設定することができます。
1511
1512 @table @code
1513 @item legacy
1514 @code{quasirename}は、0.9.7やそれ以前と全く同様に動きます。
1515 0.9.7用のコードを変更なしに動かす必要がある場合に使ってください。
1516 @item compatible
1517 @code{quasirename}はこのエントリで説明した通りに動きます。
1518 @var{form}が準クオートされていない場合、準クオートされているものと見なします。
1519 準クオートされたフォームを作り出すことを意図している稀なケース以外の
1520 既存のコードはこれで動かせるでしょう。
1521 @item warn
1522 @code{quasirename}はこのエントリで説明した通りに動きますが、
1523 @var{form}が準クオートされていなければ警告を出します。
1524 @item strict
1525 @code{quasirename}は@var{form}が準クオートされていることを要求し、
1526 そうでなければエラーを投げます。将来はこの動作がデフォルトになる予定です。
1527 @end table
1528 @c COMMON
1529 @end defmac
1530
1531 @node Identifier transformer, , Explicit-renaming macro transformer, Hygienic macros
1532 @subsection Identifier transformer
1533 @c NODE 識別子マクロ変換器
1534
1535 @defspec make-id-transformer transformer-spec
1536 @c EN
1537 Creates an identifier macro transformer from @var{transformer-spec}.
1538 The @var{transformer-spec} is the same as what can appear in
1539 @code{define-syntax} etc.
1540 @c JP
1541 @var{transformer-spec}から識別子マクロ変換器を作ります。
1542 @var{transformer-spec}は@code{define-syntax}等で使えるものと同じです。
1543 @c COMMON
1544
1545 @c EN
1546 A normal macro expands from a form @code{(M arg @dots{})} where @code{M}
1547 is an identifier bound to the macro. An identifier macro, on the other
1548 hand, expands from solely from the macro-bound identifier, or a form
1549 @code{(set! M expr)}. In other words, an identifier macro is used
1550 in the context of a variable, rather than a function call.
1551 @c JP
1552 通常のマクロは、@code{M}をマクロが束縛された識別子とすると、@code{(M arg @dots{})}という
1553 形式でマクロ変換器を呼び出します。一方識別子マクロは、マクロに束縛された識別子単独、
1554 もしくは@code{(set! M expr)}という形式でマクロ変換器を呼び出すものです。
1555 言い換えれば、識別子マクロは、関数呼び出し形式ではなく変数参照形式で使われるものです。
1556 @c COMMON
1557
1558 @c EN
1559 Suppose the following code, where @code{state-manager} is a
1560 stateful closure. The identifier macro @code{the-state} hides
1561 the closure and makes it look like a variable:
1562 @c JP
1563 次のコードを考えます。@code{state-manager}は状態を持つクロージャで、
1564 識別子マクロ@code{the-state}はクロージャを隠して
1565 あたかも変数にアクセスしているかのように見せます。
1566 @c COMMON
1567
1568 @example
1569 (define state-manager
1570 (let ([state #f])
1571 (case-lambda
1572 [() state]
1573 [(val) (set! state val)])))
1574
1575 (define-syntax the-state
1576 (make-id-transformer
1577 (syntax-rules (set!)
1578 [(set! _ expr) (state-manager expr)]
1579 [_ (state-manager)])))
1580
1581 (state-manager 'off)
1582
1583 the-state @result{} off
1584
1585 (set! the-state 'on)
1586
1587 the-state @result{} on
1588
1589 (state-manager) @result{} on
1590 @end example
1591
1592 @c EN
1593 (Note that the single @code{_} pattern in the second clause of
1594 @code{syntax-rules} above matches anything, so it should come
1595 after @code{set!} match. It is Gauche's extension.)
1596 @c JP
1597 (上の@code{syntax-rules}の二番目の節のパターンは@code{_}のみから
1598 なりますが、これはGaucheの拡張で、任意のフォームにマッチします。
1599 したがって@code{set!}のマッチより後に置く必要があります)。
1600 @c COMMON
1601
1602 @c EN
1603 Identifier macros may enable some cool tricks, but it can easily
1604 confuse readers. We generally discourage use of identifier macros
1605 except rare cases where it is absolutely necessary.
1606 In most cases, you can use ordinary macros by just adding parentheses.
1607 @c JP
1608 識別子マクロを使うとアクロバティックなことができますが、
1609 すぐに読者を混乱させるコードになってしまいます。
1610 一般的に、どうしても識別子マクロでなければ実現できないこと以外には使用を避けることをおすすめします。
1611 ほとんどの場合、カッコを足して通常のマクロとして使うのが良いでしょう。
1612 @c COMMON
1613
1614 @c EN
1615 If you want some portability, you may try @code{identifier-syntax}
1616 in @code{util.identifier-syntax}
1617 (@pxref{R6RS identifier syntax}. It is in R6RS and may be supported
1618 other implementations. It is built on top of @code{make-id-transformer}.
1619 @c JP
1620 移植性が気になる場合は、@code{util.identifier-syntax}モジュールの
1621 @code{identifier-syntax}が使えるかもしれません
1622 (@ref{R6RS identifier syntax}参照)。
1623 これはR6RSで規定されているので、サポートしている処理系も多いでしょう。
1624 Gaucheでは@code{make-id-transformer}を使って
1625 @code{util.identifier-syntax}を実装しています。
1626 @c COMMON
1627 @end defspec
1628
1629
1630 @node Traditional macros, Hybrid macros, Hygienic macros, Macros
1631 @section Traditional macros
1632 @c NODE 伝統的なマクロ
1633
1634 @defspec define-macro name procedure
1635 @defspecx define-macro (name . formals) body @dots{}
1636 @c EN
1637 Defines @var{name} to be a global macro whose transformer is @var{procedure}.
1638 The second form is a shorthand notation of the following form:
1639 @c JP
1640 変換子が @var{procedure} である大域マクロ @var{name} を定義します。
1641 2番目のフォームは、以下のフォームの簡易記法です。
1642 @c COMMON
1643 @example
1644 (define-macro name (lambda formals body @dots{}))
1645 @end example
1646
1647 @c EN
1648 When a form @code{(name @var{arg} @dots{})} is seen by the compiler,
1649 it calls @var{procedure} with @var{arg} @dots{}. When @var{procedure}
1650 returns, the compiler inserts the returned form in place of the original
1651 form, and compile it again.
1652 @c JP
1653 コンパイラが @code{(name @var{arg} @dots{})} というフォームを見つけると、
1654 @var{arg} @dots{} を引数として @var{procedure} を呼び出します。
1655 @var{procedure} が戻ると、コンパイラは元のフォームの場所に返されたフォームを
1656 挿入し、再度それをコンパイルします。
1657 @c COMMON
1658
1659 @c EN
1660 To avoid name conflict with the bindings inserted by the macro,
1661 you can use @code{gensym}, just like traditional Lisp macros
1662 (@pxref{Symbols}).
1663 @c JP
1664 マクロによって挿入される束縛の名前衝突を避けるために、
1665 伝統的なLispマクロと同様に@code{gensym}を使うことができます。
1666 (@ref{Symbols}参照)。
1667 @c COMMON
1668
1669 @example
1670 (define-macro (if-let1 var test then else)
1671 (let1 tmp (gensym)
1672 `(let ((,tmp ,test))
1673 (if ,tmp ,then ,else))))
1674
1675 (macroexpand '(if-let1 v (find odd? '(2 4 6 7 8))
1676 (* v v)
1677 #f))
1678 @result{} (let ((#:G1013 (find odd? (quote (2 4 6 7 8)))))
1679 (if #:G1013 (* v v) #f))
1680 @end example
1681
1682 @c EN
1683 Note that @code{gensym} can't protect name conflict with
1684 global bindings inserted by the macro.
1685 @ref{Why hygienic?} discusses this issue.
1686 @c JP
1687 @code{gensym}ではマクロが挿入するグローバルな束縛の衝突は回避できません。
1688 @ref{Why hygienic?}でこの点について説明しています。
1689 @c COMMON
1690 @end defspec
1691
1692 @node Hybrid macros, Syntax parameters, Traditional macros, Macros
1693 @section Hybrid macros
1694 @c NODE ハイブリッドマクロ
1695
1696 @c EN
1697 A hybrid macro is both a macro and a procedure simultaneously.
1698 If a symbol bound to a hybrid macro appears in the first position
1699 of a form, it behaves like a macro and the form is expanded accodring
1700 to its macro expander. If a symbol appears other places, it is evaluated
1701 to a procedure at runtime.
1702 @c JP
1703 ハイブリッドマクロは、マクロと手続きを合わせたものです。
1704 ハイブリッドマクロに束縛されているシンボルがフォームの最初のポジションにある場合、
1705 それはマクロのように振る舞い、マクロ展開器によって展開されます。
1706 シンボルがその他の場所に現れた場合は、実行時に手続きへと評価されます。
1707 @c COMMON
1708
1709 @c EN
1710 It can realize so-called ``compiler macros''---at a compile time,
1711 the macro part examines the arguments and can transform the form as
1712 desired. In all other circumstances, it behaves like a normal procedure
1713 binding, so you can pass the procedure to @code{map}, for example.
1714 @c JP
1715 これは、いわゆる「コンパイラマクロ」を実現するのに使えます。つまり、
1716 コンパイル時に引数を調べ好きなようにフォームを変換できます。
1717 それ以外の場合は普通の手続きへの束縛のように振る舞うので、
1718 例えば@code{map}の引数として渡すことができます。
1719 @c COMMON
1720
1721 @defmac define-hybrid-syntax variable expr transformer-spec
1722 @c EN
1723 Binds @var{variable} to both an ordinary Scheme value and a macro
1724 simultaneously. At the compile time, @var{transformer-spec} is evaluated;
1725 it must yield a macro in the the compile-time environment, and bound
1726 to @var{variable} to be used at macro expansion. At the execution time,
1727 @var{expr} is evaluated and bound to @var{variable} to be used as
1728 a run-time value.
1729 @c JP
1730 @var{variable}を通常のScheme値とマクロの両方に束縛します。
1731 コンパイル時に@var{transformer-spec}が評価されます。それはコンパイル時環境において
1732 マクロを返さなければなりません。そして、マクロ展開用に@var{variable}に束縛されます。
1733 一方@var{expr}は実行時に評価され、実行時の値として@var{variable}に束縛されます。
1734 @c COMMON
1735
1736 @c EN
1737 The macro transformer can return the input form as is (that is, returns
1738 an object @code{eq?} to the input form), to indicate that it doesn't
1739 need to expand it. In that case, Gauche compiles the form as an ordinary
1740 procedure call, to use the value of @var{expr} at run-time.
1741 @c JP
1742 マクロ展開器は、入力フォームに展開の必要がなければそれをそのまま
1743 (入力フォームと@code{eq?}になるオブジェクトとして)返すことができます。
1744 その場合、Gaucheはフォームを単なる手続き呼び出しとしてコンパイルし、
1745 @var{expr}の実行時の値が呼び出されます。
1746 @c COMMON
1747
1748 @c EN
1749 Note: If what you want to do with the hybrid macro is just to
1750 inline-expand the procedure body,
1751 use @code{define-inline} (@pxref{Definitions}).
1752 @c JP
1753 註: ハイブリッドマクロでやりたいことが、手続き本体をインライン展開するだけなら、
1754 @code{define-inline}を使った方が良いです。@ref{Definitions}参照。
1755 @c COMMON
1756
1757 @c EN
1758 Note about the syntax: Traditionally in Lisp, compiler macros
1759 are defined by a separate form from the procedure binding.
1760
1761 However, having bindings to the same identifier twice makes the program
1762 semantics ambiguous. What if the two forms are separated into different
1763 modules? What if the identifier is redefined? It would be clearer that
1764 single form determines the binding.
1765 @c JP
1766 構文についての註: 伝統的にLispでは、コンパイラマクロを定義するフォームは
1767 通常の手続きの束縛を定義するフォームと別でした。
1768
1769 しかし、一つの識別子に別々のフォームで複数の定義を与えるのは、
1770 プログラムの意味に曖昧性を持ち込みます。たとえば通常の定義とコンパイラマクロの定義が
1771 別のモジュールに分かれていたら? あるいはどちらか一方が再定義されたら?
1772 Gaucheではひとつのフォームで束縛を決定してしまう方が良いと判断しました。
1773 @c COMMON
1774 @end defmac
1775
1776 @node Syntax parameters, Identifiers, Hybrid macros, Macros
1777 @section Syntax parameters
1778 @c NODE 構文パラメータ
1779
1780 @c EN
1781 Syntax parameters allows to rebind syntactic binding dynamically
1782 during macro expandsion. The form resembles @code{parameterize}
1783 (@pxref{Parameters}), but works purely at macro expansion time.
1784 It allows to define a macro that affects other macros hygienically.
1785 It is defined by SRFI-139.
1786 @c JP
1787 構文パラメータは、マクロ展開時に動的に構文束縛を置き換えるものです。
1788 束縛フォームは@code{parameterize}に似ています(@ref{Parameters}参照)が、
1789 マクロ展開時のみに作用します。
1790 これを使うと、他のマクロに影響を与えるマクロを衛生的に書くことができます。
1791 構文パラメータはSRFI-139で定義されました。
1792 @c COMMON
1793
1794 @c EN
1795 Suppose you want to have a macro @code{(block <body> ...)} that
1796 evaluates expression @code{<body>} sequentially. Inside it,
1797 we want to have another macro @code{(return <expr>)}, which
1798 evaluates @code{<expr>} and then exits @code{(block ...)},
1799 making the value of @code{<expr>} as the value of @code{(block ...)},
1800 @c JP
1801 例えば、@code{(block <body> ...)}というマクロを考えてみます。
1802 これは@code{<body>}を順番に実行します。@var{<body>}の中で、
1803 別のマクロ@code{(return <expr>)}を呼び出すことができて、
1804 その場合、@code{<expr>}が評価され、それを値として直ちに@code{(block ...)}から
1805 脱出します。
1806 @c COMMON
1807
1808 @c EN
1809 In other words, the macro @code{block} need to change the behavior of
1810 @code{return}. It can be written, for example, as follows:
1811 @c JP
1812 言ってみれば、マクロ@code{block}はマクロ@code{return}の振る舞いを変える必要がある
1813 わけです。これは次のように書くことができるでしょう。
1814 @c COMMON
1815
1816 @example
1817 (define-syntax block
1818 (er-macro-transformer
1819 (^[f r c]
1820 (quasirename r
1821 `(let/cc ,'return ,@@(cdr f)))))
1822
1823 (block (print 1) (print 2) (return 'oops) (print 4))
1824 @result{} @r{print 1, 2, and then returns @code{oops}}
1825 @end example
1826
1827 @c EN
1828 But note that this needs to insert @code{return} unhyginenically.
1829 It may break, for example, when combined with another library that
1830 uses @code{return} for other purposes.
1831 @c JP
1832 ただ、この定義では@code{return}を非衛生的に挿入する必要があることに注目してください。
1833 これは、@code{return}を別の目的で使いたい他のライブラリがあった場合、
1834 一緒に使うと衝突してうまくいかないかもしれません。
1835 @c COMMON
1836
1837 @c EN
1838 With syntax parameters, you can write it hygienically:
1839 @c JP
1840 構文パラメータを使うと、衛生的に書くことができます:
1841 @c COMMON
1842
1843 @example
1844 (define-syntax-parameter return
1845 (syntax-rules ()
1846 ((_ . _) (syntax-error "return outside block"))))
1847
1848 (define-syntax block
1849 (syntax-rules ()
1850 ((_ body ...)
1851 (let/cc %return
1852 (syntax-parameterize ((return (syntax-rules ()
1853 ((_ expr) (%return expr)))))
1854 body ...)))))
1855 @end example
1856
1857 @c EN
1858 The @code{return} has desired effect with @code{block} only if it
1859 refers to the same bindings of @code{define-syntax-parameter}.
1860 Suppose you make the above code into
1861 a library, and the user imports the library with prefix. Then,
1862 the user can refer to the non-local-exit return with the prefix,
1863 and that can coexist of whatever @code{return} defined in the
1864 user's module.
1865 @c JP
1866 @code{block}の中の@code{return}は、@code{define-syntax-parameter}で
1867 定義された@code{return}と同じ束縛を参照している時のみ効果を持ちます。
1868 例えば上記コードをライブラリにして、ユーザがプレフィックスつきでそれを
1869 インポートしたとしましょう。
1870 その場合、非局所的脱出をする@code{return}をプレフィクスつきになり、
1871 そのモジュールで定義される別の@code{return}と共存できます。
1872 @c COMMON
1873
1874 @example
1875 (use block :prefix b:)
1876
1877 (define return ...)
1878
1879 (b:block
1880 ...
1881 @c EN
1882 (return ...) ; This refers to the 'return' in the current module
1883 @c JP
1884 (return ...) ; 現在のモジュールの 'return' を参照
1885 @c COMMON
1886 ...
1887 @c EN
1888 (b:return 'oops) ; This invokes 'return' to exit from the block
1889 @c JP
1890 (b:return 'oops) ; blockから抜ける return の呼び出し
1891 @c COMMON
1892 ...
1893 )
1894 @end example
1895
1896 @defspec define-syntax-parameter name transformer-spec
1897 [SRFI-139]
1898 @c EN
1899 Like @code{define-syntax}, binds @var{name} with
1900 a macro created by @var{transformer-spec}, but the binding
1901 is marked as a syntax parameter, and can be altered with
1902 @code{syntax-parameterize}.
1903 @c JP
1904 @code{define-syntax}と同様に、@var{transformer-spec}で作られるマクロを
1905 @var{name}に束縛します。それに加えて、束縛が構文パラメータであることが記録され、
1906 @code{syntax-parameterize}で置き換えることができるようになります。
1907 @c COMMON
1908
1909 @c EN
1910 The given @var{transformer-spec} works as a default macro, invoked
1911 when no @code{syntax-parameterize} on @var{name} is in effect.
1912 The forms allowed in @var{transformer-spec} is the same
1913 as @code{define-syntax}.
1914 @c JP
1915 与えられた@var{transformer-spec}は、@var{name}が
1916 @code{syntax-parameterize}で再束縛されていない場合のデフォルトのマクロとして
1917 動作します。@var{transformer-spec}に使える形式は
1918 @code{define-syntax}のものと同じです。
1919 @c COMMON
1920 @end defspec
1921
1922 @defspec syntax-parameterize ((key transformer-spec) @dots{}) body @dots{}
1923 [SRFI-139]
1924 @c EN
1925 The @var{key}s must be identifiers bound to syntax parameters.
1926 This form alters the macro transformers of @var{key}s with the ones
1927 specified by the given @var{transformer-spec}s, then proceed to
1928 compile @var{body} @dots{}. The altered bindings are effective
1929 during the dynamic scope of macro-expansion phase. (Be aware that
1930 it has nothing to do with the dynamic scope at runtime.)
1931 @c JP
1932 @var{key}は構文パラメタに束縛された識別子でなければなりません。
1933 このフォームは、@var{key}の構文束縛を@var{transformer-spec}で指定されるものに
1934 置き換えて、@var{body} @dots{}を実行します。
1935 この再束縛はマクロ展開時の動的スコープで有効です
1936 (実行時の動的スコープとは関係ないことに注意してください)。
1937 @c COMMON
1938 @end defspec
1939
1940
1941 @node Identifiers, Debugging macros, Syntax parameters, Macros
1942 @section Identifiers
1943 @c NODE 識別子
1944
1945 @c EN
1946 In the discussion of hygienic macros, we keep saying the symbols are
1947 @emph{effectively renamed}. What it means is that we don't actually create
1948 a new symbol with a new name. We have to remember the origin of
1949 the renamed symbol to resolve the scope of the variable, and having a separate
1950 table to keep track of renamed symbols would be costly. Instead, the ``rename''
1951 procedure wraps the symbols in the input with syntactic information.
1952 @c JP
1953 衛生的マクロの説明では、衝突を避けるためにシンボルを「リネームする」といいますが、
1954 本当に名前を変えたシンボルを作っているわけではありません。後でスコープの解決をする際に、
1955 リネームされたシンボルと元のシンボルを関連付ける必要があるのですが、
1956 それを別のテーブルで管理するのは重いのです。
1957 そこで、@code{er-macro-expander}に渡されるリネーム手続きは、
1958 実際には元のシンボルを構文情報で「包む」ということをしています。
1959 @c COMMON
1960
1961 @c EN
1962 When you play with macro internals, you'll see an object
1963 that is printed something like @code{#<identifier user#foo.fb4ca828>}.
1964 That's the wrapped symbol.
1965 @c JP
1966 マクロの中身をいじっていると、しばしば
1967 @code{#<identifier user#foo.fb4ca828>} のように印字されるオブジェクトを見るでしょう。
1968 それが包まれたシンボルです。
1969 @c COMMON
1970
1971 @c EN
1972 If one macro output is passed to another macro expander, the wrapped symbol
1973 may further be wrapped.
1974 @c JP
1975 マクロ展開結果がさらに他のマクロ展開器に渡された場合は、
1976 一旦包まれたシンボルがさらに包まれることもあります。
1977 @c COMMON
1978
1979 @c EN
1980 The macro expander must assume that symbols in the input are already
1981 wrapped by another macro expander. So, instead of calling it a ``symbol'',
1982 we call it an ``identifier''. An identifier is something that usually
1983 works as a variable or a syntactic keyword in the prorgam. It may be
1984 a symbol or a wrapped identifier.
1985 (Note that symbols in quoted literals are bare symbols, for the @code{quote}
1986 form strips wrappers.)
1987 @c JP
1988 マクロ展開器は、入力に含まれているシンボルが既に包まれていることを想定しなければなりません。
1989 「シンボル」ではなく「識別子」と呼んでいるのはそのためです。
1990 識別子は、プログラム中で変数か構文キーワードとして働くもので、
1991 その実体はシンボルか、包まれた識別子です。
1992 (クオートの中にあるシンボルは常に「裸の」シンボルになります。
1993 @code{quote}が構文情報を剥ぎ取るからです)。
1994 @c COMMON
1995
1996 @c EN
1997 Legacy Lisp macros sometimes examines the symbols in the input form.
1998 In Scheme, you have to treat the input program as
1999 a tree of identifiers and other objects. You can test whether an object
2000 is an identifier or not by @code{identifier?}, where traditional Lisp
2001 macros would have used @code{symbol?}. To compare identifiers, you need
2002 to use the ``compare'' procedure passed to the er-macro expander,
2003 or @code{free-identifier=?}.
2004 @c JP
2005 伝統的なLispのマクロではよく入力フォーム中のシンボルを調べますが、
2006 Schemeでは入力を識別子やその他のオブジェクトからなる木と考えます。
2007 伝統的なLispマクロで@code{symbol?}を使うところでは、
2008 @code{identifier?}を使ってオブジェクトが識別子かどうか調べる必要があります。
2009 また、識別子同士が等しい(同じ束縛を表している)かどうかを調べるには単なる@code{eq?}ではなく、
2010 @code{er-macro-transformer}に与えられる ``compare'' 手続きや、
2011 @code{free-identifier=?}といった特別な手続きを使う必要があります。
2012 @c COMMON
2013
2014 @deftp {Builtin Class} <identifier>
2015 @clindex identifier
2016 @c EN
2017 A class of wrapped identifier. It is created as a result of
2018 ``renaming'' in the hygienic macro expander.
2019
2020 A wrapped identifier contains transient information about the program
2021 source, and cannot be portably saved or passed around; it is only valid
2022 in the macro expansion phase.
2023
2024 For the details of identifier, @pxref{Identifiers}.
2025 @c JP
2026 構文情報で包まれた識別子を表すクラスです。衛生的マクロ展開器の
2027 ``rename''手続きにより作られます。
2028
2029 包まれた識別子は、プログラムの構文情報を含んでおり、
2030 ポータブルな形でセーブすることはできません。その情報はマクロ展開の期間内のみで有効です。
2031
2032 識別子について詳しくは@ref{Identifiers}を参照してください。
2033 @c COMMON
2034 @end deftp
2035
2036 @defun identifier? obj
2037 @c EN
2038 Returns @code{#t} if @var{obj} is either a symbol or a wrapped
2039 identifier. Returns @code{#f} otherwise.
2040
2041 Note: In R6RS, @code{identifier?} only returns @code{#t} for an
2042 identifier object, which is of a disjoint type from symbols.
2043 You can use @code{wrapped-identifier?} below to check if an object
2044 is an identifier other than a symbol.
2045 @c JP
2046 @var{obj}がシンボルもしくは包まれた識別子である場合に@code{#t}を、
2047 そうでなければ@code{#f}を返します。
2048
2049 R6RSでは、@code{identifier?}はシンボルとdisjointな型を持つ「識別子オブジェクト」
2050 についてのみ@code{#t}を返す、と規定されています。
2051 オブジェクトがシンボルでない識別子であることを確かめたい場合は、
2052 下の@code{wrapped-identifier?}が使えます。
2053 @c COMMON
2054 @end defun
2055
2056 @defun wrapped-identifier? obj
2057 @c EN
2058 Returns @code{#t} iff @var{obj} is a wrapped identifier.
2059
2060 This is R6RS's @code{identifier?}.
2061 @c JP
2062 @var{obj}が包まれた識別子なら@code{#t}を、そうでなければ@code{#f}を返します。
2063
2064 R6RSの@code{identifier?}に相当します。
2065 @c COMMON
2066 @end defun
2067
2068
2069 @defun identifier->symbol obj
2070 @c EN
2071 Returns the symbol that is the origin of the @var{obj}, which must
2072 be either a symbol or a wrapped identifier.
2073 @c JP
2074 @var{obj}はシンボルか包まれた識別子でなければなりません。@var{obj}の元となった
2075 シンボルを返します。
2076 @c COMMON
2077 @end defun
2078
2079 @defun free-identifier=? id1 id2
2080 @c EN
2081 When both arguments @var{id1} and @var{id2} are wrapped identifiers,
2082 returns @code{#t} if either (1) @var{id1} and @var{id2} both refer to
2083 the same binding, or (2) @var{id1} and @var{id2} are both unbound.
2084 Otherwise, @code{#f} is returned.
2085
2086 If at least one of @var{id1} or @var{id2} is not a wrapped identifier,
2087 @code{#f} is returned. Note that bare symbols can't be compared
2088 with this procedure, for they lack the necessary lexical information.
2089 To obtain a wrapped identifier, you need to pass a bare symbol
2090 to the ``rename'' procedure passed to the er-macro transformer.
2091
2092 Usually you don't need to use this procedure directly, for
2093 the compare procedure passed to the er-macro transformer is suffice.
2094 @c JP
2095 @var{id1}と@var{id2}がともに包まれた識別子で、次のいずれかの場合にのみ@code{#t}を
2096 返します:
2097 (1)@var{id1}と@var{id2}が同じ束縛を表しているか、
2098 (2)@var{id1}と@var{id2}がどちらも束縛されていない。
2099
2100 @var{id1}と@var{id2}の少なくとも一方が包まれた識別子でなければ、この手続きは
2101 @code{#f}を返します。「裸の」シンボルはレキシカル情報を欠いているため、この手続きでは
2102 比較することができません。シンボルをレキシカルな情報で包むには、
2103 er-macro変換器に渡されるrename手続きを通す必要があります。
2104
2105 er-macroを使っている場合、compare手続きで識別子の比較ができるので、
2106 この手続きを直接使う必要はあまりないでしょう。
2107 @c COMMON
2108 @end defun
2109
2110 @defun unwrap-syntax form
2111 @c EN
2112 Returns a copy of @var{form}, except
2113 removing wrappings of identifiers in it.
2114 The output of macro expanders contain wrapped identifiers,
2115 which is bothersome to see. This procedure traverses @var{form}
2116 and replaces any wrapped identifiers with its original symbol,
2117 retrieved by @code{identifier->symbol}.
2118
2119 Note that, although the result is an ordinary S-expression easier to read,
2120 syntactic information is completely lost. For example, distinct identifiers
2121 can become indistinguishable if they happen to have the same name
2122 (it happens often when you generate temporary variables via
2123 recursive calls of @code{syntax-rules}).
2124 If you distinguish newly inserted
2125 identifiers with the same name, use @code{unravel-syntax}.
2126 @c JP
2127 @var{form}の中に含まれる「包まれた識別子」の構文情報を全て剥ぎ取った形での
2128 @var{form}のコピーを返します。
2129 マクロ展開器の出力には包まれた識別子が含まれていてとても見づらいです。
2130 この手続きは@var{form}をトラバースし、包まれた識別子があればそれを
2131 @code{identifier->symbol}を使って元のシンボルへと戻します。
2132
2133 返り値は通常のS式で読みやすいですが、構文情報が失われていることに注意してください。
2134 例えば本来異なるはずの識別子がたまたま同じ名前を持っていると、区別ができなくなります
2135 (@code{syntax-rules}を再帰的に呼び出して一時変数を作るパターンでは
2136 そういうことが頻繁に起きます)。
2137 新たに挿入された同名の識別子を区別したい場合は、@code{unravel-syntax}を使ってください。
2138 @c COMMON
2139 @end defun
2140
2141 @defun unravel-syntax form
2142 @c EN
2143 Returns a copy of @var{form} while
2144 removing wrappings of identifiers in it, but attach suffix
2145 if two distinct identifiers have the same name, so that they won't
2146 be confused.
2147
2148 For example, a common idiom of @code{syntax-rules} to generate
2149 temporary variables with recursions create all variables with
2150 the same name, although each variable is different because they are
2151 inserted by the different invocation of the expander. If you pass
2152 its output to @code{unwrap-syntax}, all syntactic information is stripped
2153 and these variables can't be distinguished from one another.
2154
2155 This procedure is automatically called with some macro utilities;
2156 @xref{Tracing macro expansion}, and @pxref{Expanding macros manually},
2157 for the example of output of @code{unravel-syntax}.
2158
2159 Note that the global identifiers becomes bare symbols, so you are still
2160 unable to tell which module the global identifiers refer to.
2161 @c JP
2162 @var{form}中に含まれる包まれた識別子を裸のシンボルに変換した形での
2163 @var{form}のコピーを返しますが、同じ名前を持つ異なる識別子があった場合は
2164 区別できるようにサフィックスをつけた名前に変更します。
2165
2166 @code{syntax-rules}を再帰的に呼び出して一時変数を生成する定石では、
2167 新たに作られる変数は全て同じ名前になってしまいますが、それぞれ作られるタイミングが
2168 違うために異なる識別子として扱われます。その結果を@code{unwrap-syntax}に渡して
2169 構文情報を剥ぎ取ると、それらの識別子同士の区別ができなくなってしまいます。
2170
2171 この手続きはいくつかのマクロを扱うユーティリティ関数内で自動的に呼ばれます。
2172 @code{unravel-syntax}の出力例は、
2173 @ref{Tracing macro expansion}や@ref{Expanding macros manually}を
2174 参照してください。
2175
2176 ただし、グローバルな識別子は元のシンボルへと変換されるので、
2177 どのモジュールの束縛を指しているかの情報は失われます。
2178 @c COMMON
2179 @end defun
2180
2181
2182
2183 @node Debugging macros, Macro utilities, Identifiers, Macros
2184 @section Debugging macros
2185 @c NODE マクロのデバッグ
2186
2187 @c EN
2188 Macro expansion happens at the compile time, which makes it difficult
2189 to debug. The best way to avoid headache of macro debugging is
2190 not to write macros unless they're absolutely necessary, and
2191 keep them as simple as possible if you need to write ones.
2192 @c JP
2193 マクロ展開はコンパイル時に行われるため、デバッグが難しいです。
2194 マクロのデバッグに悩まされるのを避ける最良の方法は、どうしても必要でない限り
2195 マクロを書かないこと、そして書くハメになったとしてもできる限り単純なものにすることです。
2196 @c COMMON
2197
2198 @c EN
2199 However, if you find yourself in an unfortunate situation that
2200 you have to untangle hairy macros,
2201 Gauche has some tools to help.
2202 @c JP
2203 しかし、時には怪しげなマクロを解きほぐす必要に迫られるという不運に見舞われるかもしれません。
2204 Gaucheにはその助けになるツールがいくつかあります。
2205 @c COMMON
2206
2207 @menu
2208 * Tracing macro expansion::
2209 * Expanding macros manually::
2210 @end menu
2211
2212 @node Tracing macro expansion, Expanding macros manually, Debugging macros, Debugging macros
2213 @subsection Tracing macro expansion
2214 @c NODE マクロ展開をトレースする
2215
2216 @c EN
2217 Macro tracing shows the input to the macro expander and the result of
2218 its expansion on selected macros. Suppose you have the following
2219 macro definition. It's essentially the same as shown in the definition
2220 of @code{letrec} in R7RS section 7.3:
2221 @c JP
2222 マクロトレースは、選択したマクロのマクロ展開器の入力と結果を表示する機能です。
2223 例えば、次のマクロを定義したとしましょう。これはR7RSの7.3節にある@code{letrec}の
2224 定義とだいたい同じです:
2225 @c COMMON
2226
2227 @example
2228 (define-syntax my-letrec
2229 (syntax-rules ()
2230 [(_ ((var init) ...) body ...)
2231 (my-letrec "tmps" (var ...) () ((var init) ...) body ...)]
2232 [(_ "tmps" () (tmp ...) ((var init) ...) body ...)
2233 (let ((var 'undefined) ...)
2234 (let ((tmp init) ...)
2235 (set! var tmp) ...
2236 body ...))]
2237 [(_ "tmps" (x y ...) (tmp ...) binds body ...)
2238 (my-letrec "tmps" (y ...) (newtmp tmp ...) binds body ...)]))
2239 @end example
2240
2241 @c EN
2242 The @code{my-letrec} macro uses an idiom to generate temporary
2243 variables by looping with @code{"tmps"} tag. You can see how
2244 the macro is expanded step by step, by tracing @code{my-letrec}:
2245 @c JP
2246 この@code{my-letrec}マクロは、@code{"tmps"}をタグにしてループすることで
2247 一時変数を作るというイディオムを使っています。@code{my-letrec}をトレースすることで、
2248 このマクロの展開の様子をステップごとに見ることができます:
2249 @c COMMON
2250
2251 @example
2252 gosh> (trace-macro 'my-letrec)
2253 (my-letrec)
2254 gosh> (my-letrec [(ev? (^n (if (= n 0) #t (od? (- n 1)))))
2255 (od? (^n (if (= n 0) #f (ev? (- n 1)))))]
2256 (ev? 3))
2257 Macro input>>>
2258 (my-letrec
2259 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2260 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2261 (ev? 3))
2262
2263 Macro output<<<
2264 (my-letrec
2265 "tmps"
2266 (ev? od?)
2267 ()
2268 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2269 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2270 (ev? 3))
2271
2272 Macro input>>>
2273 (my-letrec
2274 "tmps"
2275 (ev? od?)
2276 ()
2277 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2278 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2279 (ev? 3))
2280
2281 Macro output<<<
2282 (my-letrec
2283 "tmps"
2284 (od?)
2285 (newtmp.0)
2286 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2287 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2288 (ev? 3))
2289
2290 Macro input>>>
2291 (my-letrec
2292 "tmps"
2293 (od?)
2294 (newtmp.0)
2295 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2296 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2297 (ev? 3))
2298
2299 Macro output<<<
2300 (my-letrec
2301 "tmps"
2302 ()
2303 (newtmp.1 newtmp.0)
2304 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2305 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2306 (ev? 3))
2307
2308 Macro input>>>
2309 (my-letrec
2310 "tmps"
2311 ()
2312 (newtmp.0 newtmp.1)
2313 ((ev? (^n (if (= n 0) #t (od? (- n 1)))))
2314 (od? (^n (if (= n 0) #f (ev? (- n 1))))))
2315 (ev? 3))
2316
2317 Macro output<<<
2318 (let
2319 ((ev? (quote undefined)) (od? (quote undefined)))
2320 (let
2321 ((newtmp.0 (^n (if (= n 0) #t (od? (- n 1)))))
2322 (newtmp.1 (^n (if (= n 0) #f (ev? (- n 1))))))
2323 (set! ev? newtmp.0)
2324 (set! od? newtmp.1)
2325 (ev? 3)))
2326
2327 #f
2328 @end example
2329
2330 @c EN
2331 In the above example, the S-expressions
2332 after @code{gosh>} prompt is what you type; all other things are
2333 Gauche's answer, including @code{Macro input} and @code{Macro output}
2334 S-expressions.
2335 @c JP
2336 上に示した例において、@code{gosh>}プロンプトの次にあるS式がユーザがタイプしたものです。
2337 他はすべて、@code{Macro input}と@code{Macro output}のS式を含め、
2338 Gaucheの出力です。
2339 @c COMMON
2340
2341 @c EN
2342 The S-expression shown with @code{Macro input} is the input of
2343 the macro expander, and the one with @code{Macro output} is the
2344 expanded result. Actual macro output has syntactic information
2345 attached, but the tracer strips them off for the legibility.
2346 @c JP
2347 @code{Macro input}の後に示されるS式がマクロ展開器の入力で、
2348 @code{Macro output}の後がその展開結果です。実際のマクロ展開結果は
2349 構文情報が付加されていますが、この出力では読みやすくするために構文情報は取り去られています。
2350 @c COMMON
2351
2352 @c EN
2353 Note that the loop introduces new temporary variables with the same
2354 name (@code{newtemp}), but they are treated as different identifiers
2355 in the macro expansion.
2356 @c JP
2357 ループの度に同じ名前(@code{newtemp})の変数が導入されていますが、
2358 それらが異なる識別子として扱われていることが展開結果からわかると思います。
2359 @c COMMON
2360
2361 @c EN
2362 Once you're done debugging,
2363 don't forget to call @code{untrace-macro} with no arguments
2364 to remove macro traces. If there's a macro trace set, all macro expansions
2365 get some overhead, so don't leave macro traces.
2366 @c JP
2367 デバッグが終わったら、@code{untrace-macro}を引数なしで呼んで
2368 マクロトレースをオフにしましょう。マクロトレースが設定されていると、
2369 すべてのマクロ展開においてオーバヘッドがかかります。
2370 @c COMMON
2371
2372 @example
2373 gosh> (untrace-macro)
2374 #f
2375 @end example
2376
2377
2378 @defun trace-macro
2379 @defunx trace-macro boolean
2380 @defunx trace-macro name-or-pattern @dots{}
2381 @c EN
2382 Get/set current macro trace setting. Macro trace setting can be
2383 one of the following values:
2384 @c JP
2385 現在のマクロトレース設定を得たり、変更したりします。
2386 マクロトレース設定は次のいずれかの値を取ります。
2387 @c COMMON
2388
2389 @table @asis
2390 @item @code{#f}
2391 @c EN
2392 Macro tracing is off. This is the default setting.
2393 @c JP
2394 マクロトレースはオフです。これがデフォルトの設定です。
2395 @c COMMON
2396 @item @code{#t}
2397 @c EN
2398 All macro expansions are traced.
2399 @c JP
2400 全てのマクロの展開がトレースされます。
2401 @c COMMON
2402 @item @code{(@var{name-or-pattern} @dots{})}
2403 @c EN
2404 Trace macros that match any one of @var{name-or-pattern}, which
2405 is either a symbol or a regexp. If it's a symbol, a macro whose name
2406 is the same as the symbol is traced. If it's a regexp, macros whose
2407 name match the regexp are traced.
2408 @c JP
2409 名前が@var{name-or-pattern}のいずれかにマッチするマクロがトレースされます。
2410 ここで各@var{name-or-pattern}は、シンボルか正規表現オブジェクトです。
2411 シンボルの場合は名前が完全に一致するもの、正規表現の場合は
2412 名前がそれに一致するものがトレースの対象となります。
2413 @c COMMON
2414 @end table
2415
2416 @c EN
2417 When called without arguments, @code{trace-macro} doesn't change
2418 the setting; it returns the current setting.
2419 @c JP
2420 引数なしで呼ばれたら、@code{trace-macro}は設定を変えず、単に現在の設定を返します。
2421 @c COMMON
2422
2423 @c EN
2424 When called with single boolean value, it sets the current setting
2425 to that value. Returns the updated setting.
2426 @c JP
2427 単一の真偽値を引数に渡した場合は、それをマクロトレースの設定値として、
2428 更新された設定値を返します。
2429 @c COMMON
2430
2431 @c EN
2432 When called with one or more @var{name-or-pattern}, it @emph{adds} them
2433 to the current setting. Note that if the current setting is @code{#t},
2434 it remains @code{#t}, for all macros are already traced.
2435 Returns the updated setting.
2436 @c JP
2437 一つ以上の@var{name-or-pattern}が渡されたら、それらが現在のマクロトレース設定に
2438 @emph{追加}されます。もし現在の設定が@code{#t}なら設定は変わらないことに注意して
2439 ください。全てのマクロは既にトレースされているからです。
2440 更新された設定値を返します。
2441 @c COMMON
2442
2443 @c EN
2444 If macro trace settings is not @code{#f}, it incurs overhead for
2445 every macro expansion. Be careful not to leave macro trace set.
2446 @c JP
2447 マクロトレースの設定値が@code{#f}でない限り、すべてのマクロ展開にオーバヘッドがかかります。
2448 マクロトレースを設定したままにしないようにしてください。
2449 @c COMMON
2450
2451 @c EN
2452 The trace information is output to the current trace port.
2453 (@pxref{Common port operations}).
2454 @c JP
2455 トレース情報は現在のトレース出力ポートに出力されます。
2456 (@ref{Common port operations}参照)。
2457 @c COMMON
2458 @end defun
2459
2460 @defun untrace-macro
2461 @defunx untrace-macro name-or-pattern @dots{}
2462 @c EN
2463 When called without arguments, it turns macro trace off.
2464
2465 When called with one or more @var{name-or-pattern}, which is either
2466 a symbol or a regexp, @code{untrace-macro} removes them from
2467 the currently traced macros. Note that if the current macro trace setting
2468 is @code{#t} (trace all macros), you can't remove traced macro individually.
2469
2470 It returns the updated macro trace setting.
2471 @c JP
2472 引数なしで呼ばれた場合、マクロトレースをオフにします。
2473
2474 1つ以上の@var{name-or-pattern}が渡された場合は、現在のマクロトレース設定から
2475 それらを除きます。ただし、現在のマクロトレース設定が@code{#t} (全てのマクロをトレース)
2476 の場合は個別にマクロを除外できません。
2477
2478 更新後のマクロトレース設定を返します。
2479 @c COMMON
2480 @end defun
2481
2482
2483 @node Expanding macros manually, , Tracing macro expansion, Debugging macros
2484 @subsection Expanding macros manually
2485 @c NODE マクロを自分で展開する
2486
2487
2488 @defun macroexpand form :optional env
2489 @defunx macroexpand-1 form :optional env
2490 @c EN
2491 If @var{form} is a list and its first element is a variable
2492 globally bound to a macro, @code{macroexpand-1}
2493 invokes its macro transformer and
2494 returns the expanded form. Otherwise, returns @var{form} as is.
2495
2496 @code{macroexpand} repeats @code{macroexpand-1} until the
2497 outermost expression of @var{form} can't be expanded.
2498 (It doesn't expand macros other than outermost one. If you want
2499 to expand all the macros within @var{form}, use @code{macroexpand-all}).
2500
2501 These procedures can be used to expand globally defined macros.
2502 @c JP
2503 @var{form} がリストで、その最初の要素が大域的にマクロに束縛された
2504 変数であるならば、@code{macroexpand-1}はそのマクロ変換子を実行し、
2505 展開されたフォームを返します。そうでなければ、@var{form} をそのまま
2506 返します。
2507
2508 @code{macroexpand} は、@var{form}の一番外側の式がが展開できなくなるまで
2509 @code{macroexpand-1} を繰り返します。
2510 (@code{macroexpand}は@var{form}の一番外側以外のマクロは展開しません。
2511 @var{form}内の全てのマクロを展開するには@code{macroexpand-all}を使ってください。)
2512
2513 これらの手続きは、大域的に定義されたマクロを展開するために使うことが
2514 できます。
2515 @c COMMON
2516
2517 @c EN
2518 Internally, hygienic macro expansion wraps symbols in @var{form}
2519 with syntactic information to keep hygiene. However, such information
2520 is hard to read, and not suitable when you just want to expand a macro
2521 in REPL to check its result. So, by default, these procedures
2522 strips syntactic information. For the identifiers introduced in the
2523 macro, it renames them to avoid name conflicts.
2524
2525 The following example expands @code{my-letrec} macro
2526 (@pxref{Tracing macro expansion}, for the definition) and
2527 results shows temporary variable introduced by the macro (@var{newtemp})
2528 to be renamed.
2529 @c JP
2530 内部的には、衛生マクロは展開されると@var{form}の中にあるシンボルを
2531 構文情報でラップします。しかし、REPLでマクロを展開して確かめたい場合に
2532 その情報がついているととても読みにくくなります。
2533 そこで、デフォルトではこれらの手続きは構文情報を取り除いて出力します。
2534 マクロ内で導入された識別子については、必要に応じて名前の衝突を避けるリネームが
2535 行われます。
2536
2537 下の例は@code{my-letrec} (定義は@ref{Tracing macro expansion}参照) を
2538 展開しています。マクロ展開で導入された変数 (@var{newtemp}) がリネームされています。
2539 @c COMMON
2540
2541 @example
2542 (macroexpand
2543 '(my-letrec [(ev? (^n (if (= n 0) #t (od? (- n 1)))))
2544 (od? (^n (if (= n 0) #f (ev? (- n 1)))))]
2545 (ev? 3)))
2546
2547 @result{}
2548
2549 (let
2550 ((ev? (quote undefined)) (od? (quote undefined)))
2551 (let
2552 ((newtmp.0 (^n (if (= n 0) #t (od? (- n 1)))))
2553 (newtmp.1 (^n (if (= n 0) #f (ev? (- n 1))))))
2554 (set! ev? newtmp.0)
2555 (set! od? newtmp.1)
2556 (ev? 3)))
2557 @end example
2558
2559 @c EN
2560 If you pass a module to the @var{env} argument, it is used as the
2561 macro use environment. You can also pass @code{#t} to let it use
2562 the current @emph{runtime} environment as the macro use environment.
2563 In those cases, syntactic information in the output won't be
2564 stripped.
2565
2566 If you want to use the output of @code{macroexpand} as a program,
2567 e.g. embed it into another macro expansion, you need syntactic
2568 information preserved.
2569 @c JP
2570 @var{env}引数にモジュールを渡すと、そのモジュールをマクロ使用環境として
2571 マクロが展開されます。@var{env}に@code{#t}を渡すと、実行時のモジュールが
2572 マクロ使用環境になります。これらの場合は、出力に構文情報が付加されたままになります。
2573
2574 @code{macroexpand}の出力を他のマクロ展開結果にプログラム的に埋め込むといった
2575 用途に使う場合には、構文情報を保ったままのフォームが必要になります。
2576 @c COMMON
2577 @end defun
2578
2579 @defun macroexpand-all form :optional env
2580 @c EN
2581 Fully expand macros inside @var{form}. The result only contains
2582 function calls and Gauche's built-in syntax.
2583 @c JP
2584 @var{form}中にあるマクロを全て展開します。結果の中に残るのは、
2585 関数呼び出しとGaucheの組み込み構文だけになります。
2586 @c COMMON
2587
2588 @c EN
2589 By default, or @code{#t} is passed to @var{env},
2590 the @var{form} is assumed to be a toplevel form within the current runtime
2591 module.
2592 You can also pass a module to @var{env} to specify
2593 the alternative toplevel environment.
2594 @c JP
2595 デフォルト、もしくは@var{env}に@code{#t}が渡された場合は、
2596 @var{form}は実行時のモジュールのトップレベルにあると解釈されます。
2597 モジュールを@var{env}に渡せば、そのモジュールをマクロ使用環境として展開できます。
2598 @c COMMON
2599
2600 @c EN
2601 Any local variables introduced in @var{form} is renamed to avoid collision.
2602 Since each local variable has unique name, all @code{let} forms become
2603 @code{letrec} forms (we can safely replace @code{let} with @code{letrec}
2604 if no bindings introduced by @code{let} shadows outer bindings.)
2605 @c JP
2606 @var{form}中で導入されるローカル変数は全て、衝突を避けるためにリネームされます。
2607 ローカル変数が全て固有の名前を持つようになるので、@code{let}フォームはすべて
2608 @code{letrec}で表されます(@code{let}による束縛が他の束縛をシャドウしないと
2609 わかっていれば、@code{let}を@code{letrec}に置き換えても意味は変わりません)。
2610 @c COMMON
2611
2612 @c EN
2613 NB: If a macro in @var{form} inserts a reference to a global variable
2614 which belongs to other module, the information is lost in the current
2615 implementation. There are a few ways to address this issue; we may
2616 leave such reference as an identifier object, convert it to
2617 @code{with-module} form, or introduce a special syntax to represent
2618 such case. It's undecided currently, so do not rely too much on
2619 the current behavior. For the time being, it's best to use this
2620 feature only for interactive macro testing.
2621 @c JP
2622 注意: もし@var{form}内で呼ばれているマクロが、他のモジュール中にあるグローバル
2623 変数への参照を挿入した場合、現在の実装ではその情報は失われてしまいます。
2624 いくつか、その問題を修正する方法は考えられるのですが(例えば他のモジュール中に
2625 グローバル変数参照は識別子オブジェクトのまま残しておくとか、
2626 @code{with-module}フォームに変換するとか、
2627 そういったケースのための特殊構文を導入するとか)、今のところどうするか
2628 決まっていません。なので、現在のふるまいにあまり依存しないようにしてください。
2629 今のところ、この手続きは、マクロの展開結果をインタラクティブに確かめる用途に
2630 限って使うのが安全です。
2631 @c COMMON
2632
2633 @example
2634 (macroexpand-all
2635 '(letrec-syntax
2636 [(when-not (syntax-rules ()
2637 [(_ test . body) (if test #f (begin . body))]))]
2638 (let ([if list])
2639 (define x (expt foo))
2640 (let1 x 3
2641 (when-not (bar) (if x))))))
2642 @result{} (letrec ((if.0 list))
2643 (letrec ((x.1 (expt foo)))
2644 (letrec ((x.2 '3))
2645 (if (bar) '#f (if.0 x.2)))))
2646 @end example
2647 @end defun
2648
2649
2650 @defspec %macroexpand form
2651 @defspecx %macroexpand-1 form
2652 @end defspec
2653
2654 @node Macro utilities, , Debugging macros, Macros
2655 @section Macro utilities
2656 @c NODE マクロユーティリティ
2657
2658 @defmac syntax-error msg arg @dots{}
2659 @defmacx syntax-errorf fmt arg @dots{}
2660 @c EN
2661 Signal an error. They are same as
2662 @code{error} and @code{errorf} (@pxref{Signaling exceptions}),
2663 except that the error is signaled at macro-expansion time
2664 (i.e. compile time) rather than run time.
2665
2666 They are useful to tell the user the wrong usage of macro in
2667 the comprehensive way, instead of the cryptic error from the macro
2668 transformer. Because of the purpose, @var{arg} @dots{} are first
2669 passed to @code{unwrap-syntax} to strip off
2670 the internal syntactic binding informations (@pxref{Identifiers}).
2671 @c JP
2672 これらは@code{error}と@code{errorf} (@ref{Signaling exceptions}参照) と
2673 ほぼ同じですが、実行時ではなくマクロ展開時(すなわち、コンパイル時)に
2674 エラーを通知するところが異なります。
2675
2676 これらの手続きは、マクロの誤った使い方を、
2677 マクロ展開ルーチンの出す複雑なエラーではなく、
2678 分かりやすい方法でユーザーに通知するのに使えます。
2679 そのため、@var{arg} @dots{}は@code{unwrap-syntax}に渡されて
2680 内部の構文的束縛情報を取り除いた後でこれらの手続きに渡されます (@ref{Identifiers}参照)。
2681 @c COMMON
2682
2683 @example
2684 (define-syntax my-macro
2685 (syntax-rules ()
2686 ((_ a b) (foo2 a b))
2687 ((_ a b c) (foo3 a b c))
2688 ((_ . ?)
2689 (syntax-error "malformed my-macro" (my-macro . ?)))))
2690
2691 (my-macro 1 2 3 4)
2692 @result{} @r{error: "malformed my-macro: (my-macro 1 2 3 4)"}
2693 @end example
2694 @end defmac
2695 @c Local variables:
2696 @c mode: texinfo
2697 @c coding: utf-8
2698 @c end: