@node Macros, Core library, Core syntax, Top @chapter Macros @c NODE マクロ @c EN Macro of Lisp-family language is very different feature from ones of other languages, such as C preprocessor macros. It allows you to extend the original language syntax. You can use macros to change Gauche syntax so that you can run a Scheme program written to other Scheme implementations, and you can even design your own mini-language to solve your problem easily. @c JP Lisp系言語のマクロは、他の言語に見られるマクロ(例えばCプリプロセッサマクロ)とは 大きく異なります。Lispのマクロは元の言語の構文を拡張する手段なのです。 例えば、Gaucheの構文を若干変えることで他のScheme実装用に書かれたSchemeプログラムを 走らせたり、あるいは自分の問題解決に適した「ミニ言語」をデザインすることさえできます。 @c COMMON @c EN Gauche supports hygienic macros, which allows to write safe macros by avoiding name collisions. If you know traditional Lisp macros but new to hygienic macros, they might seem confusing at first. We have an introductory section (@ref{Why hygienic?}) for those who are not familiar with hygienic macros; if you know what they are, you can skip the section. @c JP Gaucheは、名前の衝突を避ける安全なマクロを簡単に書ける、「衛生的な(hygienic)」 マクロをサポートします。これは、従来のLispマクロは知っていても衛生的なマクロを 初めて見る人には、やや難解に見えるかもしれません。 衛生的マクロに馴染みが無い読者向けに、紹介の節を用意しました(@ref{Why hygienic?})。 既に衛生的マクロを知っている読者はその節は読み飛ばして構いません。 @c COMMON @menu * Why hygienic?:: * Hygienic macros:: * Traditional macros:: * Hybrid macros:: * Syntax parameters:: * Identifiers:: * Debugging macros:: * Macro utilities:: @end menu @node Why hygienic?, Hygienic macros, Macros, Macros @section Why hygienic? @c NODE なぜ衛生的マクロか @c EN Lisp macro is a programmatic transformation of source code. A @emph{macro transformer} is a procedure that takes a subtree of source code, and returns a reconstructed tree of source code. @c JP Lispのマクロは、ソースコードをプログラムによって変換するものです。 @emph{マクロ変換器(macro transformer)}が、ソースコードの部分木を受け取り、 加工したソースコードの部分木を返します。 @c COMMON @c EN The traditional Lisp macros take the input source code as an S-expression, and returns the output as another S-expression. Gauche supports that type of macro, too, with @code{define-macro} form. Here's the simple definition of @code{when} with the traditional macro. @c JP 伝統的なLispマクロでは、入力となるソースコードも、出力されるコードも、単なるS式でした。 Gaucheはそのタイプのマクロも@code{define-macro}形式でサポートしています。 例えば、@code{when}は伝統的マクロで次のとおり書けます。 @c COMMON @example (define-macro (when test . body) `(if ,test (begin ,@@body))) @end example @c EN For example, if the macro is used as @code{(when (zero? x) (print "zero") 'zero)}, the above macro transformer rewrites it to @code{(if (zero? x) (begin (print "zero") 'zero))}. So far, so good. @c JP このマクロが@code{(when (zero? x) (print "zero") 'zero)}のように使われたとすれば、 上記の変換器はそれを@code{(if (zero? x) (begin (print "zero") 'zero))}と 書き換えます。一見問題なさそうですね。 @c COMMON @c EN But what if the @code{when} macro is used in an environment where the names @code{begin} or @code{if} is bound to nonstandard values? @c JP けれども、@code{begin}や@code{if}が通常とは違う意味で束縛されている環境で @code{when}が使われたらどうなるでしょう。 @c COMMON @example (let ([begin list]) (when (zero? x) (print "zero") 'zero)) @end example @c EN The expanded result would be as follows: @c JP 展開結果は次の通りになります。 @c COMMON @example (let ([begin list]) (if (zero? x) (begin (print "zero") 'zero))) @end example @c EN This obviously won't work as the macro writer intended, since @code{begin} in the expanded code refers to the locally bound name. @c JP これでは意図した通りには動きません。展開された結果の中の@code{begin}が ローカル変数と解釈されてしまいます。 @c COMMON @c EN This is a form of @emph{variable capture}. Note that, when Lisp people talk about variable capture of macros, it often means another form of capture, where the temporary variables inserted by a macro would unintentionally capture the variables passed to the macro. That kind of variable capture can be avoided easily by naming the temporary variables something that never conflict, using @code{gensym}. @c JP これは@emph{変数捕捉}の一形態です。Lispのマクロによる変数捕捉というと、 別の形態、すなわちマクロにより導入される一時変数がマクロに渡された式内の 変数を意図せずに捕捉してしまうことが話題に上ることが多いのですが、 そちらは@code{gensym}を使って一時変数を決して衝突しない名前にすることで 簡単に回避できます。 @c COMMON @c EN On the other hand, the kind of variable capture in the above example can't be avoided by @code{gensym}, because @code{(let ([begin list]) ...)} part isn't under macro writer's control. As a macro writer, you can do nothing to prevent the conflict, just hoping the macro user won't do such a thing. Sure, rebinding @code{begin} is a crazy idea that nobody perhaps wants to do, but it can happen on @emph{any} global variable, even the ones you define for your library. @c JP しかし上の例のような変数捕捉は@code{gensym}では回避できません。外側の @code{(let ([begin list]) ...)}の部分はマクロを書く人には制御できない からです。マクロ作成者が、この衝突を避けるために出来ることは何もありません。 せいぜい、マクロ使用者がそんな使い方をしないように祈るだけです。 もちろん、@code{begin}を再束縛するなんて誰もやろうとは思わないかもしれませんが、 同様の衝突はあなたのライブラリが提供するものも含めあらゆるグローバル変数について 起こり得るのです。 @c COMMON @c EN Various Lisp dialects have tried to address this issue in different ways. Common Lisp somewhat relies on the common sense of the programmer---you can use separate packages to reduce the chance of accidental conflict but can't prevent the user from binding the name in the same package. (The Common Lisp spec says it is undefined if you locally rebind names of CL standard symbols; but it doesn't prevent you from locally rebinding symbols that are provided by user libraries.) @c JP 異なるLisp方言はそれぞれ異なる方法でこの問題に対処してきました。 Common Lispは、ある意味プログラマの常識に頼ります。マクロ作成者は ライブラリのパッケージを分けることで、偶然名前が衝突してしまう危険性を 減らせますが、マクロ使用者が同じパッケージの名前を再束縛することを防げるわけではありません。 (Common Lispの仕様ではCL標準のシンボルをローカルに再束縛した場合の 動作は未定義とされていますが、ユーザが提供するライブラリについては 何も決められていません。) @c COMMON @c EN Clojure introduced a way to directly refer to the toplevel variables by a namespace prefix, so it can bypass whatever local bindings of the same name (also, it has a sophisticated quasiquote form that automatically renames free variables to refer to the toplevel ones). It works, as far as there are no local macros. With local macros, you need a way to distinguish different local bindings of the same name, as we see in the later examples. Clojure's way can only distinguish between local and toplevel bindings. It's ok for Clojure which doesn't have local macros, but in Scheme, we prefer uniform and orthogonal axioms---if functions can be defined locally with lexical scope, why not macros? @c JP Clojureは、名前空間プレフィクスによって直接トップレベル変数を参照する方法を 導入したので、同名のローカル変数束縛をバイパスして意図するトップレベル変数を確実に 参照できます (また、Clojureのquasiquoteは高機能で、自由変数を自動的に プレフィクスつきのトップレベル変数へと変換してくれます。) この方法はローカルマクロが存在しない限りはうまくいきます。 ローカルマクロがあると、後の例で見るように、複数の同名のローカル変数束縛を 区別する必要が出てきます。Clojureの方法はローカル変数束縛とトップレベル変数束縛を 区別できるだけです。Clojureにはローカルマクロが無いのでそれでよいのですが、 Schemeは一様で直交する定理を重視するので、レキシカルスコープを持つローカル関数があるなら、 レキシカルスコープを持つローカルマクロもやっぱり欲しいわけです。 @c COMMON @c EN Let's look at the local macro with lexical scope. For the sake of explanation, suppose we have @emph{hypothetical} local macro binding form, @code{let-macro}, that binds a local identifiers to a macro transformer. (We don't actually have @code{let-macro}; what we have is @code{let-syntax} and @code{letrec-syntax}, which have slightly different way to call macro transformers. But here @code{let-macro} may be easier to understand as it is similar to @code{define-macro}.) @c JP レキシカルスコープを持つローカルマクロを見てみましょう。説明のために、 ローカルなマクロ束縛を書ける@code{let-macro}という形式があると仮定します。 (実際には@code{let-macro}形式はありません。マクロ変換器の指定方法が やや異なる@code{let-syntax}と@code{letrec-syntax}という形式があります。 ただ、ここでは@code{define-macro}と似たような形で例を示す方がわかりやすいので、 そのような@code{let-macro}があるものとして説明します。) @c COMMON @example (let ([f (^x (* x x))]) (let-macro ([m (^[expr1 expr2] `(+ (f ,expr1) (f ,expr2)))]) (let ([f (^x (+ x x))]) (m 3 4)))) ; [1] @end example @c EN The local identifier @var{m} is bound to a macro transformer that takes two expressions, and returns an S-expression. So, the @code{(m 3 4)} form [1] would be expanded into @code{(+ (f 3) (f 4))}. Let's rewrite the above expression with the expanded form. (After expansion, we no longer need @code{let-macro} form, so we don't include it.) @c JP ローカルな識別子@var{m}は、二つの式を引数として取り、S式を返すマクロ変換器に 束縛されます。従って、[1]の@code{(m 3 4)}は @code{(+ (f 3) (f 4))}へと展開されます。上の式を展開結果を使って 書き直してみます (展開後は@code{let-macro}フォームはもはや必要ないので 展開結果には含めていません)。 @c COMMON @example (let ([f (^x (* x x))]) (let ([f (^x (+ x x))]) (+ (f 3) (f 4)))) ; [2] @end example @c EN Now, the question. Which binding @code{f} in the expanded form [2] should refer? If we literally interpret the expansion, it would refer to the inner binding @code{(^x (+ x x))}. However, following the Scheme's scoping principle, the outer code should be fully understood regardless of inner code: @c JP さてここで問題です。展開結果に現れた[2]のフォーム内の@code{f}は、どちらの @code{f}を参照すべきでしょう。上の式を文字通り解釈するなら、 より内側にある@code{(^x (+ x x))}への束縛となります。 けれども、Schemeのスコープ規則にしたがえば、 外側のコードは、内側にどんなコードが来るかに関わらず意味が決まって欲しいわけです。 @c COMMON @example (let ([f (^x (* x x))]) (let-macro ([m (^[expr1 expr2] `(+ (f ,expr1) (f ,expr2)))]) @c EN ;; The code here isn't expected to accidentally alter ;; the behavior defined outside. @c JP ;; ここに書かれたコードがうっかり外側のコードに影響を与えてしまう ;; のは避けたい。 @c COMMON )) @end example @c EN The macro writer may not know the inner @code{let} shadows the binding of @code{f} (the inner forms may be @code{include}d, or may be changed by other person who didn't fully realize the macro expansion needs to refer outer @code{f}). @c JP マクロ作成者は内側の@code{let}が@code{f}をシャドウしてしまうことを 知らないかもしれません(内側のフォームは他のコードを@code{include}している かもしれませんし、また他の人が、ローカルマクロが外側の@code{f}を参照することに 気づかずに内側のコードを変更してしまうかもしれません。) @c COMMON @c EN To ensure the local macro to work regardless of what's placed inside @code{let-macro}, we need a sure way to refer the outer @code{f} in the result of macro expansion. The basic idea is to ``mark'' the names inserted by the macro transformer @code{m}---which are @code{f} and @code{+}---so that we can distinguish two @code{f}'s. @c JP @code{let-macro}の中に置かれるコードが何であれローカルマクロが動作するためには、 マクロの展開結果から「外側の@code{f}」を確実に参照する方法が必要です。 基本的なアイディアは、 マクロ変換器@code{m}により挿入される名前(@code{f}と@code{+})に 「印」をつけて、二つの@code{f}を区別するというものです。 @c COMMON @c EN For example, if we would rewrite the entire form and @emph{renames} corresponding local identifiers as follows: @c JP 例えば、フォーム全体を書き直して、対応するローカル変数がユニークな名前を持つように @emph{リネーム}したらどうでしょう: @c COMMON @example (let ([f_1 (^x (* x x))]) (let-macro ([m (^[expr1 expr2] `(+ (f_1 ,expr1) (f_1 ,expr2)))]) (let ([f_2 (^x (+ x x))]) (m 3 4)))) @end example @c EN Then the naive expansion would correctly preserve scopes; that is, expansion of @code{m} refers @code{f_1}, which wouldn't conflict with inner name @code{f_2}: @c JP こうしておけばナイーブな展開でもスコープが正しく保たれます。つまり、 @code{m}の展開結果に現れる@code{f_1}は内側の@code{f_2}と衝突しません。 @c COMMON @example (let ([f_1 (^x (* x x))]) (let ([f_2 (^x (+ x x))]) (+ (f_1 3) (f_1 4)))) @end example @c EN (You may notice that this is similar to lambda calculus treating lexical bindings with higher order functions.) @c JP (ラムダ計算において、レキシカルスコープを保ったまま高階関数を扱う際に 似たようなリネーム戦略を見たことがあるかもしれません) @c COMMON @c EN The above example deal with avoiding @code{f} referred from the macro @emph{definition} (which is, in fact, @code{f_1}) from being shadowed by the binding of @code{f} at the macro @emph{use} (which is @code{f_2}). @c JP 上の例ではマクロの@emph{定義時}に現れる@code{f}(リネーム後は@code{f_1})が マクロの@emph{使用時}に現れる@code{f} (リネーム後は@code{f_2}) によって シャドウされることを避ける話でした。 @c COMMON @c EN Another type of variable capture (the one most often talked about, and can be avoided by @code{gensym}) is that a variable in macro use site is shadowed by the binding introduced by a macro definition. We can apply the same renaming strategy to avoid that type of capture, too. Let's see the following example: @c JP 一方、もう一つのタイプの変数捕捉 (より頻繁に話題に上る、@code{gensym}で回避できる捕捉) は、マクロ使用時の変数がマクロ定義時に導入される束縛によりシャドウされてしまう という問題です。これについても、同じリネーム戦略が使えます。 次の例を見てみましょう。 @c COMMON @example (let ([f (^x (* x x))]) (let-macro ([m (^[expr1] `(let ([f (^x (+ x x))]) (f ,expr1)))]) (m (f 3)))) @end example @c EN The local macro inserts binding of @code{f} into the expansion. The macro use @code{(m (f 3))} also contains a reference to @code{f}, which should be the outer @code{f}, since the macro use is lexically outside of the @code{let} inserted by the macro. @c JP ローカルマクロは@code{f}の束縛を導入しています。 一方、マクロの使用時@code{(m (f 3))}に、@code{f}への参照が含まれています。 後者の@code{f}は外側の@code{f}を指すべきです。なぜならマクロを使っている フォームは字句上、マクロ定義の@code{let}の外側にあるからです。 @c COMMON @c EN We could rename @code{f}'s according to its lexical scope: @c JP @code{f}をレキシカルスコープによってリネームすれば次のようになるでしょう。 @c COMMON @example (let ([f_1 (^x (* x x))]) (let-macro ([m (^[expr1] `(let ([f_2 (^x (+ x x))]) (f_2 ,expr1)))]) (m (f_1 3)))) @end example @c EN Then expansion unambiguously distinguish two @code{f}'s. @c JP これだと展開しても二つの@code{f}はきちんと区別されます。 @c COMMON @example (let ([f_1 (^x (* x x))]) (let ([f_2 (^x (+ x x))]) (f_2 (f_1 3)))) @end example @c EN This is, in principle, what hygienic macro is about (well, almost). In reality, we don't rename everything in batch. One caveat is in the latter example---we statically renamed @code{f} to @code{f_2}, but it is possible that the macro recursively calls itself, and we have to distinguish @code{f}'s introduced in every individual expansion of @code{m}. So macro expansion and renaming should work together. @c JP 以上が、衛生的マクロの原理です (まあ、だいたいは)。 ただし、実際の実装では、すべてを一気にリネームすることはありません。 後者の例のようなケースで注意すべき点があります。後者の例では静的に @code{f}を@code{f_2}にリネームしましたが、より複雑な場合にマクロ展開器が 再帰的に自分を呼ぶことがあり、その場合にはマクロの展開ごとに挿入される@code{f}を 別のものとして扱う必要があります。 従って、マクロの展開とリネームは協調して動作しなければなりません。 @c COMMON @c EN There are multiple strategies to implement it, and the Scheme standard doesn't want to bind implementations to single specific strategy. The standard only states the properties the macro system should satisfy, in two concise sentences: @c JP それを実装する戦略はいくつか考えられます。そして、Scheme標準は実装を どれかひとつの戦略に縛ってしまうことを良しとしません。 結果的に、標準はマクロシステムが満たすべき性質を、二つの簡潔な 文で示すに止まります: @c COMMON @quotation @c EN If a macro transformer inserts a binding for an identifier (variable or keyword), the identifier will in effect be renamed throughout its scope to avoid conflicts with other identifiers. @c JP マクロ展開器が識別子(変数かキーワード)の束縛を挿入した場合、 識別子はそのスコープ内で実効的にリネームされ、 他の識別子との衝突を避けられる。 @c COMMON @c EN If a macro transformer inserts a free reference to an identifier, the reference refers to the binding that was visible where the transformer was specified, regardless of any local bindings that surround the use of the macro. @c JP マクロ展開器が識別子の自由参照を挿入した場合、その識別子は展開器が定義された場所から 見える束縛を参照し、マクロが使われる場所を囲むローカル束縛には影響されない。 @c COMMON @end quotation @c EN Just from reading this, it may not be obvious @emph{how} to realize those properties, and the existing hygienic macro mechanisms (e.g. @code{syntax-rules}) hide the ``how'' part. That's probably one of the reason some people feel hygienic macros are difficult to grasp. It's like continuations---its description is concise but at first you have no idea how it works; then, through experience, you become familiarized yourself to it, and then you reread the original description and understand it says exactly what it is. @c JP これを読んだだけでは、これらの性質を@emph{いかにして}実現するかは すぐにはわからないかもしれません。そして既存の衛生的マクロ(@code{syntax-rules}など)は この@emph{いかにして}の部分を隠しています。それが、 衛生的マクロをとっつきにくく思う理由の一つかもしれません。 これはある意味、継続に似ています。継続の仕様はごく簡潔に述べられていて、 最初に読んだときにはどう動くかさっぱりわからないかもしれません。 しかし経験を積んで使うのに慣れた後でもう一度元の説明を読むと、 必要十分なことが書いてあるとわかるのです。 @c COMMON @c EN This introduction may not answer @emph{how} the hygienic macro realizes those properties, but I hope it showed @emph{what} it does and @emph{why} it is needed. In the following chapters we introduce a couple of hygienic macro mechanisms Gauche supports, with examples, so that you can familiarize yourself to the concept. @c JP この節では@emph{いかにして}衛生的マクロがこれらの性質を 実現しているかについての詳細には触れませんでしたが、 衛生的マクロが@emph{何を}して、@emph{何のために}必要かについて ある程度示せたのではないかと思います。 以降の節では、Gaucheがサポートする衛生的マクロシステムについて 例を交え紹介してゆきます。 @c COMMON @node Hygienic macros, Traditional macros, Why hygienic?, Macros @section Hygienic macros @c NODE 衛生的マクロ @c EN @subheading Macro bindings @c JP @subheading マクロ束縛 @c COMMON @c EN The following forms establish bindings of @var{name} and a macro transformer created by @var{transformer-spec}. The binding introduced by these forms shadows a binding of @var{name} established in outer scope, if there's any. @c JP 以下のフォームは@var{transformer-spec}で作られるマクロ変換器と @var{name}の束縛を作ります。外側のスコープに@var{name}の束縛があれば、 それはシャドウされます。 @c COMMON @c EN For toplevel bindings, it will shadow bindings of @var{name} imported or inherited from other modules (@pxref{Modules}). (Note: This toplevel shadowing behavior is Gauche's extension; in R7RS, you shouldn't redefine imported bindings, so the portable code should avoid it.) @c JP トップレベル束縛の場合、@var{name}に他のモジュールからインポートされたり 継承されている束縛があれば、それをシャドウすることになります (@ref{Modules}参照)。 (註:モジュール内でのトップレベル束縛がインポートした束縛をシャドウするのは Gaucheの拡張です。R7RSではインポートした束縛の再定義はしてはいけないことに なっているので、ポータブルなコードでは避けて下さい)。 @c COMMON @c EN The effect is undefined if you bind the same name more than once in the same scope. @c JP 同じスコープで同じ名前を複数回束縛した場合の動作は未定義です。 @c COMMON @c EN The @var{transformer-spec} can be either one of @code{syntax-rules} form, @code{er-macro-transformer} form, or another macro keyword or syntactic keyword. We'll explain them later. @c JP @var{transformer-spec}は@code{syntax-rules}フォーム、 @code{er-macro-transformer}フォーム、あるいは他のマクロキーワードか 構文キーワードです。これについては後述します。 @c COMMON @defspec define-syntax name transformer-spec [R7RS base] @c EN If this form appears in toplevel, it binds toplevel @var{name} to a macro transformer defined by @var{transformer-spec}. If this form appears in the @emph{declaration} part of body of @code{lambda} (internal define-syntax), @code{let} and other similar forms, it binds @var{name} locally within that body. Conceptually, internal @code{define-syntax}es on the same level are treated like @code{letrec-syntax}. However, mere appearance of @code{define-syntax} does not create another scope; for example, you can interleave internal @code{define} and internal @code{define-syntax} within the same scope. It is important, though, that the local macros defined by internal @code{define-syntax} should not be required to expand macro uses before the definition. @c JP トップレベルで使われた場合、このフォームはトップレベルの@var{name}を @var{transformer-spec}で定義されるマクロ変換器に束縛します。 @code{lambda}、@code{let}等の本体の宣言部分に使われた場合 (内部@code{define-syntax})、 その本体内のスコープで@var{name}を束縛します。 概念的には、同一階層にある内部@code{define-syntax}はまとめられて @code{letrec-syntax}のように振る舞います。ただし、@code{define-syntax}が出てきたところで 新たなスコープが作られるわけではありません。 例えば内部@code{define}と内部@code{define-syntax}を一つのスコープ内で混ぜこせに 並べることができます。重要なのは、内部@code{define-syntax}で定義されるローカルマクロは、 その定義前にマクロ展開に必要とされてはならない、ということです。 @c COMMON @end defspec @defspec let-syntax ((name transformer-spec) @dots{}) body @defspecx letrec-syntax ((name transformer-spec) @dots{}) body [R7RS base] @c EN Defines local macros. Each @var{name} is bound to a macro transformer as specified by the corresponding @var{transformer-spec}, then @code{body} is expanded. With @code{let-syntax}, @var{transformer-spec} is evaluated with the scope surrounding @code{let-syntax}, while with @code{letrec-syntax} the bindings of @var{name}s are included in the scope where @var{transformer-spec} is evaluated. Thus @code{letrec-syntax} allows mutually recursive macros. @c JP ローカルマクロを定義します。各@var{name}が 対応する@var{transformer-spec}で定義されるマクロ変換器へと束縛された 環境を作り@var{body}を評価します。 @code{let-syntax}では、@var{transformer-spec}は@code{let-syntax}を 囲むスコープ内で@var{transformer-spec}を評価するのに対し、 @code{letrec-syntax}では@var{name}の束縛がなされた環境で @var{transformer-spec}を評価します。つまり@code{letrec-syntax}は 相互再帰的なマクロを定義できます。 @c COMMON @end defspec @subheading Transformer specs @c EN The @var{transformer-spec} is a special expression that evaluates to a macro transformer. It is evaluated in a different phase than the other expressions, since macro transformers must be executed during compiling. So there are some restrictions. At this moment, only one of the following expressions are allowed: @c JP @var{transformer-spec}は、マクロ展開器へと評価される特別な式です。 マクロ変換器はコンパイル時に実行されるため、他の式とは異なった段階で評価されます。 そのためにいくらか制限があります。 現在のところ、以下に挙げる式しか許されていません。 @c COMMON @enumerate @item @c EN A @code{syntax-rules} form. This is called ``high-level'' macro, for it uses pattern matching entirely, which is basically a different declarative language from Scheme, thus putting the complication of the phasing and hygiene issues completely under the hood. Some kind of macros are easier to write in @code{syntax-rules}. @xref{Syntax-rules macro transformer}, for further description. @c JP @code{syntax-rules}フォーム。これは「高レベル」マクロと呼ばれ、 パターンマッチングのみによってマクロを定義します。 これはSchemeとは異なる一種の宣言的言語で、 マクロの段階や衛生の問題をボンネットの下に隠してしまいます。 ある種のマクロは@code{syntax-rules}でより簡単に書けます。 詳しくは@ref{Syntax-rules macro transformer}を参照してください。 @c COMMON @item @c EN An @code{er-macro-transformer} form. This employs @emph{explicit-renaming} (ER) macro, where you can use arbitrary Scheme code to transform the program, with required renaming to keep hygienity. The legacy Lisp macro can also be written with ER macro if you don't use renaming. @xref{Explicit-renaming macro transformer}, for the details. @c JP @code{er-macro-transfomer}フォーム。 これは@emph{explicit renaming}(ER)マクロを定義します。 ERマクロでは、必要な衛生を保ちながら、任意のSchemeコードを使って変換を書けます。 伝統的なLispのマクロは、ERマクロでリネームを使わない特別な場合と考えられます。 詳しくは@ref{Explicit-renaming macro transformer}を参照してください。 @c COMMON @item @c EN A @code{make-id-transformer} form. This creates an @emph{identifier macro}, Unlike an ordinary macro, an identifier macro expands without being at the head of a list; it looks like a variable in the source. @xref{Identifier transformer}, for the details. @c JP @code{make-id-transformer}フォーム。 これは@emph{識別子マクロ}を定義します。 通常のマクロと異なり、識別子マクロはリストの最初の位置に置かれないでも展開されます。 ソース上では通常の変数のように見えます。 詳しくは@ref{Identifier transformer}を参照してください。 @c COMMON @item @c EN Macro or syntax keyword. This is Gauche's extension, and can be used to define alias of existing macro or syntax keyword. @c JP マクロキーワードか構文キーワード。これはGauche独自の拡張で、 既存のマクロキーワードや構文キーワードの別名を定義するものです。 @c COMMON @example (define-syntax si if) (define écrivez write) (si (< 2 3) (écrivez "oui")) @end example @end enumerate @menu * Syntax-rules macro transformer:: * Explicit-renaming macro transformer:: * Identifier transformer:: @end menu @node Syntax-rules macro transformer, Explicit-renaming macro transformer, Hygienic macros, Hygienic macros @subsection Syntax-rules macro transformer @c NODE Syntax-rulesマクロ変換器 @defspec syntax-rules (literal @dots{}) clause clause2 @dots{} @defspecx syntax-rules ellipsis (literal @dots{}) clause clause2 @dots{} [R7RS base] @c EN This form creates a macro transformer by pattern matching. Each @var{clause} has the following form: @c JP パターンマッチングによるマクロ変換器を作ります。 各@var{clause}は次の形式です。 @c COMMON @example (@var{pattern} @var{template}) @end example @c EN A @var{pattern} denotes a pattern to be matched to the macro call. It is an S-expression that matches if the macro call has the same structure, except that symbols in @var{pattern} can match a whole subtree of the input; the matched symbol is called a @emph{pattern variable}, and can be referenced in the @var{template}. @c JP @var{pattern}はマクロ呼び出しにマッチすべきパターンを記述します。 パターンはS式で、マクロ呼び出しの式と同じ構造を持っている場合にマッチします。 但し、パターン中のシンボルは@emph{パターン変数}と呼ばれ、 マクロ呼び出し式の対応する任意の部分木とマッチし、 @var{template}の中でマッチした部分木を参照するのに使えます。 @c COMMON @c EN For example, if a pattern is @code{(_ "foo" (a b))}, it can match the macro call @code{(x "foo" (1 2))}, or @code{(x "foo" (1 (2 3)))}, but does not match @code{(x "bar" (1 2))}, @code{(x "foo" (1))} or @code{(x "foo" (1 2) 3)}. You can also match repeating structure or literal symbols; we'll discuss it fully later. @c JP 例えば、パターンが@code{(_ "foo" (a b))}であったとすると、それは @code{(x "foo" (1 2))}や@code{(x "foo" (1 (2 3)))}といったマクロ呼び出しとマッチしますが、 @code{(x "bar" (1 2))}、@code{(x "foo" (1))}、@code{(x "foo" (1 2) 3)}とは マッチしません。 さらに、後で説明するように、繰り返しのある構造やリテラルシンボルとマッチするような記述も可能です。 @c COMMON @c EN Clauses are examined in order to see if the macro call form matches its pattern. If matching pattern is found, the corresponding @var{template} replaces the macro call form. A pattern variable in the template is replaced with the subtree of input that is bound to the pattern variable. @c JP @var{clause}は順番に、そのパターンにマクロ呼び出しとマッチするかが検査されます。 マッチするパターンが見つかれば、対応する@var{template}でマクロ呼び出しの式が 置き換えられます。@var{template}中のパターン変数は、 マクロ呼び出し式のその変数にマッチした部分木で置き換えられます。 @c COMMON @c EN Here's a definition of @code{when} macro in @ref{Why hygienic?}, using @code{syntax-rules}: @c JP これは@ref{Why hygienic?}で例に出した@code{when}マクロを @code{syntax-rules}で書いたものです: @c COMMON @example (define-syntax when (syntax-rules () [(_ test body ...) (if test (begin body ...))])) @end example @c EN The pattern is @code{(_ test body ...)}, and the template is @code{(if test (begin body ...))}. The ellipsis @code{...} is a symbol; we're not omitting code here. It denotes that the previous pattern (@code{body}) may repeat zero or more times. @c JP パターンが@code{(_ test body ...)}で、 テンプレートが@code{(if test (begin body ...))}です。 @code{...} (エリプシス) は、記述を省略しているわけではなく、 ピリオド3つからなる名前を持つシンボルです。 これは直前のパターン(@code{body})がゼロ個以上繰り替えされるということを示します。 @c COMMON @c EN So, if the @code{when} macro is called as @code{(when (zero? x) (print "huh?") (print "we got zero!"))}, the macro expander first check if the input matches the pattern. @c JP @code{when}マクロが @code{(when (zero? x) (print "huh?") (print "we got zero!"))} という形で呼び出されたとしましょう。 マクロ展開器はまず、この入力がパターンとマッチするかどうかを調べます。 @c COMMON @itemize @bullet @item @c EN The @var{test} in pattern matches the input @code{(zero? x)}. @c JP パターン中の@var{test}は入力の@code{(zero? x)}とマッチ。 @c COMMON @item @c EN The @var{body} in pattern matches the input @code{(print "huh?")} @emph{and} @code{(print "we got zero!")}. @c JP パターン中の@var{body}は入力の@code{(print "huh?")}および@code{(print "we got zero!")}とマッチ @c COMMON @end itemize @c EN The matching of @var{body} is a bit tricky; as a pattern variable, you may think that @var{body} works like an array variable, each element holds each match---and you can use them in similarly repeating substructures in template. Let's see the template, now that the input fully matched the pattern. @c JP @var{body}とのマッチングはちょっとややこしいです。 パターン変数@var{body}は配列のようなものだと考えても良いでしょう。 配列の各要素がマッチする入力の部分木を保持します。 その値は、テンプレート中の似たような繰り返し部分構造の中で使うことができます。 ここまでで入力がパターンにマッチしたので、テンプレートの方を見てみましょう。 @c COMMON @itemize @bullet @item @c EN In the template, @code{if} and @code{begin} are not pattern variable, since they are not appeared in the pattern. So they are inserted as identifiers---that is, hygienic symbols effectively renamed to make sure to refer to the global @code{if} and @code{begin}, and will be unaffected by the macro use environment. @c JP テンプレート中の@code{if}と@code{begin}はパターン中に現れていないので パターン変数ではありません。従って、識別子として出力に挿入されます。 ここで、識別子@code{if}や@code{begin}はこのマクロのスコープから見えるグローバルな @code{if}や@code{begin}を常に参照できるように、衛生的に扱われます。 マクロが使われた場所で@code{if}や@code{begin}がシャドウされていたとしても影響を受けません。 @c COMMON @item @c EN The @var{test} in the template is a pattern variable, so it is replaced for the matched value, @code{(zero? x)}. @c JP テンプレート中の@var{test}はパターン変数なので、マッチした値である@code{(zero? x)}へと 置き換えられます。 @c COMMON @item @c EN The @var{body} is also a pattern variable. The important point is that it is also followed by ellipsis. So we repeat @var{body} as many times as the number of matched values. The first value, @code{(print "huh?")}, and the second value, @code{(print "we got zero!")}, are expanded here. @c JP @var{body}もパターン変数です。重要な点はここでも@var{body}の後にエリプシスがあることで、 @var{body}はパターン変数にマッチした値のぶんだけ繰り返されます。 最初のマッチした値である@code{(print "huh?")}と、次の @code{(print "we got zero!")}とがここに展開されます。 @c COMMON @item @c EN Hence, we get @code{(if (zero? x) (begin (print "huh?") (print "we got zero!")))} as the result of expansion. (With the note that @code{if} and @code{begin} refers to the identifiers visible from the macro definition environment.) @c JP 以上から、最終的な展開結果として @code{(if (zero? x) (begin (print "huh?") (print "we got zero!")))} が得られます (このうち、@code{if}と@code{begin}は マクロ定義環境から見える識別子を指すようになっています)。 @c COMMON @end itemize @c EN The expansion of ellipses is quite powerful. In the template, the ellipses don't need to follow the sequence-valued pattern variable immediately; the variable can be in a substructure, as long as the substructure itself is followed by an ellipsis. See the following example: @c JP エリプシスを使った展開はかなり強力です。 テンプレート中で、エリプシスは複数の値を持つパターン変数の直後にある必要はありません。 そういった変数を中に含む部分構造をエリプシスで繰り返すことも可能です。 次の例を見てください。 @c COMMON @example (define-syntax show (syntax-rules () [(_ expr ...) (begin (begin (write 'expr) (display "=") (write expr) (newline)) ...)])) @end example @c EN If you call this macro as follows: @c JP このマクロを次のように呼ぶと: @c COMMON @example (show (+ 1 2) (/ 3 4)) @end example @c EN It is expanded to the following form, modulo hygienity: @c JP 以下のとおりに展開されます (シンボルの衛生性は保たれているとします)。 @c COMMON @example (begin (begin (write '(+ 1 2)) (display "=") (write (+ 1 2)) (newline)) (begin (write '(/ 3 4)) (display "=") (write (/ 3 4)) (newline))) @end example @c EN So you'll get this output. @c JP これを実行すれば、以下の出力が得られるでしょう。 @c COMMON @example (+ 1 2)=3 (/ 3 4)=3/4 @end example @c EN You can also match with a repetition of substructures in the pattern. The following example is a simplified @code{let} that expands to @code{lambda}: @c JP また、パターン中の部分構造を繰り返しマッチするのにも使えます。 次の例は@code{let}を@code{lambda}に展開する、簡略化した例です: @c COMMON @example (define-syntax my-let (syntax-rules () [(_ ((var init) ...) body ...) ((lambda (var ...) body ...) init ...)])) @end example @c EN If you call it as @code{(my-let ((a expr1) (b expr2)) foo)}, then @var{var} is matched to @code{a} and @code{b}, while @var{init} is matched to @code{expr1} and @code{expr2}, respectively. They can be used separately in the template. @c JP このマクロを@code{(my-let ((a expr1) (b expr2)) foo)}のように呼び出すと、 @var{var}は@code{a}および@code{b}に、 @var{init}は@code{expr1}および@code{expr2}にそれぞれマッチします。 @var{var}と@var{init}はテンプレート中でばらばらに使うことができます。 @c COMMON @c EN Suppose ``level'' of a pattern variable means the number of nested ellipses that designate repetition of the pattern variable. A subtemplate can be followed as many ellipses as the maximum level of pattern variables in the subtemplate. In the following example, the level of pattern variable @code{a} is 1 (it is repeated by the last ellipsis in the pattern), while the level of @code{b} is 2 (repeated by the last two ellipses), and the level of @code{c} is 3 (repeated by all the ellipses). @c JP パターン変数の繰り返しを示すエリプシスの入れ子の数を、 そのパターン変数のレベルと呼ぶことにします。 サブテンプレートは、その中に含まれるパターン変数のレベルの最大値と同じだけの エリプシスの入れ子に中になければなりません。 次の例では、パターン変数@code{a}のレベルは1 (最後のエリプシスによって繰り返される)、 @code{b}は2 (後ろの2つのエリプシスで繰り返される)、 @code{c}は3 (全てのエリプシスで繰り返される) です。 @c COMMON @example (define-syntax ellipsis-test (syntax-rules () [(_ (a (b c ...) ...) ...) '((a ...) (((a b) ...) ...) ((((a b c) ...) ...) ...))])) @end example @c EN In this case, the subtemplate @code{a} must be repeated by one level of ellipsis, @code{(a b)} must be repeated by two, and @code{(a b c)} must be repeated by three. @c JP したがって、サブテンプレート @code{a} は1重、 サブテンプレート @code{(a b)}は2重、 @code{(a b c)}は3重のエリプシスで繰り返されることになります。 @c COMMON @example (ellipsis-test (1 (2 3 4) (5 6)) (7 (8 9 10 11))) @result{} ((1 7) (((1 2) (1 5)) ((7 8))) ((((1 2 3) (1 2 4)) ((1 5 6))) (((7 8 9) (7 8 10) (7 8 11))))) @end example @c EN In the template, more than one ellipsis directly follow a subtemplate, splicing the leaves into the surrounding list: @c JP また、サブテンプレートの後ろには複数のエリプシスを直接置くことができ、 繰り返しの「葉」の部分がそこにスプライスされます。 @c COMMON @example (define-syntax my-append (syntax-rules () [(_ (a ...) ...) '(a ... ...)])) (my-append (1 2 3) (4) (5 6)) @result{} (1 2 3 4 5 6) (define-syntax my-append2 (syntax-rules () [(_ ((a ...) ...) ...) '(a ... ... ...)])) (my-append2 ((1 2) (3 4)) ((5) (6 7 8))) @result{} (1 2 3 4 5 6 7 8) @end example @c EN Note: Allowing multiple ellipses to directly follow a subtemplate, and a pattern variable in a subtemplate to be enclosed within more than the variable's level of nesting of ellipses, are extension to R7RS, and defined in SRFI-149. In the above examples, @code{ellipsis-test}, @code{my-append} and @code{my-append2} are outside of R7RS. @c JP 註:サブテンプレートの直後に複数のエリプシスを置くこと、 及びパターン変数をそのレベルよりもエリプシスのネストが深いテンプレート中に置けることは、 R7RSに対する拡張で、SRFI-149で定義されています。上記の例では、 @code{ellipsis-test}、@code{my-append}、@code{my-append2}が R7RSの範囲外になります。 @c COMMON @c EN Identifiers in a pattern is treated as pattern variables. But sometimes you want to match a specific identifier in the input. For example, the built-in @code{cond} and @code{case} detects an identifier @code{else} as a special identifier. You can use @var{literal} @dots{} for that. See the following example. @c JP パターン中に現れる識別子はパターン変数として扱われますが、 特定の識別子そのものにマッチさせたい場合もあります。例えば組み込みの@code{cond}や @code{case}は、@code{else}という識別子を特別に認識します。 @var{literal} @dots{}がその目的に使えます。次の例を見てください。 @c COMMON @example (define-syntax if+ (syntax-rules (then else) [(_ test then expr1 else expr2) (if test expr1 expr2)])) @end example @c EN The identifiers listed as the literals don't become pattern variables, but literally match the input. If the input doesn't have the same identifier in the position, match fails. @c JP リテラルとして列挙された識別子はパターン変数にはならず、入力の識別子とそのままマッチします。 もし入力の該当する位置に同じ識別子が置かれていなければ、マッチは失敗します。 @c COMMON @example (if+ (even? x) then (/ x 2) else (/ (+ x 1) 2)) @r{expands into} (if (even? x) (/ x 2) (/ (+ x 1) 2)) (if+ (even? x) foo (/ x 2) bar (/ (+ x 1) 2)) @result{} ERROR: malformed if+ @end example @c EN We've been saying identifiers instead of symbols. Roughly speaking, an identifier is a symbol with the surrounding syntactic environment, so that they can keep identity under renaming of hygiene macro. @c JP これまで、シンボルと呼ばずに識別子という言葉を使っていました。大まかに言うと、 識別子とはシンボルに周囲の構文的環境をくっつけたもので、 衛生的マクロによるリネームによっても同一性を失わないようになっています。 @c COMMON @c EN The following example fails, because the @code{else} passed to the @code{if+} macro is the one locally bound by @code{let}, which is different from the global @code{else} when @code{if+} was defined, hence they don't match. @c JP 次の例は失敗します。@code{if+}に渡されている@code{else}は@code{let}でローカルに 束縛されており、それは@code{if+}が定義された時点でのグローバルな@code{else}とは 違うもので、したがってマッチしないからです。 @c COMMON @example (let ((else #f)) (if+ (even? x) then (/ x 2) else (/ (+ x 1) 2)) @result{} ERROR: malformed if+ @end example @end defspec @node Explicit-renaming macro transformer, Identifier transformer, Syntax-rules macro transformer, Hygienic macros @subsection Explicit-renaming macro transformer @c NODE Explicit-renamingマクロ変換器 @defspec er-macro-transformer procedure-expr @c EN Creates a macro transformer from the given @var{procedure-expr}. The created macro transformer has to be bound to the syntactic keyword by @code{define-syntax}, @code{let-syntax} or @code{letrec-syntax}. Other use of macro transformers is undefined. The @var{procedure-expr} must evaluate to a procedure that takes three arguments; @var{form}, @var{rename} and @var{id=?}. The @var{form} argument receives the S-expression of the macro call. The @var{procedure-expr} must return an S-expression as the result of macro expansion. This part is pretty much like the traditional lisp macro. In fact, if you ignore @var{rename} and @var{id=?}, the semantics is the same as the traditional (unhygienic) macro. See the following example (Note the use of @code{match}; it is a good tool to decompose macro input): @c JP @var{procedure-expr}からマクロ変換器を作ります。 作られたマクロ変換器は、@code{define-syntax}、@code{let-syntax}、 @code{letrec-syntax}により構文キーワードに束縛されなければなりません。 マクロ変換器の他の用途は定義されていません。 @var{procedure-expr}は3つの引数、@var{form}、@var{rename}、@var{id=?}を 取る手続きへと評価される式です。 @var{form}引数には、マクロ呼び出しのS式そのものが渡されます。 @var{procedure-expr}はマクロ展開の結果をS式として返します。 この点は、伝統的なマクロとよく似ています。実のところ、 @var{rename}と@var{id=?}を無視すれば、セマンティクスは伝統的な(非衛生な)マクロと 同じになります。次の例を見てください (この例では@code{match}を使っています。マクロの入力を分解するのにも 手軽なツールです。) @c COMMON @example (use util.match) ;; Unhygienic 'when-not' macro (define-syntax when-not (er-macro-transformer (^[form rename id=?] (match form [(_ test expr1 expr ...) `(if (not ,test) (begin ,expr1 ,@@expr))] [_ (error "malformed when-not:" form)])))) (macroexpand '(when-not (foo) (print "a") 'boo)) @result{} (if (not (foo)) (begin (print "a") 'boo)) @end example @c EN This is ok as long as you know you don't need hygiene---e.g. when you only use this macro locally in your code, knowing all the macro call site won't contain name conflicts. However, if you provide your @code{when-not} macro for general use, you have to protect namespace pollution around the macro use. For example, you want to make sure your macro work even if it is used as follows: @c JP 衛生を気にする必要がない場合は、これでも十分です。 例えばマクロを自分で書いたコードの中だけで使い、 すべてのマクロ呼び出しを把握していて名前の衝突が起きないことを知っている場合です。 けれども、この@code{when-not}マクロを広く使えるようにするなら、 マクロの使われる場所での名前の衝突からの防御が必要です。 たとえば、次のとおり呼び出されたとしてもちゃんと動くようにしたい場合です。 @c COMMON @example (let ((not values)) (when-not #t (print "This shouldn't be printed"))) @end example @c EN The @var{rename} argument passed to @var{procedure-expr} is a procedure that takes a symbol (or, to be precise, a symbol or an identifier) and @emph{effectively renames} it to a unique identifier that keeps identity within the macro definition environment and won't be affected in the macro use environment. @c JP @var{procedure-expr}に渡される@var{rename}引数は、 シンボル(正確には、シンボルか識別子)を取り、それをマクロ定義時の環境を保持する ユニークな識別子へと@emph{実質的にリネームする}手続きです。 リネームされた識別子はマクロ使用時の環境には影響を受けません。 @c COMMON @c EN As a rule of thumb, you have to pass @emph{all new identifiers you insert into macro output} to the @var{rename} procedure to keep hygiene. In our @code{when-not} macro, we insert @code{if}, @code{not} and @code{begin} into the macro output, so our hygienic macro would look like this: @c JP 大雑把なルールとして、マクロの出力に挿入する識別子はすべて@var{rename}を通すことを 徹底すれば、衛生は保たれます。@code{when-not}マクロの例では、 マクロの出力に@code{if}、@code{not}、@code{begin}を挿入していますから、 衛生的なバージョンは次のとおり書けます。 @c COMMON @example (define-syntax when-not (er-macro-transformer (^[form rename id=?] (match form [(_ test expr1 expr ...) `(,(rename 'if) (,(rename 'not) ,test) (,(rename 'begin) ,expr1 ,@@expr))] [_ (error "malformed when-not:" form)])))) @end example @c EN This is cumbersome and makes it hard to read the macro, so Gauche provides an auxiliary macro @code{quasirename}, which works like @code{quasiquote} but renaming identifiers in the form. See the entry of @code{quasirename} below for the details. You can write the hygienic @code{when-not} as follows: @c JP でもこれは面倒ですし読みづらいですね。そこでGaucheでは、 補助マクロ@code{quasirename}を用意しています。これは@code{quasiquote}のように 動作しますが、フォーム中の識別子をリネームしてゆきます。詳しくは後述の @code{quasirename}のエントリを参照してください。@code{quasirename}を使うと 衛生的な@code{when-not}はこうなります: @c COMMON @example (define-syntax when-not (er-macro-transformer (^[form rename id=?] (match form [(_ test expr1 expr ...) (quasirename rename `(if (not ,test) (begin ,expr1 ,@@expr)))] [_ (error "malformed when-not:" form)])))) @end example @c EN You can intentionally break hygiene by inserting a symbol without renaming. The following code implements @emph{anaphoric} @code{when}, meaning the result of the test expression is available in the @var{expr1} @var{exprs} @dots{} with the name @code{it}. Since the binding of the identifier @code{it} does not exist in the macro use site, but rather injected into the macro use site by the macro expander, it is unhygienic. @c JP シンボルをリネームせずに挿入すれば、意図的に衛生を破ることができます。 次のコードは@emph{アナフォリック(前方照応的)な}@code{when}を定義しています。 つまり、テスト式の結果が、@var{expr1} @var{exprs} @dots{} から@code{it}という 変数で参照できるということです。 @code{it}の束縛はマクロ呼び出し箇所には無かったもので、 マクロ展開器により挿入されるので、これは非衛生マクロになります。 @c COMMON @example (define-syntax awhen (er-macro-transformer (^[form rename id=?] (match form [(_ test expr1 expr ...) `(,(rename 'let1) it ,test ; 'it' is not renamed (,(rename 'begin) ,expr1 ,@@expr))])))) @end example @c EN If you use @code{quasirename}, you can write @code{,'it} to prevent @code{it} from being renamed: @c JP @code{quasirename}を使う場合、@code{it}がリネームされないようにするには @code{,'it}と書きます。 @c COMMON @example (define-syntax awhen (er-macro-transformer (^[form rename id=?] (match form [(_ test expr1 expr ...) (quasirename rename `(let1 ,'it ,test (begin ,expr1 ,@@expr)))])))) @end example @c EN Here's an example: @c JP 使用例を見てみましょう。 @c COMMON @example (awhen (find odd? '(0 2 8 7 4)) (print "Found odd number:" it)) @result{} @r{prints} Found odd number:7 @end example @c EN Finally, the @var{id=?} argument to the @var{procedure-expr} is a procedure that takes two arguments, and returns @code{#t} iff both are identifiers and either both are referring to the same binding or both are free. It can be used to compare literal syntactic keyword (e.g. @code{else} in @code{cond} and @code{case} forms) hygienically. The following @code{if=>} macro behaves like @code{if}, except that it accepts @code{(if=> test => procedure)} syntax, in which @code{procedure} is called with the value of @code{test} if it is not false (similar to @code{(cond [test => procedure])} syntax). The symbol @code{=>} must match hygienically, that is, it must refer to the same binding as in the macro definition. @c JP 最後に、@var{procedure-expr}の@var{id=?}引数はふたつの引数を取り、 それらがともに識別子であって、しかも同じ束縛を参照するか束縛されていないか、という 場合に限り@code{#t}を返します。 これはリテラル構文キーワード(@code{cond}や@code{case}フォームの@code{else}等) を比較するのに使えます。 下の@code{if=>}マクロは@code{if}と同じように動作しますが、 @code{(if=> test => procedure)}のように呼ばれた場合、 @code{(cond [test => procedure])}構文と同じように、 @code{test}が真の値を返した際には結果を引数にして@code{procedure}を呼び出します。 シンボル@code{=>}は衛生的に比較されます。つまり、マクロ定義時と同じ束縛を 参照している場合にのみ有効となります。 @c COMMON @example (define-syntax if=> (er-macro-transformer (^[form rename id=?] (match form [(_ test a b) (if (id=? (rename '=>) a) (quasirename rename `(let ((t ,test)) (if t (,b t)))) (quasirename rename `(if ,test ,a ,b)))])))) @end example @c EN The call @code{(rename '=>)} returns an identifier that captures the binding of @code{=>} in the macro definition, and using @code{id=?} with the thing passed to the macro argument checks if both refer to the same binding. @c JP @code{(rename '=>)}とすることで、マクロ定義時における@code{=>}の束縛を 参照する識別子を手に入れ、@code{id=?}でそれをマクロ引数から渡された式と 比較しています。 @c COMMON @example (if=> 3 => list) @result{} (3) (if=> #f => list) @result{} # @c EN ;; If the second argument isn't =>, if=> behaves like ordinary if: @c JP ;; 第二引数が=>でなければ、if=>は通常のifと同じ: @c COMMON (if=> #t 1 2) @result{} 1 @c EN ;; The binding of => in macro use environment differs from ;; the macro definition environment, so this if=> behaves like ;; ordinary if, instead of recognizing literal =>. @c JP ;; 下の例ではマクロ使用時の=>の束縛がマクロ定義時の束縛と違っているため、 ;; => はリテラルと認識されず、if=> は通常のifとして振る舞う。 @c COMMON (let ((=> 'oof)) (if=> 3 => list)) @result{} oof @end example @end defspec @defmac quasirename renamer quasiquoted-form @c EN It works like quasiquote, except that the symbols and identifiers that appear in the ``literal'' portion of @var{form} (i.e. outside of @code{unquote} and @code{unquote-splicing}) are replaced by the result of applying @var{rename} on themselves. @c JP @var{form}中の「リテラル」な部分 (@code{unquote}や@code{unquote-splicing}の外側) に現れるシンボルや識別子が@var{rename}によってリネームされることを除いて、 準クオートのように動作します。 @c COMMON @c EN The @var{quasiquote-form} argument must be a quasiquoted form. The outermost quasiquote @code{`} is consumed by @code{quasirename} and won't appear in the output. The reason we require it is to make nested quasiquotes/quasirenames work. @c JP @var{quasiquote-form}引数は、準クオートされたフォームです。 最も外側の準クオート@code{`} 自体は@code{quasirename}によって消費され、 出力には現れません。 この形にしたのは、ネストした@code{quasiquote}/@code{quasirename}を 正しく扱うためです。 @c COMMON @c EN For example, a form: @example (quasirename r `(a ,b c "d")) @end example would be equivalent to write: @example (list (r 'a) b (r 'c) "d") @end example @c JP 例えば次のフォームは: @example (quasirename r `(a ,b c "d")) @end example 次のとおり書くのと同じです: @example (list (r 'a) b (r 'c) "d") @end example @c COMMON @c EN This is not specifically tied to macros; the @var{renamer} can be any procedure that takes one symbol or identifier argument: @c JP この手続きはマクロ専用というわけではありません。 @var{renamer}はシンボルか識別子を取る手続きであれば何でも構いません。 @c COMMON @example (quasirename (^[x] (symbol-append 'x: x)) `(+ a ,(+ 1 2) 5)) @result{} (x:+ x:a 3 5) @end example @c EN However, it comes pretty handy to construct the result form in ER macros. Compare the following two: @c JP ただ、ERマクロを書く際にとても便利なのは確かです。次の2つを比べてみてください。 @c COMMON @example (use util.match) ;; using quasirename (define-syntax swap (er-macro-transformer (^[f r c] (match f [(_ a b) (quasirename r `(let ((tmp ,a)) (set! ,a ,b) (set! ,b tmp)))])))) ;; not using quasirename (define-syntax swap (er-macro-transformer (^[f r c] (match f [(_ a b) `((r'let) (((r'tmp) ,a)) ((r'set!) ,a ,b) ((r'set!) ,b (r'tmp)))])))) @end example @c EN Note: In Gauche 0.9.7 and before, @code{quasirename} didn't use quasiquoted form as the second argument; you can write @code{(quasirename r form)} instead of @code{(quasirename r `form)}. For the backward compatibility, we support the form without quasiquote by default for a while. If you already have a quasirename form that does intend to produce a quasiquoted form, you have to rewrite it with double quasiquote: @code{(quasirename r ``form)}. To help transition, the handling of quasiquote in of @code{quasirename} can be customized with the environment variable @code{GAUCHE_QUASIRENAME_MODE}. It can have one of the following values: @table @code @item legacy @code{Quasirename} behaves the same way as 0.9.7 and before; use this to run code for 0.9.7 without any change. @item compatible @code{Quasirename} behaves as described in this entry; if @var{form} lacks a quasiquote, it silently assumes one. Existing code should work, except the rare case when you intend to return a quasiquoted form. @item warn @code{Quasirename} behaves as described in this entry, but warns if @var{form} lacks a quasiquote. @item strict @code{Quasirename} raises an error if @var{form} lacks a quasiquote. This will be the default behavior in future. @end table @c JP 註: Gauche 0.9.7とそれ以前には、@code{quasirename}は第二引数に 準クオートを必要としませんでした。つまり@code{(quasirename r `form)} と書くかわりに@code{(quasirename r form)}で良かったのです。 互換性のため、しばらくは準クオート無しのフォームも受け付けられます。 準クオートされたフォームを返すことを意図していた既存のコードについては、 準クオートを@code{(quasirename r ``form)}のように重ねる必要があります。 移行を容易にするため、@code{quasirename}中の準クオートの扱いを、 環境変数@code{GAUCHE_QUASIRENAME_MODE}でカスタマイズできます。 次に挙げる値を設定することができます。 @table @code @item legacy @code{quasirename}は、0.9.7やそれ以前と全く同様に動きます。 0.9.7用のコードを変更なしに動かす必要がある場合に使ってください。 @item compatible @code{quasirename}はこのエントリで説明した通りに動きます。 @var{form}が準クオートされていない場合、準クオートされているものと見なします。 準クオートされたフォームを作り出すことを意図している稀なケース以外の 既存のコードはこれで動かせるでしょう。 @item warn @code{quasirename}はこのエントリで説明した通りに動きますが、 @var{form}が準クオートされていなければ警告を出します。 @item strict @code{quasirename}は@var{form}が準クオートされていることを要求し、 そうでなければエラーを投げます。将来はこの動作がデフォルトになる予定です。 @end table @c COMMON @end defmac @node Identifier transformer, , Explicit-renaming macro transformer, Hygienic macros @subsection Identifier transformer @c NODE 識別子マクロ変換器 @defspec make-id-transformer transformer-spec @c EN Creates an identifier macro transformer from @var{transformer-spec}. The @var{transformer-spec} is the same as what can appear in @code{define-syntax} etc. @c JP @var{transformer-spec}から識別子マクロ変換器を作ります。 @var{transformer-spec}は@code{define-syntax}等で使えるものと同じです。 @c COMMON @c EN A normal macro expands from a form @code{(M arg @dots{})} where @code{M} is an identifier bound to the macro. An identifier macro, on the other hand, expands from solely from the macro-bound identifier, or a form @code{(set! M expr)}. In other words, an identifier macro is used in the context of a variable, rather than a function call. @c JP 通常のマクロは、@code{M}をマクロが束縛された識別子とすると、@code{(M arg @dots{})}という 形式でマクロ変換器を呼び出します。一方識別子マクロは、マクロに束縛された識別子単独、 もしくは@code{(set! M expr)}という形式でマクロ変換器を呼び出すものです。 言い換えれば、識別子マクロは、関数呼び出し形式ではなく変数参照形式で使われるものです。 @c COMMON @c EN Suppose the following code, where @code{state-manager} is a stateful closure. The identifier macro @code{the-state} hides the closure and makes it look like a variable: @c JP 次のコードを考えます。@code{state-manager}は状態を持つクロージャで、 識別子マクロ@code{the-state}はクロージャを隠して あたかも変数にアクセスしているかのように見せます。 @c COMMON @example (define state-manager (let ([state #f]) (case-lambda [() state] [(val) (set! state val)]))) (define-syntax the-state (make-id-transformer (syntax-rules (set!) [(set! _ expr) (state-manager expr)] [_ (state-manager)]))) (state-manager 'off) the-state @result{} off (set! the-state 'on) the-state @result{} on (state-manager) @result{} on @end example @c EN (Note that the single @code{_} pattern in the second clause of @code{syntax-rules} above matches anything, so it should come after @code{set!} match. It is Gauche's extension.) @c JP (上の@code{syntax-rules}の二番目の節のパターンは@code{_}のみから なりますが、これはGaucheの拡張で、任意のフォームにマッチします。 したがって@code{set!}のマッチより後に置く必要があります)。 @c COMMON @c EN Identifier macros may enable some cool tricks, but it can easily confuse readers. We generally discourage use of identifier macros except rare cases where it is absolutely necessary. In most cases, you can use ordinary macros by just adding parentheses. @c JP 識別子マクロを使うとアクロバティックなことができますが、 すぐに読者を混乱させるコードになってしまいます。 一般的に、どうしても識別子マクロでなければ実現できないこと以外には使用を避けることをおすすめします。 ほとんどの場合、カッコを足して通常のマクロとして使うのが良いでしょう。 @c COMMON @c EN If you want some portability, you may try @code{identifier-syntax} in @code{util.identifier-syntax} (@pxref{R6RS identifier syntax}. It is in R6RS and may be supported other implementations. It is built on top of @code{make-id-transformer}. @c JP 移植性が気になる場合は、@code{util.identifier-syntax}モジュールの @code{identifier-syntax}が使えるかもしれません (@ref{R6RS identifier syntax}参照)。 これはR6RSで規定されているので、サポートしている処理系も多いでしょう。 Gaucheでは@code{make-id-transformer}を使って @code{util.identifier-syntax}を実装しています。 @c COMMON @end defspec @node Traditional macros, Hybrid macros, Hygienic macros, Macros @section Traditional macros @c NODE 伝統的なマクロ @defspec define-macro name procedure @defspecx define-macro (name . formals) body @dots{} @c EN Defines @var{name} to be a global macro whose transformer is @var{procedure}. The second form is a shorthand notation of the following form: @c JP 変換子が @var{procedure} である大域マクロ @var{name} を定義します。 2番目のフォームは、以下のフォームの簡易記法です。 @c COMMON @example (define-macro name (lambda formals body @dots{})) @end example @c EN When a form @code{(name @var{arg} @dots{})} is seen by the compiler, it calls @var{procedure} with @var{arg} @dots{}. When @var{procedure} returns, the compiler inserts the returned form in place of the original form, and compile it again. @c JP コンパイラが @code{(name @var{arg} @dots{})} というフォームを見つけると、 @var{arg} @dots{} を引数として @var{procedure} を呼び出します。 @var{procedure} が戻ると、コンパイラは元のフォームの場所に返されたフォームを 挿入し、再度それをコンパイルします。 @c COMMON @c EN To avoid name conflict with the bindings inserted by the macro, you can use @code{gensym}, just like traditional Lisp macros (@pxref{Symbols}). @c JP マクロによって挿入される束縛の名前衝突を避けるために、 伝統的なLispマクロと同様に@code{gensym}を使うことができます。 (@ref{Symbols}参照)。 @c COMMON @example (define-macro (if-let1 var test then else) (let1 tmp (gensym) `(let ((,tmp ,test)) (if ,tmp ,then ,else)))) (macroexpand '(if-let1 v (find odd? '(2 4 6 7 8)) (* v v) #f)) @result{} (let ((#:G1013 (find odd? (quote (2 4 6 7 8))))) (if #:G1013 (* v v) #f)) @end example @c EN Note that @code{gensym} can't protect name conflict with global bindings inserted by the macro. @ref{Why hygienic?} discusses this issue. @c JP @code{gensym}ではマクロが挿入するグローバルな束縛の衝突は回避できません。 @ref{Why hygienic?}でこの点について説明しています。 @c COMMON @end defspec @node Hybrid macros, Syntax parameters, Traditional macros, Macros @section Hybrid macros @c NODE ハイブリッドマクロ @c EN A hybrid macro is both a macro and a procedure simultaneously. If a symbol bound to a hybrid macro appears in the first position of a form, it behaves like a macro and the form is expanded accodring to its macro expander. If a symbol appears other places, it is evaluated to a procedure at runtime. @c JP ハイブリッドマクロは、マクロと手続きを合わせたものです。 ハイブリッドマクロに束縛されているシンボルがフォームの最初のポジションにある場合、 それはマクロのように振る舞い、マクロ展開器によって展開されます。 シンボルがその他の場所に現れた場合は、実行時に手続きへと評価されます。 @c COMMON @c EN It can realize so-called ``compiler macros''---at a compile time, the macro part examines the arguments and can transform the form as desired. In all other circumstances, it behaves like a normal procedure binding, so you can pass the procedure to @code{map}, for example. @c JP これは、いわゆる「コンパイラマクロ」を実現するのに使えます。つまり、 コンパイル時に引数を調べ好きなようにフォームを変換できます。 それ以外の場合は普通の手続きへの束縛のように振る舞うので、 例えば@code{map}の引数として渡すことができます。 @c COMMON @defmac define-hybrid-syntax variable expr transformer-spec @c EN Binds @var{variable} to both an ordinary Scheme value and a macro simultaneously. At the compile time, @var{transformer-spec} is evaluated; it must yield a macro in the the compile-time environment, and bound to @var{variable} to be used at macro expansion. At the execution time, @var{expr} is evaluated and bound to @var{variable} to be used as a run-time value. @c JP @var{variable}を通常のScheme値とマクロの両方に束縛します。 コンパイル時に@var{transformer-spec}が評価されます。それはコンパイル時環境において マクロを返さなければなりません。そして、マクロ展開用に@var{variable}に束縛されます。 一方@var{expr}は実行時に評価され、実行時の値として@var{variable}に束縛されます。 @c COMMON @c EN The macro transformer can return the input form as is (that is, returns an object @code{eq?} to the input form), to indicate that it doesn't need to expand it. In that case, Gauche compiles the form as an ordinary procedure call, to use the value of @var{expr} at run-time. @c JP マクロ展開器は、入力フォームに展開の必要がなければそれをそのまま (入力フォームと@code{eq?}になるオブジェクトとして)返すことができます。 その場合、Gaucheはフォームを単なる手続き呼び出しとしてコンパイルし、 @var{expr}の実行時の値が呼び出されます。 @c COMMON @c EN Note: If what you want to do with the hybrid macro is just to inline-expand the procedure body, use @code{define-inline} (@pxref{Definitions}). @c JP 註: ハイブリッドマクロでやりたいことが、手続き本体をインライン展開するだけなら、 @code{define-inline}を使った方が良いです。@ref{Definitions}参照。 @c COMMON @c EN Note about the syntax: Traditionally in Lisp, compiler macros are defined by a separate form from the procedure binding. However, having bindings to the same identifier twice makes the program semantics ambiguous. What if the two forms are separated into different modules? What if the identifier is redefined? It would be clearer that single form determines the binding. @c JP 構文についての註: 伝統的にLispでは、コンパイラマクロを定義するフォームは 通常の手続きの束縛を定義するフォームと別でした。 しかし、一つの識別子に別々のフォームで複数の定義を与えるのは、 プログラムの意味に曖昧性を持ち込みます。たとえば通常の定義とコンパイラマクロの定義が 別のモジュールに分かれていたら? あるいはどちらか一方が再定義されたら? Gaucheではひとつのフォームで束縛を決定してしまう方が良いと判断しました。 @c COMMON @end defmac @node Syntax parameters, Identifiers, Hybrid macros, Macros @section Syntax parameters @c NODE 構文パラメータ @c EN Syntax parameters allows to rebind syntactic binding dynamically during macro expandsion. The form resembles @code{parameterize} (@pxref{Parameters}), but works purely at macro expansion time. It allows to define a macro that affects other macros hygienically. It is defined by SRFI-139. @c JP 構文パラメータは、マクロ展開時に動的に構文束縛を置き換えるものです。 束縛フォームは@code{parameterize}に似ています(@ref{Parameters}参照)が、 マクロ展開時のみに作用します。 これを使うと、他のマクロに影響を与えるマクロを衛生的に書くことができます。 構文パラメータはSRFI-139で定義されました。 @c COMMON @c EN Suppose you want to have a macro @code{(block ...)} that evaluates expression @code{} sequentially. Inside it, we want to have another macro @code{(return )}, which evaluates @code{} and then exits @code{(block ...)}, making the value of @code{} as the value of @code{(block ...)}, @c JP 例えば、@code{(block ...)}というマクロを考えてみます。 これは@code{}を順番に実行します。@var{}の中で、 別のマクロ@code{(return )}を呼び出すことができて、 その場合、@code{}が評価され、それを値として直ちに@code{(block ...)}から 脱出します。 @c COMMON @c EN In other words, the macro @code{block} need to change the behavior of @code{return}. It can be written, for example, as follows: @c JP 言ってみれば、マクロ@code{block}はマクロ@code{return}の振る舞いを変える必要がある わけです。これは次のように書くことができるでしょう。 @c COMMON @example (define-syntax block (er-macro-transformer (^[f r c] (quasirename r `(let/cc ,'return ,@@(cdr f))))) (block (print 1) (print 2) (return 'oops) (print 4)) @result{} @r{print 1, 2, and then returns @code{oops}} @end example @c EN But note that this needs to insert @code{return} unhyginenically. It may break, for example, when combined with another library that uses @code{return} for other purposes. @c JP ただ、この定義では@code{return}を非衛生的に挿入する必要があることに注目してください。 これは、@code{return}を別の目的で使いたい他のライブラリがあった場合、 一緒に使うと衝突してうまくいかないかもしれません。 @c COMMON @c EN With syntax parameters, you can write it hygienically: @c JP 構文パラメータを使うと、衛生的に書くことができます: @c COMMON @example (define-syntax-parameter return (syntax-rules () ((_ . _) (syntax-error "return outside block")))) (define-syntax block (syntax-rules () ((_ body ...) (let/cc %return (syntax-parameterize ((return (syntax-rules () ((_ expr) (%return expr))))) body ...))))) @end example @c EN The @code{return} has desired effect with @code{block} only if it refers to the same bindings of @code{define-syntax-parameter}. Suppose you make the above code into a library, and the user imports the library with prefix. Then, the user can refer to the non-local-exit return with the prefix, and that can coexist of whatever @code{return} defined in the user's module. @c JP @code{block}の中の@code{return}は、@code{define-syntax-parameter}で 定義された@code{return}と同じ束縛を参照している時のみ効果を持ちます。 例えば上記コードをライブラリにして、ユーザがプレフィックスつきでそれを インポートしたとしましょう。 その場合、非局所的脱出をする@code{return}をプレフィクスつきになり、 そのモジュールで定義される別の@code{return}と共存できます。 @c COMMON @example (use block :prefix b:) (define return ...) (b:block ... @c EN (return ...) ; This refers to the 'return' in the current module @c JP (return ...) ; 現在のモジュールの 'return' を参照 @c COMMON ... @c EN (b:return 'oops) ; This invokes 'return' to exit from the block @c JP (b:return 'oops) ; blockから抜ける return の呼び出し @c COMMON ... ) @end example @defspec define-syntax-parameter name transformer-spec [SRFI-139] @c EN Like @code{define-syntax}, binds @var{name} with a macro created by @var{transformer-spec}, but the binding is marked as a syntax parameter, and can be altered with @code{syntax-parameterize}. @c JP @code{define-syntax}と同様に、@var{transformer-spec}で作られるマクロを @var{name}に束縛します。それに加えて、束縛が構文パラメータであることが記録され、 @code{syntax-parameterize}で置き換えることができるようになります。 @c COMMON @c EN The given @var{transformer-spec} works as a default macro, invoked when no @code{syntax-parameterize} on @var{name} is in effect. The forms allowed in @var{transformer-spec} is the same as @code{define-syntax}. @c JP 与えられた@var{transformer-spec}は、@var{name}が @code{syntax-parameterize}で再束縛されていない場合のデフォルトのマクロとして 動作します。@var{transformer-spec}に使える形式は @code{define-syntax}のものと同じです。 @c COMMON @end defspec @defspec syntax-parameterize ((key transformer-spec) @dots{}) body @dots{} [SRFI-139] @c EN The @var{key}s must be identifiers bound to syntax parameters. This form alters the macro transformers of @var{key}s with the ones specified by the given @var{transformer-spec}s, then proceed to compile @var{body} @dots{}. The altered bindings are effective during the dynamic scope of macro-expansion phase. (Be aware that it has nothing to do with the dynamic scope at runtime.) @c JP @var{key}は構文パラメタに束縛された識別子でなければなりません。 このフォームは、@var{key}の構文束縛を@var{transformer-spec}で指定されるものに 置き換えて、@var{body} @dots{}を実行します。 この再束縛はマクロ展開時の動的スコープで有効です (実行時の動的スコープとは関係ないことに注意してください)。 @c COMMON @end defspec @node Identifiers, Debugging macros, Syntax parameters, Macros @section Identifiers @c NODE 識別子 @c EN In the discussion of hygienic macros, we keep saying the symbols are @emph{effectively renamed}. What it means is that we don't actually create a new symbol with a new name. We have to remember the origin of the renamed symbol to resolve the scope of the variable, and having a separate table to keep track of renamed symbols would be costly. Instead, the ``rename'' procedure wraps the symbols in the input with syntactic information. @c JP 衛生的マクロの説明では、衝突を避けるためにシンボルを「リネームする」といいますが、 本当に名前を変えたシンボルを作っているわけではありません。後でスコープの解決をする際に、 リネームされたシンボルと元のシンボルを関連付ける必要があるのですが、 それを別のテーブルで管理するのは重いのです。 そこで、@code{er-macro-expander}に渡されるリネーム手続きは、 実際には元のシンボルを構文情報で「包む」ということをしています。 @c COMMON @c EN When you play with macro internals, you'll see an object that is printed something like @code{#}. That's the wrapped symbol. @c JP マクロの中身をいじっていると、しばしば @code{#} のように印字されるオブジェクトを見るでしょう。 それが包まれたシンボルです。 @c COMMON @c EN If one macro output is passed to another macro expander, the wrapped symbol may further be wrapped. @c JP マクロ展開結果がさらに他のマクロ展開器に渡された場合は、 一旦包まれたシンボルがさらに包まれることもあります。 @c COMMON @c EN The macro expander must assume that symbols in the input are already wrapped by another macro expander. So, instead of calling it a ``symbol'', we call it an ``identifier''. An identifier is something that usually works as a variable or a syntactic keyword in the prorgam. It may be a symbol or a wrapped identifier. (Note that symbols in quoted literals are bare symbols, for the @code{quote} form strips wrappers.) @c JP マクロ展開器は、入力に含まれているシンボルが既に包まれていることを想定しなければなりません。 「シンボル」ではなく「識別子」と呼んでいるのはそのためです。 識別子は、プログラム中で変数か構文キーワードとして働くもので、 その実体はシンボルか、包まれた識別子です。 (クオートの中にあるシンボルは常に「裸の」シンボルになります。 @code{quote}が構文情報を剥ぎ取るからです)。 @c COMMON @c EN Legacy Lisp macros sometimes examines the symbols in the input form. In Scheme, you have to treat the input program as a tree of identifiers and other objects. You can test whether an object is an identifier or not by @code{identifier?}, where traditional Lisp macros would have used @code{symbol?}. To compare identifiers, you need to use the ``compare'' procedure passed to the er-macro expander, or @code{free-identifier=?}. @c JP 伝統的なLispのマクロではよく入力フォーム中のシンボルを調べますが、 Schemeでは入力を識別子やその他のオブジェクトからなる木と考えます。 伝統的なLispマクロで@code{symbol?}を使うところでは、 @code{identifier?}を使ってオブジェクトが識別子かどうか調べる必要があります。 また、識別子同士が等しい(同じ束縛を表している)かどうかを調べるには単なる@code{eq?}ではなく、 @code{er-macro-transformer}に与えられる ``compare'' 手続きや、 @code{free-identifier=?}といった特別な手続きを使う必要があります。 @c COMMON @deftp {Builtin Class} @clindex identifier @c EN A class of wrapped identifier. It is created as a result of ``renaming'' in the hygienic macro expander. A wrapped identifier contains transient information about the program source, and cannot be portably saved or passed around; it is only valid in the macro expansion phase. For the details of identifier, @pxref{Identifiers}. @c JP 構文情報で包まれた識別子を表すクラスです。衛生的マクロ展開器の ``rename''手続きにより作られます。 包まれた識別子は、プログラムの構文情報を含んでおり、 ポータブルな形でセーブすることはできません。その情報はマクロ展開の期間内のみで有効です。 識別子について詳しくは@ref{Identifiers}を参照してください。 @c COMMON @end deftp @defun identifier? obj @c EN Returns @code{#t} if @var{obj} is either a symbol or a wrapped identifier. Returns @code{#f} otherwise. Note: In R6RS, @code{identifier?} only returns @code{#t} for an identifier object, which is of a disjoint type from symbols. You can use @code{wrapped-identifier?} below to check if an object is an identifier other than a symbol. @c JP @var{obj}がシンボルもしくは包まれた識別子である場合に@code{#t}を、 そうでなければ@code{#f}を返します。 R6RSでは、@code{identifier?}はシンボルとdisjointな型を持つ「識別子オブジェクト」 についてのみ@code{#t}を返す、と規定されています。 オブジェクトがシンボルでない識別子であることを確かめたい場合は、 下の@code{wrapped-identifier?}が使えます。 @c COMMON @end defun @defun wrapped-identifier? obj @c EN Returns @code{#t} iff @var{obj} is a wrapped identifier. This is R6RS's @code{identifier?}. @c JP @var{obj}が包まれた識別子なら@code{#t}を、そうでなければ@code{#f}を返します。 R6RSの@code{identifier?}に相当します。 @c COMMON @end defun @defun identifier->symbol obj @c EN Returns the symbol that is the origin of the @var{obj}, which must be either a symbol or a wrapped identifier. @c JP @var{obj}はシンボルか包まれた識別子でなければなりません。@var{obj}の元となった シンボルを返します。 @c COMMON @end defun @defun free-identifier=? id1 id2 @c EN When both arguments @var{id1} and @var{id2} are wrapped identifiers, returns @code{#t} if either (1) @var{id1} and @var{id2} both refer to the same binding, or (2) @var{id1} and @var{id2} are both unbound. Otherwise, @code{#f} is returned. If at least one of @var{id1} or @var{id2} is not a wrapped identifier, @code{#f} is returned. Note that bare symbols can't be compared with this procedure, for they lack the necessary lexical information. To obtain a wrapped identifier, you need to pass a bare symbol to the ``rename'' procedure passed to the er-macro transformer. Usually you don't need to use this procedure directly, for the compare procedure passed to the er-macro transformer is suffice. @c JP @var{id1}と@var{id2}がともに包まれた識別子で、次のいずれかの場合にのみ@code{#t}を 返します: (1)@var{id1}と@var{id2}が同じ束縛を表しているか、 (2)@var{id1}と@var{id2}がどちらも束縛されていない。 @var{id1}と@var{id2}の少なくとも一方が包まれた識別子でなければ、この手続きは @code{#f}を返します。「裸の」シンボルはレキシカル情報を欠いているため、この手続きでは 比較することができません。シンボルをレキシカルな情報で包むには、 er-macro変換器に渡されるrename手続きを通す必要があります。 er-macroを使っている場合、compare手続きで識別子の比較ができるので、 この手続きを直接使う必要はあまりないでしょう。 @c COMMON @end defun @defun unwrap-syntax form @c EN Returns a copy of @var{form}, except removing wrappings of identifiers in it. The output of macro expanders contain wrapped identifiers, which is bothersome to see. This procedure traverses @var{form} and replaces any wrapped identifiers with its original symbol, retrieved by @code{identifier->symbol}. Note that, although the result is an ordinary S-expression easier to read, syntactic information is completely lost. For example, distinct identifiers can become indistinguishable if they happen to have the same name (it happens often when you generate temporary variables via recursive calls of @code{syntax-rules}). If you distinguish newly inserted identifiers with the same name, use @code{unravel-syntax}. @c JP @var{form}の中に含まれる「包まれた識別子」の構文情報を全て剥ぎ取った形での @var{form}のコピーを返します。 マクロ展開器の出力には包まれた識別子が含まれていてとても見づらいです。 この手続きは@var{form}をトラバースし、包まれた識別子があればそれを @code{identifier->symbol}を使って元のシンボルへと戻します。 返り値は通常のS式で読みやすいですが、構文情報が失われていることに注意してください。 例えば本来異なるはずの識別子がたまたま同じ名前を持っていると、区別ができなくなります (@code{syntax-rules}を再帰的に呼び出して一時変数を作るパターンでは そういうことが頻繁に起きます)。 新たに挿入された同名の識別子を区別したい場合は、@code{unravel-syntax}を使ってください。 @c COMMON @end defun @defun unravel-syntax form @c EN Returns a copy of @var{form} while removing wrappings of identifiers in it, but attach suffix if two distinct identifiers have the same name, so that they won't be confused. For example, a common idiom of @code{syntax-rules} to generate temporary variables with recursions create all variables with the same name, although each variable is different because they are inserted by the different invocation of the expander. If you pass its output to @code{unwrap-syntax}, all syntactic information is stripped and these variables can't be distinguished from one another. This procedure is automatically called with some macro utilities; @xref{Tracing macro expansion}, and @pxref{Expanding macros manually}, for the example of output of @code{unravel-syntax}. Note that the global identifiers becomes bare symbols, so you are still unable to tell which module the global identifiers refer to. @c JP @var{form}中に含まれる包まれた識別子を裸のシンボルに変換した形での @var{form}のコピーを返しますが、同じ名前を持つ異なる識別子があった場合は 区別できるようにサフィックスをつけた名前に変更します。 @code{syntax-rules}を再帰的に呼び出して一時変数を生成する定石では、 新たに作られる変数は全て同じ名前になってしまいますが、それぞれ作られるタイミングが 違うために異なる識別子として扱われます。その結果を@code{unwrap-syntax}に渡して 構文情報を剥ぎ取ると、それらの識別子同士の区別ができなくなってしまいます。 この手続きはいくつかのマクロを扱うユーティリティ関数内で自動的に呼ばれます。 @code{unravel-syntax}の出力例は、 @ref{Tracing macro expansion}や@ref{Expanding macros manually}を 参照してください。 ただし、グローバルな識別子は元のシンボルへと変換されるので、 どのモジュールの束縛を指しているかの情報は失われます。 @c COMMON @end defun @node Debugging macros, Macro utilities, Identifiers, Macros @section Debugging macros @c NODE マクロのデバッグ @c EN Macro expansion happens at the compile time, which makes it difficult to debug. The best way to avoid headache of macro debugging is not to write macros unless they're absolutely necessary, and keep them as simple as possible if you need to write ones. @c JP マクロ展開はコンパイル時に行われるため、デバッグが難しいです。 マクロのデバッグに悩まされるのを避ける最良の方法は、どうしても必要でない限り マクロを書かないこと、そして書くハメになったとしてもできる限り単純なものにすることです。 @c COMMON @c EN However, if you find yourself in an unfortunate situation that you have to untangle hairy macros, Gauche has some tools to help. @c JP しかし、時には怪しげなマクロを解きほぐす必要に迫られるという不運に見舞われるかもしれません。 Gaucheにはその助けになるツールがいくつかあります。 @c COMMON @menu * Tracing macro expansion:: * Expanding macros manually:: @end menu @node Tracing macro expansion, Expanding macros manually, Debugging macros, Debugging macros @subsection Tracing macro expansion @c NODE マクロ展開をトレースする @c EN Macro tracing shows the input to the macro expander and the result of its expansion on selected macros. Suppose you have the following macro definition. It's essentially the same as shown in the definition of @code{letrec} in R7RS section 7.3: @c JP マクロトレースは、選択したマクロのマクロ展開器の入力と結果を表示する機能です。 例えば、次のマクロを定義したとしましょう。これはR7RSの7.3節にある@code{letrec}の 定義とだいたい同じです: @c COMMON @example (define-syntax my-letrec (syntax-rules () [(_ ((var init) ...) body ...) (my-letrec "tmps" (var ...) () ((var init) ...) body ...)] [(_ "tmps" () (tmp ...) ((var init) ...) body ...) (let ((var 'undefined) ...) (let ((tmp init) ...) (set! var tmp) ... body ...))] [(_ "tmps" (x y ...) (tmp ...) binds body ...) (my-letrec "tmps" (y ...) (newtmp tmp ...) binds body ...)])) @end example @c EN The @code{my-letrec} macro uses an idiom to generate temporary variables by looping with @code{"tmps"} tag. You can see how the macro is expanded step by step, by tracing @code{my-letrec}: @c JP この@code{my-letrec}マクロは、@code{"tmps"}をタグにしてループすることで 一時変数を作るというイディオムを使っています。@code{my-letrec}をトレースすることで、 このマクロの展開の様子をステップごとに見ることができます: @c COMMON @example gosh> (trace-macro 'my-letrec) (my-letrec) gosh> (my-letrec [(ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))] (ev? 3)) Macro input>>> (my-letrec ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro output<<< (my-letrec "tmps" (ev? od?) () ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro input>>> (my-letrec "tmps" (ev? od?) () ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro output<<< (my-letrec "tmps" (od?) (newtmp.0) ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro input>>> (my-letrec "tmps" (od?) (newtmp.0) ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro output<<< (my-letrec "tmps" () (newtmp.1 newtmp.0) ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro input>>> (my-letrec "tmps" () (newtmp.0 newtmp.1) ((ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))) (ev? 3)) Macro output<<< (let ((ev? (quote undefined)) (od? (quote undefined))) (let ((newtmp.0 (^n (if (= n 0) #t (od? (- n 1))))) (newtmp.1 (^n (if (= n 0) #f (ev? (- n 1)))))) (set! ev? newtmp.0) (set! od? newtmp.1) (ev? 3))) #f @end example @c EN In the above example, the S-expressions after @code{gosh>} prompt is what you type; all other things are Gauche's answer, including @code{Macro input} and @code{Macro output} S-expressions. @c JP 上に示した例において、@code{gosh>}プロンプトの次にあるS式がユーザがタイプしたものです。 他はすべて、@code{Macro input}と@code{Macro output}のS式を含め、 Gaucheの出力です。 @c COMMON @c EN The S-expression shown with @code{Macro input} is the input of the macro expander, and the one with @code{Macro output} is the expanded result. Actual macro output has syntactic information attached, but the tracer strips them off for the legibility. @c JP @code{Macro input}の後に示されるS式がマクロ展開器の入力で、 @code{Macro output}の後がその展開結果です。実際のマクロ展開結果は 構文情報が付加されていますが、この出力では読みやすくするために構文情報は取り去られています。 @c COMMON @c EN Note that the loop introduces new temporary variables with the same name (@code{newtemp}), but they are treated as different identifiers in the macro expansion. @c JP ループの度に同じ名前(@code{newtemp})の変数が導入されていますが、 それらが異なる識別子として扱われていることが展開結果からわかると思います。 @c COMMON @c EN Once you're done debugging, don't forget to call @code{untrace-macro} with no arguments to remove macro traces. If there's a macro trace set, all macro expansions get some overhead, so don't leave macro traces. @c JP デバッグが終わったら、@code{untrace-macro}を引数なしで呼んで マクロトレースをオフにしましょう。マクロトレースが設定されていると、 すべてのマクロ展開においてオーバヘッドがかかります。 @c COMMON @example gosh> (untrace-macro) #f @end example @defun trace-macro @defunx trace-macro boolean @defunx trace-macro name-or-pattern @dots{} @c EN Get/set current macro trace setting. Macro trace setting can be one of the following values: @c JP 現在のマクロトレース設定を得たり、変更したりします。 マクロトレース設定は次のいずれかの値を取ります。 @c COMMON @table @asis @item @code{#f} @c EN Macro tracing is off. This is the default setting. @c JP マクロトレースはオフです。これがデフォルトの設定です。 @c COMMON @item @code{#t} @c EN All macro expansions are traced. @c JP 全てのマクロの展開がトレースされます。 @c COMMON @item @code{(@var{name-or-pattern} @dots{})} @c EN Trace macros that match any one of @var{name-or-pattern}, which is either a symbol or a regexp. If it's a symbol, a macro whose name is the same as the symbol is traced. If it's a regexp, macros whose name match the regexp are traced. @c JP 名前が@var{name-or-pattern}のいずれかにマッチするマクロがトレースされます。 ここで各@var{name-or-pattern}は、シンボルか正規表現オブジェクトです。 シンボルの場合は名前が完全に一致するもの、正規表現の場合は 名前がそれに一致するものがトレースの対象となります。 @c COMMON @end table @c EN When called without arguments, @code{trace-macro} doesn't change the setting; it returns the current setting. @c JP 引数なしで呼ばれたら、@code{trace-macro}は設定を変えず、単に現在の設定を返します。 @c COMMON @c EN When called with single boolean value, it sets the current setting to that value. Returns the updated setting. @c JP 単一の真偽値を引数に渡した場合は、それをマクロトレースの設定値として、 更新された設定値を返します。 @c COMMON @c EN When called with one or more @var{name-or-pattern}, it @emph{adds} them to the current setting. Note that if the current setting is @code{#t}, it remains @code{#t}, for all macros are already traced. Returns the updated setting. @c JP 一つ以上の@var{name-or-pattern}が渡されたら、それらが現在のマクロトレース設定に @emph{追加}されます。もし現在の設定が@code{#t}なら設定は変わらないことに注意して ください。全てのマクロは既にトレースされているからです。 更新された設定値を返します。 @c COMMON @c EN If macro trace settings is not @code{#f}, it incurs overhead for every macro expansion. Be careful not to leave macro trace set. @c JP マクロトレースの設定値が@code{#f}でない限り、すべてのマクロ展開にオーバヘッドがかかります。 マクロトレースを設定したままにしないようにしてください。 @c COMMON @c EN The trace information is output to the current trace port. (@pxref{Common port operations}). @c JP トレース情報は現在のトレース出力ポートに出力されます。 (@ref{Common port operations}参照)。 @c COMMON @end defun @defun untrace-macro @defunx untrace-macro name-or-pattern @dots{} @c EN When called without arguments, it turns macro trace off. When called with one or more @var{name-or-pattern}, which is either a symbol or a regexp, @code{untrace-macro} removes them from the currently traced macros. Note that if the current macro trace setting is @code{#t} (trace all macros), you can't remove traced macro individually. It returns the updated macro trace setting. @c JP 引数なしで呼ばれた場合、マクロトレースをオフにします。 1つ以上の@var{name-or-pattern}が渡された場合は、現在のマクロトレース設定から それらを除きます。ただし、現在のマクロトレース設定が@code{#t} (全てのマクロをトレース) の場合は個別にマクロを除外できません。 更新後のマクロトレース設定を返します。 @c COMMON @end defun @node Expanding macros manually, , Tracing macro expansion, Debugging macros @subsection Expanding macros manually @c NODE マクロを自分で展開する @defun macroexpand form :optional env @defunx macroexpand-1 form :optional env @c EN If @var{form} is a list and its first element is a variable globally bound to a macro, @code{macroexpand-1} invokes its macro transformer and returns the expanded form. Otherwise, returns @var{form} as is. @code{macroexpand} repeats @code{macroexpand-1} until the outermost expression of @var{form} can't be expanded. (It doesn't expand macros other than outermost one. If you want to expand all the macros within @var{form}, use @code{macroexpand-all}). These procedures can be used to expand globally defined macros. @c JP @var{form} がリストで、その最初の要素が大域的にマクロに束縛された 変数であるならば、@code{macroexpand-1}はそのマクロ変換子を実行し、 展開されたフォームを返します。そうでなければ、@var{form} をそのまま 返します。 @code{macroexpand} は、@var{form}の一番外側の式がが展開できなくなるまで @code{macroexpand-1} を繰り返します。 (@code{macroexpand}は@var{form}の一番外側以外のマクロは展開しません。 @var{form}内の全てのマクロを展開するには@code{macroexpand-all}を使ってください。) これらの手続きは、大域的に定義されたマクロを展開するために使うことが できます。 @c COMMON @c EN Internally, hygienic macro expansion wraps symbols in @var{form} with syntactic information to keep hygiene. However, such information is hard to read, and not suitable when you just want to expand a macro in REPL to check its result. So, by default, these procedures strips syntactic information. For the identifiers introduced in the macro, it renames them to avoid name conflicts. The following example expands @code{my-letrec} macro (@pxref{Tracing macro expansion}, for the definition) and results shows temporary variable introduced by the macro (@var{newtemp}) to be renamed. @c JP 内部的には、衛生マクロは展開されると@var{form}の中にあるシンボルを 構文情報でラップします。しかし、REPLでマクロを展開して確かめたい場合に その情報がついているととても読みにくくなります。 そこで、デフォルトではこれらの手続きは構文情報を取り除いて出力します。 マクロ内で導入された識別子については、必要に応じて名前の衝突を避けるリネームが 行われます。 下の例は@code{my-letrec} (定義は@ref{Tracing macro expansion}参照) を 展開しています。マクロ展開で導入された変数 (@var{newtemp}) がリネームされています。 @c COMMON @example (macroexpand '(my-letrec [(ev? (^n (if (= n 0) #t (od? (- n 1))))) (od? (^n (if (= n 0) #f (ev? (- n 1)))))] (ev? 3))) @result{} (let ((ev? (quote undefined)) (od? (quote undefined))) (let ((newtmp.0 (^n (if (= n 0) #t (od? (- n 1))))) (newtmp.1 (^n (if (= n 0) #f (ev? (- n 1)))))) (set! ev? newtmp.0) (set! od? newtmp.1) (ev? 3))) @end example @c EN If you pass a module to the @var{env} argument, it is used as the macro use environment. You can also pass @code{#t} to let it use the current @emph{runtime} environment as the macro use environment. In those cases, syntactic information in the output won't be stripped. If you want to use the output of @code{macroexpand} as a program, e.g. embed it into another macro expansion, you need syntactic information preserved. @c JP @var{env}引数にモジュールを渡すと、そのモジュールをマクロ使用環境として マクロが展開されます。@var{env}に@code{#t}を渡すと、実行時のモジュールが マクロ使用環境になります。これらの場合は、出力に構文情報が付加されたままになります。 @code{macroexpand}の出力を他のマクロ展開結果にプログラム的に埋め込むといった 用途に使う場合には、構文情報を保ったままのフォームが必要になります。 @c COMMON @end defun @defun macroexpand-all form :optional env @c EN Fully expand macros inside @var{form}. The result only contains function calls and Gauche's built-in syntax. @c JP @var{form}中にあるマクロを全て展開します。結果の中に残るのは、 関数呼び出しとGaucheの組み込み構文だけになります。 @c COMMON @c EN By default, or @code{#t} is passed to @var{env}, the @var{form} is assumed to be a toplevel form within the current runtime module. You can also pass a module to @var{env} to specify the alternative toplevel environment. @c JP デフォルト、もしくは@var{env}に@code{#t}が渡された場合は、 @var{form}は実行時のモジュールのトップレベルにあると解釈されます。 モジュールを@var{env}に渡せば、そのモジュールをマクロ使用環境として展開できます。 @c COMMON @c EN Any local variables introduced in @var{form} is renamed to avoid collision. Since each local variable has unique name, all @code{let} forms become @code{letrec} forms (we can safely replace @code{let} with @code{letrec} if no bindings introduced by @code{let} shadows outer bindings.) @c JP @var{form}中で導入されるローカル変数は全て、衝突を避けるためにリネームされます。 ローカル変数が全て固有の名前を持つようになるので、@code{let}フォームはすべて @code{letrec}で表されます(@code{let}による束縛が他の束縛をシャドウしないと わかっていれば、@code{let}を@code{letrec}に置き換えても意味は変わりません)。 @c COMMON @c EN NB: If a macro in @var{form} inserts a reference to a global variable which belongs to other module, the information is lost in the current implementation. There are a few ways to address this issue; we may leave such reference as an identifier object, convert it to @code{with-module} form, or introduce a special syntax to represent such case. It's undecided currently, so do not rely too much on the current behavior. For the time being, it's best to use this feature only for interactive macro testing. @c JP 注意: もし@var{form}内で呼ばれているマクロが、他のモジュール中にあるグローバル 変数への参照を挿入した場合、現在の実装ではその情報は失われてしまいます。 いくつか、その問題を修正する方法は考えられるのですが(例えば他のモジュール中に グローバル変数参照は識別子オブジェクトのまま残しておくとか、 @code{with-module}フォームに変換するとか、 そういったケースのための特殊構文を導入するとか)、今のところどうするか 決まっていません。なので、現在のふるまいにあまり依存しないようにしてください。 今のところ、この手続きは、マクロの展開結果をインタラクティブに確かめる用途に 限って使うのが安全です。 @c COMMON @example (macroexpand-all '(letrec-syntax [(when-not (syntax-rules () [(_ test . body) (if test #f (begin . body))]))] (let ([if list]) (define x (expt foo)) (let1 x 3 (when-not (bar) (if x)))))) @result{} (letrec ((if.0 list)) (letrec ((x.1 (expt foo))) (letrec ((x.2 '3)) (if (bar) '#f (if.0 x.2))))) @end example @end defun @defspec %macroexpand form @defspecx %macroexpand-1 form @end defspec @node Macro utilities, , Debugging macros, Macros @section Macro utilities @c NODE マクロユーティリティ @defmac syntax-error msg arg @dots{} @defmacx syntax-errorf fmt arg @dots{} @c EN Signal an error. They are same as @code{error} and @code{errorf} (@pxref{Signaling exceptions}), except that the error is signaled at macro-expansion time (i.e. compile time) rather than run time. They are useful to tell the user the wrong usage of macro in the comprehensive way, instead of the cryptic error from the macro transformer. Because of the purpose, @var{arg} @dots{} are first passed to @code{unwrap-syntax} to strip off the internal syntactic binding informations (@pxref{Identifiers}). @c JP これらは@code{error}と@code{errorf} (@ref{Signaling exceptions}参照) と ほぼ同じですが、実行時ではなくマクロ展開時(すなわち、コンパイル時)に エラーを通知するところが異なります。 これらの手続きは、マクロの誤った使い方を、 マクロ展開ルーチンの出す複雑なエラーではなく、 分かりやすい方法でユーザーに通知するのに使えます。 そのため、@var{arg} @dots{}は@code{unwrap-syntax}に渡されて 内部の構文的束縛情報を取り除いた後でこれらの手続きに渡されます (@ref{Identifiers}参照)。 @c COMMON @example (define-syntax my-macro (syntax-rules () ((_ a b) (foo2 a b)) ((_ a b c) (foo3 a b c)) ((_ . ?) (syntax-error "malformed my-macro" (my-macro . ?))))) (my-macro 1 2 3 4) @result{} @r{error: "malformed my-macro: (my-macro 1 2 3 4)"} @end example @end defmac @c Local variables: @c mode: texinfo @c coding: utf-8 @c end: