perlguts - Perl API の紹介
このドキュメントでは Perl API の使い方、および Perl コアの基本的な動作に 関するいくばくかの情報を提供しようとしています。 完璧からは程遠いものですし、間違いも多いと思います。 疑問点やコメントは後述する著者に対して行なってください。
(変数)
(データ型)
Perl では、主となる三つのデータ型を扱うために三つの型定義を行なっています:
SV Scalar Value
AV Array Value
HV Hash Value
それぞれの typedef には様々なデータ型を操作するための特別なルーチンが 用意されています。
("IV" ってなに?)
Perl では、符号付き整数でもポインタでも十分に入れることのできる特別な typedef である IV を使います。 更に、単に符号なしの IV である UV もあります。
Perl はまた、二つの特殊な typedef である I32 と I16 を使っています。 これらはそれぞれ、常に最低 32bit、16bit の長さを持っているものです。 (再び、同様に U32 と U16 もあります。) これらは普通は正確に 32 ビットと 16 ビットですが、Cray では両方とも 64 ビットです。
(SV に対する作業)
SV は、1 つのコマンドで生成し、値をロードすることができます。 ロードできる値の型には、整数 (IV)、符号なし整数 (UV)、 倍精度 (NV)、文字列 (PV)、その他のスカラ (SV) があります。
これらを行なう、7 つのルーチンは:
SV* newSViv(IV);
SV* newSVuv(UV);
SV* newSVnv(double);
SV* newSVpv(const char*, STRLEN);
SV* newSVpvn(const char*, STRLEN);
SV* newSVpvf(const char*, ...);
SV* newSVsv(SV*);
STRLEN は perl が扱えるどんな文字列のサイズも表現するのに十分なだけの
大きさを持つことが保証されている整数型(Size_t, 普通は config.h で
size_t として定義されています)。
あまりなさそうですが、SV がもっと複雑な初期化を必要とする場合、
newSV(len) で空の SV も作成できます。
もし len が 0 なら、NULL 型の空の SV が返され、さもなければ
PV 型の SV は、SvPVX でアクセスできる len + 1 (NUL のため) バイトの領域を
割り当てられて返されます。
両方の場合で、SV の値は未定義値です。
SV *sv = newSV(0); /* no storage allocated */
SV *sv = newSV(10); /* 10 (+1) bytes of uninitialised storage allocated */
既に存在する スカラの値を変更するために 8 つのルーチンがあります:
void sv_setiv(SV*, IV);
void sv_setuv(SV*, UV);
void sv_setnv(SV*, double);
void sv_setpv(SV*, const char*);
void sv_setpvn(SV*, const char*, STRLEN)
void sv_setpvf(SV*, const char*, ...);
void sv_vsetpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool *);
void sv_setsv(SV*, SV*);
代入すべき文字列の長さを sv_setpvn や newSVpv、あるいは
newSVpv を使って指定することもできますし、sv_setpv を使ったり
newSVpv の第二引数に 0 を指定することによって、Perl 自身に
文字列の長さを計算させることもできます。
ただし Perl は、NUL 文字で終了することに依存している
strlen を使って長さを計算しているということに注意してください。
sv_setpvf の引数は sprintf と同じように処理され、書式化された
出力が値となります。
sv_vsetpvfn は vsprintf と同じようなものですが、
可変引数リストに対するポインタか
SV の配列のアドレスと長さのいずれかを指定することができます。
最後の引数はブール値を指し示します。
関数から返ってきたときに
これが true であれば、フォーマット文字列としてロカール固有の
情報が使われているのでその文字列の内容は信頼するできないことを
表わしています(perlsec を参照)。
ロカールに関する情報が重要でないのなら、
このポインタは NULL であってもかまいません。
この関数はフォーマットの長さを要求していることに注意してください。
sv_set*() 関数群は“magic”を持っている値に対する
操作に対して充分に一般化されたものではありません。
後述する Magic Virtual Tables を参照してください。
すべてのSV は、必須と言うわけではありませんが NUL キャラクターで 終端されているべきです。 この終端の NUL が無かった場合、コアダンプしたり文字列を (文字列が NUL で終端されていることを期待している) C 関数やシステムコールに 渡すコードをおかしくする危険があります。 Perl 自身の典型的な関数は、この理由により終端に NUL を追加します。 そうであったとしても、あなたが SV に格納されている文字列を C の関数や システムコールに渡す時には十二分に気をつけるべきなのです。
SV が指し示す実際の値をアクセスするには、以下のマクロを使えます:
SvIV(SV*)
SvUV(SV*)
SvNV(SV*)
SvPV(SV*, STRLEN len)
SvPV_nolen(SV*)
これは実際のスカラの型を自動的にに IV や UV や倍精度や文字列にします。
SvPV マクロでは、返される文字列の長さは、変数 len に格納されます
(これはマクロですから、&len と しないで ください)。
もしデータの長さを気にしないのであれば、SvPV_nolen マクロを
使ってください。
歴史的に、この場合にはグローバル変数 PL_na に SvPV マクロが
使われてきました。
しかしこれは可能ですが効率は良くありません;
なぜなら PL_na はスレッド化した Perl ではスレッドローカルな
領域にアクセスしなければならないからです。
いずれの場合にも、Perl は NUL を含んでいる文字列と NUL で
終端されていないような文字列の両方を扱うことができるということを
覚えておいてください。
同様に、Cで SvPV(s, len), len) とすることが安全ではないことを
忘れないでください。
これはあなたの使うコンパイラによってはうまくいきますが、
いつでもそうだとは限らないのです。
そこで、こういったステートメントは以下のように分割します:
SV *s;
STRLEN len;
char * ptr;
ptr = SvPV(s, len);
foo(ptr, len);
単にスカラ値が真かどうかを知りたいだけならば、
SvTRUE(SV*)
Perl は、SV にもっとメモリを割り当てて欲しいときには自動的に文字列を 大きくしてくれますが、さらにメモリを割り当てさせることが必要であれば
SvGROW(SV*, STRLEN newlen)
というマクロが使えます。
もし必要なら、このマクロが sv_growを呼びます。
SvGROW は SV に割り当てたメモリを増やすだけで、減らすことは
できないということと、終端の NUL の分のバイトが自動的に加算されない
(perl自身の文字列関数は 大概 SvGROW(sv, len + 1) としています)と
いうことに注意してください。
手元にある SV の、 Perl から見たデータの種類を知りたいときには、 その SV の型をチェックするのに
SvIOK(SV*)
SvNOK(SV*)
SvPOK(SV*)
SV に納められた文字列の現在の長さを取得したり設定したりするのに は以下のマクロが使えます。
SvCUR(SV*)
SvCUR_set(SV*, I32 val)
同様に、SV に格納されている文字列の終端へのポインタを以下のマクロを 使って得ることができます。
SvEND(SV*)
ただし、これらは SvPOK() が真のときだけ有効だということに気を
つけてください。
SV* に格納されている文字列の末尾になにかを追加したいときに以下のような
関数が使えます。
void sv_catpv(SV*, const char*);
void sv_catpvn(SV*, const char*, STRLEN);
void sv_catpvf(SV*, const char*, ...);
void sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
void sv_catsv(SV*, SV*);
最初の関数は strlen を使って追加する文字列の長さを計算します。
二番目の関数では、関数を使用する人が文字列の長さを指定します。
三番目の関数はその引数を sprintf の様に処理し、整形された結果を
追加します。
四番目の関数は vsprintf のように動作します。
va_list 引数の代わりに、SV の配列のアドレスと長さを指定することが
できます。
五番目の関数は最初の SV にある文字列を二番目の SV にある文字列で
拡張します。
また、この関数は二番目の SV を強制的に文字列として解釈します。
sv_cat*() 関数群は“magic”を持っている値に対する
操作に対して充分に一般化されたものではありません。
後述する Magic Virtual Tables を参照してください。
スカラ変数の名前がわかれば、その SV へのポインタは
SV* get_sv("package::varname", FALSE);
を使って得ることができます。 その変数が存在しない場合には NULL が返されます。
その変数 (もしくは他の任意の SV) が、実際に 定義されているか を 知りたいならば、
SvOK(SV*)
スカラの undef 値は、PL_sv_undef という SV のインスタンスに
納められています。
そのアドレスは、SV* が必要とされるところで使用することができます。
任意の sv を &PL_sv_undef を比較しようとしないように気をつけてください。
例えば、Perl コードとのインターフェースで、以下は正しく動きます:
foo(undef);
しかし、以下のように呼び出すと動作しません:
$x = undef; foo($x);
従って、sv が定義されているかをチェックするために、毎回繰り返して SvOK() を使ってください。
また、AV や HV の値として &PL_sv_undef を使うときにも
注意しなければなりません (AVs, HVs and undefined values を
参照してください)。
ブール値の真と偽を表わす、PL_sv_yes や PL_sv_no という値もあります。
PL_sv_undef と同様に、これらのアドレスも SV* が必要なところで
使うことができます。
(SV *0) と &PL_sv_undef が同じであると考えて、だまされてはいけません。
次のようなコードを見てください:
SV* sv = (SV*) 0;
if (I-am-to-return-a-real-value) {
sv = sv_2mortal(newSViv(42));
}
sv_setsv(ST(0), sv);
このコードは、実値を返さなければならないときには、(値として 42 を
持つ) 新しい SV を返そうとし、さもなくば undef を返そうとします。
ですが、どこかの行でナルポインタを返して、セグメントバイオレーションが
起こるか、何かおかしな結果になってしまいます。
最初の行の 0 を &PL_sv_undef に変えれば、すべてがうまくいきます。
生成した SV を解放するためには、SvREFCNT_dec(SV*) を呼びます。
普通は、この呼び出しは必要ありません。
Reference Counts and Mortality を参照してください。
(オフセット)
Perl provides the function sv_chop to efficiently remove characters
from the beginning of a string; you give it an SV and a pointer to
somewhere inside the PV, and it discards everything before the
pointer. The efficiency comes by means of a little hack: instead of
actually removing the characters, sv_chop sets the flag OOK
(offset OK) to signal to other functions that the offset hack is in
effect, and it puts the number of bytes chopped off into the IV field
of the SV. It then moves the PV pointer (called SvPVX) forward that
many bytes, and adjusts SvCUR and SvLEN.
(TBT)
Hence, at this point, the start of the buffer that we allocated lives
at SvPVX(sv) - SvIV(sv) in memory and the PV pointer is pointing
into the middle of this allocated storage.
(TBT)
これは例による最良の実演です:
% ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
SV = PVIV(0x8128450) at 0x81340f0
REFCNT = 1
FLAGS = (POK,OOK,pPOK)
IV = 1 (OFFSET)
PV = 0x8135781 ( "1" . ) "2345"\0
CUR = 4
LEN = 5
Here the number of bytes chopped off (1) is put into IV, and
Devel::Peek::Dump helpfully reminds us that this is an offset. The
portion of the string between the "real" and the "fake" beginnings is
shown in parentheses, and the values of SvCUR and SvLEN reflect
the fake beginning, not the real one.
(TBT)
Something similar to the offset hack is performed on AVs to enable
efficient shifting and splicing off the beginning of the array; while
AvARRAY points to the first element in the array that is visible from
Perl, AvALLOC points to the real start of the C array. These are
usually the same, but a shift operation can be carried out by
increasing AvARRAY by one and decreasing AvFILL and AvLEN.
Again, the location of the real start of the C array only comes into
play when freeing the array. See av_shift in av.c.
(TBT)
(SV に実際に格納されているものは何ですか?)
自分で保持しているスカラの型を決定する通常の方法は、マクロ Sv*OK を
使うものでした。
スカラは数値にも文字列にもなり得ますから、普通、
これらのマクロはいつも真を返します。
そして Sv*V マクロを呼ぶことで、
文字列から整数/倍精度、整数/倍精度から文字列への変換を行ないます。
もし、本当に SV にあるのが整数か、倍精度か、文字列ポインタかを 知りたいのであれば、
SvIOKp(SV*)
SvNOKp(SV*)
SvPOKp(SV*)
というマクロを代わりに使うことができます。 これらのマクロは、実際に SV に入っているものが整数か、倍精度か、 文字列ポインタかを教えてくれます。
The are various ways in which the private and public flags may differ. For example, a tied SV may have a valid underlying value in the IV slot (so SvIOKp is true), but the data should be accessed via the FETCH routine rather than directly, so SvIOK is false. Another is when numeric conversion has occurred and precision has been lost: only the private flag is set on 'lossy' values. So when an NV is converted to an IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be. (TBT)
しかし一般的には、Sv*V マクロを使うだけにした方が良いでしょう。
(AV に対する作業)
AV を生成して値を設定するのには、二つの方法があります。 最初の方法は、単に空の AV を作るものです:
AV* newAV();
ふたつめの方法は、AV を生成した上で、初期値として SV の値を入れます:
AV* av_make(I32 num, SV **ptr);
二番目の引数は num 個の SV* の配列を指しています。 AV が生成されてしまえば、SV は(それを望むのなら)破棄することができます。
いったん AV が生成されると、AV に対して、
void av_push(AV*, SV*);
SV* av_pop(AV*);
SV* av_shift(AV*);
void av_unshift(AV*, I32 num);
といった操作が行えます。
これらは、av_unshift を除いては、お馴染みの演算でしょう。
av_unshift は、配列の先頭に num 個の undef 値の要素を付け加えます。
その後で、(後述する) av_store を使って新しい要素に値を
代入しなければなりません。
他にもいくつか関数があります:
I32 av_len(AV*);
SV** av_fetch(AV*, I32 key, I32 lval);
SV** av_store(AV*, I32 key, SV* val);
関数 av_len は配列における最高位の添え字を(ちょうど Perl の $#array と
同じように)返します。
もし配列が空であれば、-1 を返します。
関数 av_fetch は添え字 key の位置にある値を返しますが、lval が
非ゼロであれば、av_fetch はその位置に undef を格納しようとします。
関数 av_store は添え字 key の位置に値 val を格納し、val の
参照カウントをインクリメントしません。
従って、呼び出し側はこの振る舞いに注意して対処し、av_store が
NULL を返した場合には、メモリリークを防ぐために参照カウントの
デクリメントを行う必要があるでしょう。
av_fetch と av_store の両方ともがその戻り値として
SV* ではなく、SV** を返すということに注意してください。
void av_clear(AV*);
void av_undef(AV*);
void av_extend(AV*, I32 key);
関数 av_clear は、配列 AV* にあるすべての要素を削除しますが、
配列自身の削除は行いません。
関数 av_undef は配列にあるすべての要素に加え、配列自身の削除も行います。
関数 av_extend は配列を key+1 要素だけ拡張します。
key+1 が配列のその時点での長さより短ければ、何も行なわれません。
配列変数の名前がわかっているのであれば、次のようにしてその配列に 対応する AV へのポインタを得ることができます。
AV* get_av("package::varname", FALSE);
これは変数が存在していない場合には NULL を返します。
tie された配列における配列アクセス関数の使い方についての詳細は Understanding the Magic of Tied Hashes and Arrays を参照してください。
(HV に対する作業)
HV を生成するには、
HV* newHV();
というルーチンを使います。 いったん HV が生成されると HV に対して、
SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
という操作が行えます。
引数 klen は、渡される key の長さです
(Perl にキーの長さを計算させるために、klen> の値として 0 を渡すことは
できないということに注意してください)。
引数 val は、設定されるスカラへの SV ポインタを入れ、hash は、
あらかじめ計算したハッシュ値 (hv_store に計算させる場合には、
ゼロ) です。
引数 lval で、このフェッチ操作が実はストア操作の一部であるかどうかを
示します。
ストア操作であれば、新たなundefind value が与えられた
キーを伴って HV に追加され、hv_fetch はその値が既に
存在していたかのようにリターンします。
hv_store や hv_fetch は、SV** を返すもので、SV* ではないことに
注意してください。
スカラ値をアクセスするには、まず戻り値の参照外し(dereference)をする
必要があります。
しかし、その前に返却値が NULL でないことを確認すべきです。
ハッシュテーブルのエントリが存在するかをチェックし、削除を行う 関数があります。
bool hv_exists(HV*, const char* key, U32 klen);
SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
flag に G_DISCARD フラグが含まれていなければ、hv_delete は
削除された値の揮発性のコピー(mortal copy)を生成し、それを返します。
さらに様々な関数があります:
void hv_clear(HV*);
void hv_undef(HV*);
引数に AV を取る似たような関数と同様、hv_clear はハッシュテーブルにある
すべてのエントリーを削除しますがハッシュテーブル自身は削除しません。
hv_undef はエントリーとハッシュテーブル自身の両方を削除します。
Perl は実際のデータを HE と typedef された構造体のリンクリストを使って
保持しています。
これらは実際のキーと値のポインタ(それに加えて管理のための
ちょっとしたもの)を保持しています。
キーは文字列へのポインタであり、値は SV* です。
しかしながら、一度 HE* を持てば、実際のキーと値とを取得するためには
以下に挙げるようなルーチンを使います。
I32 hv_iterinit(HV*);
/* ハッシュテーブルをたどるための開始点を準備 */
HE* hv_iternext(HV*);
/* 次のエントリーを取得して、キーと値両方を持つ構造
体へのポインタを返す */
char* hv_iterkey(HE* entry, I32* retlen);
/* HE 構造体からキーを取得し、そのキー文字列の長さを
返す */
SV* hv_iterval(HV*, HE* entry);
/* HE 構造体の値に対する SV ポインタを返す */
SV* hv_iternextsv(HV*, char** key, I32* retlen);
/* この便利なルーチンは、hv_iternext、hv_iterkey、
hv_itervalを組み合わせたものです。
引数keyとretlenは、キーとその長さを表わす戻り値です。
関数の戻り値はSV* で返されます。*/
配列変数の名前がわかるのであれば、
HV* get_hv("package::varname", FALSE);
を使えば、その変数の HV へのポインタが得られます。 その変数が存在しない場合には NULL を返します。
ハッシュアルゴリズムは PERL_HASH(hash, key, klen) というマクロで
定義されています。
hash = 0;
while (klen--)
hash = (hash * 33) + *key++;
hash = hash + (hash >> 5); /* after 5.6 */
最後のステップは、結果となるハッシュ値の低位ビットの分散を改良するために バージョン 5.6 で追加されました。
tie されたハッシュに対するハッシュアクセス関数の使い方に 関する詳細は、Understanding the Magic of Tied Hashes and Arrays を 参照してください。
(ハッシュ API 拡張)
バージョン 5.004 から、以下の関数がサポートされました。
HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
bool hv_exists_ent (HV* tb, SV* key, U32 hash);
SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
SV* hv_iterkeysv (HE* entry);
これらの関数が、ハッシュ構造を扱うエクステンションの記述を単純にする
SV* キーを引数にとることに注意してください。
これらの関数はまた、SV* キーを(先に挙げた関数群とは異なり)
文字列化することなしに tie 関数に渡すことを許しています。
これらの関数はまた、ハッシュエントリー全体 (HE*) を返したり受け付けて、
より効率良く使用します(特定の文字列に対するハッシュ番号は
毎回計算しなおす必要はないからです)。
詳しくは perlapi を参照してください。
以下に挙げるマクロは、ハッシュエントリーの内容にアクセスするのに 常に使わなければならないものです。 これらのマクロはその引数を二度以上評価する可能性があるので、マクロに 対する引数は単純な変数でなければならないということに注意してください。 これらのマクロに関する詳細は perlapi を参照してください。
HePV(HE* he, STRLEN len)
HeVAL(HE* he)
HeHASH(HE* he)
HeSVKEY(HE* he)
HeSVKEY_force(HE* he)
HeSVKEY_set(HE* he, SV* sv)
低レベルマクロが二つ定義されていますが、これらは SV* ではないキーを
扱うときにのみ使わなければならないものです。
HeKEY(HE* he)
HeKLEN(HE* he)
hv_store と hv_store_ent の両方ともが、val に格納されている
参照カウントのインクリメントをしないということに注意してください。
それは呼び出し側の責任です。
これらの関数が NULL を返した場合、
呼び出し側はメモリリークを防ぐために、val の参照カウントの
デクリメントを行う必要が一般にはあるでしょう。
(AV, HV と未定義値)
AV や HV に未定義値を保管しなければならないこともあります。
これは珍しい場合ですが、手の込んだものになります。
なぜなら、未定義の SV が必要なら、&PL_sv_undef を使うことになるからです。
例えば、直感ではこの XS コードは:
AV *av = newAV();
av_store( av, 0, &PL_sv_undef );
以下の Perl コードと等価です:
my @av;
$av[0] = undef;
残念ながら、これは正しくありません。
AV は、配列要素がまだ初期化されていないことを示すための印として
&PL_sv_undef を使います。
従って、上述の Perl コードは exists $av[0] は真ですが、
XS コードによって生成された配列では偽です。
HV に &PL_sv_undef を保管する時にも別の問題が起こりえます:
hv_store( hv, "key", 3, &PL_sv_undef, 0 );
実際これは undef 値を作りますが、key の値を変更しようとすると、
以下のようなエラーが出ます:
Modification of non-creatable hash value attempted
In perl 5.8.0, &PL_sv_undef was also used to mark placeholders
in restricted hashes. This caused such hash entries not to appear
when iterating over the hash or when checking for the keys
with the hv_exists function.
(TBT)
You can run into similar problems when you store &PL_sv_true or
&PL_sv_false into AVs or HVs. Trying to modify such elements
will give you the following error:
(TBT)
Modification of a read-only value attempted
To make a long story short, you can use the special variables
&PL_sv_undef, &PL_sv_true and &PL_sv_false with AVs and
HVs, but you have to make sure you know what you're doing.
(TBT)
Generally, if you want to store an undefined value in an AV
or HV, you should not use &PL_sv_undef, but rather create a
new undefined value using the newSV function, for example:
(TBT)
av_store( av, 42, newSV(0) );
hv_store( hv, "foo", 3, newSV(0), 0 );
(リファレンス)
リファレンスは、(リファレンスを含む) 他のスカラ型を指す特別な スカラ型です。
リファレンスを生成するには、
SV* newRV_inc((SV*) thing);
SV* newRV_noinc((SV*) thing);
thing には、SV*, AV*, HV* のいずれかを置くことができます。
これら二つの関数は、newRV_inc が thing の参照カウントを
インクリメントするが newRV_noinc はインクリメントしないという点を
除き、同一です。
歴史的な理由により、newRV は newRV_inc の同義語となっています。
リファレンスができれば、以下のマクロを使ってリファレンスの参照外し (dereference)ができます。
SvRV(SV*)
というマクロが使うことができ、返された SV* を AV* か HV* に
キャストして、適切なルーチンを呼ぶことになります。
SV がリファレンスであるかどうかを確認するために、 以下のマクロを使うことができます。
SvROK(SV*)
リファレンスが参照している型を見つけるために、以下のマクロを 使いその戻り値をチェックします。
SvTYPE(SvRV(SV*))
戻り値として返される型で有益なものは以下の通りです。
SVt_IV スカラ
SVt_NV スカラ
SVt_PV スカラ
SVt_RV スカラ
SVt_PVAV 配列
SVt_PVHV ハッシュ
SVt_PVCV コード
SVt_PVGV グロブ (ファイルハンドルかも)
SVt_PVMG bress されたかマジカルなスカラ
詳しくはヘッダファイル sv.h を参照してください。
(bless されたリファレンスとクラスオブジェクト)
リファレンスはオブジェクト指向プログラミングをサポートするためにも 使われます。 perl のオブジェクト指向用語では、オブジェクトとはパッケージ (もしくはクラス)に bless された単純なリファレンスです。 一度 bless されれば、プログラマーはそのリファレンスをクラスにおける様々な メソッドにアクセスするために使うことができます。
以下の関数を使って、リファレンスをパッケージに bless することができます。
SV* sv_bless(SV* sv, HV* stash);
引数 sv はリファレンス値でなければなりません。
引数 stash はリファレンスが属するクラスを指定します。
クラス名のstashへの変換についての詳細は Stashes and Globs を
参照してください。
/* Still under construction */
まだ存在していなければ、rv をリファレンスにアップグレードします。
rv が指し示すための新たな SV を生成します。
classname がナルでなければ、SV は指定されたクラスに bless され、
SV が返されます。
SV* newSVrv(SV* rv, const char* classname);
整数、符号なし整数、倍精度実数を rv が参照している SV へコピーします。
SV は classname がナルでなければblessされます。
SV* sv_setref_iv(SV* rv, const char* classname, IV iv); SV* sv_setref_uv(SV* rv, const char* classname, UV uv); SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
ポインタ値(アドレスであって、文字列ではありません!)を rv が
参照しているSVへコピーします。
SV は classname がナルでなければ bless されます。
SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
文字列を rv が参照している SV へコピーします。
length に 0 を設定すると、Perl が文字列の長さを計算します。
SV は classname がナルでなければ bless されます。
SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
SV が特定のクラスに bless されているかどうかを検査します。 これは継承の関係のチェックはしません。
int sv_isa(SV* sv, const char* name);
SV が bless されたオブジェクトのリファレンスであるかどうかを検査します。
int sv_isobject(SV* sv);
SV が特定のクラスから派生したものがどうかを検査します。
SV は bless されたオブジェクトのリファレンスでも、
クラス名を保持している文字列であってもかまいません。
これは UNIVERSAL::isa の機能を実装している関数です。
bool sv_derived_from(SV* sv, const char* name);
ある特定のクラスの派生オブジェクトを受け取ったかどうか検査するには、 以下のように書く必要があります。
if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
(新しい変数の作成)
undef という値を持つあなたの Perl スクリプトからアクセスできる新たな Perl の変数を生成するには、以下に示すルーチンを変数の型に応じて 使います。
SV* get_sv("package::varname", TRUE);
AV* get_av("package::varname", TRUE);
HV* get_hv("package::varname", TRUE);
二番目のパラメータとして TRUE を使っているということに注意してください。 新しい変数はここでデータ型に対する適切なルーチンを使うことで 設定することができます。
TRUE 引数とビット和を取って、幾つかの追加機能を有効とするような
二つのマクロがあります。
変数に多重定義 (multiply defined) であると印を付け:
Name <varname> used only once: possible typo
警告を防ぎます。
以下の警告を:
Had to create <varname> unexpectedly
変数が、その関数の呼び出し以前に存在してなかった場合に発生させます。
パッケージ名を指定しなかった場合、変数はカレントパッケージで 生成されます。
(参照カウントと揮発性)
Perl は参照カウント駆動(reference count-driven)のガベージコレクション 機構を使用しています。 SV、AV、そしてHV(以下 xV と省略します) はその一生を参照カウント 1 から始めます。 xV の参照カウントが0まで落ちた場合、そのリファレンスは破棄されて、 それが使っていたメモリは 再利用できるようにされます。
これは、Perl レベルにおいては、変数が undef されるとかリファレンスを 保持している最後の変数が変更されたとか上書きされるということがない限りは 起こりません。 しかし内部的には、参照カウントは以下に挙げるマクロを使って 操作することができます。
int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);
その引数の参照カウントを操作する別の関数が一つあります。
newRV_inc という関数がそれです。
これは指定された引数の参照を生成して、その副作用として引数の
参照カウントをインクリメントします。
もしこの副作用が邪魔であれば、newRV_noinc を代わりに使ってください。
たとえば、XSUB 関数からリファレンスを返したいと思ったとしましょう。
XSUB ルーチンの中で、初期値として参照カウント 1 を持つ SV を生成します。
それから今作成した SV を引数にして newRV_inc を呼びます。
これは新たな SV としての参照を返しますが、newRV_inc に引数として渡した
SV の参照カウントは 2 にインクリメントされます。
ここで XSUB ルーチンからそのリファレンスを戻り値として返し、SV のことは
忘れましょう。
けれども Perl は忘れてません!
戻り値で返されたリファレンスが破棄されたときにはいつも、元々の SV の
参照カウントが 1 へと減じられ、そして何事もおこりません。
その SV は、Perl 自身が終了するまではそれにアクセスするなんの手段も
持たずに中ぶらりんになります。
ここでの正しい手順は、newRV_inc ではなく newRV_noinc を
使うということです。
これによって、最後のリファレンスが破棄されたときに
SV のリファレンスカウントは0となってその SV が破棄されて、メモリ
リークを食い止めます。
xV を破棄するのを助けるような便利な関数が幾つかあります。 これらの関数は「揮発性」(mortality) のコンセプトを導入します。 ある揮発性の xV はその参照カウントをデクリメントするようにマークしますが、 実際には「ちょっと後」(a short time later)までデクリメントが 行なわれません。 一般的には、「ちょっと後」とは、XSUB 関数の呼び出しのような Perl の一つの文です。 揮発性の xV が持っている参照カウントの デクリメントを行うタイミングの決定は二つのマクロ、SAVETMPS と FREETMPS に依存しています。 これら二つのマクロについての説明は perlcall と perlxs を参照してください。
「揮発化」("Mortalization") はそれから、SvREFCNT_dec に決定権を委ねます。
しかし、ある変数を二度揮発的にした場合、その参照カウントは後で
二度デクリメントされます。
「揮発性」SVs は主に、perl のスタックに置かれる SV に対して使われます。 For example an SV which is created just to pass a number to a called sub is made mortal to have it cleaned up automatically when it's popped off the stack. Similarly, results returned by XSUBs (which are pushed on the stack) are often made mortal. (TBT)
揮発性の変数を生成するには、以下の関数を使います:
SV* sv_newmortal()
SV* sv_2mortal(SV*)
SV* sv_mortalcopy(SV*)
最初のものは(値のない)揮発性の SV を生成し、ふたつめは既にある SV を
揮発性の SV に変換します(そして、このために SvREFCNT_dec を呼び出しを
遅らせます)。
三つめは、既に存在する SV の揮発性のコピーを生成します。
sv_newmortal は値のない新しい SV を作るので、普通は
sv_setpv, sv_setiv などを使って作らなければなりません:
SV *tmp = sv_newmortal();
sv_setiv(tmp, an_integer);
これは C の複数文なので、代わりにこの慣用法がとても一般的です:
SV *tmp = sv_2mortal(newSViv(an_integer));
揮発性の変数を生成するに当たっては十分注意すべきです。
もし、同じ変数を複合コンテキストの中で揮発性にしたり、ある変数を複数回
揮発性にしてしまったりすればおかしな自体が起こるかもしれません。
Thinking of "Mortalization"
as deferred SvREFCNT_dec should help to minimize such problems.
For example if you are passing an SV which you know has high enough REFCNT
to survive its use on the stack you need not do any mortalization.
If you are not sure then doing an SvREFCNT_inc and sv_2mortal, or
making a sv_mortalcopy is safer.
(TBT)
揮発性のルーチンは、単に SV のためだけではありません。
AV や HV も、sv_2mortal や sv_mortalcopy ルーチンに、アドレスを
(SV* にキャストして) 渡すことで、揮発性にすることができます。
(スタッシュとグロブ)
スタッシュ ("stash")とは、パッケージ内で定義された全ての変数が 入っているハッシュのことです。 ハッシュテーブルにあるそれぞれの key は、(同じ名前のすべての異なる型の オブジェクトで共有される) シンボル名で、ハッシュテーブルの個々の 値は、(グローバル値のための) GV と呼ばれます。 GV には、以下のものを含む (これらに限りませんが)、その名前の様々な オブジェクトへのリファレンスが次々に入ることになります。
Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine
main パッケージにあるアイテムを保持する PL_defstash と呼ばれる
スタッシュがあります。
他のパッケージにあるアイテムを取得するため
には、パッケージ名に「::」を付加します。
Foo というパッケージにあるアイテムは Foo:: という
PL_defstash の中にあります。
パッケージ Bar::Baz にあるアイテムは Bar:: のスタッシュの中の
Baz:: のスタッシュの中にあります。
特定のパッケージの HV ポインタの入手には、以下の関数が使えます:
HV* gv_stashpv(const char* name, I32 flags)
HV* gv_stashsv(SV*, I32 flags)
最初の関数が、リテラル文字列をとり、二番目が SV に入れた文字列を使います。
stash は単なるハッシュなので、HV* を受け取るということを
忘れないでください。
flags フラグが GV_ADD にセットされている場合には新たなパッケージを
生成します。
gv_stash*v が要求する name はシンボルテーブルを手に入れようとする
パッケージの名前です。
デフォルトのパッケージは、main というものです。
多重にネストしたパッケージであれば、Perl での場合と同様に、
:: で区切って gv_stash*v に名前を渡すのが正しい方法です。
あるいは、もし bless されたリファレンスである SV があれば、 以下のようにしてを使ってもスタッシュポインタを探すことができ:
HV* SvSTASH(SvRV(SV*));
パッケージ名自身は、以下のようにして得られます:
char* HvNAME(HV* stash);
Perl スクリプトへ bless された値を返す必要があれば、以下の関数が使えます:
SV* sv_bless(SV*, HV* stash)
最初の引数 SV* はリファレンスで、二番目の引数がスタッシュです。
返された SV* は、他の SV と同様に使うことができます。
リファレンスと bless についてのより詳しい情報は perlref を 参照してください。
(二重型 SV)
スカラ変数は通常、整数、倍精度、ポインタ、リファレンスのうちの いずれか一つの型をとります。 Perl は実際のデータに対して、蓄積されている型から要求されている型へ、 自動的に変換を行ないます。
ある種のスカラ変数は、複数の型のスカラデータを持つようになっています。
たとえば変数 $! は、errno の数値としての値と、
strerror や sys_errlist[] から得たのと同値な文字列を持っています。
SV に複数のデータ値を入れるようにするには、二つのことを
しなくてはなりません。
スカラ型を別に追加するために sv_set*v ルーチンを使用すること。
それから、フラグを設定して Perl に複数のデータを
持っていることを知らせることです。
フラグを設定するための四つのマクロは以下のものです:
SvIOK_on SvNOK_on SvPOK_on SvROK_on
使用するマクロは、最初にどの sv_set*v ルーチンを呼ぶのかに
関わってきます。
これは、sv_set*v ルーチンはすべて特定のデータ型のビットだけを
設定して、他をクリアしてしまうからです。
たとえば、"dberror" という新しい Perl 変数を作って、エラー値を数値と メッセージ文字列で持つようにするには、以下のように書きます:
extern int dberror;
extern char *dberror_list;
SV* sv = get_sv("dberror", TRUE);
sv_setiv(sv, (IV) dberror);
sv_setpv(sv, dberror_list[dberror]);
SvIOK_on(sv);
sv_setiv と sv_setpv の順序が逆であった場合、SvIOK_on マクロの
代わりに SvPOK_on マクロを呼ばなければなりません。
(マジック変数)
[This section still under construction. Ignore everything here. Post no bills. Everything not permitted is forbidden.] (TBT)
すべての SV は magical、つまり、通常の SV が持っていないような特殊な
属性を持つようにすることができます。
これらの属性は MAGIC として typedef されている struct magic の
リンクリストにある SV 構造体に格納されます。
struct magic {
MAGIC* mg_moremagic;
MGVTBL* mg_virtual;
U16 mg_private;
char mg_type;
U8 mg_flags;
I32 mg_len;
SV* mg_obj;
char* mg_ptr;
};
これは、パッチレベル 0 の時点でのものです。 変更される可能性があります。
(マジックの代入)
Perl は sv_magic 関数を使った SV にマジックを追加します。
void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
引数 sv は、新たにマジック機能を獲得する SV へのポインタです。
sv がまだマジカルでなければ、Perl は sv を SVt_PVMG に変換
するために SvUPGRADE を使います。
Perl はそれから、マジック機能のリンクリストの先頭にそれを追加します。
以前に存在していた同じタイプのマジックは削除されます。
これはオーバーライドすることができ、
複数の同じ型のマジックのインスタンスを一つの SV に
結び付けることができるということに注意してください。
引数 name と namlen はある文字列と magic とを結び付けるために
使われます。
典型的には変数の名前です。
namlen は mg_len フィールドに格納され、name がヌルなら、
name の savepvn コピーか、name 自身 is stored in the mg_ptr field, depending on
whether namlen is greater than zero or equal to zero respectively. As a
special case, if (name && namlen == HEf_SVKEY) then name is assumed
to contain an SV* and is stored as-is with its REFCNT incremented.
(TBT)
関数 sv_magic は how を、あらかじめ定義されている
マジック仮想テーブル("Magic Virtual Table") のどれを
mg_virtual フィールドに設定するかを決定するのに使います。
See the Magic Virtual Tables section below. The how argument is also
stored in the mg_type field. The value of how should be chosen
from the set of macros PERL_MAGIC_foo found in perl.h. Note that before
these macros were added, Perl internals used to directly use character
literals, so you may occasionally come across old code or documentation
referring to 'U' magic rather than PERL_MAGIC_uvar for example.
(TBT)
引数 obj は MAGIC 構造体の mg_obj フィールドに格納されます。
これが sv 引数と同じでなかった場合、obj の参照カウントは
インクリメントされます。
同じであった場合、もしくは引数 how が
PERL_MAGIC_arylen かナルポインタであった場合には、obj は
参照カウントのインクリメントをさせることなく格納されます。
SV にマジックを追加する、より柔軟な方法については perlapi の
sv_magicext も参照してください。
同様に HV にマジックを付加する関数があります。
void hv_magic(HV *hv, GV *gv, int how);
これは単純に sv_magic を呼び出し、引数 gv を強制的に SV にします。
SV からマジックを取り除くには、sv_unmagic という関数を呼び出します。
void sv_unmagic(SV *sv, int type);
引数 type は、SV が magical にされたときの how の値と同じに
なるようにすべきです。
(マジック仮想テーブル)
MAGIC 構造体の mg_virtual フィールドは MGVTBL へのポインタで、
これは関数ポインタの構造体であり、また対応する変数に対して
適用される可能性のあるさまざまな操作を扱うための
「マジック仮想テーブル」("Magic Virtual Table") を意味しています。
MGVTBL は、以下に挙げる 5 種類(あるいは時々 8 種類)の
ポインタを持っています。
int (*svt_get)(SV* sv, MAGIC* mg);
int (*svt_set)(SV* sv, MAGIC* mg);
U32 (*svt_len)(SV* sv, MAGIC* mg);
int (*svt_clear)(SV* sv, MAGIC* mg);
int (*svt_free)(SV* sv, MAGIC* mg);
int (*svt_copy)(SV *sv, MAGIC* mg, SV *nsv, const char *name, int namlen);
int (*svt_dup)(MAGIC *mg, CLONE_PARAMS *param);
int (*svt_local)(SV *nsv, MAGIC *mg);
この MGVTBL は perl.h の中でコンパイル時に設定され、現在 19 の型 (オーバーロード込みで 21)があります。 これらの異なった構造体は、関数が呼び出されたときに依存して 追加動作を行うような様々なルーチンへのポインタを保持しています。
関数ポインタ その振る舞い
---------------- ------------
svt_get SV の値が取得された前に何かを行う。
svt_set SV に値を代入した後で何かを行う。
svt_len SV の長さを報告する。
svt_clear SV が表わしているものををクリアする。
svt_free SV に結び付けられてい領域を解放する。
svt_copy tie された変数のマジックを tie された要素にコピーする
svt_dup スレッドのクローン化中にマジック構造体を複製する
svt_local 'local' 中にマジックをローカル変数にコピーする
たとえば、vtbl_sv (PERL_MAGIC_sv の mg_type に対応します)と
呼ばれる MGVTBL 構造体の内容は以下の様になっています。
{ magic_get, magic_set, magic_len, 0, 0 }
したがって、ある SV がマジカルであると決定されてその型が
PERL_MAGIC_sv であったとき、操作が実行されたならば、magic_get が
呼び出されます。
マジカル型に対するルーチンはすべて、magic_ で始まります。
NOTE: マジックルーチンは Perl API の一部として扱われず、
Perl ライブラリによってエクスポートされません。
The last three slots are a recent addition, and for source code compatibility they are only checked for if one of the three flags MGf_COPY, MGf_DUP or MGf_LOCAL is set in mg_flags. This means that most code can continue declaring a vtable as a 5-element value. These three are currently used exclusively by the threading code, and are highly subject to change. (TBT)
現時点でのMagic Virtual Tables の種類は以下の通りです。
mg_type
(old-style char and macro) MGVTBL Type of magic
-------------------------- ------ -------------
\0 PERL_MAGIC_sv vtbl_sv 特殊スカラ変数
A PERL_MAGIC_overload vtbl_amagic %OVERLOAD ハッシュ
a PERL_MAGIC_overload_elem vtbl_amagicelem %OVERLOAD ハッシュ要素
c PERL_MAGIC_overload_table (none) スタッシュのオーバーロード
テーブル(AMT) を保持
B PERL_MAGIC_bm vtbl_bm Boyer-Moore (高速文字列検索)
D PERL_MAGIC_regdata vtbl_regdata 正規表現マッチング位置データ
(@+ と @- の変数)
d PERL_MAGIC_regdatum vtbl_regdatum 正規表現マッチング位置データ
要素
E PERL_MAGIC_env vtbl_env %ENV ハッシュ
e PERL_MAGIC_envelem vtbl_envelem %ENV ハッシュ要素
f PERL_MAGIC_fm vtbl_fm フォーム行(「コンパイル済み」
フォーマット)
g PERL_MAGIC_regex_global vtbl_mglob m//g のターゲット / study() した文字列
H PERL_MAGIC_hints vtbl_sig %^H ハッシュ
h PERL_MAGIC_hintselem vtbl_hintselem %^H ハッシュ要素
I PERL_MAGIC_isa vtbl_isa @ISA 配列
i PERL_MAGIC_isaelem vtbl_isaelem @ISA 配列要素
k PERL_MAGIC_nkeys vtbl_nkeys scalar(keys()) 左辺値
L PERL_MAGIC_dbfile (none) デバッガの %_<filename
l PERL_MAGIC_dbline vtbl_dbline デバッガの %_<filename 要素
o PERL_MAGIC_collxfrm vtbl_collxfrm ロケール照合変換
P PERL_MAGIC_tied vtbl_pack tie された配列やハッシュ
p PERL_MAGIC_tiedelem vtbl_packelem tie された配列やハッシュの要素
q PERL_MAGIC_tiedscalar vtbl_packelem tie されたスカラやハンドル
r PERL_MAGIC_qr vtbl_qr 事前コンパイルされた qr// 正規表現
S PERL_MAGIC_sig vtbl_sig %SIG ハッシュ
s PERL_MAGIC_sigelem vtbl_sigelem %SIG ハッシュ要素
t PERL_MAGIC_taint vtbl_taint 汚染性
U PERL_MAGIC_uvar vtbl_uvar エクステンションで使用可能
v PERL_MAGIC_vec vtbl_vec vec() 左辺値
V PERL_MAGIC_vstring (none) v-文字列スカラ
w PERL_MAGIC_utf8 vtbl_utf8 UTF-8 長さ+オフセットキャッシュ
x PERL_MAGIC_substr vtbl_substr substr() 左辺値
y PERL_MAGIC_defelem vtbl_defelem 影の "foreach" 反復子
変数 / スマート引数
自動有効化
# PERL_MAGIC_arylen vtbl_arylen 配列の長さ ($#ary)
. PERL_MAGIC_pos vtbl_pos pos() 左辺値
< PERL_MAGIC_backref vtbl_backref 弱いリファレンスへの後方ポインタ
~ PERL_MAGIC_ext (none) エクステンションで使用可能
: PERL_MAGIC_symtab (none) シンボルテーブルとして使われるハッシュ
% PERL_MAGIC_rhash (none) 制限ハッシュとして使われるハッシュ
@ PERL_MAGIC_arylen_p vtbl_arylen_p @a から $#a へのポインタ
テーブル中で大文字小文字の両方が存在していた場合、大文字は典型的には複合型 (リストもしくはハッシュ)の種類を表わすのに使われ、小文字はその複合型の 要素を表わすのに使われます。 内部コードにはこの大文字小文字の関係を使っているものもあります。 しかし、'v' と 'V' (ベクタと v-文字列) は全く関係がありません。
マジック型 PERL_MAGIC_ext と PERL_MAGIC_uvar は
エクステンションから使われ、Perl 自身からは使われないように特別に
定義されています。
エクステンションは PERL_MAGIC_ext マジックを、
プライベート情報を変数(典型的なオブジェクト)に「アタッチ」(attach)
するために使うことができます。
これは、通常の perl コードが(ハッシュオブジェクトの要素を使うのとは違って)
そのプライベート情報を壊す恐れがないのでとても便利です。
Similarly, PERL_MAGIC_uvar magic can be used much like tie() to call a
C function any time a scalar's value is used or changed. The MAGIC's
mg_ptr field points to a ufuncs structure:
(TBT)
struct ufuncs {
I32 (*uf_val)(pTHX_ IV, SV*);
I32 (*uf_set)(pTHX_ IV, SV*);
IV uf_index;
};
When the SV is read from or written to, the uf_val or uf_set
function will be called with uf_index as the first arg and a pointer to
the SV as the second. A simple example of how to add PERL_MAGIC_uvar
magic is shown below. Note that the ufuncs structure is copied by
sv_magic, so you can safely allocate it on the stack.
(TBT)
void
Umagic(sv)
SV *sv;
PREINIT:
struct ufuncs uf;
CODE:
uf.uf_val = &my_get_fn;
uf.uf_set = &my_set_fn;
uf.uf_index = 0;
sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
PERL_MAGIC_uvar を配列にアタッチすることは可能ですが、何の意味も
ありません。
For hashes there is a specialized hook that gives control over hash
keys (but not values). This hook calls PERL_MAGIC_uvar 'get' magic
if the "set" function in the ufuncs structure is NULL. The hook
is activated whenever the hash is accessed with a key specified as
an SV through the functions hv_store_ent, hv_fetch_ent,
hv_delete_ent, and hv_exists_ent. Accessing the key as a string
through the functions without the ..._ent suffix circumvents the
hook. See Hash::Util::Fieldhash/Guts for a detailed description.
(TBT)
複数のエクステンションが PERL_MAGIC_ext や PERL_MAGIC_uvar マジックを
使う可能性があるので、エクステンションがそれを扱うには気をつけることが
重要であることに注意してください。
典型的には、これはオブジェクトをエクステンションが扱えるように同じクラスに
bless するときにのみ使います。
PERL_MAGIC_ext マジックでは、これはまた、プライベートなデータ領域の
先頭においてそれをチェックするために I32「シグネチャ」(signature) を
付加するのに適切なものです。
sv_set*() と sv_cat*() といった関数群はそのターゲットに対して
'set' マジックを 起動しない ということにも注意してください。
これには、ユーザーが svSETMAGIC マクロを呼び出した後でこれらの関数を
呼び出すか、あるいは sv_set*_mg() か
sv_cat*_mg() の何れかの関数を使わなければなりません。
同様に、一般的な C コードは、
それがマジックを扱っていないような関数から得られた
SV を使っているのであれば、
'get' マジックを起動するために
SvGETMAGIC を呼び出さなければなりません。
これらの関数については perlapi を参照してください。
例えば、sv_cat*() 関数群の
呼び出しは通常引き続いて SvSETMAGIC() を呼び出す必要がありますが、
SvGETMAGIC が先行している必要はありません;
なぜなら、その実装は 'get' マジックを扱うからです。
(マジックを見つけだす)
MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
このルーチンは SV に格納されている MAGIC 構造体へのポインタを
返します。
SV がマジカル機能を持っていなければ、NULL が返されます。
また、SV が Svt_PVMG の型でなければ Perl はコアダンプするかもしれません。
int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
このルーチンは sv が持っているマジックの型を検査します。
mg_type フィールドが大文字であれば、mg_obj が nsv にコピーされますが、
mg_type フィールドは小文字に変更されます。
(tie されたハッシュと配列のマジックを理解する)
tie されたハッシュと配列は PERL_MAGIC_tied マジック型の magical beast です。
警告: リリース 5.004 以降、配列やハッシュに対するアクセス 関数の正しい使い方は、幾つかの注意点を理解していることを要求しています。 これら幾つかの注意点は実際には API におけるバグとして みなされるものであって、将来のリリースにおいては修正されます。 また、注意点は [MAYCHANGE] というブラケットで囲まれています。 このセクションにある情報をあなたが実際に使おうというのであれば、 将来それらは警告なしに変わる可能性があることに注意してください。
perl の tie 関数は、ある変数と GET、SET 等といった様々なメソッドを 実装しているオブジェクトとを結び付けるものです。 XSUB から perl の tie 関数と等価な働きをさせるには、 ちょっとしたオマジナイをしなければなりません。 以下の例が必要なステップです。 まず最初にハッシュを作り、それから tie メソッドを実装するクラスに bless した二番目のハッシュを作ります。 最後に二つのハッシュを tie し、新たに生成した tie されたハッシュに対する リファレンスを返します。 以下の例では MyTie クラスの中で TIEHASH を呼び出していないということに 注意してください。 この件に関する詳細は Calling Perl Routines from within C Programs を 参照してください。
SV*
mytie()
PREINIT:
HV *hash;
HV *stash;
SV *tie;
CODE:
hash = newHV();
tie = newRV_noinc((SV*)newHV());
stash = gv_stashpv("MyTie", GV_ADD);
sv_bless(tie, stash);
hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
RETVAL = newRV_noinc(hash);
OUTPUT:
RETVAL
tie された配列を引数に与えられたときの av_store 関数は、単に配列の
magic を mg_copy を使って「保管」されるように値をコピーするだけです。
この関数は、その値が実際には配列に格納する必要のないものであることを
示す NULL を返す可能性があります。
[MAYCHANGE]
tie された配列に対して av_store を呼び出した後、呼び出し側は TIEARRAY
オブジェクトに対して Perl レベルの "STORE" メソッドを起動するために
av_store を呼び出すことが通常は必要となります。
av_store が NULL を返したならば、メモリリークを防ぐために
SvREFCNT_dec(val) を呼び出すことが必要となります。
[/MAYCHANGE]
先のパラグラフの説明は、tie されたハッシュにアクセスするのに使用する
hv_store と hv_store_ent についても同様です。
av_fetch と、対応するハッシュ関数 hv_fetch および hv_fetch_ent は
実際には mg_copy を使って初期化が行なわれている未定義の揮発値を返します。
返された値はすでに揮発性なので、解放する必要がないことに注意してください。
[MAYCHANGE]
しかし、TIE オブジェクトに対応した perl レベルの
"FETCH" メソッドを実行するには、返されたその値に対して
mg_get() を呼び出す必要があるでしょう。
同様に、TIE オブジェクトに対する "STORE" メソッドの起動である
sv_setsv を使って適切な値を代入した後で、返された値に対して
mg_set() を呼び出すことができます。
[/MAYCHANGE]
[MAYCHANGE]
言い換えれば、配列やハッシュをフェッチしたりストアする関数は、
tie されている配列やハッシュに対する場合には実際に値をフェッチしたり
保管したりするわけではないということです。
それらの関数は「保管」されたり「フェッチ」された値に対してマジックを
付加するために、単に mg_copy を呼び出すだけです。
現在(バージョン 5.004)、ハッシュや配列に対するアクセス関数を使用する 際には、ユーザーが「通常の」ハッシュや配列なのか、あるいはそれが tie されたものであるのかを気をつけることが要求されています。 将来のバージョンでは、この API は tie されたデータに対するアクセスと 通常のデータに対するアクセスをより透過的にするために変更されるかも しれません。 [/MAYCHANGE]
TIEARRAY や TIEHASH といったインターフェースが、統一的な ハッシュ/配列構文を使うための perl メソッドを起動をするための単なる 砂糖であることを良く理解したことでしょう。 これらの砂糖の使用はいくらかのオーバーヘッド(通常、FETCH/STORE 操作 当たり二つから四つの余分なオペコード、それに加えてメソッドを 起動するために必要なすべての揮発性変数の生成)を招きます。 このオーバーヘッドは TIE メソッド自身がしっかりしたものであれば、ほぼ 同等なくらい小さなものでしかありませんが、ほんの少し文が長いだけでも オーバーヘッドは無視できないものになります。
(変更をローカル化する)
Perl には非常に便利な構造があります。
{
local $var = 2;
...
}
この構造は以下のものと ほぼ 同じです
{
my $oldvar = $var;
$var = 2;
...
$var = $oldvar;
}
両者の最も大きな違いは、最初のものが
goto、return、die/eval など
どのようにブロックから脱出しようとも、
$var の元々の値を復帰するということです。
効率といった面では大きな違いはありません。
Perl API を通して C から同様の処理を行う方法もあります。
擬似ブロック(pseudo-block)を生成し、そのブロックの最後で自動的に
復帰するような幾つかの変更を行います。
ブロックから抜けるのは、明示的に抜けるための指示があっても良いし、
非局所的な脱出(die() を使ったもの)でもかまいません。
ブロックに似たこの構造は ENTER/LEAVE マクロのペアによって
生成されます(perlcall/"Returning a Scalar" を参照してください)。
このような構造ではなにか重要なローカル化された
タスクのための特別なものを作成したり、あるいは
既に存在しているもの(Perl のサブルーチン/ブロックに束縛されたものとか、
あるいは解放する一時変数のペア)を使うことも可能です
(二番目のケースでは、ローカル化するためのオーバーヘッドはほとんど
無視できるものです)。
すべての XSUB は自動的に ENTER/LEAVE の
ペアによって囲まれているということに注意してください。
このような 擬似ブロック の中では以下のサービスが利用可能です:
SAVEINT(int i)
SAVEIV(IV i)
SAVEI32(I32 i)
SAVELONG(long i)
これらのマクロはそれを囲む 擬似ブロック において
整数変数 i の値をリストアするようにします。
SAVESPTR(s)
SAVEPPTR(p)
これらのマクロは、ポインタsもしくは p の値を
リストアします。
s は SV* に対する型変換をできるポインタでなければなりません。
p は char* への型変換が可能であるべきものです。
SAVEFREESV(SV *sv)
擬似ブロック の終端において sv の参照カウントは
デクリメントされます。
これは、遅延した SvREFCNT_dec を行うための機構という意味で
sv_2motral に似たものです。
However, while sv_2mortal
extends the lifetime of sv until the beginning of the next statement,
SAVEFREESV extends it until the end of the enclosing scope. These
lifetimes can be wildly different.
(TBT)
また、SAVEMORTALIZESV を比較します。
SAVEMORTALIZESV(SV *sv)
Just like SAVEFREESV, but mortalizes sv at the end of the current
scope instead of decrementing its reference count. This usually has the
effect of keeping sv alive until the statement that called the currently
live scope has finished executing.
(TBT)
SAVEFREEOP(OP *op)
OP * は 擬似ブロック の終端において op_free() されます。
SAVEFREEPV(p)
p によって指し示されているメモリの塊は 擬似ブロック の終端で
Safefree() されます。
SAVECLEARSV(SV *sv)
擬似ブロック の終端において、
sv に対応している
カレントのスクラッチパッドにおけるスロットをクリアします。
SAVEDELETE(HV *hv, char *key, I32 length)
擬似ブロック の終端で hv にあるキー key は削除されます。
key によって指し示されている文字列は Safefree() されます。
short-lived storageにある key を持っているものがあった場合には
以下のようにして対応する文字列が再割り当てされます。
SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)
擬似ブロック の終端において関数 f が呼び出されます。
この関数 f は p のみを引数に取ります。
SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)
疑似ブロック の最後に、関数 f が(もしあれば)暗黙のコンテキスト
引数と p で呼び出されます。
SAVESTACK_POS()
擬似ブロック の終端において Perl の内部スタック(SP)のカレント
オフセットがリストアされます。
以下の API リストは、変更可能なデータを指し示すポインタ
(C のポインタか、Perl 的な GV * のいずれか)
を必要とする関数群です。
前述の int を引数に取るマクロに似て、
int * を引数に取る関数があります。
SV* save_scalar(GV *gv)
Perl コード local $gv と等価です。
AV* save_ary(GV *gv)
HV* save_hash(GV *gv)
save_scalar に似ていますが、@gv と %gv の局所化を行います。
void save_item(SV *item)
SV のカレントの値を複製し、カレントの ENTER/LEAVE
擬似ブロック を抜けるときに SV の保存した値を復帰します。
マジックを扱いません。
マジックを有効にしたい場合は save_scalar を使ってください。
void save_list(SV **sarg, I32 maxsarg)
複数の引数を長さ maxarg の SV* の配列 sarg として取る
save_item の複数の値を取るバリエーションです。
SV* save_svref(SV **sptr)
save_scalar に似ていますが、SV * の復帰を行います。
void save_aptr(AV **aptr)
void save_hptr(HV **hptr)
save_svref に似ていますが、AV * と HV * のローカル化を行います。
Alias モジュールは 呼び出し側のスコープ 中での基本型のローカル化を
実装します。
スコープを持った何かのローカル化に興味のある人は
そこに何があるかも見ておいた方が良いでしょう。
(XSUB と引数スタック)
XSUB の仕組みは、Perl プログラムが C のサブルーチンを アクセスするための単純な方法です。 XSUB には、Perl プログラムからの引数を入れるスタックと、Perl のデータ 構造を C の等価なものにマッピングする方法を用意しています。
スタック引数は ST(n) というマクロを使ってアクセスできます。
これは、n 番目のスタック引数を返すものです。
引数 0 は、Perl のサブルーチン呼び出しで渡された最初の引数です。
これらの引数は SV* で、SV* が使われるところであればどこでも
使うことができます。
ほとんどの場合には、C ルーチンからの出力は RETVAL 指示子と OUTPUT 指示子を使って扱うことができます。 しかし、引数スタックのスペースがすべての返却値を扱うのに十分で なくなる場合があります。 例としては、引数をとらないでローカルなタイムゾーンと夏時間の省略形の 二つの返却値を返す、POSIX の tzname() の呼び出しがあります。
このような状況を扱うためには、PPCODE ディレクティブを使い、さらに スタックを以下のマクロを使って拡張します:
EXTEND(SP, num);
ここで SP はスタックポインタで、num はスタックを拡張すべき
要素の数です。
スタック上に場所を確保したら、PUSHs マクロを使って値をスタックへ
プッシュします。
The pushed values will often need to be "mortal" (See
/Reference Counts and Mortality):
(TBT)
PUSHs(sv_2mortal(newSViv(an_integer)))
PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
PUSHs(sv_2mortal(newSVnv(a_double)))
PUSHs(sv_2mortal(newSVpv("Some String",0)))
これで、tzname を呼ぶ Perl プログラムでは、二つの値は
以下のように代入できます。
($standard_abbrev, $summer_abbrev) = POSIX::tzname;
スタックに値を積む、別の (おそらくはより簡単な) 方法は、 以下のマクロを使うことです。
XPUSHs(SV*)
こちらのマクロは、必要ならば自動的にスタックを調整してくれます。
このため、EXTEND をスタックを拡張するために呼ぶ必要はありません。
Despite their suggestions in earlier versions of this document the macros
(X)PUSH[iunp] are not suited to XSUBs which return multiple results.
For that, either stick to the (X)PUSHs macros shown above, or use the new
m(X)PUSH[iunp] macros instead; see /Putting a C value on Perl stack.
(TBT)
より詳しい情報は、perlxs と perlxstut を参照してください。
(CプログラムからのPerlルーチンの呼び出し)
C プログラムから Perl サブルーチンを呼び出すために使用することのできる ルーチンが 四つあります。 その四つは:
I32 call_sv(SV*, I32);
I32 call_pv(const char*, I32);
I32 call_method(const char*, I32);
I32 call_argv(const char*, I32, register char**);
最もよく使われるはずのものは、call_sv です。
引数 SV* には呼び出される Perl サブルーチンの名前か、その
サブルーチンへのリファレンスが含まれます。
二番目の引数には、そのサブルーチンが呼び出されたコンテキストを制御する
フラグが置かれます。
これはサブルーチンに引数が渡されたか渡されていないか、エラーを
どのようにトラップすべきなのか、どのように戻り値を返すのかを
制御するものです。
四つのルーチンはいずれも、サブルーチンが Perl スタック上に返した 引数の数を返します。
These routines used to be called perl_call_sv, etc., before Perl v5.6.0,
しかしこれらの名前は現在では非推奨です; 同じ名前のマクロが互換性のために
提供されています。
(TBT)
これらのルーチンを使うときには(call_argv を除いて)、プログラマが
Perl スタックを操作しなくてはなりません。
以下のマクロと関数が用意されています:
dSP
SP
PUSHMARK()
PUTBACK
SPAGAIN
ENTER
SAVETMPS
FREETMPS
LEAVE
XPUSH*()
POP*()
C から Perl を呼び出す約束ごとについての詳しい記述は perlcall を参照してください。
(メモリ割り当て)
(割り当て)
Perl API 関数と共に使うような全てのメモリはこのセクションで 説明されているマクロを使って扱うべきです。 マクロは実際の malloc の 実装と、perl で使われているものとの差を透過的にします。
Perl と一緒に配布されていて、あなたがこれを使うことを推奨されている malloc の変種です。 これは様々な大きさの未割り付けのメモリをプールしておき、 より早く割り付け要求に応えようとするものです。 しかしながら一部のプラットフォームでは、これは不法なmallocエラーや freeエラーを引き起こす可能性があります。
これら三つのマクロはメモリの割り付けのために使われます:
Newx(pointer, number, type);
Newxc(pointer, number, type, cast);
Newxz(pointer, number, type);
1 番目の引数 pointer は、新たにメモリを割り付けられる変数の
名前にします。
3 番目と 4 番目の引数 number と type は、指定された構造体を
どれだけ割り付けるのかを指定します。
引数 type は sizeof に渡されます。
Newxcに対する最後の引数 castは、引数 pointer が
引数 type と異なるときに使うべきものです。
Newx や Newxc とは異なり、Newxz は割り付けたメモリのすべてを
ゼロで埋めるために memzero を呼び出します。
Renew(pointer, number, type);
Renewc(pointer, number, type, cast);
Safefree(pointer)
上記の三つのマクロは、メモリのバッファーサイズを変更したりもう
使わなくなったメモリ領域を解放するために使われます。
Renew と
Renewc の引数は、“魔法のクッキー”引数が必要ないということを
除きそれぞれ New と Renewc に一致します。
Move(source, dest, number, type);
Copy(source, dest, number, type);
Zero(dest, number, type);
この三つのマクロは、それぞれ割り付けたメモリ領域に対する移動、
複写、ゼロで埋めるといったことに使われます。
source と dest という引数は、転送元と転送先の開始番地への
ポインタです。
Perl は、構造体 type の大きさ (sizeof 関数を使います)のインスタンスの
number 個分だけ、移動、複写、ゼロ埋めを行います。
最新リリースの Perl の開発では、Perl の「通常の」標準入出力ライブラリに 依存している部分を取り除くことと、Perl で別の標準入出力の実装が 使えるようにすることが試みられました。 これにより必然的に、Perl と共にコンパイルされた標準入出力の実装を 呼び出すような新しい抽象層が作られました。 すべての XSUB は、今では PerlIO 抽象層の関数を使うべきで、 これまで使っていた標準入出力に関してのすべての仮定はすべきではありません。
PerlIO 抽象化に関する詳しい記述は perlapio を参照してください。
(C での値を Perl スタックに入れる)
たくさんのオペコード(これは内部的な perl スタックマシンでの基本的な 操作です)が SV をスタックに置きます。 しかしながら、SV に対する最適化のようなものは(通常は)毎回 行なわれるわけではありません。 オペコードは解放されたり、生成されることのない特別に割り当てられた SVs (targets) を再利用します。
それぞれの targets は、一度だけ生成して(ただし、後述する Scratchpads and recursion を参照のこと)、オペコードがスタックに 整数値、倍精度実数値、文字列といったものを置くことを必要とするときに、 スタックに target を置きます。
この target をスタックに置くためのマクロが PUSHTARG です。
このマクロは、他の多くのマクロが (X)PUSH[iunp] を通じて間接的に
使っているのと同様に、幾つかのオペコードで直接使われています。
Because the target is reused, you must be careful when pushing multiple values on the stack. The following code will not do what you think: (TBT)
XPUSHi(10);
XPUSHi(20);
This translates as "set TARG to 10, push a pointer to TARG onto
the stack; set TARG to 20, push a pointer to TARG onto the stack".
At the end of the operation, the stack does not contain the values 10
and 20, but actually contains two pointers to TARG, which we have set
to 20.
(TBT)
If you need to push multiple different values then you should either use
the (X)PUSHs macros, or else use the new m(X)PUSH[iunp] macros,
none of which make use of TARG. The (X)PUSHs macros simply push an
SV* on the stack, which, as noted under /XSUBs and the Argument Stack,
will often need to be "mortal". The new m(X)PUSH[iunp] macros make
this a little easier to achieve by creating a new mortal for you (via
(X)PUSHmortal), pushing that onto the stack (extending it if necessary
in the case of the mXPUSH[iunp] macros), and then setting its value.
Thus, instead of writing this to "fix" the example above:
(TBT)
XPUSHs(sv_2mortal(newSViv(10)))
XPUSHs(sv_2mortal(newSViv(20)))
you can simply write: (TBT)
mXPUSHi(10)
mXPUSHi(20)
On a related note, if you do use (X)PUSH[iunp], then you're going to
need a dTARG in your variable declarations so that the *PUSH*
macros can make use of the local variable TARG. See also dTARGET
and dXSTARG.
(TBT)
(スクラッチパッド)
残っている疑問は、オペコードに対する targets である SV をいつ 生成するのかということでしょう。 その答えは、カレントユニット -- サブルーチンもしくは(サブルーチンの 外側にある文のためのオペコードのための)ファイル -- が コンパイルされたときです。 この間、特別な無名配列が生成されます。 これはカレントユニットのためのスクラッチパッド (scrachpad) と 呼ばれるものです。
スクラッチパッドはカレントユニットのためのレキシカルやオペコードの
ための target である SV を保持します。
SV があるスクラッチパッドを、
SV のフラグを見ることによって推測することができます。
レキシカルでは
SVs_PADMY されていて、targets では SVs_PADTMP が
セットされています。
オペコードと targets の間の対応は一対一ではありません。 あるユニットの翻訳木 (compile tree)にある異なるオペコードは、 これが一時変数の expected life と衝突していなければ同じ target を使うことが できます。
(スクラッチパッドと再帰)
コンパイルされたユニットがスクラッチパッド AV へのポインタを 保持しているということは、100% 本当のことではありません。 実際は、(初期値では)一要素の AV へのポインタを保持していて、この要素が スクラッチパッド AV なのです。 なぜ、こういう余計な間接レベルを必要としているのでしょう?
その答えは 再帰 と、おそらく スレッド です。 これら二つは同じサブルーチンに対する別々の実行ポインタを 生成しようとするかもしれません。 子サブルーチンが(呼び出す子サブルーチンを覆っている寿命を持つ) 親サブルーチンの一時変数を上書きしてしまわないように、 親と子では、異なるスクラッチパッドを持つようにすべきです (かつ、レキシカルは分けておくべきなのです!)。
各サブルーチンは、スクラッチパッドの(長さが 1 の)配列を伴って生成されます。 サブルーチンに対する各エントリーはその時点での再帰の深さが この配列の長さよりも大きくないことをチェックします。 そして、もしそうであれば、新たなスクラッチパッドが生成されて配列へと プッシュされます。
このスクラッチパッドにある targets は undef ですが、これらはすでに
正しいフラグによってマークされています。
(コンパイルされたコード)
(コード木)
ここで、Perl によって変換されたプログラムの内部形式を説明しましょう。 簡単な例から始めます。
$a = $b + $c;
これは次のような木構造へ変換されます(実際にはもっと複雑です)。
assign-to
/ \
+ $a
/ \
$b $c
この木構造は、Perl があなたのプログラムを解析したやり方を 反映していますが、実行の順序については反映していません。 ノードの実行順序を表わす木構造のノードを辿ろうとする別の 「スレッド」(thread) があります。 先の簡単な例では、次のようになります。
$b ---> $c ---> + ---> $a ---> assign-to
しかし、$a = $b + $c に対する実際の解析木はこれと異なります。
一部のノードが最適化されています。
その結果として、実際の木構造が私たちの単純な例よりも多くのノードを
持っていたとしても、その実行順序は同じになります。
(木を検査する)
perl をデバッグ用にコンパイルした(通常は Configure のコマンドラインで
-DDEBUGGING を使って行います)場合、Perl のコマンドラインで
-Dx を指定することによって解析木を検査することができます。
その出力はノード毎に数行を取り、$b+$c は以下のようになります。
5 TYPE = add ===> 6
TARG = 1
FLAGS = (SCALAR,KIDS)
{
TYPE = null ===> (4)
(was rv2sv)
FLAGS = (SCALAR,KIDS)
{
3 TYPE = gvsv ===> 4
FLAGS = (SCALAR)
GV = main::b
}
}
{
TYPE = null ===> (5)
(was rv2sv)
FLAGS = (SCALAR,KIDS)
{
4 TYPE = gvsv ===> 5
FLAGS = (SCALAR)
GV = main::c
}
}
この木には五つのノード(TYPE 毎にひとつ)があって、そのうちの
三つだけが最適化されないものです(左側に数字のあるもの)。
与えられたノードのすぐ下にある子供は同じレベルのインデントにある {} の
ペアに対応します。
したがって、このリストは以下の木に対応します。
add
/ \
null null
| |
gvsv gvsv
実行順序は ===> マークによって表わされますから、3 4 5 6
(ノード 6は、上にあるリストには含まれません)となります。
つまり、gvsv gvsv add whatever ということになります。
Each of these nodes represents an op, a fundamental operation inside the
Perl core. The code which implements each operation can be found in the
pp*.c files; the function which implements the op with type gvsv
is pp_gvsv, and so on. As the tree above shows, different ops have
different numbers of children: add is a binary operator, as one would
expect, and so has two children. To accommodate the various different
numbers of children, there are various types of op data structure, and
they link together in different ways.
(TBT)
The simplest type of op structure is OP: this has no children. Unary
operators, UNOPs, have one child, and this is pointed to by the
op_first field. Binary operators (BINOPs) have not only an
op_first field but also an op_last field. The most complex type of
op is a LISTOP, which has any number of children. In this case, the
first child is pointed to by op_first and the last child by
op_last. The children in between can be found by iteratively
following the op_sibling pointer from the first child to the last.
(TBT)
There are also two other op types: a PMOP holds a regular expression,
and has no children, and a LOOP may or may not have children. If the
op_children field is non-zero, it behaves like a LISTOP. To
complicate matters, if a UNOP is actually a null op after
optimization (see /Compile pass 2: context propagation) it will still
have children in accordance with its former type.
(TBT)
Another way to examine the tree is to use a compiler back-end module, such as B::Concise. (TBT)
この木構造は、yacc が perl プログラムを読み込んでその構造を解析している 間にコンパイラによって生成されます。 yacc はボトムアップで動作するので、perl によるコンパイルの最初のパスで 行なわれます。
perl 開発者にとって興味深いのは、このパスで行なわれるいくつかの
最適化でしょう。
これは、"check routines" とも呼ばれる最適化です。
ノード名と対応するチェックルーチンとの間の対応は opcode.pl に
記述されています(このファイルを修正した場合には、make regen_headers を
実行することを忘れないでください)。
チェックルーチンは、ノードが実行順序スレッドを除いて完全に 構築されたときに呼び出されます。 この時点では、構築されたノードに対する back-line が存在しないので、 トップレベルノードに対して、新たなノードを生成したりノードを 解放したりすることを含めて、ほとんどの操作を行うことができます。
このチェックルーチンは木に挿入すべきノードを返します(トップレベルの ノードが変更されていなければ、チェックルーチンはその引数を返します)。
規約により、チェックルーチンは ck_* のような名前を持ちます。
これらは通常サブルーチン new*OP (もしくは convert) から
呼び出されます(これらのサブルーチンは perly.y から呼び出されます)。
(コンパイルパス1a: 定数の畳み込み)
チェックルーチンが呼び出された直後に、返されたノードはコンパイル時 実行のためのチェックが行なわれます。 もしそうであれば(値が定数であると判定された)、そのノードは即座に 実行されて、「戻り値」に対応する部分木は 定数 ノードで置換され、 部分木が削除されます。
定数の畳み込み(constant folding)が働かなければ、実行順序スレッドが 生成されます。
(コンパイルパス2: コンテキスト伝播)
解析木の一部分のコンテキストがわかっているとき、それは木の末端へ 伝播します。 このとき、コンテキストは(実行時コンテキストの二種類ではなく) 無効、真偽値、スカラ、リスト、左辺値の五種類の値を持つことができます。 パス 1 とは対照的に、このパスではトップから末端へと処理が進みます。 あるノードのコンテキストは、その下にある部分のコンテキストを決定します。
コンテキストに依存した最適化はこのときに行なわれます。 この動作では解析木が(“スレッド”ポインタを通じて)後方参照を 含んでいるので、ノードをこの時に free() することはできません。 このステージでノードを最適化するのを許すために、対象となるノードは free() されるかわりに null() されます(つまり、そのノードの型が OP_NULL に変えられるということ)。
(コンパイルパス 3: 覗き穴最適化)
サブルーチン(もしくは eval かファイル)に対する解析木が生成された後で、
そのコードに対する追加パスが実行されます。
このパスはトップダウンでもボトムアップでもなく、(条件に対する
複雑さを伴った)実行順序です。
これらの最適化はサブルーチン peep() で行なわれます。
このステージで行なわれる最適化はパス 2 でのものと同じ制限に従います。
The compile tree is executed in a runops function. There are two runops
functions, in run.c and in dump.c. Perl_runops_debug is used
with DEBUGGING and Perl_runops_standard is used otherwise. For fine
control over the execution of the compile tree it is possible to provide
your own runops function.
(TBT)
It's probably best to copy one of the existing runops functions and change it to suit your needs. Then, in the BOOT section of your XS file, add the line: (TBT)
PL_runops = my_runops;
This function should be as efficient as possible to keep your programs running as fast as possible. (TBT)
dump functionsTo aid debugging, the source file dump.c contains a number of functions which produce formatted output of internal data structures. (TBT)
The most commonly used of these functions is Perl_sv_dump; it's used
for dumping SVs, AVs, HVs, and CVs. The Devel::Peek module calls
sv_dump to produce debugging output from Perl-space, so users of that
module should already be familiar with its format.
(TBT)
Perl_op_dump can be used to dump an OP structure or any of its
derivatives, and produces output similar to perl -Dx; in fact,
Perl_dump_eval will dump the main root of the code being evaluated,
exactly like -Dx.
(TBT)
Other useful functions are Perl_dump_sub, which turns a GV into an
op tree, Perl_dump_packsubs which calls Perl_dump_sub on all the
subroutines in a package like so: (Thankfully, these are all xsubs, so
there is no op tree)
(TBT)
(gdb) print Perl_dump_packsubs(PL_defstash)
SUB attributes::bootstrap = (xsub 0x811fedc 0)
SUB UNIVERSAL::can = (xsub 0x811f50c 0)
SUB UNIVERSAL::isa = (xsub 0x811f304 0)
SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
and Perl_dump_all, which dumps all the subroutines in the stash and
the op tree of the main root.
(TBT)
The Perl interpreter can be regarded as a closed box: it has an API for feeding it code or otherwise making it do things, but it also has functions for its own use. This smells a lot like an object, and there are ways for you to build Perl so that you can have multiple interpreters, with one interpreter represented either as a C structure, or inside a thread-specific structure. These structures contain all the context, the state of that interpreter. (TBT)
One macro controls the major Perl build flavor: MULTIPLICITY. The MULTIPLICITY build has a C structure that packages all the interpreter state. With multiplicity-enabled perls, PERL_IMPLICIT_CONTEXT is also normally defined, and enables the support for passing in a "hidden" first argument that represents all three data structures. MULTIPLICITY makes mutli-threaded perls possible (with the ithreads threading model, related to the macro USE_ITHREADS.) (TBT)
Two other "encapsulation" macros are the PERL_GLOBAL_STRUCT and
PERL_GLOBAL_STRUCT_PRIVATE (the latter turns on the former, and the
former turns on MULTIPLICITY.) The PERL_GLOBAL_STRUCT causes all the
internal variables of Perl to be wrapped inside a single global struct,
struct perl_vars, accessible as (globals) &PL_Vars or PL_VarsPtr or
the function Perl_GetVars(). The PERL_GLOBAL_STRUCT_PRIVATE goes
one step further, there is still a single struct (allocated in main()
either from heap or from stack) but there are no global data symbols
pointing to it. In either case the global struct should be initialised
as the very first thing in main() using Perl_init_global_struct() and
correspondingly tear it down after perl_free() using Perl_free_global_struct(),
please see miniperlmain.c for usage details. You may also need
to use dVAR in your coding to "declare the global variables"
when you are using them. dTHX does this for you automatically.
(TBT)
To see whether you have non-const data you can use a BSD-compatible nm:
(TBT)
nm libperl.a | grep -v ' [TURtr] '
If this displays any D or d symbols, you have non-const data.
(TBT)
For backward compatibility reasons defining just PERL_GLOBAL_STRUCT doesn't actually hide all symbols inside a big global struct: some PerlIO_xxx vtables are left visible. The PERL_GLOBAL_STRUCT_PRIVATE then hides everything (see how the PERLIO_FUNCS_DECL is used). (TBT)
All this obviously requires a way for the Perl internal functions to be either subroutines taking some kind of structure as the first argument, or subroutines taking nothing as the first argument. To enable these two very different ways of building the interpreter, the Perl source (as it does in so many other situations) makes heavy use of macros and subroutine naming conventions. (TBT)
First problem: deciding which functions will be public API functions and
which will be private. All functions whose names begin S_ are private
(think "S" for "secret" or "static"). All other functions begin with
"Perl_", but just because a function begins with "Perl_" does not mean it is
part of the API. (See /Internal Functions.) The easiest way to be sure a
function is part of the API is to find its entry in perlapi.
If it exists in perlapi, it's part of the API. If it doesn't, and you
think it should be (i.e., you need it for your extension), send mail via
perlbug explaining why you think it should be.
(TBT)
Second problem: there must be a syntax so that the same subroutine declarations and calls can pass a structure as their first argument, or pass nothing. To solve this, the subroutines are named and declared in a particular way. Here's a typical start of a static function used within the Perl guts: (TBT)
STATIC void S_incline(pTHX_ char *s)
STATIC becomes "static" in C, and may be #define'd to nothing in some configurations in future. (TBT)
A public function (i.e. part of the internal API, but not necessarily sanctioned for use in extensions) begins like this: (TBT)
void Perl_sv_setiv(pTHX_ SV* dsv, IV num)
pTHX_ is one of a number of macros (in perl.h) that hide the
details of the interpreter's context. THX stands for "thread", "this",
or "thingy", as the case may be. (And no, George Lucas is not involved. :-)
The first character could be 'p' for a prototype, 'a' for argument,
or 'd' for declaration, so we have pTHX, aTHX and dTHX, and
their variants.
(TBT)
When Perl is built without options that set PERL_IMPLICIT_CONTEXT, there is no first argument containing the interpreter's context. The trailing underscore in the pTHX_ macro indicates that the macro expansion needs a comma after the context argument because other arguments follow it. If PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the subroutine is not prototyped to take the extra argument. The form of the macro without the trailing underscore is used when there are no additional explicit arguments. (TBT)
When a core function calls another, it must pass the context. This
is normally hidden via macros. Consider sv_setiv. It expands into
something like this:
(TBT)
#ifdef PERL_IMPLICIT_CONTEXT
#define sv_setiv(a,b) Perl_sv_setiv(aTHX_ a, b)
/* can't do this for vararg functions, see below */
#else
#define sv_setiv Perl_sv_setiv
#endif
This works well, and means that XS authors can gleefully write: (TBT)
sv_setiv(foo, bar);
and still have it work under all the modes Perl could have been compiled with. (TBT)
This doesn't work so cleanly for varargs functions, though, as macros
imply that the number of arguments is known in advance. Instead we
either need to spell them out fully, passing aTHX_ as the first
argument (the Perl core tends to do this with functions like
Perl_warner), or use a context-free version.
(TBT)
The context-free version of Perl_warner is called
Perl_warner_nocontext, and does not take the extra argument. Instead
it does dTHX; to get the context from thread-local storage. We
#define warner Perl_warner_nocontext so that extensions get source
compatibility at the expense of performance. (Passing an arg is
cheaper than grabbing it from thread-local storage.)
(TBT)
You can ignore [pad]THXx when browsing the Perl headers/sources. Those are strictly for use within the core. Extensions and embedders need only be aware of [pad]THX. (TBT)
dTHR was introduced in perl 5.005 to support the older thread model.
The older thread model now uses the THX mechanism to pass context
pointers around, so dTHR is not useful any more. Perl 5.6.0 and
later still have it for backward source compatibility, but it is defined
to be a no-op.
(TBT)
When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call any functions in the Perl API will need to pass the initial context argument somehow. The kicker is that you will need to write it in such a way that the extension still compiles when Perl hasn't been built with PERL_IMPLICIT_CONTEXT enabled. (TBT)
There are three ways to do this. First, the easy but inefficient way, which is also the default, in order to maintain source compatibility with extensions: whenever XSUB.h is #included, it redefines the aTHX and aTHX_ macros to call a function that will return the context. Thus, something like: (TBT)
sv_setiv(sv, num);
in your extension will translate to this when PERL_IMPLICIT_CONTEXT is in effect: (TBT)
Perl_sv_setiv(Perl_get_context(), sv, num);
or to this otherwise: (TBT)
Perl_sv_setiv(sv, num);
You have to do nothing new in your extension to get this; since the Perl library provides Perl_get_context(), it will all just work. (TBT)
The second, more efficient way is to use the following template for your Foo.xs: (TBT)
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
STATIC void my_private_function(int arg1, int arg2);
STATIC void
my_private_function(int arg1, int arg2)
{
dTHX; /* fetch context */
... call many Perl API functions ...
}
[... etc ...]
MODULE = Foo PACKAGE = Foo
/* typical XSUB */
void
my_xsub(arg)
int arg
CODE:
my_private_function(arg, 10);
Note that the only two changes from the normal way of writing an
extension is the addition of a #define PERL_NO_GET_CONTEXT before
including the Perl headers, followed by a dTHX; declaration at
the start of every function that will call the Perl API. (You'll
know which functions need this, because the C compiler will complain
that there's an undeclared identifier in those functions.) No changes
are needed for the XSUBs themselves, because the XS() macro is
correctly defined to pass in the implicit context if needed.
(TBT)
The third, even more efficient way is to ape how it is done within the Perl guts: (TBT)
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* pTHX_ only needed for functions that call Perl API */
STATIC void my_private_function(pTHX_ int arg1, int arg2);
STATIC void
my_private_function(pTHX_ int arg1, int arg2)
{
/* dTHX; not needed here, because THX is an argument */
... call Perl API functions ...
}
[... etc ...]
MODULE = Foo PACKAGE = Foo
/* typical XSUB */
void
my_xsub(arg)
int arg
CODE:
my_private_function(aTHX_ arg, 10);
This implementation never has to fetch the context using a function call, since it is always passed as an extra argument. Depending on your needs for simplicity or efficiency, you may mix the previous two approaches freely. (TBT)
Never add a comma after pTHX yourself--always use the form of the
macro with the underscore for functions that take explicit arguments,
or the form without the argument for functions with no explicit arguments.
(TBT)
If one is compiling Perl with the -DPERL_GLOBAL_STRUCT the dVAR
definition is needed if the Perl global variables (see perlvars.h
or globvar.sym) are accessed in the function and dTHX is not
used (the dTHX includes the dVAR if necessary). One notices
the need for dVAR only with the said compile-time define, because
otherwise the Perl global variables are visible as-is.
(TBT)
If you create interpreters in one thread and then proceed to call them in another, you need to make sure perl's own Thread Local Storage (TLS) slot is initialized correctly in each of those threads. (TBT)
The perl_alloc and perl_clone API functions will automatically set
the TLS slot to the interpreter they created, so that there is no need to do
anything special if the interpreter is always accessed in the same thread that
created it, and that thread did not create or call any other interpreters
afterwards. If that is not the case, you have to set the TLS slot of the
thread before calling any functions in the Perl API on that particular
interpreter. This is done by calling the PERL_SET_CONTEXT macro in that
thread as the first thing you do:
(TBT)
/* do this before doing anything else with some_perl */ PERL_SET_CONTEXT(some_perl);
... other Perl API calls on some_perl go here ...
Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything that the interpreter knows about itself and pass it around, so too are there plans to allow the interpreter to bundle up everything it knows about the environment it's running on. This is enabled with the PERL_IMPLICIT_SYS macro. Currently it only works with USE_ITHREADS on Windows. (TBT)
This allows the ability to provide an extra pointer (called the "host" environment) for all the system calls. This makes it possible for all the system stuff to maintain their own state, broken down into seven C structures. These are thin wrappers around the usual system calls (see win32/perllib.c) for the default perl executable, but for a more ambitious host (like the one that would do fork() emulation) all the extra work needed to pretend that different interpreters are actually different "processes", would be done here. (TBT)
The Perl engine/interpreter and the host are orthogonal entities. There could be one or more interpreters in a process, and one or more "hosts", with free association between them. (TBT)
All of Perl's internal functions which will be exposed to the outside
world are prefixed by Perl_ so that they will not conflict with XS
functions or functions used in a program in which Perl is embedded.
Similarly, all global variables begin with PL_. (By convention,
static functions start with S_.)
(TBT)
Inside the Perl core, you can get at the functions either with or
without the Perl_ prefix, thanks to a bunch of defines that live in
embed.h. This header file is generated automatically from
embed.pl and embed.fnc. embed.pl also creates the prototyping
header files for the internal functions, generates the documentation
and a lot of other bits and pieces. It's important that when you add
a new function to the core or change an existing one, you change the
data in the table in embed.fnc as well. Here's a sample entry from
that table:
(TBT)
Apd |SV** |av_fetch |AV* ar|I32 key|I32 lval
The second column is the return type, the third column the name. Columns after that are the arguments. The first column is a set of flags: (TBT)
This function is a part of the public API. All such functions should also have 'd', very few do not. (TBT)
This function has a Perl_ prefix; i.e. it is defined as
Perl_av_fetch.
(TBT)
This function has documentation using the apidoc feature which we'll
look at in a second. Some functions have 'd' but not 'A'; docs are good.
(TBT)
Other available flags are: (TBT)
This is a static function and is defined as STATIC S_whatever, and
usually called within the sources as whatever(...).
(TBT)
This does not need a interpreter context, so the definition has no
pTHX, and it follows that callers don't use aTHX. (See
perlguts/Background and PERL_IMPLICIT_CONTEXT.)
(TBT)
This function never returns; croak, exit and friends.
(TBT)
This function takes a variable number of arguments, printf style.
The argument list should end with ..., like this:
(TBT)
Afprd |void |croak |const char* pat|...
This function is part of the experimental development API, and may change or disappear without notice. (TBT)
This function should not have a compatibility macro to define, say,
Perl_parse to parse. It must be called as Perl_parse.
(TBT)
この関数は Perl コアの外側へエクスポートされません。
これはマクロとして実装されています。
この関数は明示的にエクスポートされます。
この関数は Perl コアに含まれるエクステンションから見えます。
Binary backward compatibility; this function is a macro but also has
a Perl_ implementation (which is exported).
(TBT)
See the comments at the top of embed.fnc for others.
(TBT)
If you edit embed.pl or embed.fnc, you will need to run
make regen_headers to force a rebuild of embed.h and other
auto-generated files.
(TBT)
If you are printing IVs, UVs, or NVS instead of the stdio(3) style
formatting codes like %d, %ld, %f, you should use the
following macros for portability
(TBT)
IVdf IV in decimal
UVuf UV in decimal
UVof UV in octal
UVxf UV in hexadecimal
NVef NV %e-like
NVff NV %f-like
NVgf NV %g-like
These will take care of 64-bit integers and long doubles. For example: (TBT)
printf("IV is %"IVdf"\n", iv);
The IVdf will expand to whatever is the correct format for the IVs. (TBT)
If you are printing addresses of pointers, use UVxf combined with PTR2UV(), do not use %lx or %p. (TBT)
Because pointer size does not necessarily equal integer size, use the follow macros to do it right. (TBT)
PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)
例えば:
IV iv = ...;
SV *sv = INT2PTR(SV*, iv);
および
AV *av = ...;
UV uv = PTR2UV(av);
There are a couple of macros to do very basic exception handling in XS
modules. You have to define NO_XSLOCKS before including XSUB.h to
be able to use these macros:
(TBT)
#define NO_XSLOCKS
#include "XSUB.h"
You can use these macros if you call code that may croak, but you need to do some cleanup before giving control back to Perl. For example: (TBT)
dXCPT; /* set up necessary variables */
XCPT_TRY_START {
code_that_may_croak();
} XCPT_TRY_END
XCPT_CATCH
{
/* do cleanup here */
XCPT_RETHROW;
}
Note that you always have to rethrow an exception that has been
caught. Using these macros, it is not possible to just catch the
exception and ignore it. If you have to ignore the exception, you
have to use the call_* function.
(TBT)
The advantage of using the above macros is that you don't have
to setup an extra function for call_*, and that using these
macros is faster than using call_*.
(TBT)
There's an effort going on to document the internal functions and automatically produce reference manuals from them - perlapi is one such manual which details all the functions which are available to XS writers. perlintern is the autogenerated manual for the functions which are not part of the API and are supposedly for internal use only. (TBT)
Source documentation is created by putting POD comments into the C source, like this: (TBT)
/* =for apidoc sv_setiv
Copies an integer into the given SV. Does not handle 'set' magic. See C<sv_setiv_mg>.
=cut */
Please try and supply some documentation if you add functions to the Perl core. (TBT)
(後方互換性)
The Perl API changes over time. New functions are added or the interfaces
of existing functions are changed. The Devel::PPPort module tries to
provide compatibility code for some of these changes, so XS writers don't
have to code it themselves when supporting multiple versions of Perl.
(TBT)
Devel::PPPort generates a C header file ppport.h that can also
be run as a Perl script. To generate ppport.h, run:
(TBT)
perl -MDevel::PPPort -eDevel::PPPort::WriteFile
Besides checking existing XS code, the script can also be used to retrieve
compatibility information for various API calls using the --api-info
command line switch. For example:
(TBT)
% perl ppport.h --api-info=sv_magicext
詳細については、perldoc ppport.h を参照してください。
(Unicode 対応)
Perl 5.6.0 introduced Unicode support. It's important for porters and XS writers to understand this support and make sure that the code they write does not corrupt Unicode data. (TBT)
(ところで、Unicode って 何 ?)
In the olden, less enlightened times, we all used to use ASCII. Most of us did, anyway. The big problem with ASCII is that it's American. Well, no, that's not actually the problem; the problem is that it's not particularly useful for people who don't use the Roman alphabet. What used to happen was that particular languages would stick their own alphabet in the upper range of the sequence, between 128 and 255. Of course, we then ended up with plenty of variants that weren't quite ASCII, and the whole point of it being a standard was lost. (TBT)
Worse still, if you've got a language like Chinese or Japanese that has hundreds or thousands of characters, then you really can't fit them into a mere 256, so they had to forget about ASCII altogether, and build their own systems using pairs of numbers to refer to one character. (TBT)
To fix this, some people formed Unicode, Inc. and produced a new character set containing all the characters you can possibly think of and more. There are several ways of representing these characters, and the one Perl uses is called UTF-8. UTF-8 uses a variable number of bytes to represent a character. You can learn more about Unicode and Perl's Unicode model in perlunicode. (TBT)
(UTF-8 文字列を認識するには?)
You can't. This is because UTF-8 data is stored in bytes just like
non-UTF-8 data. The Unicode character 200, (0xC8 for you hex types)
capital E with a grave accent, is represented by the two bytes
v196.172. Unfortunately, the non-Unicode string chr(196).chr(172)
has that byte sequence as well. So you can't tell just by looking - this
is what makes Unicode input an interesting problem.
(TBT)
In general, you either have to know what you're dealing with, or you
have to guess. The API function is_utf8_string can help; it'll tell
you if a string contains only valid UTF-8 characters. However, it can't
do the work for you. On a character-by-character basis, is_utf8_char
will tell you whether the current character in a string is valid UTF-8.
(TBT)
As mentioned above, UTF-8 uses a variable number of bytes to store a
character. Characters with values 0...127 are stored in one byte, just
like good ol' ASCII. Character 128 is stored as v194.128; this
continues up to character 191, which is v194.191. Now we've run out of
bits (191 is binary 10111111) so we move on; 192 is v195.128. And
so it goes on, moving to three bytes at character 2048.
(TBT)
Assuming you know you're dealing with a UTF-8 string, you can find out
how long the first character in it is with the UTF8SKIP macro:
(TBT)
char *utf = "\305\233\340\240\201";
I32 len;
len = UTF8SKIP(utf); /* len is 2 here */
utf += len;
len = UTF8SKIP(utf); /* len is 3 here */
Another way to skip over characters in a UTF-8 string is to use
utf8_hop, which takes a string and a number of characters to skip
over. You're on your own about bounds checking, though, so don't use it
lightly.
(TBT)
All bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you need to do something special with this character like this (the UTF8_IS_INVARIANT() is a macro that tests whether the byte can be encoded as a single byte even in UTF-8): (TBT)
U8 *utf;
UV uv; /* Note: a UV, not a U8, not a char */
if (!UTF8_IS_INVARIANT(*utf))
/* Must treat this as UTF-8 */
uv = utf8_to_uv(utf);
else
/* OK to treat this character as a byte */
uv = *utf;
You can also see in that example that we use utf8_to_uv to get the
value of the character; the inverse function uv_to_utf8 is available
for putting a UV into UTF-8:
(TBT)
if (!UTF8_IS_INVARIANT(uv))
/* Must treat this as UTF8 */
utf8 = uv_to_utf8(utf8, uv);
else
/* OK to treat this character as a byte */
*utf8++ = uv;
You must convert characters to UVs using the above functions if
you're ever in a situation where you have to match UTF-8 and non-UTF-8
characters. You may not skip over UTF-8 characters in this case. If you
do this, you'll lose the ability to match hi-bit non-UTF-8 characters;
for instance, if your UTF-8 string contains v196.172, and you skip
that character, you can never match a chr(200) in a non-UTF-8 string.
So don't do that!
(TBT)
Currently, Perl deals with Unicode strings and non-Unicode strings
slightly differently. A flag in the SV, SVf_UTF8, indicates that the
string is internally encoded as UTF-8. Without it, the byte value is the
codepoint number and vice versa (in other words, the string is encoded
as iso-8859-1). You can check and manipulate this flag with the
following macros:
(TBT)
SvUTF8(sv)
SvUTF8_on(sv)
SvUTF8_off(sv)
This flag has an important effect on Perl's treatment of the string: if
Unicode data is not properly distinguished, regular expressions,
length, substr and other string handling operations will have
undesirable results.
(TBT)
The problem comes when you have, for instance, a string that isn't flagged as UTF-8, and contains a byte sequence that could be UTF-8 - especially when combining non-UTF-8 and UTF-8 strings. (TBT)
Never forget that the SVf_UTF8 flag is separate to the PV value; you
need be sure you don't accidentally knock it off while you're
manipulating SVs. More specifically, you cannot expect to do this:
(TBT)
SV *sv;
SV *nsv;
STRLEN len;
char *p;
p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);
The char* string does not tell you the whole story, and you can't
copy or reconstruct an SV just by copying the string value. Check if the
old SV has the UTF8 flag set, and act accordingly:
(TBT)
p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);
if (SvUTF8(sv))
SvUTF8_on(nsv);
In fact, your frobnicate function should be made aware of whether or
not it's dealing with UTF-8 data, so that it can handle the string
appropriately.
(TBT)
Since just passing an SV to an XS function and copying the data of
the SV is not enough to copy the UTF8 flags, even less right is just
passing a char * to an XS function.
(TBT)
If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade one of the strings to UTF-8. If you've got an SV, the easiest way to do this is: (TBT)
sv_utf8_upgrade(sv);
However, you must not do this, for example: (TBT)
if (!SvUTF8(left))
sv_utf8_upgrade(left);
If you do this in a binary operator, you will actually change one of the strings that came into the operator, and, while it shouldn't be noticeable by the end user, it can cause problems in deficient code. (TBT)
Instead, bytes_to_utf8 will give you a UTF-8-encoded copy of its
string argument. This is useful for having the data available for
comparisons and so on, without harming the original SV. There's also
utf8_to_bytes to go the other way, but naturally, this will fail if
the string contains any characters above 255 that can't be represented
in a single byte.
(TBT)
(他に知っておくべきことは?)
実際にはありません。 単に以下のことを覚えておいてください:
There's no way to tell if a string is UTF-8 or not. You can tell if an SV
is UTF-8 by looking at is SvUTF8 flag. Don't forget to set the flag if
something should be UTF-8. Treat the flag as part of the PV, even though
it's not - if you pass on the PV to somewhere, pass on the flag too.
(TBT)
If a string is UTF-8, always use utf8_to_uv to get at the value,
unless UTF8_IS_INVARIANT(*s) in which case you can use *s.
(TBT)
When writing a character uv to a UTF-8 string, always use
uv_to_utf8, unless UTF8_IS_INVARIANT(uv)) in which case
you can use *s = uv.
(TBT)
Mixing UTF-8 and non-UTF-8 strings is tricky. Use bytes_to_utf8 to get
a new string which is UTF-8 encoded. There are tricks you can use to
delay deciding whether you need to use a UTF-8 string until you get to a
high character - HALF_UPGRADE is one of those.
(TBT)
Custom operator support is a new experimental feature that allows you to
define your own ops. This is primarily to allow the building of
interpreters for other languages in the Perl core, but it also allows
optimizations through the creation of "macro-ops" (ops which perform the
functions of multiple ops which are usually executed together, such as
gvsv, gvsv, add.)
(TBT)
This feature is implemented as a new op type, OP_CUSTOM. The Perl
core does not "know" anything special about this op type, and so it will
not be involved in any optimizations. This also means that you can
define your custom ops to be any op structure - unary, binary, list and
so on - you like.
(TBT)
It's important to know what custom operators won't do for you. They
won't let you add new syntax to Perl, directly. They won't even let you
add new keywords, directly. In fact, they won't change the way Perl
compiles a program at all. You have to do those changes yourself, after
Perl has compiled the program. You do this either by manipulating the op
tree using a CHECK block and the B::Generate module, or by adding
a custom peephole optimizer with the optimize module.
(TBT)
When you do this, you replace ordinary Perl ops with custom ops by
creating ops with the type OP_CUSTOM and the pp_addr of your own
PP function. This should be defined in XS code, and should look like
the PP ops in pp_*.c. You are responsible for ensuring that your op
takes the appropriate number of values from the stack, and you are
responsible for adding stack marks if necessary.
(TBT)
You should also "register" your op with the Perl interpreter so that it
can produce sensible error and warning messages. Since it is possible to
have multiple custom ops within the one "logical" op type OP_CUSTOM,
Perl uses the value of o->op_ppaddr as a key into the
PL_custom_op_descs and PL_custom_op_names hashes. This means you
need to enter a name and description for your op at the appropriate
place in the PL_custom_op_names and PL_custom_op_descs hashes.
(TBT)
Forthcoming versions of B::Generate (version 1.0 and above) should
directly support the creation of custom ops by name.
(TBT)
Until May 1997, this document was maintained by Jeff Okamoto <okamoto@corp.hp.com>. It is now maintained as part of Perl itself by the Perl 5 Porters <perl5-porters@perl.org>. (TBT)
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy. (TBT)
perlapi(1), perlintern(1), perlxs(1), perlembed(1)