diff --git a/doc/extension.ja.rdoc b/doc/extension.ja.rdoc index a943f7a1094b2f..8c382dd7a9b6f9 100644 --- a/doc/extension.ja.rdoc +++ b/doc/extension.ja.rdoc @@ -31,42 +31,42 @@ VALUEからCにとって意味のあるデータを取り出すためには Rubyにはユーザが使う可能性のある以下のタイプがあります. -T_NIL :: nil -T_OBJECT :: 通常のオブジェクト -T_CLASS :: クラス -T_MODULE :: モジュール -T_FLOAT :: 浮動小数点数 -T_STRING :: 文字列 -T_REGEXP :: 正規表現 -T_ARRAY :: 配列 -T_HASH :: 連想配列 -T_STRUCT :: (Rubyの)構造体 -T_BIGNUM :: 多倍長整数 -T_FIXNUM :: Fixnum(31bitまたは63bit長整数) -T_COMPLEX :: 複素数 -T_RATIONAL :: 有理数 -T_FILE :: 入出力 -T_TRUE :: 真 -T_FALSE :: 偽 -T_DATA :: データ -T_SYMBOL :: シンボル ++T_NIL+ :: +nil+ ++T_OBJECT+ :: 通常のオブジェクト ++T_CLASS+ :: クラス ++T_MODULE+ :: モジュール ++T_FLOAT+ :: 浮動小数点数 ++T_STRING+ :: 文字列 ++T_REGEXP+ :: 正規表現 ++T_ARRAY+ :: 配列 ++T_HASH+ :: 連想配列 ++T_STRUCT+ :: (Rubyの)構造体 ++T_BIGNUM+ :: 多倍長整数 ++T_FIXNUM+ :: Fixnum(31bitまたは63bit長整数) ++T_COMPLEX+ :: 複素数 ++T_RATIONAL+ :: 有理数 ++T_FILE+ :: 入出力 ++T_TRUE+ :: 真 ++T_FALSE+ :: 偽 ++T_DATA+ :: データ ++T_SYMBOL+ :: シンボル その他に内部で利用されている以下のタイプがあります. - T_ICLASS - T_MATCH - T_UNDEF - T_NODE - T_ZOMBIE ++T_ICLASS+ :: includeされたモジュール ++T_MATCH+ :: MatchDataオブジェクト ++T_UNDEF+ :: 未定義値 ++T_NODE+ :: シンタックスツリーのノード ++T_ZOMBIE+ :: 解放待ち中のオブジェクト ほとんどのタイプはCの構造体で実装されています. === VALUEのデータタイプをチェックする -ruby.hではTYPE()というマクロが定義されていて,VALUEのデータ -タイプを知ることが出来ます.TYPE()マクロは上で紹介したT_XXXX -の形式の定数を返します.VALUEのデータタイプに応じて処理する -場合には,TYPE()の値で分岐することになります. +ruby.hではTYPE()というマクロが定義されていて,VALUEのデータ +タイプを知ることが出来ます.TYPE()マクロは上で紹介した+T_XXXX+ +の形式の定数を返します.VALUEのデータタイプに応じて処理する場合には, +TYPE()の値で分岐することになります. switch (TYPE(obj)) { case T_FIXNUM: @@ -89,70 +89,67 @@ ruby.hではTYPE()というマクロが定義されていて,VALUEのデータ void Check_Type(VALUE value, int type) -この関数はvalueがtypeで無ければ,例外を発生させます.引数と -して与えられたVALUEのデータタイプが正しいかどうかチェックす -るためには,この関数を使います. +この関数は _value_ が _type_ で無ければ,例外を発生させます.引数として +与えられたVALUEのデータタイプが正しいかどうかチェックするためには,この +関数を使います. -FIXNUMとNILに関してはより高速な判別マクロが用意されています. ++FIXNUM+と+NIL+に関してはより高速な判別マクロが用意されています. FIXNUM_P(obj) NIL_P(obj) === VALUEをCのデータに変換する -データタイプがT_NIL,T_FALSE,T_TRUEである時,データはそれぞ -れnil,false,trueです.このデータタイプのオブジェクトはひと -つずつしか存在しません. - -データタイプがT_FIXNUMの時,これは31bitまたは63bitのサイズを -持つ整数です.longのサイズが32bitのプラットフォームであれば -31bitに,longのサイズが64bitのプラットフォームであれば63bit -になります. FIXNUM を C の整数に変換するためにはマクロ -「FIX2INT()」または「FIX2LONG()」を使います.これらのマクロ -を使用する際には事前にデータタイプがFIXNUMであることを確認す -る必要がありますが,比較的高速に変換を行うことができます.ま -た,「FIX2LONG()」は例外を発生しませんが,「FIX2INT()」は変 -換結果がintのサイズに収まらない場合には例外を発生します. -それから,FIXNUMに限らずRubyのデータを整数に変換する -「NUM2INT()」および「NUM2LONG()」というマクロがあります.こ -れらのマクロはデータタイプのチェック無しで使えます -(整数に変換できない場合には例外が発生する).同様にチェック無し -で使える変換マクロはdoubleを取り出す「NUM2DBL()」があります. - -char* を取り出す場合, StringValue() と StringValuePtr() +データタイプが+T_NIL+,+T_FALSE+,+T_TRUE+である時,データはそれぞれ ++nil+,+false+,+true+です.このデータタイプのオブジェクトはひとつずつし +か存在しません. + +データタイプが +T_FIXNUM+の時,これは31bitまたは63bitのサイズを持つ整数 +です.longのサイズが32bitのプラットフォームであれば31bitに,longのサイズ +が64bitのプラットフォームであれば63bitになります. +FIXNUM+を C の整数に +変換するためにはマクロ「FIX2INT()」または「FIX2LONG()」 +を使います.これらのマクロを使用する際には事前にデータタイプが+FIXNUM+で +あることを確認する必要がありますが,比較的高速に変換を行うことができます. +また,「FIX2LONG()」は例外を発生しませんが, +「FIX2INT()」は変換結果がintのサイズに収まらない場合には例外を +発生します.それから,FIXNUMに限らずRubyのデータを整数に変換する +「NUM2INT()」および「NUM2LONG()」というマクロがありま +す.これらのマクロはデータタイプのチェック無しで使えます(整数に変換でき +ない場合には例外が発生する).同様にチェック無しで使える変換マクロは +doubleを取り出す「NUM2DBL()」があります. + +char* を取り出す場合, StringValue()StringValuePtr() を使います. -StringValue(var) は var が String -であれば何もせず,そうでなければ var を var.to_str() の結果 -に置き換えるマクロ,StringValuePtr(var) は同様に var を -String に置き換えてから var のバイト列表現に対する char* を -返すマクロです.var の内容を直接置き換える処理が入るので, -var は lvalue である必要があります. -また,StringValuePtr() に類似した StringValueCStr() というマ -クロもあります.StringValueCStr(var) は var を String に置き -換えてから var の文字列表現に対する char* を返します.返され -る文字列の末尾には NUL 文字が付加されます.なお,途中に NUL -文字が含まれる場合は ArgumentError が発生します. -一方,StringValuePtr() では,末尾に NUL 文字がある保証はなく, -途中に NUL 文字が含まれている可能性もあります. +StringValue(var) は _var_ が Stringであれば何もせず,そうでなけ +れば _var_ をvar.to_str()の結果に置き換えるマクロ, +StringValuePtr(var)は同様に _var_ をString に置き換えてから +_var_ のバイト列表現に対する char* を返すマクロです._var_ の内容を直接 +置き換える処理が入るので,_var_ は lvalue である必要があります.また, +StringValuePtr() に類似した StringValueCStr()というマ +クロもあります.StringValueCStr(var)は _var_ を String に置き換 +えてから _var_ の文字列表現に対する char* を返します.返される文字列の末 +尾には NUL 文字が付加されます.なお,途中に NUL文字が含まれる場合は +ArgumentError が発生します.一方,StringValuePtr()では,末尾に +NUL 文字がある保証はなく,途中に NUL 文字が含まれている可能性もあります. それ以外のデータタイプは対応するCの構造体があります.対応す る構造体のあるVALUEはそのままキャスト(型変換)すれば構造体の ポインタに変換できます. -構造体は「struct RXxxxx」という名前でruby.hで定義されていま -す.例えば文字列は「struct RString」です.実際に使う可能性が +構造体は「struct RXxxxx」という名前でruby.hで定義されていま +す.例えば文字列は「struct RString」です.実際に使う可能性が あるのは文字列と配列くらいだと思います. -ruby.hでは構造体へキャストするマクロも「RXXXXX()」(全部大文 -字にしたもの)という名前で提供されています(例: RSTRING()).た -だし、構造体への直接のアクセスはできるだけ避け,対応する -rb_xxxx() といった関数を使うようにして下さい.例えば,配列の -要素へアクセスする場合は,rb_ary_entry(ary, offset), -rb_ary_store(ary, offset, obj) を利用するようにして下さい. +ruby.hでは構造体へキャストするマクロも「RXXXXX()」(全部大文字にしたもの)と +いう名前で提供されています(例: RSTRING()).ただし,構造体への +直接のアクセスはできるだけ避け,対応するrb_xxxx() といった関数を使うよ +うにして下さい.例えば,配列の要素へアクセスする場合は, +rb_ary_entry(ary, offset)rb_ary_store(ary, offset, +obj) を利用するようにして下さい. -構造体からデータを取り出すマクロが提供されています.文字列 -strの長さを得るためには「RSTRING_LEN(str)」とし,文字列strを -char*として得るためには「RSTRING_PTR(str)」とします. +構造体からデータを取り出すマクロが提供されています.文字列 _str_ の長さ +を得るためには「RSTRING_LEN(str)」とし,文字列 _str_ をchar*と +して得るためには「RSTRING_PTR(str)」とします. Rubyの構造体を直接アクセスする時に気をつけなければならないこ とは,配列や文字列の構造体の中身は参照するだけで,直接変更し @@ -185,12 +182,12 @@ FIXNUMに関しては変換マクロを経由する必要があります.Cの からVALUEに変換するマクロは以下のものがあります.必要に応じ て使い分けてください. -INT2FIX() :: もとの整数が31bitまたは63bit以内に収まる自信 - がある時 -INT2NUM() :: 任意の整数からVALUEへ +INT2FIX() :: もとの整数が31bitまたは63bit以内に収まる自信 + がある時 +INT2NUM() :: 任意の整数からVALUEへ -INT2NUM()は整数がFIXNUMの範囲に収まらない場合,Bignumに変換 -してくれます(が,少し遅い). +INT2NUM()は整数がFIXNUMの範囲に収まらない場合,Bignumに変換し +てくれます(が,少し遅い). === Rubyのデータを操作する @@ -203,126 +200,126 @@ Rubyが用意している関数を用いてください. ==== 文字列に対する関数 -rb_str_new(const char *ptr, long len) :: +rb_str_new(const char *ptr, long len) :: 新しいRubyの文字列を生成する. -rb_str_new2(const char *ptr) :: -rb_str_new_cstr(const char *ptr) :: +rb_str_new2(const char *ptr) :: +rb_str_new_cstr(const char *ptr) :: Cの文字列からRubyの文字列を生成する.この関数の機能は - rb_str_new(ptr, strlen(ptr))と同等である. + rb_str_new(ptr, strlen(ptr))と同等である. -rb_str_new_literal(const char *ptr) :: +rb_str_new_literal(const char *ptr) :: Cのリテラル文字列からRubyの文字列を生成する. -rb_str_append(VALUE str1, VALUE str2) :: +rb_str_append(VALUE str1, VALUE str2) :: - Rubyの文字列str1にRubyの文字列str2を追加する. + Rubyの文字列 _str1_ にRubyの文字列 _str2_ を追加する. -rb_sprintf(const char *format, ...) :: -rb_vsprintf(const char *format, va_list ap) :: +rb_sprintf(const char *format, ...) :: +rb_vsprintf(const char *format, va_list ap) :: - Cの文字列formatと続く引数をprintf(3)のフォーマットにしたがって + Cの文字列 _format_ と続く引数をprintf(3)のフォーマットにしたがって 整形し,Rubyの文字列を生成する. - 注意: "%"PRIsVALUEがObject#to_s('+'フラグが指定されている - ときはObject#inspect)を使ったVALUEの出力に利用できる.これ - は"%i"と衝突するため,整数には"%d"を使用すること. + 注意: "%"PRIsVALUEが Object#to_s('+'フラグが指定されている + ときは Object#inspect)を使ったVALUEの出力に利用できる.これ + は"%i"と衝突するため,整数には"%d"を使用すること. -rb_str_cat(VALUE str, const char *ptr, long len) :: +rb_str_cat(VALUE str, const char *ptr, long len) :: - Rubyの文字列strにlenバイトの文字列ptrを追加する. + Rubyの文字列 _str_ に _len_ バイトの文字列 _ptr_ を追加する. -rb_str_cat2(VALUE str, const char* ptr) :: -rb_str_cat_cstr(VALUE str, const char* ptr) :: +rb_str_cat2(VALUE str, const char* ptr) :: +rb_str_cat_cstr(VALUE str, const char* ptr) :: - Rubyの文字列strにCの文字列ptrを追加する.この関数の機能は - rb_str_cat(str, ptr, strlen(ptr))と同等である. + Rubyの文字列 _str_ にCの文字列 _ptr_ を追加する.この関数の機能は + rb_str_cat(str, ptr, strlen(ptr))と同等である. -rb_str_catf(VALUE str, const char* format, ...) :: -rb_str_vcatf(VALUE str, const char* format, va_list ap) :: +rb_str_catf(VALUE str, const char* format, ...) :: +rb_str_vcatf(VALUE str, const char* format, va_list ap) :: - Cの文字列formatと続く引数をprintf(3)のフォーマットにしたがって + Cの文字列 _format_ と続く引数をprintf(3)のフォーマットにしたがって 整形し,Rubyの文字列strに追加する.この関数の機能は,それぞれ - rb_str_append(str, rb_sprintf(format, ...)) や - rb_str_append(str, rb_vsprintf(format, ap)) と同等である. + rb_str_append(str, rb_sprintf(format, ...)) や + rb_str_append(str, rb_vsprintf(format, ap)) と同等である. -rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) :: -rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) :: +rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) :: +rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) :: 指定されたエンコーディングでRubyの文字列を生成する. -rb_enc_str_new_literal(const char *ptr, rb_encoding *enc) :: +rb_enc_str_new_literal(const char *ptr, rb_encoding *enc) :: Cのリテラル文字列から指定されたエンコーディングでRubyの文字列を生成する. -rb_usascii_str_new(const char *ptr, long len) :: -rb_usascii_str_new_cstr(const char *ptr) :: +rb_usascii_str_new(const char *ptr, long len) :: +rb_usascii_str_new_cstr(const char *ptr) :: エンコーディングがUS-ASCIIのRubyの文字列を生成する. -rb_usascii_str_new_literal(const char *ptr) :: +rb_usascii_str_new_literal(const char *ptr) :: Cのリテラル文字列からエンコーディングがUS-ASCIIのRubyの文字列を生成する. -rb_utf8_str_new(const char *ptr, long len) :: -rb_utf8_str_new_cstr(const char *ptr) :: +rb_utf8_str_new(const char *ptr, long len) :: +rb_utf8_str_new_cstr(const char *ptr) :: エンコーディングがUTF-8のRubyの文字列を生成する. -rb_utf8_str_new_literal(const char *ptr) :: +rb_utf8_str_new_literal(const char *ptr) :: Cのリテラル文字列からエンコーディングがUTF-8のRubyの文字列を生成する. -rb_str_resize(VALUE str, long len) :: +rb_str_resize(VALUE str, long len) :: - Rubyの文字列のサイズをlenバイトに変更する.strの長さは前 - 以てセットされていなければならない.lenが元の長さよりも短 - い時は,lenバイトを越えた部分の内容は捨てられる.lenが元 + Rubyの文字列のサイズを _len_ バイトに変更する._str_ の長さは前 + 以てセットされていなければならない._len_ が元の長さよりも短 + い時は,_len_ バイトを越えた部分の内容は捨てられる._len_ が元 の長さよりも長い時は,元の長さを越えた部分の内容は保存さ れないでゴミになるだろう.この関数の呼び出しによって - RSTRING_PTR(str)が変更されるかもしれないことに注意. + RSTRING_PTR(str)が変更されるかもしれないことに注意. -rb_str_set_len(VALUE str, long len) :: +rb_str_set_len(VALUE str, long len) :: - Rubyの文字列のサイズをlenバイトにセットする.strが変更可 - 能でなければ例外が発生する.RSTRING_LEN(str)とは無関係に, - lenバイトまでの内容は保存される.lenはstrの容量を越えてい + Rubyの文字列のサイズを _len_ バイトにセットする._str_ が変更可 + 能でなければ例外が発生する.RSTRING_LEN(str)とは無関係に, + len_ バイトまでの内容は保存される._len_ は _str_ の容量を越えてい てはならない. -rb_str_modify(VALUE str) :: +rb_str_modify(VALUE str) :: - Rubyの文字列の変更する準備をする.strが変更可能でなければ例 - 外が発生する.strのバッファが共有されている場合は,新しいバッ - ファを割り当てて共有されていない状態にする.RSTRING_PTRを使っ - て中身を変更したり,rb_str_set_lenを呼んだりする前には, + Rubyの文字列の変更する準備をする._str_ が変更可能でなければ例 + 外が発生する._str_ のバッファが共有されている場合は,新しいバッ + ファを割り当てて共有されていない状態にする.+RSTRING_PTR+ を使っ + て中身を変更したり,+rb_str_set_len+ を呼んだりする前には, 必ずこの関数を呼ばなけれならない. ==== 配列に対する関数 -rb_ary_new() :: +rb_ary_new() :: 要素が0の配列を生成する. -rb_ary_new2(long len) :: -rb_ary_new_capa(long len) :: +rb_ary_new2(long len) :: +rb_ary_new_capa(long len) :: - 要素が0の配列を生成する.len要素分の領域をあらかじめ割り + 要素が0の配列を生成する._len_ 要素分の領域をあらかじめ割り 当てておく. -rb_ary_new3(long n, ...) :: -rb_ary_new_from_args(long n, ...) :: +rb_ary_new3(long n, ...) :: +rb_ary_new_from_args(long n, ...) :: - 引数で指定したn要素を含む配列を生成する. + 引数で指定した _n_ 要素を含む配列を生成する. -rb_ary_new4(long n, VALUE *elts) :: -rb_ary_new_from_values(long n, VALUE *elts) :: +rb_ary_new4(long n, VALUE *elts) :: +rb_ary_new_from_values(long n, VALUE *elts) :: - 配列で与えたn要素の配列を生成する. + 配列で与えた _n_ 要素の配列を生成する. -rb_ary_to_ary(VALUE obj) :: +rb_ary_to_ary(VALUE obj) :: オブジェクトを配列に変換する. Object#to_aryと同等である. @@ -331,32 +328,32 @@ rb_ary_to_ary(VALUE obj) :: 引数aryに配列を渡さなければならない. さもないと コアを吐く. -rb_ary_aref(int argc, const VALUE *argv, VALUE ary) :: +rb_ary_aref(int argc, const VALUE *argv, VALUE ary) :: Array#[]と同等. -rb_ary_entry(VALUE ary, long offset) :: +rb_ary_entry(VALUE ary, long offset) :: - ary\[offset] + ary[offset] -rb_ary_store(VALUE ary, long offset, VALUE obj) :: +rb_ary_store(VALUE ary, long offset, VALUE obj) :: - ary\[offset] = obj + ary[offset] = obj -rb_ary_subseq(VALUE ary, long beg, long len) :: +rb_ary_subseq(VALUE ary, long beg, long len) :: - ary[beg, len] + ary[beg, len] -rb_ary_push(VALUE ary, VALUE val) :: -rb_ary_pop(VALUE ary) :: -rb_ary_shift(VALUE ary) :: -rb_ary_unshift(VALUE ary, VALUE val) :: +rb_ary_push(VALUE ary, VALUE val) :: +rb_ary_pop(VALUE ary) :: +rb_ary_shift(VALUE ary) :: +rb_ary_unshift(VALUE ary, VALUE val) :: - ary.push, ary.pop, ary.shift, ary.unshift + ary.push(val), ary.pop, ary.shift, ary.unshift(val) -rb_ary_cat(VALUE ary, const VALUE *ptr, long len) :: +rb_ary_cat(VALUE ary, const VALUE *ptr, long len) :: - 配列aryにptrからlen個のオブジェクトを追加する. + 配列 _ary_ に _ptr_ から _len_ 個のオブジェクトを追加する. == Rubyの機能を使う @@ -409,14 +406,14 @@ Rubyで提供されている関数を使えばRubyインタプリタに新しい けるクラスメソッドとして,クラスに対する特異メソッドが使われ ます. -これらの関数の argcという引数はCの関数へ渡される引数の数(と -形式)を決めます.argcが0以上の時は関数に引き渡す引数の数を意 +これらの関数の _argc_ という引数はCの関数へ渡される引数の数(と +形式)を決めます._argc_ が0以上の時は関数に引き渡す引数の数を意 味します.16個以上の引数は使えません(が,要りませんよね,そ -んなに).実際の関数には先頭の引数としてselfが与えられますの +んなに).実際の関数には先頭の引数として _self_ が与えられますの で,指定した数より1多い引数を持つことになります. -argcが負の時は引数の数ではなく,形式を指定したことになります. -argcが-1の時は引数を配列に入れて渡されます.argcが-2の時は引 +_argc_ が負の時は引数の数ではなく,形式を指定したことになります. +_argc_ が-1の時は引数を配列に入れて渡されます._argc_ が-2の時は引 数はRubyの配列として渡されます. メソッドを定義する関数はまだいくつかあります. ひとつはメソッド @@ -435,10 +432,10 @@ private/protectedなメソッドを定義するふたつの関数があります privateメソッドとは関数形式でしか呼び出すことの出来ないメソッ ドです. -最後に, rb_define_module関数はモジュール関数を定義します. +最後に, +rb_define_module+ 関数はモジュール関数を定義します. モジュール関数とはモジュールの特異メソッドであり,同時に -privateメソッドでもあるものです.例をあげるとMathモジュール -のsqrt()などがあげられます.このメソッドは +privateメソッドでもあるものです.例をあげると Math モジュール +の +sqrt+ などがあげられます.このメソッドは Math.sqrt(4) @@ -453,7 +450,7 @@ privateメソッドでもあるものです.例をあげるとMathモジュー void rb_define_module_function(VALUE module, const char *name, VALUE (*func)(ANYARGS), int argc) -関数的メソッド(Kernelモジュールのprivate method)を定義するた +関数的メソッド(Kernel モジュールのprivate method)を定義するた めの関数は以下の通りです. void rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc) @@ -466,13 +463,13 @@ privateメソッドでもあるものです.例をあげるとMathモジュー void rb_define_attr(VALUE klass, const char *name, int read, int write) -クラスメソッドallocateを定義したり削除したりするための関数は +クラスメソッド +allocate+ を定義したり削除したりするための関数は 以下の通りです. void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass)); void rb_undef_alloc_func(VALUE klass); -funcはクラスを引数として受け取って,新しく割り当てられたイン +_func_ はクラスを引数として受け取って,新しく割り当てられたイン スタンスを返さなくてはなりません.このインスタンスは,外部リ ソースなどを含まない,できるだけ「空」のままにしておいたほう がよいでしょう. @@ -526,7 +523,7 @@ CからRubyの機能を呼び出すもっとも簡単な方法として,文字 VALUE rb_eval_string_protect(const char *str, int *state) この関数はエラーが発生するとnilを返します.そして,成功時には -*stateはゼロに,さもなくば非ゼロになります. +*stateはゼロに,さもなくば非ゼロになります. ==== IDまたはシンボル @@ -554,10 +551,10 @@ IDとは変数名,メソッド名を表す整数です.Rubyの中では rb_check_id(volatile VALUE *name) rb_check_id_cstr(const char *name, long len, rb_encoding *enc) -もし引数がシンボルでも文字列でもなければ,to_strメソッドで文 -字列に変換しようとします.第二の関数はその変換結果を*nameに保 +もし引数がシンボルでも文字列でもなければ,+to_str+ メソッドで文 +字列に変換しようとします.第二の関数はその変換結果を*nameに保 存し,その名前が既知のシンボルでない場合は0を返します.この関 -数が0以外を返した場合は*nameは常にシンボルか文字列であり,0を +数が0以外を返した場合は*nameは常にシンボルか文字列であり,0を 返した場合は常に文字列です.第三の関数はRubyの文字列ではなく NUL終端されたCの文字列を使います. @@ -578,7 +575,7 @@ Cから文字列を経由せずにRubyのメソッドを呼び出すためには VALUE rb_funcall(VALUE recv, ID mid, int argc, ...) -この関数はオブジェクトrecvのmidで指定されるメソッドを呼び出 +この関数はオブジェクト _recv_ の _mid_ で指定されるメソッドを呼び出 します.その他に引数の指定の仕方が違う以下の関数もあります. VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) @@ -599,7 +596,7 @@ Cから関数を使って参照・更新できるのは,定数,インスタ VALUE rb_ivar_get(VALUE obj, ID id) VALUE rb_ivar_set(VALUE obj, ID id, VALUE val) -idはrb_intern()で得られるものを使ってください. +_id_ はrb_intern()で得られるものを使ってください. 定数を参照するには以下の関数を使ってください. @@ -616,22 +613,23 @@ C言語とRubyの間で情報を共有する方法について解説します. 以下のRubyの定数はCのレベルから参照できます. -Qtrue :: -Qfalse :: ++Qtrue+ :: ++Qfalse+ :: - 真偽値.C言語から見た「true」と「false」. + 真偽値.C言語から見た「+true+」と「+false+」. -Qnil :: ++Qnil+ :: - C言語から見た「nil」. + C言語から見た「+nil+」. -RTEST(obj)というマクロはobjがQfalseかQnilのとき0を返します. +RTEST(obj)というマクロは _obj_ が +Qfalse+ か +Qnil+ のとき0を +返します. === CとRubyで共有される大域変数 CとRubyで大域変数を使って情報を共有できます.共有できる大域 変数にはいくつかの種類があります.そのなかでもっとも良く使わ -れると思われるのはrb_define_variable()です. +れると思われるのはrb_define_variable()です. void rb_define_variable(const char *name, VALUE *var) @@ -652,14 +650,14 @@ CとRubyで大域変数を使って情報を共有できます.共有できる VALUE (*getter)(), void (*setter)()) この関数はCの関数によってhookのつけられた大域変数を定義しま -す.変数が参照された時には関数getterが,変数に値がセットされ -た時には関数setterが呼ばれる.hookを指定しない場合はgetterや -setterに0を指定します. +す.変数が参照された時には関数 _getter_ が,変数に値がセットされ +た時には関数 _setter_ が呼ばれる.hookを指定しない場合は _getter_ や +_setter_ に0を指定します. -- -getterもsetterも0ならばrb_define_variable()と同じになる. +_getter_ も _setter_ も0ならばrb_define_variable()と同じになる. ++ -getterとsetterの仕様は次の通りです. +_getter_ と _setter_ の仕様は次の通りです. VALUE (*getter)(ID id, VALUE *var); void (*setter)(VALUE val, ID id, VALUE *var); @@ -672,9 +670,9 @@ getterとsetterの仕様は次の通りです. VALUE (*getter)(), void (*setter)()) この関数によって定義されたRubyの大域変数が参照された時には -getterが,変数に値がセットされた時にはsetterが呼ばれます. +_getter_ が,変数に値がセットされた時には _setter_ が呼ばれます. -getterとsetterの仕様は以下の通りです. +_getter_ と _setter_ の仕様は以下の通りです. (*getter)(ID id); (*setter)(VALUE val, ID id); @@ -694,21 +692,26 @@ Cの世界で定義されたデータ(構造体)をRubyのオブジェクトと ==== 構造体からオブジェクトへ -構造体へのポインタsvalをRubyオブジェクトに変換するには次のマ -クロを使います。 +構造体へのポインタ _sval_ をRubyオブジェクトに変換するには次のマ +クロを使います. TypedData_Wrap_Struct(klass, data_type, sval) このマクロの戻り値は生成されたオブジェクトを表すVALUE値です. -klassはこのオブジェクトのクラスです.klassは, Objectクラスか -ら派生し, 必ずrb_define_alloc_funcかrb_undef_alloc_funcを呼 +このマクロは +RUBY_TYPED_EMBEDDABLE+ フラグを持つ _data_type_ に対しては +使えません.そのような型には +TypedData_Make_Struct+ や ++rb_data_typed_object_zalloc+ を使ってください. + +_klass_ はこのオブジェクトのクラスです._klass_ は, Object クラスか +ら派生し, 必ず +rb_define_alloc_func+ か +rb_undef_alloc_func+ を呼 び出してallocatorを設定してください. -data_typeはこの構造体をRubyが管理するための情報を記述した -const rb_data_type_t型へのポインタです. +_data_type_ はこの構造体をRubyが管理するための情報を記述したconst +rb_data_type_t型へのポインタです. -rb_data_type_tは次のように定義されています. ++rb_data_type_t+ は概ね次のように定義されています.将来の使用のために予 +約されているフィールドは省略されています. typedef struct rb_data_type_struct rb_data_type_t; @@ -718,62 +721,67 @@ rb_data_type_tは次のように定義されています. void (*dmark)(void*); void (*dfree)(void*); size_t (*dsize)(const void *); - void *reserved[2]; + /* reserved fields */ } function; const rb_data_type_t *parent; void *data; VALUE flags; }; -wrap_struct_nameはこの構造体を識別する名前です.主に統計情報 -の収集と出力に用いられます.プロセス内で一意であれば特にCや ++wrap_struct_name+ はこの構造体を識別する名前です.主に統計情報の収集と +出力に用いられます.プロセス内で一意であることが望ましいですが,特にCや Rubyの識別子として有効である必要はありません. -dmarkおよびdfree関数はGC実行中に呼び出されます. ++dmark+ および +dfree+ 関数はGC実行中に呼び出されます. なお, GC実行中はRubyオブジェクトのアロケーションは禁止されま -す. よって, dmarkおよびdfree関数でRubyオブジェクトのアロケー +す. よって, +dmark+ および +dfree+ 関数でRubyオブジェクトのアロケー ションは行わないでください. -dmarkはガーベージコレクタがオブジェクトへの参照をマークする -ときに用いる関数です.この構造体がRubyのオブジェクトへの参照 -を保持するときには, dmarkではrb_gc_markなどを用いて構造体内 -のすべての参照をマークしなければなりません. -そのような参照を含まない時には0を指定します. ++dmark+ はガーベージコレクタがオブジェクトへの参照をマークするときに用い +る関数です.この構造体がRubyのオブジェクトへの参照を保持するときには, ++dmark+ では +rb_gc_mark+ などを用いて構造体内のすべての参照をマークしな +ければなりません.そのような参照を含まない時には0を指定します. -- そのような参照は勧められません. ++ -dfreeはこの構造体がもう不要になった時に呼ばれる関数です.こ ++dfree+ はこの構造体がもう不要になった時に呼ばれる関数です.こ の関数がガーベージコレクタから呼ばれます.これが -RUBY_DEFAULT_FREEの場合は,単純に構造体が解放されます. ++RUBY_DEFAULT_FREE+ の場合は,単純に構造体が解放されます. -dsizeは構造体が消費しているメモリのバイト数を返す関数です. ++dsize+ は構造体が消費しているメモリのバイト数を返す関数です. 引数として構造体へのポインタが渡されます.実装困難であれば0 を渡しても差し支えありませんが, できるだけ指定するようにして ください. -reservedとparentは0で埋めなければなりません. ++dcompact+ はメモリコンパクションが行われるときに呼び出されます. +rb_gc_mark_movable()によってマークされた参照対象の Ruby オブジェクト +は,ここでrb_gc_location()に基づいて更新することができます. + ++parent+ はこの構造体が継承する別の構造体に対応する +rb_data_type_t+ を +指定します.その場合TypedData_Get_Struct()が派生オブジェクトも +受け付けるようになります. -dataにはユーザー定義の任意の値を指定できます.Rubyはこの値に ++data+ にはユーザー定義の任意の値を指定できます.Rubyはこの値に は関知しないので,好きに使ってください. -flagsには次のフラグのうち当てはまるもののビット和を指定しま ++flags+ には次のフラグのうち当てはまるもののビット和を指定しま す.いずれもRubyのガーベージコレクタについての深い理解を必要 としますので,良くわからない場合には0を指定すると良いでしょ う. -RUBY_TYPED_FREE_IMMEDIATELY :: ++RUBY_TYPED_FREE_IMMEDIATELY+ :: このフラグを指定すると,ガーベージコレクタはこの構造体が不 - 要になった場合にはGC中に直ちにdfreeを呼び出します. - dfreeがRuby内部のロック(GVL)を解放する可能性がない場合はこ + 要になった場合にはGC中に直ちに +dfree+ を呼び出します. + +dfree+ がRuby内部のロック(GVL)を解放する可能性がない場合はこ のフラグを指定できます. - 指定しない場合はdfree呼び出しは遅延され, ファイナライザと + 指定しない場合は +dfree+ 呼び出しは遅延され, ファイナライザと 同じタイミングで実行されます. -RUBY_TYPED_WB_PROTECTED :: ++RUBY_TYPED_WB_PROTECTED+ :: オブジェクトの実装がライトバリアをサポートしていることを示 します.このフラグを指定するとRubyはそのオブジェクトに対し @@ -786,10 +794,76 @@ RUBY_TYPED_WB_PROTECTED :: GC}[rdoc-ref:@Appendix+D.+-E4-B8-96-E4-BB-A3-E5-88-A5GC] も参照してください. -このマクロは例外を発生させる可能性があることに注意してくださ -い. ラップされる sval が,解放する必要があるリソース (割り -当てられたメモリ,外部ライブラリからのハンドルなど) を保持し -ている場合は,rb_protect を使用する必要があります. ++RUBY_TYPED_FROZEN_SHAREABLE+ :: + + オブジェクトがfreezeされていればRactor間で共有できることを示します. + {Appendix F. Ractor + support}[rdoc-ref:extension.rdoc@Appendix+F.+Ractor+support]を参照し + てください. + + このフラグがセットされていなければ,Ractor.make_shareable() + で共有可能にはできません. + ++RUBY_TYPED_EMBEDDABLE+ :: + + このフラグは,RubyがC構造体を +malloc+ で別に割り当てるのではなく, + オブジェクトのスロット内に格納してもよいことを示します. + ただし,これは保証されるものではありません.Rubyはオブジェクトを埋め込 + まないことを選択する場合もあります.例えば,そのオブジェクトが大きすぎ + て,利用可能なスロットサイズのいずれにも収まらない場合などです. + + C構造体をオブジェクトスロット内に埋め込むことで,ポインタの追跡や + +malloc+ によるオーバーヘッドが削減され,スイープのパフォーマンスが向 + 上します.場合によっては,オブジェクトのメモリ使用量も削減できることが + あります. + + 埋め込み可能となるためには,型はいくつかの制限に従う必要があります: + + * C構造体へのポインタ,またはC構造体内部へのポインタは,GCのコンパク + ションが発生すると無効になるため,保存してはなりません.ただし,Ruby + オブジェクトがスタック上に残っている限り,そのようなポインタを渡した + り使用したりすることは有効です. + + ある意味,これはスタック上に割り当てられた構造体に対する制限と似てい + ます. + + オブジェクトがコンパクションによって移動されたり解放されたりしないこ + とを保証するには,+RB_GC_GUARD+ マクロを使用する必要があります.ただ + し,オブジェクトがRuby から C へ直接引数として渡される場合,すなわち + +rb_define_method+ などで使用される関数のパラメータとして渡される場 + 合は除きます. + + * +DATA_PTR+ や +RTYPEDDATA_DATA+,+TypedData_Wrap_Struct+ マクロは使 + 用できません. + 埋め込み可能なオブジェクトに対しては,+RTYPEDDATA_GET_DATA+ または + +TypedData_Get_Struct+ マクロのみ使用可能です.また, + `RTYPEDDATA(obj)->data` へのアクセスも無効です. + + * +dfree+ 関数は,C構造体自体を解放してはなりません. + +dfree+ を +RUBY_DEFAULT_FREE+ に設定しても問題ありません.この機能 + を持たない古いバージョンのRubyをサポートするために, + +RUBY_TYPED_EMBEDDABLE+ が定義されていない場合に限り,C構造体を条件 + 付きで解放することができます. + + * 型には +RUBY_TYPED_FREE_IMMEDIATELY+ フラグが設定されている必要があ + ります. + + 埋め込みC構造体のサイズが可変である場合,+TypedData_Make_Struct+ の代 + わりに +rb_data_typed_object_zalloc+を使用できます. + + +RUBY_TYPED_EMBEDDABLE+ の使用方法に関する注釈付きの例については, + {Embedded TypedData}[rdoc-ref:@Appendix+G.+Embedded+TypedData] を参照 + してください. + +上記以外のフィールドは将来の使用のために予約されており、通常は初期化子 +は省略されます。ごく稀なケースですが,動的に `rb_data_type_t` 自体を確 +保する場合は,0クリアしてください. + +このマクロは例外を発生させる可能性があることに注意してください. ラップ +される _sval_ が,解放する必要があるリソース (割り当てられたメモリ,外部 +ライブラリからのハンドルなど) を保持している場合は,+rb_protect+ を使用 +する必要があります.あるいは,まずデータポインタを +NULL+ に設定してオブ +ジェクトを作成し,その後リソースを割り当ててそのオブジェクトに格納します. Cの構造体の割当と対応するオブジェクトの生成を同時に行うマク ロとして以下のものが提供されています. @@ -801,19 +875,85 @@ Cの構造体の割当と対応するオブジェクトの生成を同時に行 (sval = ZALLOC(type), TypedData_Wrap_Struct(klass, data_type, sval)) -klass, data_typeはData_Wrap_Structと同じ働きをします.type -は割り当てるC構造体の型です.割り当てられた構造体は変数sval -に代入されます.この変数の型は (type*) である必要があります. +ただし,単にメモリを割り当てるだけなら,上記のコードのような「割り当て後 +にラップする」方法ではなく,このマクロを使用すべきです.なぜなら,「ラッ +プ」の際に +NoMemoryError+ が発生する可能性があり,その場合は _sval_ が +メモリリークとなるからです. + +_klass_, _data_type_ は +Data_Wrap_Struct+ と同じ働きをします._type_ +は割り当てるC構造体の型です.割り当てられた構造体は変数 _sval_ +に代入されます.この変数の型は type* である必要があります. + +単純なメモリ割り当て以外の場合も同様です: + + obj = TypedData_Wrap_Struct(klass, data_type, NULL); + sval = allocate_some_resource(); + if (success(sval)) RTYPEDDATA_DATA(obj) = sval; + +_sval_ がポインタ型でない場合は,void*にキャストする必要がある +かもしれません. + +==== 宣言的マーク/コンパクト構造体参照 + +構造体の参照しているRubyオブジェクトが,条件付きロジックや複雑なデータ +構造でラップされていない,単純な参照だけの場合は,VALUEへの参照のオフセッ +ト(edge)によってマーク付けと参照更新を宣言することもできます. + +これにより,+dmark+ や +dcompact+ コールバック関数を定義せずに済みます. + +参照が配置されている構造体内のオフセットへのVALUEポインタの静的リストを +定義し,この参照リストを指すように +data+ メンバーを設定します. 参照リ +ストは +RUBY_END_REFS+ で終わる必要があります. + +以下のマクロが使用できます: + +RUBY_TYPED_DECL_MARKING :: + +ruby_data_type_t+ がedgeを使用していることを示すフラグ + +RUBY_REFERENCES(ref_list_name) :: + _ref_list_name_ を参照リストとして定義する +RUBY_REF_END :: 参照リストの終端 +RUBY_REF_EDGE(struct, member) :: + _struct_ から _member_ をedgeとして宣言する. +RUBY_REFERENCES+ の + ブロックの中で使用する. ++RUBY_REFS_LIST_PTR+ :: + 参照リストを +dmark+ として使用できるように変換する + +以下は +dir.c+ で定義されている Dir の例です. + + // ラップされる構造体.3つのメンバの内,2番目が他のrubyオブジェクトへの参照 + struct dir_data { + DIR *dir; + const VALUE path; + rb_encoding *enc; + } + + // `path` エントリを持つ参照リスト `dir_refs` を定義 + // RUBY_REF_ENDで終了していなければならない + RUBY_REFERENCES(dir_refs) = { + RUBY_REF_EDGE(dir_data, path), + RUBY_REF_END + }; + + // RUBY_TYPED_DECL_MARKINGをセットして定義された参照リストを"dmark"に使用しているので, + // マーク用コールバック関数は不要 + static const rb_data_type_t dir_data_type = { + "dir", + {RUBY_REFS_LIST_PTR(dir_refs), dir_free, dir_memsize,}, + 0, NULL, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_DECL_MARKING + }; + +このように,単純な参照を宣言的に宣言することで,GCがマークや移動,コン +パクション中の参照の自動更新などをできるようになります. ==== オブジェクトから構造体へ -TypedData_Wrap_StructやTypedData_Make_Structで生成したオブジェ -クトから構造体へのポインタを復元するには以下のマクロを用いま -す. ++TypedData_Wrap_Struct+ や +TypedData_Make_Struct+ で生成したオブジェク +トから構造体へのポインタを復元するには以下のマクロを用います. TypedData_Get_Struct(obj, type, &data_type, sval) -Cの構造体へのポインタは変数svalに代入されます. +Cの構造体へのポインタは変数 _sval_ に代入されます. これらのマクロの使い方はちょっと分かりにくいので,後で説明す る例題を参照してください. @@ -824,11 +964,9 @@ Cの構造体へのポインタは変数svalに代入されます. % mkdir ext/dbm -Ruby 1.1からは任意のディレクトリでダイナミックライブラリを作 -ることができるようになりました.Rubyに静的にリンクする場合に -はRubyを展開したディレクトリの下,extディレクトリの中に拡張 -ライブラリ用のディレクトリを作る必要があります.名前は適当に -選んで構いません. +Rubyに静的にリンクする場合にはRubyを展開したディレクトリの下, +extディレクトリの中に拡張ライブラリ用のディレクトリを作る必 +要があります.名前は適当に選んで構いません. === 設計する @@ -840,20 +978,18 @@ Ruby 1.1からは任意のディレクトリでダイナミックライブラリ === Cコードを書く 拡張ライブラリ本体となるC言語のソースを書きます.C言語のソー -スがひとつの時には「ライブラリ名.c」を選ぶと良いでしょう.C -言語のソースが複数の場合には逆に「ライブラリ名.c」というファ -イル名は避ける必要があります.オブジェクトファイルとモジュー -ル生成時に中間的に生成される「ライブラリ名.o」というファイル -とが衝突するからです.また,後述する mkmf ライブラリのいくつ -かの関数がコンパイルを要するテストのために「conftest.c」とい -うファイル名を使用することに注意してください.ソースファイル -名として「conftest.c」を使用してはなりません. - -Rubyは拡張ライブラリをロードする時に「Init_ライブラリ名」と -いう関数を自動的に実行します.dbmライブラリの場合「Init_dbm」 +スがひとつの時には「ライブラリ名.c」を選ぶと良いでしょう.ま +た,後述する mkmf ライブラリのいくつかの関数がコンパイルを要 +するテストのために「conftest.c」というファイル名を使用するこ +とに注意してください.ソースファイル名として「conftest.c」を +使用してはなりません. + +Rubyは拡張ライブラリをロードする時に「+Init_ライブラリ名+」と +いう関数を自動的に実行します.dbmライブラリの場合「+Init_dbm+」 です.この関数の中でクラス,モジュール,メソッド,定数などの 定義を行います.dbm.cから一部引用します. + #include void Init_dbm(void) { @@ -895,11 +1031,11 @@ dbm.cではTypedData_Make_Structを以下のように使っています. obj = TypedData_Make_Struct(klass, struct dbmdata, &dbm_type, dbmp); -ここではdbmdata構造体へのポインタをRubyオブジェクトにカプセ +ここでは +dbmdata+ 構造体へのポインタをRubyオブジェクトにカプセ ル化しています.DBM*を直接カプセル化しないのはclose()した時 の処理を考えてのことです. -Rubyオブジェクトからdbmdata構造体のポインタを取り出すために +Rubyオブジェクトから +dbmdata+ 構造体のポインタを取り出すために 以下のマクロを使っています. #define GetDBM(obj, dbmp) do {\ @@ -912,24 +1048,26 @@ Rubyオブジェクトからdbmdata構造体のポインタを取り出すため の取り出しと,closeされているかどうかのチェックをまとめてい るだけです. -DBMクラスにはたくさんメソッドがありますが,分類すると3種類の -引数の受け方があります.ひとつは引数の数が固定のもので,例と -してはdeleteメソッドがあります.deleteメソッドを実装している -fdbm_delete()はこのようになっています. +DBMクラスにはたくさんメソッドがありますが,分類すると3種類の引数の受け +方があります.ひとつは以下のように引数の数が固定のものです. static VALUE - fdbm_delete(VALUE obj, VALUE keystr) + fdbm_aref(VALUE obj, VALUE keystr) { + struct dbmdata *dbmp; + GetDBM(obj, dbmp); + /* Use dbmp to access the key */ + dbm_fetch(dbmp->di_dbm, StringValueCStr(keystr)); /* ... */ } -引数の数が固定のタイプは第1引数がself,第2引数以降がメソッド -の引数となります. +引数の数が固定のタイプは第1引数が +self+,第2引数以降がメソッ +ドの引数となります. -引数の数が不定のものはCの配列で受けるものとRubyの配列で受け -るものとがあります.dbmライブラリの中で,Cの配列で受けるもの -はDBMのクラスメソッドであるopen()です.これを実装している関 -数fdbm_s_open()はこうなっています. +引数の数が不定のものはCの配列で受けるものとRubyの配列で受けるものとがあります. +dbmライブラリの中で,Cの配列で受けるものはDBMのクラスメソッドである +open()です.これを実装している関数fdbm_s_open()はこうなってい +ます. static VALUE fdbm_s_open(int argc, VALUE *argv, VALUE klass) @@ -943,16 +1081,14 @@ fdbm_delete()はこのようになっています. /* ... */ } -このタイプの関数は第1引数が与えられた引数の数,第2引数が与え -られた引数の入っている配列になります.selfは第3引数として与 -えられます. +このタイプの関数は第1引数が与えられた引数の数,第2引数が与えられた引数の入ってい +る配列になります.+self+ は第3引数として与えられます. -この配列で与えられた引数を解析するための関数がopen()でも使わ -れているrb_scan_args()です.第3引数に指定したフォーマットに従 -い,第4引数以降に指定したVALUEへの参照に値を代入してくれま -す. +この配列で与えられた引数を解析するための関数が open() でも使われている +rb_scan_args() です.第3引数に指定したフォーマットに従い,第4引数以降に +指定したVALUEへの参照に値を代入してくれます. -引数の数をチェックするだけならrb_check_arity()が使えます. +引数の数をチェックするだけなら rb_check_arity() が使えます. これは引数をリストとして扱いたいときに便利です. 引数をRubyの配列として受け取るメソッドの例には @@ -966,14 +1102,17 @@ Thread#initializeがあります.実装はこうです. 第1引数はself,第2引数はRubyの配列です. -*注意事項* - +注意事項: Rubyと共有はしないがRubyのオブジェクトを格納する可能性のある Cの大域変数は以下の関数を使ってRubyインタプリタに変数の存在 を教えてあげてください.でないとGCでトラブルを起こします. void rb_global_variable(VALUE *var) +またはそのオブジェクト自身を登録してください. + + void rb_gc_register_mark_object(VALUE object) + === extconf.rbを用意する Makefileを作る場合の雛型になるextconf.rbというファイルを作り @@ -1102,41 +1241,47 @@ parse.y :: 字句解析器と構文定義 parse.c :: 自動生成 defs/keywords :: 予約語 lex.c :: 自動生成 +id.c :: 定義済みID === Rubyの評価器 (通称YARV) - compile.c - eval.c - eval_error.c - eval_jump.c - eval_safe.c - insns.def : 仮想機械語の定義 - iseq.c : VM::ISeqの実装 - thread.c : スレッド管理とコンテキスト切り替え - thread_win32.c : スレッド実装 - thread_pthread.c : 同上 - vm.c - vm_dump.c - vm_eval.c - vm_exec.c - vm_insnhelper.c - vm_method.c - - defs/opt_insns_unif.def : 命令融合 - defs/opt_operand.def : 最適化のための定義 - - -> insn*.inc : 自動生成 - -> opt*.inc : 自動生成 - -> vm.inc : 自動生成 +eval.c :: +eval_error.c :: +eval_jump.c :: + 評価機 + +compile.c :: ASTからVM命令へのコンパイラ +iseq.c :: VM::ISeqの実装 + +thread.c :: +thread_win32.c :: +thread_pthread.c :: + スレッド管理とコンテキスト切り替え + +vm.c :: +vm_dump.c :: +vm_eval.c :: +vm_exec.c :: +vm_insnhelper.c :: +vm_method.c :: + VM実装 + +insns.def :: + 仮想機械語の定義 + defs/opt_insns_unif.def :: + 命令融合 + defs/opt_operand.def :: + 最適化のための定義 + -> insn*.inc opt*.inc vm.inc :: 自動生成 === 正規表現エンジン (鬼雲) - regcomp.c - regenc.c - regerror.c - regexec.c - regparse.c - regsyntax.c +regcomp.c :: コンパイラ +regenc.c :: エンコーディング +regerror.c :: エラー +regexec.c :: 実行器 +regparse.c :: パーサ +regsyntax.c :: 定義済みシンタックスオプション === ユーティリティ関数 @@ -1148,22 +1293,26 @@ util.c :: その他のユーティリティ === Rubyコマンドの実装 - dmyext.c - dmydln.c - dmyencoding.c - id.c - inits.c - main.c - ruby.c - version.c +dmyext.c :: +dmydln.c :: +dmyencoding.c :: + miniruby用 + +inits.c :: +main.c :: +ruby.c :: +version.c :: + Rubyコマンド - gem_prelude.rb - prelude.rb +builtin.c :: +gem_prelude.rb :: +prelude.rb :: + 起動時に実行されるRubyコード用 === クラスライブラリ array.c :: Array -bignum.c :: Bignum +bignum.c :: Integer (Bignum) compar.c :: Comparable complex.c :: Complex cont.c :: Fiber, Continuation @@ -1175,11 +1324,11 @@ hash.c :: Hash io.c :: IO marshal.c :: Marshal math.c :: Math -numeric.c :: Numeric, Integer, Fixnum, Float +numeric.c :: Numeric, Integer (Fixnum), Float pack.c :: Array#pack, String#unpack proc.c :: Binding, Proc process.c :: Process -random.c :: 乱数 +random.c :: 乱数 (Random) range.c :: Range rational.c :: Rational re.c :: Regexp, MatchData @@ -1187,10 +1336,12 @@ signal.c :: Signal sprintf.c :: String#sprintf string.c :: String struct.c :: Struct +symbol.c :: Symbol time.c :: Time -defs/known_errors.def :: 例外クラス Errno::* --> known_errors.inc :: 自動生成 +defs/known_errors.def :: + Errno の下の例外クラス + -> known_errors.inc :: 自動生成 === 多言語化 @@ -1201,9 +1352,10 @@ enc/trans/* :: コードポイント対応表 === gorubyコマンドの実装 - goruby.c - golf_prelude.rb : goruby固有のライブラリ - -> golf_prelude.c : 自動生成 +goruby.c :: gorubyコマンド +golf_prelude.rb :: + goruby固有のライブラリ + -> golf_prelude.c :: 自動生成 == Appendix B. 拡張用関数リファレンス @@ -1211,7 +1363,7 @@ C言語からRubyの機能を利用するAPIは以下の通りである. === 型 -VALUE :: ++VALUE+ :: Rubyオブジェクトを表現する型.必要に応じてキャストして用いる. 組み込み型を表現するCの型はruby.hに記述してあるRで始まる構造 @@ -1220,46 +1372,60 @@ VALUE :: === 変数・定数 -Qnil :: ++Qnil+ :: - 定数: nilオブジェクト + 定数: +nil+ オブジェクト -Qtrue :: ++Qtrue+ :: - 定数: trueオブジェクト(真のデフォルト値) + 定数: +true+ オブジェクト(真のデフォルト値) -Qfalse :: ++Qfalse+ :: - 定数: falseオブジェクト + 定数: +false+ オブジェクト === Cデータのカプセル化 -Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval) :: +Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval) :: Cの任意のポインタをカプセル化したRubyオブジェクトを返す.こ - のポインタがRubyからアクセスされなくなった時,freeで指定した + のポインタがRubyからアクセスされなくなった時,_free_ で指定した 関数が呼ばれる.また,このポインタの指すデータが他のRubyオブ - ジェクトを指している場合,markに指定する関数でマークする必要 + ジェクトを指している場合,_mark_ に指定する関数でマークする必要 がある. -Data_Make_Struct(klass, type, mark, free, sval) :: +Data_Make_Struct(klass, type, mark, free, sval) :: - type型のメモリをmallocし,変数svalに代入した後,それをカプセ + _type_ 型のメモリをmallocし,変数 _sval_ に代入した後,それをカプセ ル化したデータを返すマクロ. -Data_Get_Struct(data, type, sval) :: +Data_Get_Struct(data, type, sval) :: - dataからtype型のポインタを取り出し変数svalに代入するマクロ. + _data_ から _type_ 型のポインタを取り出し変数 _sval_ に代入するマクロ. === 型チェック - RB_TYPE_P(value, type) - TYPE(value) - FIXNUM_P(value) - NIL_P(value) - RB_INTEGER_TYPE_P(value) - RB_FLOAT_TYPE_P(value) - void Check_Type(VALUE value, int type) +RB_TYPE_P(value, type) :: + _value_ の内部的な型が _type_ (+T_NIL+, +T_FIXNUM+, etc.)か? + +TYPE(value) :: + 内部的な型 (+T_NIL+, +T_FIXNUM+, etc.) + +FIXNUM_P(value) :: + _value_ が Fixnum か? + +NIL_P(value) :: + _value_ が +nil+ か? + +RB_INTEGER_TYPE_P(value) :: + _value_ が Integer か? + +RB_FLOAT_TYPE_P(value) :: + _value_ が Float か? + +void Check_Type(VALUE value, int type) :: + + _value_ の内部的な型が _type_ でなければ TypeError を発生させる === 型変換 @@ -1286,76 +1452,81 @@ Data_Get_Struct(data, type, sval) :: === クラス/モジュール定義 -VALUE rb_define_class(const char *name, VALUE super) :: +VALUE rb_define_class(const char *name, VALUE super) :: - superのサブクラスとして新しいRubyクラスを定義する. + _super_ のサブクラスであるRubyクラスをトップレベルの定数 _name_ として + 定義する. -VALUE rb_define_class_under(VALUE module, const char *name, VALUE super) :: +VALUE rb_define_class_under(VALUE module, const char *name, VALUE super) :: - superのサブクラスとして新しいRubyクラスを定義し,moduleの - 定数として定義する. + _super_ のサブクラスであるRubyクラスを _module_ の定数 _name_ として + 定義する. -VALUE rb_define_module(const char *name) :: +VALUE rb_define_module(const char *name) :: - 新しいRubyモジュールを定義する. + Rubyモジュールをトップレベルの定数 _name_ として定義する. -VALUE rb_define_module_under(VALUE module, const char *name) :: +VALUE rb_define_module_under(VALUE module, const char *name) :: - 新しいRubyモジュールを定義し,moduleの定数として定義する. + Rubyモジュールを _module_ の定数 _name_ として定義する. -void rb_include_module(VALUE klass, VALUE module) :: +void rb_include_module(VALUE klass, VALUE module) :: モジュールをインクルードする.classがすでにmoduleをインク ルードしている時には何もしない(多重インクルードの禁止). -void rb_extend_object(VALUE object, VALUE module) :: +void rb_extend_object(VALUE object, VALUE module) :: オブジェクトをモジュール(で定義されているメソッド)で拡張する. === 大域変数定義 -void rb_define_variable(const char *name, VALUE *var) :: +void rb_define_variable(const char *name, VALUE *var) :: - RubyとCとで共有するグローバル変数を定義する.変数名が`$'で - 始まらない時には自動的に追加される.nameとしてRubyの識別子 - として許されない文字(例えば` ')を含む場合にはRubyプログラ - ムからは見えなくなる. + RubyとCとで共有するグローバル変数 _name_ を定義する.変数名が +$+ で始 + まらない時には自動的に追加される.その変数名がRubyのグローバル変数名と + して許されない文字(例えば` ')を含む場合にはRubyプログラムからは見えな + くなる. -void rb_define_readonly_variable(const char *name, VALUE *var) :: +void rb_define_readonly_variable(const char *name, VALUE *var) :: RubyとCとで共有するread onlyのグローバル変数を定義する. - read onlyであること以外はrb_define_variable()と同じ. + read onlyであること以外はrb_define_variable()と同じ. -void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) :: +void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) :: - 関数によって実現されるRuby変数を定義する.変数が参照された - 時にはgetterが,変数に値がセットされた時にはsetterが呼ばれ - る. + 関数によって実現されるRuby変数を定義する.変数が参照された時には + _getter_ が,変数に値がセットされた時には _setter_ が呼ばれる.これら + の関数は +rb_define_hooked_variable+ と同じですが,_var_ 引数は意味が + ない. + +void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) :: -void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) :: + 関数によってhookのつけられたグローバル変数を定義する.変数が参照された + 時には _getter_ が,関数に値がセットされた時には _setter_ が呼ばれ + る._getter_ や _setter_ に0を指定した時にはhookを指定しないのと同じ事 + になる. - 関数によってhookのつけられたグローバル変数を定義する.変数 - が参照された時にはgetterが,関数に値がセットされた時には - setterが呼ばれる.getterやsetterに0を指定した時にはhookを - 指定しないのと同じ事になる. + VALUE getter(ID id, VALUE *var) + void setter(VALUE val, ID id, VALUE *var) -void rb_global_variable(VALUE *var) :: +void rb_global_variable(VALUE *var) :: マークする必要のあるRubyオブジェクトを含む大域変数を,GC によって解放されないように保護する. -void rb_gc_register_mark_object(VALUE object) :: +void rb_gc_register_mark_object(VALUE object) :: マークする必要のあるRubyオブジェクトを,GCによって解放さ れないように登録する. === 定数 -void rb_define_const(VALUE klass, const char *name, VALUE val) :: +void rb_define_const(VALUE klass, const char *name, VALUE val) :: 定数を定義する. -void rb_define_global_const(const char *name, VALUE val) :: +void rb_define_global_const(const char *name, VALUE val) :: 大域定数を定義する. @@ -1365,31 +1536,30 @@ void rb_define_global_const(const char *name, VALUE val) :: === メソッド定義 -rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: - メソッドを定義する.argcはselfを除く引数の数.argcが-1の時, - 関数には引数の数(selfを含まない)を第1引数, 引数の配列を第2 - 引数とする形式で与えられる(第3引数はself).argcが-2の時, - 第1引数がself, 第2引数がargs(argsは引数を含むRubyの配列)と - いう形式で与えられる. + メソッドを定義する._argc_ は +self+ を除く引数の数._argc_ が-1の時, + 関数には引数の数(+self+ を含まない)を第1引数, 引数の配列を第2引数とす + る形式で与えられる(第3引数は +self+)._argc_ が-2の時,第1引数が + +self+, 第2引数が _args_(引数を含むRubyの配列)という形式で与えられる. -rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: - privateメソッドを定義する.引数はrb_define_method()と同じ. + privateメソッドを定義する.引数はrb_define_method()と同じ. -rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: - 特異メソッドを定義する.引数はrb_define_method()と同じ. + 特異メソッドを定義する.引数はrb_define_method()と同じ. -rb_check_arity(int argc, int min, int max) :: +rb_check_arity(int argc, int min, int max) :: - 引数の数であるargcがmin..maxの範囲に入っているかをチェックします. - もしmaxがUNLIMITED_ARGUMENTSなら,上限はチェックしません. - もしargcが範囲外ならArgumentErrorが発生します. + 引数の数である _argc_ が +min..max+ の範囲に入っているかをチェックします. + もし _max_ が +UNLIMITED_ARGUMENTS+ なら,上限はチェックしません. + もし _argc_ が範囲外なら ArgumentError が発生します. -rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: +rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: - argc, argv形式で与えられた指定されたフォーマットに従って引 + _argc_, _argv_ 形式で与えられた指定されたフォーマットに従って引 数を分解し,続くVALUEへの参照にセットします.このフォーマッ トは,ABNFで記述すると以下の通りです. @@ -1427,205 +1597,203 @@ rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: て3つのVALUEへの参照を置く必要があります.それらには取得した 変数がセットされます.変数への参照の代わりにNULLを指定する こともでき,その場合は取得した引数の値は捨てられます.なお, - 省略可能引数が省略された時の変数の値はnil(C言語のレベルでは - Qnil)になります. + 省略可能引数が省略された時の変数の値は +nil+(C言語のレベルでは + +Qnil+)になります. 返り値は与えられた引数の数です.オプションハッシュおよびイ テレータブロックは数えません. -int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values) :: +int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values) :: - キーワードで指定された値をtableにしたがって取り出します. - tableの最初のrequired個のIDは必須キーワードを表し,続く - optional (optionalが負の場合は-optional-1) 個のIDは省略可能 - キーワードです.必須キーワードがkeyword_hash中にない場合, - "missing keyword"ArgumentErrorが発生します.省略可能キーワー - ドがない場合は,values中の対応する要素にはQundefがセットされ - ます.keyword_hashに使用されない要素がある場合は,optionalが - 負なら無視されますが,そうでなければ"unknown keyword" - ArgumentErrorが発生します. + キーワードで指定された値を _table_ にしたがって取り出します._table_ + の最初の _required_ 個のIDは必須キーワードを表し,続く _optional_ + (_optional_ が負の場合は-optional-1) 個のIDは省略可能キーワー + ドです.必須キーワードが _keyword_hash_ 中にない場合,"missing + keyword" ArgumentError が発生します.省略可能キーワードがない場合は, + _values_ 中の対応する要素には +Qundef+ がセットされます._keyword_hash_ に使用さ + れない要素がある場合は,_optional_ が負なら無視されますが,そうでなければ + "unknown keyword" ArgumentError が発生します. -VALUE rb_extract_keywords(VALUE *original_hash) :: +VALUE rb_extract_keywords(VALUE *original_hash) :: - original_hashで参照されるHashオブジェクトから,Symbolである - キーとその値を新しいHashに取り出します.original_hashの指す + _original_hash_ で参照されるHashオブジェクトから,Symbolである + キーとその値を新しいHashに取り出します._original_hash_ の指す 先には,元のHashがSymbol以外のキーを含んでいた場合はそれらが コピーされた別の新しいHash,そうでなければ0が保存されます. === Rubyメソッド呼び出し -VALUE rb_funcall(VALUE recv, ID mid, int narg, ...) :: +VALUE rb_funcall(VALUE recv, ID mid, int narg, ...) :: - メソッド呼び出し.文字列からmidを得るためにはrb_intern()を + メソッド呼び出し.文字列からmidを得るためにはrb_intern()を 使う. private/protectedなメソッドでも呼び出せる. -VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) :: -VALUE rb_funcallv(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcallv(VALUE recv, ID mid, int argc, VALUE *argv) :: - メソッド呼び出し.引数をargc, argv形式で渡す. + メソッド呼び出し.引数を _argc_, _argv_ 形式で渡す. private/protectedなメソッドでも呼び出せる. -VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, VALUE *argv) :: メソッド呼び出し. publicなメソッドしか呼べない. -VALUE rb_eval_string(const char *str) :: +VALUE rb_eval_string(const char *str) :: 文字列をRubyスクリプトとしてコンパイル・実行する. -ID rb_intern(const char *name) :: +ID rb_intern(const char *name) :: 文字列に対応するIDを返す. -char *rb_id2name(ID id) :: +char *rb_id2name(ID id) :: IDに対応する文字列を返す(デバッグ用). -char *rb_class2name(VALUE klass) :: +char *rb_class2name(VALUE klass) :: クラスの名前を返す(デバッグ用).クラスが名前を持たない時に は, 祖先を遡って名前を持つクラスの名前を返す. -int rb_respond_to(VALUE obj, ID id) :: +int rb_respond_to(VALUE obj, ID id) :: - objがidで示されるメソッドを持つかどうかを返す. + _obj_ が _id_ で示されるメソッドを持つかどうかを返す. === インスタンス変数 -VALUE rb_iv_get(VALUE obj, const char *name) :: +VALUE rb_iv_get(VALUE obj, const char *name) :: objのインスタンス変数の値を得る.`@'で始まらないインスタン ス変数は Rubyプログラムからアクセスできない「隠れた」イン スタンス変数になる.定数は大文字の名前を持つクラス(または モジュール)のインスタンス変数として実装されている. -VALUE rb_iv_set(VALUE obj, const char *name, VALUE val) :: +VALUE rb_iv_set(VALUE obj, const char *name, VALUE val) :: - objのインスタンス変数をvalにセットする. + _obj_ のインスタンス変数 _name_ を _val_ にセットする. === 制御構造 -VALUE rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2) :: +VALUE rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2) :: - funcをブロックとして設定し,objをレシーバ,argcとargvを引数 - としてmidメソッドを呼び出す.funcは第一引数にyieldされた値, - 第二引数にdata2を受け取る.複数の値がyieldされた場合(Cでは - rb_yield_values()とrb_yield_values2(), rb_yield_splat()), - data2はArrayとしてパックされている.第三, 第四引数のargcと - argvによってyieldされた値を取り出すことができる. + _func_ をブロックとして設定し,_obj_ をレシーバ,_argc_ と _argv_ を引数 + として _mid_ メソッドを呼び出す._func_ は第一引数に +yield+ された値, + 第二引数に _data2_ を受け取る.複数の値が +yield+ された場合(Cでは + rb_yield_values()rb_yield_values2(), rb_yield_splat()), + _data2_ はArrayとしてパックされている.第三, 第四引数の _argc_ と + _argv_ によって +yield+ された値を取り出すことができる. -\[OBSOLETE] VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2) :: +\[OBSOLETE] VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2) :: - func2をブロックとして設定し, func1をイテレータとして呼ぶ. - func1には arg1が引数として渡され, func2には第1引数にイテレー - タから与えられた値, 第2引数にarg2が渡される. + _func2_ をブロックとして設定し, _func1_ をイテレータとして呼ぶ. + _func1_ には _arg1_ が引数として渡され, _func2_ には第1引数にイテレー + タから与えられた値, 第2引数に _arg2_が渡される. - 1.9でrb_iterateを使う場合は, func1の中でRubyレベルのメソッド + 1.9で +rb_iterate+ を使う場合は, _func1_ の中でRubyレベルのメソッド を呼び出さなければならない. - 1.9でobsoleteとなった. 代わりにrb_block_callが用意された. + 1.9でobsoleteとなった. 代わりに +rb_block_call+ が用意された. -VALUE rb_yield(VALUE val) :: +VALUE rb_yield(VALUE val) :: - valを値としてイテレータブロックを呼び出す. + _val_ を値としてイテレータブロックを呼び出す. -VALUE rb_rescue(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: +VALUE rb_rescue(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: - 関数func1をarg1を引数に呼び出す.func1の実行中に例外が発生 - した時には func2をarg2を第一引数, 発生した例外オブジェクト - を第二引数として呼ぶ.戻り値は例外が発生しなかった時はfunc1 - の戻り値, 例外が発生した時にはfunc2の戻り値である. + 関数 _func1_ を _arg1_ を引数に呼び出す.func1の実行中に例外が発生し + た時には _func2_ を _arg2_ を第一引数, 発生した例外オブジェクトを第 + 二引数として呼ぶ.戻り値は例外が発生しなかった時は _func1_の戻り値, + 例外が発生した時には _func2_ の戻り値である. -VALUE rb_ensure(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: +VALUE rb_ensure(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: - 関数func1をarg1を引数として実行し, 実行終了後(たとえ例外が - 発生しても) func2をarg2を引数として実行する.戻り値はfunc1 - の戻り値である(例外が発生した時は戻らない). + 関数 _func1_ を _arg1_ を引数として実行し, 実行終了後(たとえ例外が発 + 生しても) _func2_ を _arg2_ を引数として実行する.戻り値は _func1_の + 戻り値である(例外が発生した時は戻らない). -VALUE rb_protect(VALUE (*func) (VALUE), VALUE arg, int *state) :: +VALUE rb_protect(VALUE (*func) (VALUE), VALUE arg, int *state) :: - 関数funcをargを引数として実行し, 例外が発生しなければその戻 - り値を返す.例外が発生した場合は, *stateに非0をセットして - Qnilを返す. - rb_jump_tag()を呼ばずに捕捉した例外を無視する場合には, - rb_set_errinfo(Qnil)でエラー情報をクリアしなければならない. + 関数 _func_ を _arg_ を引数として実行し, 例外が発生しなければその戻 + り値を返す.例外が発生した場合は, *stateに非0をセットして + +Qnil+ を返す. + rb_jump_tag()を呼ばずに捕捉した例外を無視する場合には, + rb_set_errinfo(Qnil)でエラー情報をクリアしなければならない. -void rb_jump_tag(int state) :: +void rb_jump_tag(int state) :: - rb_protect()やrb_eval_string_protect()で捕捉された例外を再 - 送する.stateはそれらの関数から返された値でなければならない. + rb_protect()rb_eval_string_protect()で捕捉された例 + 外を再送する._state_ はそれらの関数から返された値でなければならない. この関数は直接の呼び出し元に戻らない. -void rb_iter_break() :: +void rb_iter_break() :: 現在の最も内側のブロックを終了する.この関数は直接の呼び出 し元に戻らない. -void rb_iter_break_value(VALUE value) :: +void rb_iter_break_value(VALUE value) :: - 現在の最も内側のブロックをvalueで終了する.ブロックは引数で - 与えられたvalueを返す.この関数は直接の呼び出し元に戻らない. + 現在の最も内側のブロックを _value_ で終了する.ブロックは引数で与え + られた _value_ を返す.この関数は直接の呼び出し元に戻らない. === 例外・エラー -void rb_warning(const char *fmt, ...) :: +void rb_warning(const char *fmt, ...) :: - rb_verbose時に標準エラー出力に警告情報を表示する.引数は + +rb_verbose+ 時に標準エラー出力に警告情報を表示する.引数は printf()と同じ. -void rb_raise(rb_eRuntimeError, const char *fmt, ...) :: +void rb_raise(rb_eRuntimeError, const char *fmt, ...) :: - RuntimeError例外を発生させる.引数はprintf()と同じ. + RuntimeError 例外を発生させる._fmt_ 以下の引数はprintf()と同じ. -void rb_raise(VALUE exception, const char *fmt, ...) :: +void rb_raise(VALUE exception, const char *fmt, ...) :: - exceptionで指定した例外を発生させる.fmt以下の引数は - printf()と同じ. + _exception_ で指定した例外を発生させる._fmt_ 以下の引数はprintf()と同じ. -void rb_fatal(const char *fmt, ...) :: +void rb_fatal(const char *fmt, ...) :: 致命的例外を発生させる.通常の例外処理は行なわれず, インター - プリタが終了する(ただしensureで指定されたコードは終了前に + プリタが終了する(ただし +ensure+ で指定されたコードは終了前に 実行される). -void rb_bug(const char *fmt, ...) :: +void rb_bug(const char *fmt, ...) :: インタープリタなどプログラムのバグでしか発生するはずのない 状況の時呼ぶ.インタープリタはコアダンプし直ちに終了する. 例外処理は一切行なわれない. -注意: "%"PRIsVALUEがObject#to_s('+'フラグが指定されていると -きはObject#inspect)を使ったVALUEの出力に利用できる.これは -"%i"と衝突するため,整数には"%d"を使用すること. +注意: "%"PRIsVALUEが Object#to_s('+'フラグが指定されていると +きは Object#inspect)を使ったVALUEの出力に利用できる.これは +"%i"と衝突するため,整数には"%d"を使用すること. === Rubyの初期化・実行 Rubyをアプリケーションに埋め込む場合には以下のインタフェース を使う.通常の拡張ライブラリには必要ない. -void ruby_init() :: +void ruby_init() :: Rubyインタプリタの初期化を行なう. -void *ruby_options(int argc, char **argv) :: +void *ruby_options(int argc, char **argv) :: Rubyインタプリタのコマンドライン引数の処理を行ない, Rubyのソースコードをコンパイルする. コンパイルされたソースへのポインタ,もしくは特殊値を返す. -int ruby_run_node(void *n) :: +int ruby_run_node(void *n) :: コンパイルされたコードを実行する. 実行に成功した場合はEXIT_SUCCESSを,エラーが起こったときはそれ以外を返す. -void ruby_script(char *name) :: +void ruby_script(char *name) :: Rubyのスクリプト名($0)を設定する. === インタプリタのイベントのフック -void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data) :: +void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data) :: 指定されたインタプリタのイベントに対するフック関数を追加します. eventsは以下の値のorでなければなりません: @@ -1640,74 +1808,78 @@ void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE RUBY_EVENT_RAISE RUBY_EVENT_ALL - rb_event_hook_func_tの定義は以下の通りです: + +rb_event_hook_func_t+ の定義は以下の通りです: typedef void (*rb_event_hook_func_t)(rb_event_t event, VALUE data, VALUE self, ID id, VALUE klass) - rb_add_event_hook() の第3引数 data は,フック関数の第2引数と - して渡されます.これは1.8では現在のNODEへのポインタでした.以 - 下の RB_EVENT_HOOKS_HAVE_CALLBACK_DATA も参照してください. + rb_add_event_hook() の第3引数 _data_ は,フック関数の第2引数 + として渡されます. + -- + これは1.8では現在の +NODE+ へのポインタでした. + ++ + 以下の +RB_EVENT_HOOKS_HAVE_CALLBACK_DATA+ も参照してください. -int rb_remove_event_hook(rb_event_hook_func_t func) :: +int rb_remove_event_hook(rb_event_hook_func_t func) :: 指定されたフック関数を削除します. === メモリ使用量 -void rb_gc_adjust_memory_usage(ssize_t diff) :: +void rb_gc_adjust_memory_usage(ssize_t diff) :: 登録された外部のメモリ使用量を調整します.この関数で外部のライブラリが - どのくらいメモリを使っているのかをGCに伝えることができます.正のdiffで - この関数を呼び出すとメモリ使用量の増加を意味します.新しいメモリブロッ - クが確保されたり,ブロックがより大きなサイズで再割り当てされたりした場 - 合などです.負のdiffでこの関数を呼び出すとメモリ使用量の減少を意味しま - す.メモリブロックが解放されたり,メモリブロックがより小さいサイズで再 - 確保されたりした場合などです.この関数はGCを引き起こすかもしれません. + どのくらいメモリを使っているのかをGCに伝えることができます.正の + _diff_ でこの関数を呼び出すとメモリ使用量の増加を意味します.新しいメ + モリブロックが確保されたり,ブロックがより大きなサイズで再割り当てされ + たりした場合などです.負の _diff_ でこの関数を呼び出すとメモリ使用量の + 減少を意味します.メモリブロックが解放されたり,メモリブロックがより小 + さいサイズで再確保されたりした場合などです.この関数はGCを引き起こすか + もしれません. === 互換性のためのマクロ APIの互換性をチェックするために以下のマクロがデフォルトで定義されています. -NORETURN_STYLE_NEW :: ++NORETURN_STYLE_NEW+ :: - NORETURN マクロが関数型マクロとして定義されていることを意味する. + +NORETURN+ マクロが関数型マクロとして定義されていることを意味する. -HAVE_RB_DEFINE_ALLOC_FUNC :: ++HAVE_RB_DEFINE_ALLOC_FUNC+ :: - rb_define_alloc_func() 関数が提供されていること,つまり + rb_define_alloc_func() 関数が提供されていること,つまり allocation framework が使われることを意味する. - have_func("rb_define_alloc_func", "ruby.h") + have_func("rb_define_alloc_func", "ruby.h") の結果と同じ. -HAVE_RB_REG_NEW_STR :: ++HAVE_RB_REG_NEW_STR+ :: - StringオブジェクトからRegexpオブジェクトを作る - rb_reg_new_str() 関数が提供されていることを意味する. - have_func("rb_reg_new_str", "ruby.h"). + String オブジェクトから Regexp オブジェクトを作る + rb_reg_new_str() 関数が提供されていることを意味する. + have_func("rb_reg_new_str", "ruby.h") の結果と同じ. -HAVE_RB_IO_T :: ++HAVE_RB_IO_T+ :: - rb_io_t 型が提供されていることを意味する. + +rb_io_t+ 型が提供されていることを意味する. -USE_SYMBOL_AS_METHOD_NAME :: ++USE_SYMBOL_AS_METHOD_NAME+ :: - メソッド名を返すメソッド,Module#methods, \#singleton_methods - などがSymbolを返すことを意味する. + メソッド名を返すメソッド, Kernel#methods, Object#singleton_methods + などが Symbol を返すことを意味する. -HAVE_RUBY_*_H :: +HAVE_RUBY_*_H :: - ruby.h で定義されている.対応するヘッダが提供されていること - を意味する.たとえば,HAVE_RUBY_ST_H が定義されている場合は - 単なる st.h ではなく ruby/st.h を使用する. + ruby.h で定義されている.対応するヘッダが提供されていることを意味する. + たとえば,+HAVE_RUBY_ST_H+ が定義されている場合は単なる st.h ではなく + ruby/st.h を使用する. これらのマクロに対応するヘッダーファイルは,拡張ライブラリ から直接インクルードしてもよい. -RB_EVENT_HOOKS_HAVE_CALLBACK_DATA :: ++RB_EVENT_HOOKS_HAVE_CALLBACK_DATA+ :: - rb_add_event_hook() がフック関数に渡す data を第3引数として + rb_add_event_hook()がフック関数に渡す _data_ を第3引数として 受け取ることを意味する. == Appendix C. extconf.rbで使える関数たち @@ -1715,133 +1887,135 @@ RB_EVENT_HOOKS_HAVE_CALLBACK_DATA :: extconf.rbの中では利用可能なコンパイル条件チェックの関数は以 下の通りである. -have_macro(macro, headers) :: +マクロ名に含まれる{VAR}は, _var_ の英小文字を大文字に,英数字 +以外の文字をアンダースコアに置換したものを示す. + +have_macro(macro, headers) :: - ヘッダファイルheaderをインクルードしてマクロmacroが定義さ - れているかどうかチェックする.マクロが定義されている時true - を返す. + ヘッダファイル _header_ をインクルードしてマクロ _macro_ が定義されて + いるかどうかチェックする.マクロが定義されている時 +true+ を返す. -have_library(lib, func) :: +have_library(lib, func) :: - 関数funcを定義しているライブラリlibの存在をチェックする. - チェックに成功すると,-llibを$libsに追加し,trueを返す. + 関数 _func_ を定義しているライブラリ _lib_ の存在をチェックする.チェッ + クに成功すると,_lib_ をリンクするための指定を$libsに追加し, + +true+ を返す. -find_library(lib, func, path...) :: +find_library(lib, func, path...) :: - 関数funcを定義しているライブラリlibの存在を -Lpath を追加 - しながらチェックする.チェックに成功すると,-llibを$libsに - 追加し,trueを返す. + 関数 _func_ を定義しているライブラリ _lib_ の存在を,ライブラリパスに + _path_ を追加しながらチェックする.チェックに成功すると,_lib_ をリン + クするための指定を$libsに追加し,+true+ を返す. -have_func(func, header) :: +have_func(func, header) :: - ヘッダファイルheaderをインクルードして関数funcの存在をチェ - ックする.funcが標準ではリンクされないライブラリ内のもので - ある時には先にhave_libraryでそのライブラリをチェックしてお - く事.チェックに成功すると,プリプロセッサマクロ - HAVE_{FUNC} を定義し,trueを返す. + ヘッダファイル _header_ をインクルードして関数 _func_ の存在をチェック + する._func_ が標準ではリンクされないライブラリ内のものである時には先 + に +have_library+ でそのライブラリをチェックしておく事.チェックに成功 + すると,プリプロセッサマクロHAVE_{FUNC} を定義し,+true+ を返 + す. -have_var(var, header) :: +have_var(var, header) :: - ヘッダファイルheaderをインクルードして変数varの存在をチェッ - クする.varが標準ではリンクされないライブラリ内のものであ - る時には先にhave_libraryでそのライブラリをチェックしておく - 事.チェックに成功すると,プリプロセッサマクロ - HAVE_{VAR} を定義し,trueを返す. + ヘッダファイル _header_ をインクルードして変数 _var_ の存在をチェック + する._var_ が標準ではリンクされないライブラリ内のものである時には先に + +have_library+ でそのライブラリをチェックしておく事.チェックに成功す + ると,プリプロセッサマクロHAVE_{VAR} を定義し,+true+ を返す. -have_header(header) :: +have_header(header) :: - ヘッダファイルの存在をチェックする.チェックに成功すると, - プリプロセッサマクロ HAVE_{HEADER_H} を定義し,trueを返す. - (スラッシュやドットはアンダースコアに置換される) + ヘッダファイルの存在をチェックする.チェックに成功すると,プリプロセッ + サマクロ HAVE_{HEADER_H}を定義し,+true+ を返す. -find_header(header, path...) :: +find_header(header, path...) :: - ヘッダファイルheaderの存在を -Ipath を追加しながらチェック - する.チェックに成功すると,プリプロセッサマクロ - HAVE_{HEADER_H} を定義し,trueを返す. - (スラッシュやドットはアンダースコアに置換される) + ヘッダファイル _header_ の存在を,インクルードパスに _path_ を追加しな + がらチェックする.チェックに成功すると,プリプロセッサマクロ + HAVE_{HEADER_H} を定義し,+true+ を返す. -have_struct_member(type, member[, header[, opt]]) :: +have_struct_member(type, member[, header[, opt]]) :: - ヘッダファイルheaderをインクルードして型typeが定義され, - なおかつメンバmemberが存在するかをチェックする.チェックに - 成功すると,プリプロセッサマクロ HAVE_{TYPE}_{MEMBER} を - 定義し,trueを返す. + ヘッダファイル _header_ をインクルードして,メンバ _member_ を持つ集 + 合型 _type_ が存在するかをチェックする.チェックに成功すると,プリプロ + セッサマクロ HAVE_{TYPE}_{MEMBER} を定義し,+true+ を返す. -have_type(type, header, opt) :: +have_type(type, header, opt) :: - ヘッダファイルheaderをインクルードして型typeが存在するかを + ヘッダファイル _header_ をインクルードして型 _type_ が存在するかを チェックする.チェックに成功すると,プリプロセッサマクロ - HAVE_TYPE_{TYPE} を定義し,trueを返す. + HAVE_TYPE_{TYPE}を定義し,trueを返す. -check_sizeof(type, header) :: +check_sizeof(type, header) :: - ヘッダファイルheaderをインクルードして型typeのchar単位サイ - ズを調べる.チェックに成功すると,プリプロセッサマクロ - SIZEOF_{TYPE} を定義し,そのサイズを返す.定義されていな - いときはnilを返す. + ヘッダファイル _header_ をインクルードして型 _type_ の +char+ 単位のサ + イズを調べる.チェックに成功すると,プリプロセッサマクロ + SIZEOF_{TYPE} を定義し,そのサイズを返す.定義されていないと + きは +nil+ を返す. -append_cppflags(array-of-flags[, opt]) :: -append_cflags(array-of-flags[, opt]) :: -append_ldflags(array-of-flags[, opt]) :: +append_cppflags(array-of-flags[, opt]) :: +append_cflags(array-of-flags[, opt]) :: +append_ldflags(array-of-flags[, opt]) :: - 各flagが使用可能であれば,それぞれ$CPPFLAGS, $CFLAGS, - $LDFLAGSに追加する.コンパイラのフラグには移植性がないので, - 変数に直接追加せずこれらを使うことが望ましい. + 各 _flag_ が使用可能であれば,それぞれ$CPPFLAGS,$CFLAGS, + $LDFLAGSに追加する.コンパイラのフラグには移植性がないので,変 + 数に直接追加せずこれらを使うことが望ましい. -create_makefile(target[, target_prefix]) :: +create_makefile(target[, target_prefix]) :: - 拡張ライブラリ用のMakefileを生成する.この関数を呼ばなけれ - ばそのライブラリはコンパイルされない.targetはモジュール名 - を表す. + 拡張ライブラリ用のMakefileを生成する.この関数を呼ばなければそのライブ + ラリはコンパイルされない._target_ はモジュール名を表す. -find_executable(command, path) :: +find_executable(command, path) :: - コマンドcommandをFile::PATH_SEPARATORで区切られたパス名の - リストpathから探す.pathがnilまたは省略された場合は,環境 - 変数PATHの値を使用する.実行可能なコマンドが見つかった場合 - はパスを含むファイル名,見つからなかった場合はnilを返す. + コマンド _command_ を +File::PATH_SEPARATOR+ で区切られたパス名のリス + ト _path_ から探す._path_ が +nil+ または省略された場合は,環境変数 + +PATH+ の値を使用する.実行可能なコマンドが見つかった場合はパスを含む + ファイル名,見つからなかった場合は +nil+ を返す. -with_config(withval[, default=nil]) :: +with_config(withval[, default=nil]) :: - コマンドライン上の--with-で指定されたオプション値 - を得る. + コマンドライン上の--with-_withval_ で指定されたオプション値を + 得る. -enable_config(config, *defaults) :: -disable_config(config, *defaults) :: +enable_config(config, *defaults) :: +disable_config(config, *defaults) :: - コマンドライン上の--enable-または - --disable-で指定された真偽値を得る. - --enable-が指定されていた場合はtrue, - --disable-が指定されていた場合はfalseを返す. - どちらも指定されていない場合は,ブロックつきで呼び出されて - いる場合は*defaultsをyieldした結果,ブロックなしなら - \*defaultsを返す. + コマンドライン上の--enable-_config_ または + --disable-_config_ で指定された真偽値を得る. + --enable-_config_ が指定されていた場合は +true+, + --disable-_config_ が指定されていた場合は +false+ を返す.ど + ちらも指定されていない場合は,ブロックつきで呼び出されている場合は + *defaultsを +yield+ した結果,ブロックなしなら + *defaultsを返す. -dir_config(target[, default_dir]) :: -dir_config(target[, default_include, default_lib]) :: +dir_config(target[, default_dir]) :: +dir_config(target[, default_include, default_lib]) :: - コマンドライン上の--with--dir, --with--include, - --with--libのいずれかで指定されるディレクトリを - $CFLAGS や $LDFLAGS に追加する.--with--dir=/pathは - --with--include=/path/include --with--lib=/path/lib - と等価である.追加された include ディレクトリと lib ディレ - クトリの配列を返す. ([include_dir, lib_dir]) + コマンドライン上の--with-_target_-dir, + --with-_target_-include, + --with-_target_-libのいずれかで指定されるディレクト + リを$CFLAGS$LDFLAGSに追加する. + --with-_target_-dir=/pathは + --with-_target_-include=/path/include + --with-_target_-lib=/path/libと等価である.追 + 加された _include_ ディレクトリと _lib_ ディレクトリの配列を返す. + ([include_dir, lib_dir]) -pkg_config(pkg, option=nil) :: +pkg_config(pkg, option=nil) :: - pkg-configコマンドからパッケージpkgの情報を [cflags, ldflags, libs] - の配列として得る.$CFLAGS, $LDFLAGS, $libs にはそれぞれの値が - 追加される. + pkg-configコマンドからパッケージpkgの情報を [cflags, + ldflags, libs]の配列として得る. + $CFLAGS,$LDFLAGS,$libsにはそれぞれの値が追加され + る. - pkg-configの実際のコマンドは,以下の順で試される. + pkg-configの実際のコマンドは,以下の順で試される. - 1. コマンドラインで--with-{pkg}-config={command}オプションが - 指定された場合: {command} {option} - 2. {pkg}-config {option} - 3. pkg-config {option} {pkg} + 1. コマンドラインで--with-_pkg_-config=_command_ オ + プションが指定された場合: _command_ _option_ + 2. _pkg_-config _option_ + 3. pkg-config _option_ _pkg_ - optionが指定された場合は,上記の配列の代わりにそのオプションを + _option_ が指定された場合は,上記の配列の代わりにそのオプションを 指定して得られた出力をstripしたものを返す. == Appendix D. 世代別GC @@ -1853,27 +2027,26 @@ RGenGCは,過去の拡張ライブラリに(ほぼ)互換性を保つよ ただし,対応をすることで性能を向上することができる可能性があります.もし 拡張ライブラリに高い性能が必要である場合は対応を検討して下さい. -とくにRARRAY_PTR()/RHASH_TBL()のようなマクロを用いてポインタに直接アクセ -スするようなコードは書かないようにして下さい.代わりに,rb_ary_aref(), -rb_ary_store() などの,適切な API 関数を利用するようにして下さい. +とくにRARRAY_PTR()/RHASH_TBL()のようなマクロを用いてポ +インタに直接アクセスするようなコードは書かないようにして下さい.代わりに, +rb_ary_aref(), rb_ary_store() などの,適切な API 関数 +を利用するようにして下さい. -そのほか,対応についての詳細は {Appendix D. Generational -GC}[rdoc-ref:extension.rdoc@Appendix+D.+Generational+GC]を参 -照して下さい. +そのほか,対応についての詳細は {Appendix D. Generational GC +}[rdoc-ref:extension.rdoc@Appendix+D.+Generational+GC]を参照して下さい. == Appendix E. Ractor サポート -Ruby 3.0 から、Ruby プログラムを並列に実行するための仕組みである Ractor -が導入されました。適切に並列に実行するためには、Ractor サポートが必要に -なります。サポートしていないライブラリは、メイン Ractor 以外で実行すると -エラーになります(Ractor::UnsafeError)。 +Ruby 3.0 から,Ruby プログラムを並列に実行するための仕組みである Ractor +が導入されました.適切に並列に実行するためには,Ractor サポートが必要に +なります.サポートしていないライブラリは,メイン Ractor 以外で実行すると +エラーになります(Ractor::UnsafeError). -Ractor をサポートするための詳細は、{Appendix F. Ractor -support}[rdoc-ref:extension.rdoc@Appendix+F.+Ractor+support] -を参照してください。 +Ractor をサポートするための詳細は,{Appendix F. Ractor support +}[rdoc-ref:extension.rdoc@Appendix+F.+Ractor+support]を参照してください. -- Local variables: -fill-column: 60 +fill-column: 72 end: ++ diff --git a/doc/extension.rdoc b/doc/extension.rdoc index 9fc507706effde..95d8139e2c6132 100644 --- a/doc/extension.rdoc +++ b/doc/extension.rdoc @@ -12,7 +12,7 @@ In C, variables have types and data do not have types. In contrast, Ruby variables do not have a static type, and data themselves have types, so data will need to be converted between the languages. -Objects in Ruby are represented by the C type `VALUE'. Each VALUE +Objects in Ruby are represented by the C type +VALUE+. Each VALUE data has its data type. To retrieve C data from a VALUE, you need to: @@ -26,41 +26,41 @@ Converting to the wrong data type may cause serious problems. The Ruby interpreter has the following data types: -T_NIL :: nil -T_OBJECT :: ordinary object -T_CLASS :: class -T_MODULE :: module -T_FLOAT :: floating point number -T_STRING :: string -T_REGEXP :: regular expression -T_ARRAY :: array -T_HASH :: associative array -T_STRUCT :: (Ruby) structure -T_BIGNUM :: multi precision integer -T_FIXNUM :: Fixnum(31bit or 63bit integer) -T_COMPLEX :: complex number -T_RATIONAL :: rational number -T_FILE :: IO -T_TRUE :: true -T_FALSE :: false -T_DATA :: data -T_SYMBOL :: symbol ++T_NIL+ :: +nil+ ++T_OBJECT+ :: ordinary object ++T_CLASS+ :: class ++T_MODULE+ :: module ++T_FLOAT+ :: floating point number ++T_STRING+ :: string ++T_REGEXP+ :: regular expression ++T_ARRAY+ :: array ++T_HASH+ :: associative array ++T_STRUCT+ :: (Ruby) structure ++T_BIGNUM+ :: multi precision integer ++T_FIXNUM+ :: Fixnum(31bit or 63bit integer) ++T_COMPLEX+ :: complex number ++T_RATIONAL+ :: rational number ++T_FILE+ :: IO ++T_TRUE+ :: +true+ ++T_FALSE+ :: +false+ ++T_DATA+ :: data ++T_SYMBOL+ :: symbol In addition, there are several other types used internally: -T_ICLASS :: included module -T_MATCH :: MatchData object -T_UNDEF :: undefined -T_NODE :: syntax tree node -T_ZOMBIE :: object awaiting finalization ++T_ICLASS+ :: included module ++T_MATCH+ :: MatchData object ++T_UNDEF+ :: undefined ++T_NODE+ :: syntax tree node ++T_ZOMBIE+ :: object awaiting finalization Most of the types are represented by C structures. === Check type of the VALUE data -The macro TYPE() defined in ruby.h shows the data type of the VALUE. -TYPE() returns the constant number T_XXXX described above. To handle -data types, your code will look something like this: +The macro TYPE() defined in ruby.h shows the data type of the VALUE. +TYPE() returns the constant number T__XXXX_ described above. +To handle data types, your code will look something like this: switch (TYPE(obj)) { case T_FIXNUM: @@ -92,54 +92,56 @@ There are also faster check macros for fixnums and nil. === Convert VALUE into C data -The data for type T_NIL, T_FALSE, T_TRUE are nil, false, true -respectively. They are singletons for the data type. -The equivalent C constants are: Qnil, Qfalse, Qtrue. -RTEST() will return true if a VALUE is neither Qfalse nor Qnil. -If you need to differentiate Qfalse from Qnil, -specifically test against Qfalse. - -The T_FIXNUM data is a 31bit or 63bit length fixed integer. -This size depends on the size of long: if long is 32bit then -T_FIXNUM is 31bit, if long is 64bit then T_FIXNUM is 63bit. -T_FIXNUM can be converted to a C integer by using the -FIX2INT() macro or FIX2LONG(). Though you have to check that the -data is really FIXNUM before using them, they are faster. FIX2LONG() -never raises exceptions, but FIX2INT() raises RangeError if the -result is bigger or smaller than the size of int. -There are also NUM2INT() and NUM2LONG() which converts any Ruby -numbers into C integers. These macros include a type check, -so an exception will be raised if the conversion failed. NUM2DBL() +The data for type +T_NIL+, +T_FALSE+, +T_TRUE+ are +nil+, +false+, ++true+ respectively. They are singletons for the data type. The +equivalent C constants are: +Qnil+, +Qfalse+, +Qtrue+. +RTEST() will return true if a VALUE is neither +Qfalse+ nor ++Qnil+. If you need to differentiate +Qfalse+ from +Qnil+, +specifically test against +Qfalse+. + +The +T_FIXNUM+ data is a 31bit or 63bit length fixed integer. This +size depends on the size of long: if long is 32bit then +T_FIXNUM+ is +31bit, if long is 64bit then +T_FIXNUM+ is 63bit. +T_FIXNUM+ can be +converted to a C integer by using the FIX2INT() macro or +FIX2LONG(). Though you have to check that the data is really +FIXNUM before using them, they are faster. FIX2LONG() never +raises exceptions, but FIX2INT() raises RangeError if the +result is bigger or smaller than the size of int. There are also +NUM2INT() and NUM2LONG() which converts any Ruby +numbers into C integers. These macros include a type check, so an +exception will be raised if the conversion failed. NUM2DBL() can be used to retrieve the double float value in the same way. -You can use the macros -StringValue() and StringValuePtr() to get a char* from a VALUE. -StringValue(var) replaces var's value with the result of "var.to_str()". -StringValuePtr(var) does the same replacement and returns the char* -representation of var. These macros will skip the replacement if var -is a String. Notice that the macros take only the lvalue as their -argument, to change the value of var in place. - -You can also use the macro named StringValueCStr(). This is just -like StringValuePtr(), but always adds a NUL character at the end of -the result. If the result contains a NUL character, this macro causes -the ArgumentError exception. -StringValuePtr() doesn't guarantee the existence of a NUL at the end -of the result, and the result may contain NUL. - -Other data types have corresponding C structures, e.g. struct RArray -for T_ARRAY etc. The VALUE of the type which has the corresponding -structure can be cast to retrieve the pointer to the struct. The -casting macro will be of the form RXXXX for each data type; for -instance, RARRAY(obj). See "ruby.h". However, we do not recommend -to access RXXXX data directly because these data structures are complex. -Use corresponding rb_xxx() functions to access the internal struct. -For example, to access an entry of array, use rb_ary_entry(ary, offset) -and rb_ary_store(ary, offset, obj). +You can use the macros StringValue() and +StringValuePtr() to get a char* from a VALUE. +StringValue(var) replaces var's value with the result of +"var.to_str()". StringValuePtr(var) does the same +replacement and returns the char* representation of var. These macros +will skip the replacement if var is a String. Notice that the macros +take only the lvalue as their argument, to change the value of var in +place. + +You can also use the macro named StringValueCStr(). This is +just like StringValuePtr(), but always adds a NUL character +at the end of the result. If the result contains a NUL character, this +macro causes the ArgumentError exception. StringValuePtr() +doesn't guarantee the existence of a NUL at the end of the result, and +the result may contain NUL. + +Other data types have corresponding C structures, e.g. struct +RArray for +T_ARRAY+ etc. The VALUE of the type which has the +corresponding structure can be cast to retrieve the pointer to the +struct. The casting macro will be of the form RXXXX for each data +type; for instance, RARRAY(obj). See "ruby.h". However, we +do not recommend to access RXXXX data directly because these data +structures are complex. Use corresponding rb_xxx() functions to +access the internal struct. For example, to access an entry of array, +use rb_ary_entry(ary, offset) and rb_ary_store(ary, +offset, obj). There are some accessing macros for structure members, for example -`RSTRING_LEN(str)' to get the size of the Ruby String object. The -allocated region can be accessed by `RSTRING_PTR(str)'. +RSTRING_LEN(str) to get the size of the Ruby String object. The +allocated region can be accessed by RSTRING_PTR(str). Notice: Do not change the value of the structure directly, unless you are responsible for the result. This ends up being the cause of @@ -149,7 +151,7 @@ interesting bugs. To convert C data to Ruby values: -FIXNUM :: ++FIXNUM+ :: left shift 1 bit, and turn on its least significant bit (LSB). @@ -165,11 +167,11 @@ structures are defined in . To convert C numbers to Ruby values, use these macros: -INT2FIX() :: for integers within 31bits. -INT2NUM() :: for arbitrary sized integers. +INT2FIX() :: for integers within 31bits. +INT2NUM() :: for arbitrary sized integers. -INT2NUM() converts an integer into a Bignum if it is out of the FIXNUM -range, but is a bit slower. +INT2NUM() converts an integer into a Bignum if it is out +of the +FIXNUM+ range, but is a bit slower. === Manipulating Ruby object @@ -180,130 +182,130 @@ listed below: ==== String functions -rb_str_new(const char *ptr, long len) :: +rb_str_new(const char *ptr, long len) :: Creates a new Ruby string. -rb_str_new2(const char *ptr) :: -rb_str_new_cstr(const char *ptr) :: +rb_str_new2(const char *ptr) :: +rb_str_new_cstr(const char *ptr) :: Creates a new Ruby string from a C string. This is equivalent to - rb_str_new(ptr, strlen(ptr)). + rb_str_new(ptr, strlen(ptr)). -rb_str_new_literal(const char *ptr) :: +rb_str_new_literal(const char *ptr) :: Creates a new Ruby string from a C string literal. -rb_sprintf(const char *format, ...) :: -rb_vsprintf(const char *format, va_list ap) :: +rb_sprintf(const char *format, ...) :: +rb_vsprintf(const char *format, va_list ap) :: Creates a new Ruby string with printf(3) format. - Note: In the format string, "%"PRIsVALUE can be used for Object#to_s - (or Object#inspect if '+' flag is set) output (and related argument - must be a VALUE). Since it conflicts with "%i", for integers in - format strings, use "%d". + Note: In the format string, "%"PRIsVALUE can be used for Object#to_s + (or Object#inspect if + flag is set) output (and related argument + must be a VALUE). Since it conflicts with "%i", for integers in + format strings, use "%d". -rb_str_append(VALUE str1, VALUE str2) :: +rb_str_append(VALUE str1, VALUE str2) :: Appends Ruby string str2 to Ruby string str1. -rb_str_cat(VALUE str, const char *ptr, long len) :: +rb_str_cat(VALUE str, const char *ptr, long len) :: Appends len bytes of data from ptr to the Ruby string. -rb_str_cat2(VALUE str, const char* ptr) :: -rb_str_cat_cstr(VALUE str, const char* ptr) :: +rb_str_cat2(VALUE str, const char* ptr) :: +rb_str_cat_cstr(VALUE str, const char* ptr) :: Appends C string ptr to Ruby string str. This function is - equivalent to rb_str_cat(str, ptr, strlen(ptr)). + equivalent to rb_str_cat(str, ptr, strlen(ptr)). -rb_str_catf(VALUE str, const char* format, ...) :: -rb_str_vcatf(VALUE str, const char* format, va_list ap) :: +rb_str_catf(VALUE str, const char* format, ...) :: +rb_str_vcatf(VALUE str, const char* format, va_list ap) :: Appends C string format and successive arguments to Ruby string str according to a printf-like format. These functions are - equivalent to rb_str_append(str, rb_sprintf(format, ...)) and - rb_str_append(str, rb_vsprintf(format, ap)), respectively. + equivalent to rb_str_append(str, rb_sprintf(format, ...)) and + rb_str_append(str, rb_vsprintf(format, ap)), respectively. -rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) :: -rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) :: +rb_enc_str_new(const char *ptr, long len, rb_encoding *enc) :: +rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc) :: Creates a new Ruby string with the specified encoding. -rb_enc_str_new_literal(const char *ptr, rb_encoding *enc) :: +rb_enc_str_new_literal(const char *ptr, rb_encoding *enc) :: Creates a new Ruby string from a C string literal with the specified encoding. -rb_usascii_str_new(const char *ptr, long len) :: -rb_usascii_str_new_cstr(const char *ptr) :: +rb_usascii_str_new(const char *ptr, long len) :: +rb_usascii_str_new_cstr(const char *ptr) :: Creates a new Ruby string with encoding US-ASCII. -rb_usascii_str_new_literal(const char *ptr) :: +rb_usascii_str_new_literal(const char *ptr) :: Creates a new Ruby string from a C string literal with encoding US-ASCII. -rb_utf8_str_new(const char *ptr, long len) :: -rb_utf8_str_new_cstr(const char *ptr) :: +rb_utf8_str_new(const char *ptr, long len) :: +rb_utf8_str_new_cstr(const char *ptr) :: Creates a new Ruby string with encoding UTF-8. -rb_utf8_str_new_literal(const char *ptr) :: +rb_utf8_str_new_literal(const char *ptr) :: Creates a new Ruby string from a C string literal with encoding UTF-8. -rb_str_resize(VALUE str, long len) :: +rb_str_resize(VALUE str, long len) :: Resizes a Ruby string to len bytes. If str is not modifiable, this function raises an exception. The length of str must be set in advance. If len is less than the old length the content beyond len bytes is discarded, else if len is greater than the old length the content beyond the old length bytes will not be preserved but - will be garbage. Note that RSTRING_PTR(str) may change by calling + will be garbage. Note that RSTRING_PTR(str) may change by calling this function. -rb_str_set_len(VALUE str, long len) :: +rb_str_set_len(VALUE str, long len) :: Sets the length of a Ruby string. If str is not modifiable, this function raises an exception. This function preserves the content - up to len bytes, regardless RSTRING_LEN(str). len must not exceed + up to len bytes, regardless RSTRING_LEN(str). len must not exceed the capacity of str. -rb_str_modify(VALUE str) :: +rb_str_modify(VALUE str) :: Prepares a Ruby string to modify. If str is not modifiable, this function raises an exception, or if the buffer of str is shared, this function allocates new buffer to make it unshared. Always you MUST call this function before modifying the contents using - RSTRING_PTR and/or rb_str_set_len. + +RSTRING_PTR+ and/or +rb_str_set_len+. ==== Array functions -rb_ary_new() :: +rb_ary_new() :: Creates an array with no elements. -rb_ary_new2(long len) :: -rb_ary_new_capa(long len) :: +rb_ary_new2(long len) :: +rb_ary_new_capa(long len) :: Creates an array with no elements, allocating internal buffer for len elements. -rb_ary_new3(long n, ...) :: -rb_ary_new_from_args(long n, ...) :: +rb_ary_new3(long n, ...) :: +rb_ary_new_from_args(long n, ...) :: Creates an n-element array from the arguments. -rb_ary_new4(long n, VALUE *elts) :: -rb_ary_new_from_values(long n, VALUE *elts) :: +rb_ary_new4(long n, VALUE *elts) :: +rb_ary_new_from_values(long n, VALUE *elts) :: Creates an n-element array from a C array. -rb_ary_to_ary(VALUE obj) :: +rb_ary_to_ary(VALUE obj) :: Converts the object into an array. Equivalent to Object#to_ary. @@ -311,32 +313,32 @@ rb_ary_to_ary(VALUE obj) :: There are many functions to operate an array. They may dump core if other types are given. -rb_ary_aref(int argc, const VALUE *argv, VALUE ary) :: +rb_ary_aref(int argc, const VALUE *argv, VALUE ary) :: Equivalent to Array#[]. -rb_ary_entry(VALUE ary, long offset) :: +rb_ary_entry(VALUE ary, long offset) :: - ary\[offset] + ary[offset] -rb_ary_store(VALUE ary, long offset, VALUE obj) :: +rb_ary_store(VALUE ary, long offset, VALUE obj) :: - ary\[offset] = obj + ary[offset] = obj -rb_ary_subseq(VALUE ary, long beg, long len) :: +rb_ary_subseq(VALUE ary, long beg, long len) :: - ary[beg, len] + ary[beg, len] -rb_ary_push(VALUE ary, VALUE val) :: -rb_ary_pop(VALUE ary) :: -rb_ary_shift(VALUE ary) :: -rb_ary_unshift(VALUE ary, VALUE val) :: +rb_ary_push(VALUE ary, VALUE val) :: +rb_ary_pop(VALUE ary) :: +rb_ary_shift(VALUE ary) :: +rb_ary_unshift(VALUE ary, VALUE val) :: - ary.push, ary.pop, ary.shift, ary.unshift + ary.push(val), ary.pop, ary.shift, ary.unshift(val) -rb_ary_cat(VALUE ary, const VALUE *ptr, long len) :: +rb_ary_cat(VALUE ary, const VALUE *ptr, long len) :: - Appends len elements of objects from ptr to the array. + Appends _len_ elements of objects from _ptr_ to the array. == Extending Ruby with C @@ -374,25 +376,25 @@ To define methods or singleton methods, use these functions: void rb_define_singleton_method(VALUE object, const char *name, VALUE (*func)(ANYARGS), int argc) -The `argc' represents the number of the arguments to the C function, +The _argc_ represents the number of the arguments to the C function, which must be less than 17. But I doubt you'll need that many. -If `argc' is negative, it specifies the calling sequence, not number of +If _argc_ is negative, it specifies the calling sequence, not number of the arguments. -If argc is -1, the function will be called as: +If _argc_ is -1, the function will be called as: VALUE func(int argc, VALUE *argv, VALUE obj) -where argc is the actual number of arguments, argv is the C array of -the arguments, and obj is the receiver. +where _argc_ is the actual number of arguments, _argv_ is the C array of +the arguments, and _obj_ is the receiver. -If argc is -2, the arguments are passed in a Ruby array. The function +If _argc_ is -2, the arguments are passed in a Ruby array. The function will be called like: VALUE func(VALUE obj, VALUE args) -where obj is the receiver, and args is the Ruby array containing +where _obj_ is the receiver, and _args_ is the Ruby array containing actual arguments. There are some more functions to define methods. One takes an ID @@ -408,9 +410,9 @@ There are two functions to define private/protected methods: void rb_define_protected_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) -At last, rb_define_module_function defines a module function, +At last, +rb_define_module_function+ defines a module function, which are private AND singleton methods of the module. -For example, sqrt is a module function defined in the Math module. +For example, +sqrt+ is a module function defined in the Math module. It can be called in the following way: Math.sqrt(4) @@ -438,12 +440,12 @@ To define a reader/writer for an attribute, void rb_define_attr(VALUE klass, const char *name, int read, int write) -To define and undefine the `allocate' class method, +To define and undefine the +allocate+ class method, void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass)); void rb_undef_alloc_func(VALUE klass); -func has to take the klass as the argument and return a newly +_func_ has to take the _klass_ as the argument and return a newly allocated instance. This instance should be as empty as possible, without any expensive (including external) resources. @@ -456,13 +458,13 @@ To specify whether keyword arguments are passed when calling super: VALUE rb_call_super_kw(int argc, const VALUE *argv, int kw_splat) -+kw_splat+ can have these possible values (used by all methods that accept -+kw_splat+ argument): +_kw_splat_ can have these possible values (used by all methods that accept +_kw_splat_ argument): -RB_NO_KEYWORDS :: Do not pass keywords -RB_PASS_KEYWORDS :: Pass keywords, final argument should be a hash of keywords -RB_PASS_CALLED_KEYWORDS :: Pass keywords if current method was called with - keywords, useful for argument delegation ++RB_NO_KEYWORDS+ :: Do not pass keywords ++RB_PASS_KEYWORDS+ :: Pass keywords, final argument should be a hash of keywords ++RB_PASS_CALLED_KEYWORDS+ :: Pass keywords if current method was called with + keywords, useful for argument delegation To achieve the receiver of the current scope (if no other way is available), you can use: @@ -498,8 +500,8 @@ function: VALUE rb_eval_string_protect(const char *str, int *state) -It returns nil when an error occurred. Moreover, *state is zero if str was -successfully evaluated, or nonzero otherwise. +It returns +nil+ when an error occurred. Moreover, *state is +zero if _str_ was successfully evaluated, or nonzero otherwise. ==== ID or Symbol @@ -527,12 +529,13 @@ argument by using rb_check_id(volatile VALUE *name) rb_check_id_cstr(const char *name, long len, rb_encoding *enc) -These functions try to convert the argument to a String if it was not -a Symbol nor a String. The second function stores the converted -result into *name, and returns 0 if the string is not a known symbol. -After this function returned a non-zero value, *name is always a -Symbol or a String, otherwise it is a String if the result is 0. -The third function takes NUL-terminated C string, not Ruby VALUE. +These functions try to convert the argument to a String if it was not a +Symbol nor a String. The second function stores the converted result into +*name, and returns 0 if the string is not a known symbol. +After this function returned a non-zero value, *name is +always a Symbol or a String, otherwise it is a String if the result is +0. The third function takes C string (pointer to +char+ array) and its +length, not Ruby VALUE. You can retrieve Symbol from Ruby object (Symbol or String) given as an argument by using @@ -558,8 +561,8 @@ To invoke methods directly, you can use the function below VALUE rb_funcall(VALUE recv, ID mid, int argc, ...) -This function invokes a method on the recv, with the method name -specified by the symbol mid. +This function invokes a method on the _recv_, with the method name +specified by the symbol _mid_. ==== Accessing the variables and constants @@ -572,7 +575,7 @@ The functions to access/modify instance variables are below: VALUE rb_ivar_get(VALUE obj, ID id) VALUE rb_ivar_set(VALUE obj, ID id, VALUE val) -id must be the symbol, which can be retrieved by rb_intern(). +_id_ must be the symbol, which can be retrieved by rb_intern(). To access the constants of the class/module: @@ -587,14 +590,14 @@ See also Constant Definition above. As stated in section 1.3, the following Ruby constants can be referred from C. -Qtrue :: -Qfalse :: +Qtrue :: +Qfalse :: - Boolean values. Qfalse is false in C also (i.e. 0). + Boolean values. +Qfalse+ is +false+ in C also (i.e. 0). -Qnil :: +Qnil :: - Ruby nil in C scope. + Ruby +nil+ in C scope. === Global variables shared between C and Ruby @@ -604,25 +607,25 @@ variables. To define them, you can use functions listed below: void rb_define_variable(const char *name, VALUE *var) This function defines the variable which is shared by both environments. -The value of the global variable pointed to by `var' can be accessed -through Ruby's global variable named `name'. +The value of the global variable pointed to by _var_ can be accessed +through Ruby's global variable named _name_. You can define read-only (from Ruby, of course) variables using the function below. void rb_define_readonly_variable(const char *name, VALUE *var) -You can define hooked variables. The accessor functions (getter and -setter) are called on access to the hooked variables. +You can define hooked variables. The accessor functions (_getter_ and +_setter_) are called on access to the hooked variables. void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) If you need to supply either setter or getter, just supply 0 for the -hook you don't need. If both hooks are 0, rb_define_hooked_variable() -works just like rb_define_variable(). +hook you don't need. If both hooks are 0, rb_define_hooked_variable() +works just like rb_define_variable(). -The prototypes of the getter and setter functions are as follows: +The prototypes of the _getter_ and _setter_ functions are as follows: VALUE (*getter)(ID id, VALUE *var); void (*setter)(VALUE val, ID id, VALUE *var); @@ -633,7 +636,7 @@ variable. The value of the variable will be set/get only by hooks. void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) -The prototypes of the getter and setter functions are as follows: +The prototypes of the _getter_ and _setter_ functions are as follows: VALUE (*getter)(ID id); void (*setter)(VALUE val, ID id); @@ -654,22 +657,27 @@ work. ==== C struct to Ruby object -You can convert sval, a pointer to your struct, into a Ruby object -with the next macro. +You can convert _sval_, a pointer to your struct, into a Ruby object with the +next macro. TypedData_Wrap_Struct(klass, data_type, sval) -TypedData_Wrap_Struct() returns a created Ruby object as a VALUE. +TypedData_Wrap_Struct() returns a created Ruby object as a +VALUE. + +This macro cannot be used with data types that have the +RUBY_TYPED_EMBEDDABLE+ +flag; use +TypedData_Make_Struct+ or +rb_data_typed_object_zalloc+ for such +types. -The klass argument is the class for the object. The klass should -derive from rb_cObject, and the allocator must be set by calling -rb_define_alloc_func or rb_undef_alloc_func. +The _klass_ argument is the class for the object. The _klass_ should derive +from _rb_cObject_, and the allocator must be set by calling ++rb_define_alloc_func+ or +rb_undef_alloc_func+. -data_type is a pointer to a const rb_data_type_t which describes -how Ruby should manage the struct. +_data_type_ is a pointer to a const +rb_data_type_t+ which describes how Ruby +should manage the struct. -rb_data_type_t is defined like this. Let's take a look at each -member of the struct. ++rb_data_type_t+ is roughly defined like this. Fields reserved for future use +are omitted. typedef struct rb_data_type_struct rb_data_type_t; @@ -680,66 +688,62 @@ member of the struct. void (*dfree)(void*); size_t (*dsize)(const void *); void (*dcompact)(void*); - void *reserved[1]; + /* reserved fields */ } function; const rb_data_type_t *parent; void *data; VALUE flags; }; -wrap_struct_name is an identifier of this instance of the struct. -It is basically used for collecting and emitting statistics. -So the identifier must be unique in the process, but doesn't need -to be valid as a C or Ruby identifier. ++wrap_struct_name+ is an identifier of this instance of the struct. It is +basically used for collecting and emitting statistics. So the identifier should +be unique in the process, but doesn't need to be valid as a C or Ruby +identifier. -These dmark / dfree functions are invoked during GC execution. No -object allocations are allowed during it, so do not allocate ruby -objects inside them. +These +dmark+ / +dfree+ functions are invoked during GC execution. No object +allocations are allowed during it, so do not allocate ruby objects inside them. -dmark is a function to mark Ruby objects referred from your struct. -It must mark all references from your struct with rb_gc_mark or -its family if your struct keeps such references. ++dmark+ is a function to mark Ruby objects referred from your struct. It must +mark all references from your struct with +rb_gc_mark+ or its family if your +struct keeps such references. -- Note that it is recommended to avoid such a reference. ++ -dfree is a function to free the pointer allocation. -If this is RUBY_DEFAULT_FREE, the pointer will be just freed. - -dsize calculates memory consumption in bytes by the struct. -Its parameter is a pointer to your struct. -You can pass 0 as dsize if it is hard to implement such a function. -But it is still recommended to avoid 0. ++dfree+ is a function to free the pointer allocation. If this is ++RUBY_DEFAULT_FREE+, the pointer will be just freed. -dcompact is invoked when memory compaction took place. -Referred Ruby objects that were marked by rb_gc_mark_movable() -can here be updated per rb_gc_location(). ++dsize+ calculates memory consumption in bytes by the struct. Its parameter is +a pointer to your struct. You can pass 0 as dsize if it is hard to implement +such a function. But it is still recommended to avoid 0. -You have to fill reserved with 0. ++dcompact+ is invoked when memory compaction took place. Referred Ruby objects +that were marked by rb_gc_mark_movable() can here be updated per +rb_gc_location(). -parent can point to another C type definition that the Ruby object -is inherited from. Then TypedData_Get_Struct() does also accept ++parent+ can point to another C type definition that the Ruby object is +inherited from. Then TypedData_Get_Struct() does also accept derived objects. -You can fill "data" with an arbitrary value for your use. -Ruby does nothing with the member. +You can fill +data+ with an arbitrary value for your use. Ruby does nothing +with the member. -flags is a bitwise-OR of the following flag values. -Since they require deep understanding of garbage collector in Ruby, -you can just set 0 to flags if you are not sure. ++flags+ is a bitwise-OR of the following flag values. Since they require deep +understanding of garbage collector in Ruby, you can just set 0 to +flags+ if you +are not sure. -RUBY_TYPED_FREE_IMMEDIATELY :: ++RUBY_TYPED_FREE_IMMEDIATELY+ :: - This flag makes the garbage collector immediately invoke dfree() + This flag makes the garbage collector immediately invoke dfree() during GC when it need to free your struct. - You can specify this flag if the dfree never unlocks Ruby's + You can specify this flag if the dfree never unlocks Ruby's internal lock (GVL). - If this flag is not set, Ruby defers invocation of dfree() - and invokes dfree() at the same time as finalizers. + If this flag is not set, Ruby defers invocation of dfree() + and invokes dfree() at the same time as finalizers. -RUBY_TYPED_WB_PROTECTED :: ++RUBY_TYPED_WB_PROTECTED+ :: It shows that implementation of the object supports write barriers. If this flag is set, Ruby is better able to do garbage collection @@ -752,16 +756,16 @@ RUBY_TYPED_WB_PROTECTED :: More about write barriers can be found in {Generational GC}[rdoc-ref:@Appendix+D.+Generational+GC]. -RUBY_TYPED_FROZEN_SHAREABLE :: ++RUBY_TYPED_FROZEN_SHAREABLE+ :: This flag indicates that the object is shareable object if the object is frozen. See {Ractor support}[rdoc-ref:@Appendix+F.+Ractor+support] more details. If this flag is not set, the object can not become a shareable - object by Ractor.make_shareable() method. + object by Ractor.make_shareable() method. -RUBY_TYPED_EMBEDDABLE :: ++RUBY_TYPED_EMBEDDABLE+ :: This flag indicates that Ruby may store the C struct inside the object slot, rather than allocate it separately with +malloc+. @@ -769,8 +773,8 @@ RUBY_TYPED_EMBEDDABLE :: For instance if it's too large to fit into one of the available slot sizes. Embedding the C struct inside the object slot reduces pointer chasing, - malloc overhead, and improves sweep performance. - In some cases, it can also reduce the memory footprint of the object. + +malloc+ overhead, and improves sweep performance. In some cases, it can also + reduce the memory footprint of the object. To be embeddable, types must abide by some restrictions: @@ -786,10 +790,10 @@ RUBY_TYPED_EMBEDDABLE :: argument from Ruby to C, i.e. as a parameter of a function used with +rb_define_method+ and similar. - * The +DATA_PTR+ and +RTYPEDDATA_DATA+ macro can't be used. - Only +RTYPEDDATA_GET_DATA+` or +TypedData_Get_Struct+ macros can be used - with embeddable objects. - Accessing `RDATA(obj)->data` or `RTYPEDDATA(obj)->data` is invalid too. + * The +DATA_PTR+, +RTYPEDDATA_DATA+ and +TypedData_Wrap_Struct+ macro can't be + used. + Only +RTYPEDDATA_GET_DATA+ or +TypedData_Get_Struct+ macros can be used with + embeddable objects. Accessing RTYPEDDATA(obj)->data is invalid too. * The +dfree+ function MUST NOT free the C struct itself. Setting +dfree+ to +RUBY_DEFAULT_FREE+ is fine. @@ -804,55 +808,72 @@ RUBY_TYPED_EMBEDDABLE :: See {Embedded TypedData}[rdoc-ref:@Appendix+G.+Embedded+TypedData] for a commented example of how to use +RUBY_TYPED_EMBEDDABLE+. +Fields other than those listed above are reserved for future use, and +initializers are typically omitted. In the rare case that you need to +dynamically allocate a +rb_data_type_t+, these fields must be filled with +zeros. -Note that this macro can raise an exception. If sval to be wrapped -holds a resource needs to be released (e.g., allocated memory, handle -from an external library, and etc), you will have to use rb_protect. +Note that this macro can raise an exception. If _sval_ already holds a +resource that must be released, such as allocated memory or a handle from an +external library, protect the call with +rb_protect+ and release the resource +when an exception is raised. Alternatively, create the object first with a ++NULL+ data pointer, then allocate the resource and store it in the object. You can allocate and wrap the structure in one step, in more preferable manner. - TypedData_Make_Struct(klass, type, data_type, sval) + obj = TypedData_Make_Struct(klass, type, data_type, sval) -This macro returns an allocated T_DATA object, wrapping the pointer to -the structure, which is also allocated. This macro works like: +This macro returns an allocated +T_DATA+ object, wrapping the pointer to the +structure, which is also allocated. This macro works like: - (sval = ZALLOC(type), TypedData_Wrap_Struct(klass, data_type, sval)) + obj = TypedData_Wrap_Struct(klass, data_type, NULL); + RTYPEDDATA_DATA(obj) = sval = ZALLOC(type); -However, you should use this macro instead of "allocation then wrap" -like the above code if it is simply allocated, because the latter can -raise a NoMemoryError and sval will be memory leaked in that case. +However, you should use this macro instead of "allocation then wrap" like the +above code if it is simply allocated, because the "wrap" can raise a ++NoMemoryError+ and _sval_ will be memory leaked in that case. -Arguments klass and data_type work like their counterparts in -TypedData_Wrap_Struct(). A pointer to the allocated structure will -be assigned to sval, which should be a pointer of the type specified. +Arguments _klass_ and _data_type_ work like their counterparts in +TypedData_Wrap_Struct(). A pointer to the allocated structure will be +assigned to _sval_, which should be a pointer of the type specified. + +Same for other than simple memory allocation: + + obj = TypedData_Wrap_Struct(klass, data_type, NULL); + sval = allocate_some_resource(); + if (success(sval)) RTYPEDDATA_DATA(obj) = sval; + +You may have to cast _sval_ to void*, if it is not a pointer type. ==== Declaratively marking/compacting struct references In the case where your struct refers to Ruby objects that are simple values, not wrapped in conditional logic or complex data structures an alternative approach to marking and reference updating is provided, by declaring offset -references to the VALUES in your struct. +references to the VALUEs (or edge) in your struct. Doing this allows the Ruby GC to support marking these references and GC compaction without the need to define the +dmark+ and +dcompact+ callbacks. You must define a static list of VALUE pointers to the offsets within your -struct where the references are located, and set the "data" member to point to -this reference list. The reference list must end with +RUBY_END_REFS+. - -Some Macros have been provided to make edge referencing easier: - -* RUBY_TYPED_DECL_MARKING =A flag that can be set on the +ruby_data_type_t+ to indicate that references are being declared as edges. - -* RUBY_REFERENCES(ref_list_name) - Define _ref_list_name_ as a list of references - -* RUBY_REF_END - The end mark of the references list. - -* RUBY_REF_EDGE(struct, member) - Declare _member_ as a VALUE edge from _struct_. Use this after +RUBY_REFERENCES_START+ - -* +RUBY_REFS_LIST_PTR+ - Coerce the reference list into a format that can be - accepted by the existing +dmark+ interface. +struct where the references are located, and set the +data+ member to point +to this reference list. The reference list must end with +RUBY_END_REFS+. + +Some macros have been provided to make edge referencing easier: + +RUBY_TYPED_DECL_MARKING :: + A flag that can be set on the +ruby_data_type_t+ to indicate that + references are being declared as edges. +RUBY_REFERENCES(ref_list_name) :: + Define _ref_list_name_ as a list of references +RUBY_REF_END :: The end mark of the references list. +RUBY_REF_EDGE(struct, member) :: + Declare _member_ as a VALUE edge from _struct_. Use this inside + the block of +RUBY_REFERENCES+. ++RUBY_REFS_LIST_PTR+ :: + Coerce the reference list into a format that can be accepted by the + existing +dmark+ interface. The example below is from Dir (defined in +dir.c+) @@ -886,12 +907,12 @@ it during compaction. ==== Ruby object to C struct -To retrieve the C pointer from the T_DATA object, use the macro -TypedData_Get_Struct(). +To retrieve the C pointer from the +T_DATA+ object, use the macro +TypedData_Get_Struct(). TypedData_Get_Struct(obj, type, &data_type, sval) -A pointer to the structure will be assigned to the variable sval. +A pointer to the structure will be assigned to the variable _sval_. See the example below for details. @@ -905,7 +926,8 @@ directory in the Ruby's source tree. % mkdir ext/dbm -Make a directory for the extension library under ext directory. +Make a directory for the extension library under ext directory if you +want to link it to statically Ruby. You can use an arbitrary name. === Design the Library @@ -915,16 +937,14 @@ You need to design the library features, before making it. You need to write C code for your extension library. If your library has only one source file, choosing ``LIBRARY.c'' as a file name is -preferred. On the other hand, in case your library has multiple source -files, avoid choosing ``LIBRARY.c'' for a file name. It may conflict -with an intermediate file ``LIBRARY.o'' on some platforms. +preferred. Note that some functions in mkmf library described below generate a file ``conftest.c'' for checking with compilation. You shouldn't choose ``conftest.c'' as a name of a source file. -Ruby will execute the initializing function named ``Init_LIBRARY'' in -the library. For example, ``Init_dbm()'' will be executed when loading -the library. +Ruby will execute the initializing function named +Init_LIBRARY+ in +the library. For example, Init_dbm() will be executed when +loading the library. Here's the example of an initializing function. @@ -954,7 +974,7 @@ Here's the example of an initializing function. } The dbm extension wraps the dbm struct in the C environment using -TypedData_Make_Struct. ++TypedData_Make_Struct+. struct dbmdata { int di_size; @@ -976,13 +996,13 @@ TypedData_Make_Struct. return TypedData_Make_Struct(klass, struct dbmdata, &dbm_type, dbmp); } -This code wraps the dbmdata structure into a Ruby object. We avoid -wrapping DBM* directly, because we want to cache size information. -Since Object.allocate allocates an ordinary T_OBJECT type (instead -of T_DATA), it's important to either use rb_define_alloc_func() to -overwrite it or rb_undef_alloc_func() to delete it. +This code wraps the +dbmdata+ structure into a Ruby object. We avoid +wrapping DBM* directly, because we want to cache size information. +Since Class.allocate allocates an ordinary +T_OBJECT+ type (instead +of +T_DATA+), it's important to either use rb_define_alloc_func() to +overwrite it or rb_undef_alloc_func() to delete it. -To retrieve the dbmdata structure from a Ruby object, we define the +To retrieve the +dbmdata+ structure from a Ruby object, we define the following macro: #define GetDBM(obj, dbmp) do {\ @@ -1007,7 +1027,7 @@ methods with a fixed number of arguments receive arguments like this: /* ... */ } -The first argument of the C function is the self, the rest are the +The first argument of the C function is the +self+, the rest are the arguments to the method. Second, methods with an arbitrary number of arguments receive @@ -1027,13 +1047,13 @@ The first argument is the number of method arguments, the second argument is the C array of the method arguments, and the third argument is the receiver of the method. -You can use the function rb_scan_args() to check and retrieve the -arguments. The third argument is a string that specifies how to +You can use the function rb_scan_args() to check and retrieve +the arguments. The third argument is a string that specifies how to capture method arguments and assign them to the following VALUE references. -You can just check the argument number with rb_check_arity(), this is -handy in the case you want to treat the arguments as a list. +You can just check the argument number with rb_check_arity(), +this is handy in the case you want to treat the arguments as a list. The following is an example of a method that takes arguments by Ruby's array: @@ -1101,7 +1121,7 @@ The value of the variables below will affect the Makefile. $objs: list of object file names Compiler/linker flags are not portable usually, you should use -+append_cppflags+, +append_cpflags+ and +append_ldflags+ respectively ++append_cppflags+, +append_cflags+ and +append_ldflags+ respectively instead of appending the above variables directly. Normally, the object files list is automatically generated by searching @@ -1109,8 +1129,8 @@ source files, but you must define them explicitly if any sources will be generated while building. If a compilation condition is not fulfilled, you should not call -``create_makefile''. The Makefile will not be generated, compilation will -not be done. +{create_makefile}[rdoc-ref:MakeMakefile#create_makefile]. The Makefile will not be generated, +compilation will not be done. === Prepare depend (Optional) @@ -1191,41 +1211,48 @@ parse.y :: grammar definition parse.c :: automatically generated from parse.y defs/keywords :: reserved keywords lex.c :: automatically generated from keywords +id.c :: pre-defined IDs === Ruby evaluator (a.k.a. YARV) - compile.c - eval.c - eval_error.c - eval_jump.c - eval_safe.c - insns.def : definition of VM instructions - iseq.c : implementation of VM::ISeq - thread.c : thread management and context switching - thread_win32.c : thread implementation - thread_pthread.c : ditto - vm.c - vm_dump.c - vm_eval.c - vm_exec.c - vm_insnhelper.c - vm_method.c - - defs/opt_insns_unif.def : instruction unification - defs/opt_operand.def : definitions for optimization - - -> insn*.inc : automatically generated - -> opt*.inc : automatically generated - -> vm.inc : automatically generated +eval.c :: +eval_error.c :: +eval_jump.c :: + Evaluator + +compile.c :: AST to VM instruction compiler +iseq.c :: implementation of VM::ISeq + +thread.c :: +thread_win32.c :: +thread_pthread.c :: + thread management and context switching + +vm.c :: +vm_dump.c :: +vm_eval.c :: +vm_exec.c :: +vm_insnhelper.c :: +vm_method.c :: + VM implementation + +insns.def :: definition of VM instructions +defs/opt_insns_unif.def :: instruction unification +defs/opt_operand.def :: definitions for optimization + +-> insn*.inc :: +-> opt*.inc :: +-> vm.inc :: + automatically generated === Regular expression engine (Onigumo) - regcomp.c - regenc.c - regerror.c - regexec.c - regparse.c - regsyntax.c +regcomp.c :: compiler +regenc.c :: encodings +regerror.c :: error handling +regexec.c :: executer +regparse.c :: parser +regsyntax.c :: pre-defined syntax options === Utility functions @@ -1237,22 +1264,27 @@ util.c :: misc utilities === Ruby interpreter implementation - dmyext.c - dmydln.c - dmyencoding.c - id.c - inits.c - main.c - ruby.c - version.c +dmyext.c :: +dmydln.c :: +dmyencoding.c :: + for miniruby + +id.c :: +inits.c :: +main.c :: +ruby.c :: +version.c :: + Ruby command - gem_prelude.rb - prelude.rb +builtijns.c :: +gem_prelude.rb :: +prelude.rb :: + for Ruby code loaded at start up === Class library array.c :: Array -bignum.c :: Bignum +bignum.c :: Integer (Bignum) compar.c :: Comparable complex.c :: Complex cont.c :: Fiber, Continuation @@ -1264,11 +1296,11 @@ hash.c :: Hash io.c :: IO marshal.c :: Marshal math.c :: Math -numeric.c :: Numeric, Integer, Fixnum, Float +numeric.c :: Numeric, Integer (Fixnum), Float pack.c :: Array#pack, String#unpack proc.c :: Binding, Proc process.c :: Process -random.c :: random number +random.c :: Random number generator range.c :: Range rational.c :: Rational re.c :: Regexp, MatchData @@ -1276,9 +1308,10 @@ signal.c :: Signal sprintf.c :: String#sprintf string.c :: String struct.c :: Struct +symbol.c :: Symbol time.c :: Time -defs/known_errors.def :: Errno::* exception classes +defs/known_errors.def :: exception classes under Errno -> known_errors.inc :: automatically generated === Multilingualization @@ -1290,280 +1323,265 @@ enc/trans/* :: codepoint mapping tables === goruby interpreter implementation - goruby.c - golf_prelude.rb : goruby specific libraries. - -> golf_prelude.c : automatically generated +goruby.c :: +golf_prelude.rb :: goruby specific libraries. +-> golf_prelude.c :: automatically generated == Appendix B. Ruby extension API reference === Types -VALUE :: ++VALUE+ :: The type for the Ruby object. Actual structures are defined in ruby.h, - such as struct RString, etc. To refer the values in structures, use - casting macros like RSTRING(obj). + such as struct RString, etc. To refer the values in structures, use + casting macros like RSTRING(obj). === Variables and constants -Qnil :: - - nil object - -Qtrue :: - - true object (default true value) ++Qnil+ :: -Qfalse :: + +nil+ object - false object ++Qtrue+ :: -=== C pointer wrapping + +true+ object (default true value) -Data_Wrap_Struct(VALUE klass, void (*mark)(), void (*free)(), void *sval) :: ++Qfalse+ :: - Wrap a C pointer into a Ruby object. If object has references to other - Ruby objects, they should be marked by using the mark function during - the GC process. Otherwise, mark should be 0. When this object is no - longer referred by anywhere, the pointer will be discarded by free - function. - -Data_Make_Struct(klass, type, mark, free, sval) :: - - This macro allocates memory using malloc(), assigns it to the variable - sval, and returns the DATA encapsulating the pointer to memory region. - -Data_Get_Struct(data, type, sval) :: - - This macro retrieves the pointer value from DATA, and assigns it to - the variable sval. + +false+ object === Checking VALUE types -RB_TYPE_P(value, type) :: +RB_TYPE_P(value, type) :: - Is +value+ an internal type (T_NIL, T_FIXNUM, etc.)? + Is _value_ an internal _type_ (+T_NIL+, +T_FIXNUM+, etc.)? -TYPE(value) :: +TYPE(value) :: - Internal type (T_NIL, T_FIXNUM, etc.) + Internal type (+T_NIL+, +T_FIXNUM+, etc.) -FIXNUM_P(value) :: +FIXNUM_P(value) :: - Is +value+ a Fixnum? + Is _value_ a Fixnum? -NIL_P(value) :: +NIL_P(value) :: - Is +value+ nil? + Is _value_ +nil+? -RB_INTEGER_TYPE_P(value) :: +RB_INTEGER_TYPE_P(value) :: - Is +value+ an Integer? + Is _value_ an Integer? -RB_FLOAT_TYPE_P(value) :: +RB_FLOAT_TYPE_P(value) :: - Is +value+ a Float? + Is _value_ a Float? -void Check_Type(VALUE value, int type) :: +void Check_Type(VALUE value, int type) :: - Ensures +value+ is of the given internal +type+ or raises a TypeError + Ensures _value_ is of the given internal _type_ or raises a TypeError === VALUE type conversion -FIX2INT(value), INT2FIX(i) :: +FIX2INT(value), INT2FIX(i) :: Fixnum <-> integer -FIX2LONG(value), LONG2FIX(l) :: +FIX2LONG(value), LONG2FIX(l) :: Fixnum <-> long -NUM2INT(value), INT2NUM(i) :: +NUM2INT(value), INT2NUM(i) :: Numeric <-> integer -NUM2UINT(value), UINT2NUM(ui) :: +NUM2UINT(value), UINT2NUM(ui) :: Numeric <-> unsigned integer -NUM2LONG(value), LONG2NUM(l) :: +NUM2LONG(value), LONG2NUM(l) :: Numeric <-> long -NUM2ULONG(value), ULONG2NUM(ul) :: +NUM2ULONG(value), ULONG2NUM(ul) :: Numeric <-> unsigned long -NUM2LL(value), LL2NUM(ll) :: +NUM2LL(value), LL2NUM(ll) :: Numeric <-> long long -NUM2ULL(value), ULL2NUM(ull) :: +NUM2ULL(value), ULL2NUM(ull) :: Numeric <-> unsigned long long -NUM2OFFT(value), OFFT2NUM(off) :: +NUM2OFFT(value), OFFT2NUM(off) :: Numeric <-> off_t -NUM2SIZET(value), SIZET2NUM(size) :: +NUM2SIZET(value), SIZET2NUM(size) :: Numeric <-> size_t -NUM2SSIZET(value), SSIZET2NUM(ssize) :: +NUM2SSIZET(value), SSIZET2NUM(ssize) :: Numeric <-> ssize_t -rb_integer_pack(value, words, numwords, wordsize, nails, flags), rb_integer_unpack(words, numwords, wordsize, nails, flags) :: +rb_integer_pack(value, words, numwords, wordsize, nails, flags), rb_integer_unpack(words, numwords, wordsize, nails, flags) :: Numeric <-> Arbitrary size integer buffer -NUM2DBL(value) :: +NUM2DBL(value) :: Numeric -> double -rb_float_new(f) :: +rb_float_new(f) :: double -> Float -RSTRING_LEN(str) :: +RSTRING_LEN(str) :: String -> length of String data in bytes -RSTRING_PTR(str) :: +RSTRING_PTR(str) :: String -> pointer to String data Note that the result pointer may not be NUL-terminated -StringValue(value) :: +StringValue(value) :: - Object with \#to_str -> String + Object with #to_str -> String -StringValuePtr(value) :: +StringValuePtr(value) :: - Object with \#to_str -> pointer to String data + Object with #to_str -> pointer to String data -StringValueCStr(value) :: +StringValueCStr(value) :: - Object with \#to_str -> pointer to String data without NUL bytes + Object with #to_str -> pointer to String data without NUL bytes It is guaranteed that the result data is NUL-terminated -rb_str_new2(s) :: +rb_str_new2(s) :: char * -> String === Defining classes and modules -VALUE rb_define_class(const char *name, VALUE super) :: +VALUE rb_define_class(const char *name, VALUE super) :: - Defines a new Ruby class as a subclass of super. + Defines a Ruby class as a subclass of _super_ with named specified by + _name_ at the top-level. -VALUE rb_define_class_under(VALUE module, const char *name, VALUE super) :: +VALUE rb_define_class_under(VALUE module, const char *name, VALUE super) :: - Creates a new Ruby class as a subclass of super, under the module's - namespace. + Defines a Ruby class as a subclass of _super_ with named specified by + _name_ under the module's namespace. -VALUE rb_define_module(const char *name) :: +VALUE rb_define_module(const char *name) :: - Defines a new Ruby module. + Defines a Ruby module with named specified by _name_ at the top-level. -VALUE rb_define_module_under(VALUE module, const char *name) :: +VALUE rb_define_module_under(VALUE module, const char *name) :: - Defines a new Ruby module under the module's namespace. + Defines a Ruby module with named specified by _name_ under the + module's namespace. -void rb_include_module(VALUE klass, VALUE module) :: +void rb_include_module(VALUE klass, VALUE module) :: - Includes module into class. If class already includes it, just ignored. + Includes _module_ into _class_. If _class_ already includes it, just + ignored. -void rb_extend_object(VALUE object, VALUE module) :: +void rb_extend_object(VALUE object, VALUE module) :: - Extend the object with the module's attributes. + Extend the _object_ with the module's attributes. === Defining global variables -void rb_define_variable(const char *name, VALUE *var) :: +void rb_define_variable(const char *name, VALUE *var) :: - Defines a global variable which is shared between C and Ruby. If name - contains a character which is not allowed to be part of the symbol, - it can't be seen from Ruby programs. + Defines a global variable _name_ which is shared between C and Ruby. If + _name_ does not start with +$+, it is prefixed automatically. If that + variable name contains a character which is not allowed a global + variable, that variable can't be seen from Ruby programs. -void rb_define_readonly_variable(const char *name, VALUE *var) :: +void rb_define_readonly_variable(const char *name, VALUE *var) :: Defines a read-only global variable. Works just like - rb_define_variable(), except the defined variable is read-only. + rb_define_variable(), except the defined variable is read-only. -void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) :: +void rb_define_virtual_variable(const char *name, VALUE (*getter)(), void (*setter)()) :: Defines a virtual variable, whose behavior is defined by a pair of C - functions. The getter function is called when the variable is - referenced. The setter function is called when the variable is set to a - value. The prototype for getter/setter functions are: + functions. The _getter_ function is called when the variable is + referenced. The _setter_ function is called when the variable is set to a + value. - VALUE getter(ID id) - void setter(VALUE val, ID id) + These functions are the same as +rb_define_hooked_variable+, but the + _var_ argument is meaningless. - The getter function must return the value for the access. - -void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) :: +void rb_define_hooked_variable(const char *name, VALUE *var, VALUE (*getter)(), void (*setter)()) :: Defines hooked variable. It's a virtual variable with a C variable. - The getter is called as + The _getter_ is called as VALUE getter(ID id, VALUE *var) - returning a new value. The setter is called as + returning a new value. The _setter_ is called as void setter(VALUE val, ID id, VALUE *var) -void rb_global_variable(VALUE *var) :: + _id_ is the ID interned from _name_, and _var_ is the argument itself. + _val_ is the value to be set. + +void rb_global_variable(VALUE *var) :: Tells GC to protect C global variable, which holds Ruby value to be marked. -void rb_gc_register_mark_object(VALUE object) :: +void rb_gc_register_mark_object(VALUE object) :: - Tells GC to protect the +object+, which may not be referenced anywhere. + Tells GC to protect the _object_, which may not be referenced anywhere. === Constant definition -void rb_define_const(VALUE klass, const char *name, VALUE val) :: +void rb_define_const(VALUE klass, const char *name, VALUE val) :: Defines a new constant under the class/module. -void rb_define_global_const(const char *name, VALUE val) :: +void rb_define_global_const(const char *name, VALUE val) :: Defines a global constant. This is just the same as rb_define_const(rb_cObject, name, val) -=== Method definition +=== \Method definition -rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: Defines a method for the class. func is the function pointer. argc - is the number of arguments. if argc is -1, the function will receive - 3 arguments: argc, argv, and self. if argc is -2, the function will - receive 2 arguments, self and args, where args is a Ruby array of + is the number of arguments. if _argc_ is -1, the function will receive + 3 arguments: _argc_, _argv_, and _self_. if _argc_ is -2, the function will + receive 2 arguments, _self_ and _args_, where _args_ is a Ruby array of the method arguments. -rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: Defines a private method for the class. Arguments are same as - rb_define_method(). + rb_define_method(). -rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: +rb_define_singleton_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc) :: - Defines a singleton method. Arguments are same as rb_define_method(). + Defines a singleton method. Arguments are same as rb_define_method(). -rb_check_arity(int argc, int min, int max) :: +rb_check_arity(int argc, int min, int max) :: - Check the number of arguments, argc is in the range of min..max. If - max is UNLIMITED_ARGUMENTS, upper bound is not checked. If argc is + Check the number of arguments, _argc_ is in the range of +min..max+. If + _max_ is +UNLIMITED_ARGUMENTS+, upper bound is not checked. If _argc_ is out of bounds, an ArgumentError will be raised. -rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: +rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: - Retrieve argument from argc and argv to given VALUE references - according to the format string. The format can be described in ABNF + Retrieve argument from _argc_ and _argv_ to given VALUE references + according to the format string _fmt_. The format can be described in ABNF as follows: scan-arg-spec := param-arg-spec [keyword-arg-spec] [block-arg-spec] @@ -1599,220 +1617,222 @@ rb_scan_args(int argc, VALUE *argv, const char *fmt, ...) :: argument, and at most receives three (1+2) arguments. So, the format string must be followed by three variable references, which are to be assigned to captured arguments. For omitted arguments, variables are - set to Qnil. NULL can be put in place of a variable reference, which + set to +Qnil+. NULL can be put in place of a variable reference, which means the corresponding captured argument(s) should be just dropped. The number of given arguments, excluding an option hash or iterator block, is returned. -rb_scan_args_kw(int kw_splat, int argc, VALUE *argv, const char *fmt, ...) :: +rb_scan_args_kw(int kw_splat, int argc, VALUE *argv, const char *fmt, ...) :: - The same as +rb_scan_args+, except the +kw_splat+ argument specifies whether + The same as +rb_scan_args+, except the _kw_splat_ argument specifies whether keyword arguments are provided (instead of being determined by the call - from Ruby to the C function). +kw_splat+ should be one of the following + from Ruby to the C function). _kw_splat_ should be one of the following values: - RB_SCAN_ARGS_PASS_CALLED_KEYWORDS :: Same behavior as +rb_scan_args+. - RB_SCAN_ARGS_KEYWORDS :: The final argument should be a hash treated as - keywords. - RB_SCAN_ARGS_LAST_HASH_KEYWORDS :: Treat a final argument as keywords if it - is a hash, and not as keywords otherwise. - -int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values) :: - - Retrieves argument VALUEs bound to keywords, which directed by +table+ - into +values+, deleting retrieved entries from +keyword_hash+ along - the way. First +required+ number of IDs referred by +table+ are - mandatory, and succeeding +optional+ (- +optional+ - 1 if - +optional+ is negative) number of IDs are optional. If a - mandatory key is not contained in +keyword_hash+, raises "missing - keyword" +ArgumentError+. If an optional key is not present in - +keyword_hash+, the corresponding element in +values+ is set to +Qundef+. - If +optional+ is negative, rest of +keyword_hash+ are ignored, otherwise - raises "unknown keyword" +ArgumentError+. + +RB_SCAN_ARGS_PASS_CALLED_KEYWORDS+ :: Same behavior as +rb_scan_args+. + +RB_SCAN_ARGS_KEYWORDS+ :: The final argument should be a hash treated as + keywords. + +RB_SCAN_ARGS_LAST_HASH_KEYWORDS+ :: Treat a final argument as keywords if it + is a hash, and not as keywords otherwise. + +int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values) :: + + Retrieves argument VALUEs bound to keywords, which directed by _table_ + into _values_, deleting retrieved entries from _keyword_hash_ along + the way. First _required_ number of IDs referred by _table_ are + mandatory, and succeeding _optional_ (- optional - 1 if + _optional_ is negative) number of IDs are optional. If a + mandatory key is not contained in _keyword_hash_, raises "missing + keyword" ArgumentError. If an optional key is not present in + _keyword_hash_, the corresponding element in _values_ is set to +Qundef+. + If _optional_ is negative, rest of _keyword_hash_ are ignored, otherwise + raises "unknown keyword" ArgumentError. Be warned, handling keyword arguments in the C API is less efficient than handling them in Ruby. Consider using a Ruby wrapper method around a non-keyword C function. ref: https://bugs.ruby-lang.org/issues/11339 -VALUE rb_extract_keywords(VALUE *original_hash) :: +VALUE rb_extract_keywords(VALUE *original_hash) :: Extracts pairs whose key is a symbol into a new hash from a hash - object referred by +original_hash+. If the original hash contains + object referred by _original_hash_. If the original hash contains non-symbol keys, then they are copied to another hash and the new hash - is stored through +original_hash+, else 0 is stored. + is stored through _original_hash_, else 0 is stored. === Invoking Ruby method -VALUE rb_funcall(VALUE recv, ID mid, int narg, ...) :: +VALUE rb_funcall(VALUE recv, ID mid, int narg, ...) :: - Invokes a method. To retrieve mid from a method name, use rb_intern(). - Able to call even private/protected methods. + Invokes a method specified by _mid_ on _recv_. To retrieve _mid_ + from a method name, use rb_intern(). Able to call even + private/protected methods. Arguments after _narg_ are passe to the + method, and _narg_ should be the number of arguments. -VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) :: -VALUE rb_funcallv(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcall2(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcallv(VALUE recv, ID mid, int argc, VALUE *argv) :: Invokes a method, passing arguments as an array of values. Able to call even private/protected methods. -VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) :: +VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) :: - Same as rb_funcallv, using +kw_splat+ to determine whether keyword + Same as rb_funcallv, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, VALUE *argv) :: +VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, VALUE *argv) :: Invokes a method, passing arguments as an array of values. Able to call only public methods. -VALUE rb_funcallv_public_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) :: +VALUE rb_funcallv_public_kw(VALUE recv, ID mid, int argc, VALUE *argv, int kw_splat) :: - Same as rb_funcallv_public, using +kw_splat+ to determine whether keyword + Same as +rb_funcallv_public+, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE* argv) :: +VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE* argv) :: - Same as rb_funcallv_public, except is passes the currently active block as + Same as +rb_funcallv_public+, except is passes the currently active block as the block when calling the method. -VALUE rb_funcall_passing_block_kw(VALUE recv, ID mid, int argc, const VALUE* argv, int kw_splat) :: +VALUE rb_funcall_passing_block_kw(VALUE recv, ID mid, int argc, const VALUE* argv, int kw_splat) :: - Same as rb_funcall_passing_block, using +kw_splat+ to determine whether + Same as +rb_funcall_passing_block+, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval) :: +VALUE rb_funcall_with_block(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval) :: - Same as rb_funcallv_public, except +passed_procval+ specifies the block to + Same as +rb_funcallv_public+, except _passed_procval_ specifies the block to pass to the method. -VALUE rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat) :: +VALUE rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat) :: - Same as rb_funcall_with_block, using +kw_splat+ to determine whether + Same as +rb_funcall_with_block+, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_eval_string(const char *str) :: +VALUE rb_eval_string(const char *str) :: Compiles and executes the string as a Ruby program. -ID rb_intern(const char *name) :: +ID rb_intern(const char *name) :: - Returns ID corresponding to the name. + Returns ID corresponding to the _name_. -char *rb_id2name(ID id) :: +char *rb_id2name(ID id) :: Returns the name corresponding ID. -char *rb_class2name(VALUE klass) :: +char *rb_class2name(VALUE klass) :: Returns the name of the class. -int rb_respond_to(VALUE obj, ID id) :: +int rb_respond_to(VALUE obj, ID id) :: - Returns true if the object responds to the message specified by id. + Returns true if the object responds to the message specified by _id_. === Instance variables -VALUE rb_iv_get(VALUE obj, const char *name) :: +VALUE rb_iv_get(VALUE obj, const char *name) :: Retrieve the value of the instance variable. If the name is not - prefixed by `@', that variable shall be inaccessible from Ruby. + prefixed by @, that variable shall be inaccessible from Ruby. -VALUE rb_iv_set(VALUE obj, const char *name, VALUE val) :: +VALUE rb_iv_set(VALUE obj, const char *name, VALUE val) :: Sets the value of the instance variable. === Control structure -VALUE rb_block_call(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2) :: +VALUE rb_block_call(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2) :: - Calls a method on the recv, with the method name specified by the - symbol mid, with argc arguments in argv, supplying func as the - block. When func is called as the block, it will receive the value - from yield as the first argument, and data2 as the second argument. - When yielded with multiple values (in C, rb_yield_values(), - rb_yield_values2() and rb_yield_splat()), data2 is packed as an Array, - whereas yielded values can be gotten via argc/argv of the third/fourth - arguments. + Calls a method on the _recv_, with the method name specified by the + symbol _mid_, with _argc_ arguments in _argv_, supplying _func_ as the + block. When _func_ is called as the block, it will receive the value + from +yield+ as the first argument, and _data2_ as the second argument. + When yielded with multiple values (in C, rb_yield_values(), + rb_yield_values2() and rb_yield_splat()), _data2_ is + packed as an Array, whereas yielded values can be gotten via + _argc_/_argv_ of the third/fourth arguments. -VALUE rb_block_call_kw(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2, int kw_splat) :: +VALUE rb_block_call_kw(VALUE recv, ID mid, int argc, VALUE * argv, VALUE (*func) (ANYARGS), VALUE data2, int kw_splat) :: - Same as rb_funcall_with_block, using +kw_splat+ to determine whether + Same as +rb_funcall_with_block+, using _kw_splat_ to determine whether keyword arguments are passed. -\[OBSOLETE] VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2) :: +\[OBSOLETE] VALUE rb_iterate(VALUE (*func1)(), VALUE arg1, VALUE (*func2)(), VALUE arg2) :: - Calls the function func1, supplying func2 as the block. func1 will be - called with the argument arg1. func2 receives the value from yield as - the first argument, arg2 as the second argument. + Calls the function _func1_, supplying _func2_ as the block. _func1_ will be + called with the argument _arg1_. _func2_ receives the value from +yield+ as + the first argument, _arg2_ as the second argument. - When rb_iterate is used in 1.9, func1 has to call some Ruby-level method. - This function is obsolete since 1.9; use rb_block_call instead. + When +rb_iterate+ is used in 1.9, _func1_ has to call some Ruby-level method. + This function is obsolete since 1.9; use +rb_block_call+ instead. -VALUE rb_yield(VALUE val) :: +VALUE rb_yield(VALUE val) :: - Yields val as a single argument to the block. + Yields _val_ as a single argument to the block. -VALUE rb_yield_values(int n, ...) :: +VALUE rb_yield_values(int n, ...) :: - Yields +n+ number of arguments to the block, using one C argument per Ruby + Yields _n_ number of arguments to the block, using one C argument per Ruby argument. -VALUE rb_yield_values2(int n, VALUE *argv) :: +VALUE rb_yield_values2(int n, VALUE *argv) :: - Yields +n+ number of arguments to the block, with all Ruby arguments in the + Yields _n_ number of arguments to the block, with all Ruby arguments in the C argv array. -VALUE rb_yield_values_kw(int n, VALUE *argv, int kw_splat) :: +VALUE rb_yield_values_kw(int n, VALUE *argv, int kw_splat) :: - Same as rb_yield_values2, using +kw_splat+ to determine whether + Same as +rb_yield_values2+, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_yield_splat(VALUE args) :: +VALUE rb_yield_splat(VALUE args) :: - Same as rb_yield_values2, except arguments are specified by the Ruby + Same as +rb_yield_values2+, except arguments are specified by the Ruby array +args+. -VALUE rb_yield_splat_kw(VALUE args, int kw_splat) :: +VALUE rb_yield_splat_kw(VALUE args, int kw_splat) :: - Same as rb_yield_splat, using +kw_splat+ to determine whether + Same as +rb_yield_splat+, using _kw_splat_ to determine whether keyword arguments are passed. -VALUE rb_rescue(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: +VALUE rb_rescue(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: - Calls the function func1, with arg1 as the argument. If an exception - occurs during func1, it calls func2 with arg2 as the first argument - and the exception object as the second argument. The return value - of rb_rescue() is the return value from func1 if no exception occurs, - from func2 otherwise. + Calls the function _func1_, with _arg1_ as the argument. If an exception + occurs during _func1_, it calls _func2_ with _arg2_ as the first argument + and the exception object as the second argument. The return value of + rb_rescue() is the return value from _func1_ if no exception + occurs, from _func2_ otherwise. -VALUE rb_ensure(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: +VALUE rb_ensure(VALUE (*func1)(ANYARGS), VALUE arg1, VALUE (*func2)(ANYARGS), VALUE arg2) :: - Calls the function func1 with arg1 as the argument, then calls func2 - with arg2 if execution terminated. The return value from - rb_ensure() is that of func1 when no exception occurred. + Calls the function _func1_ with _arg1_ as the argument, then calls _func2_ + with _arg2_ if execution terminated. The return value from + rb_ensure() is that of _func1 when no exception occurred. -VALUE rb_protect(VALUE (*func) (VALUE), VALUE arg, int *state) :: +VALUE rb_protect(VALUE (*func) (VALUE), VALUE arg, int *state) :: - Calls the function func with arg as the argument. If no exception - occurred during func, it returns the result of func and *state is zero. - Otherwise, it returns Qnil and sets *state to nonzero. If state is - NULL, it is not set in both cases. - You have to clear the error info with rb_set_errinfo(Qnil) when - ignoring the caught exception. + Calls the function _func_ with _arg_ as the argument. If no exception + occurred during _func_, it returns the result of _func_ and + *state is zero. + Otherwise, it returns +Qnil+ and sets *state to nonzero. If + state is NULL, it is not set in both cases. You have to clear the error + info with rb_set_errinfo(Qnil) when ignoring the caught exception. -void rb_jump_tag(int state) :: +void rb_jump_tag(int state) :: - Continues the exception caught by rb_protect() and rb_eval_string_protect(). - state must be the returned value from those functions. This function + Continues the exception caught by rb_protect() and rb_eval_string_protect(). + _state_ must be the returned value from those functions. This function never return to the caller. -void rb_iter_break() :: +void rb_iter_break() :: Exits from the current innermost block. This function never return to the caller. -void rb_iter_break_value(VALUE value) :: +void rb_iter_break_value(VALUE value) :: Exits from the current innermost block with the value. The block will return the given argument value. This function never return to the @@ -1820,76 +1840,76 @@ void rb_iter_break_value(VALUE value) :: === Exceptions and errors -void rb_warn(const char *fmt, ...) :: +void rb_warn(const char *fmt, ...) :: Prints a warning message according to a printf-like format. -void rb_warning(const char *fmt, ...) :: +void rb_warning(const char *fmt, ...) :: Prints a warning message according to a printf-like format, if - $VERBOSE is true. + _$VERBOSE_ is true. -void rb_raise(rb_eRuntimeError, const char *fmt, ...) :: +void rb_raise(rb_eRuntimeError, const char *fmt, ...) :: - Raises RuntimeError. The fmt is a format string just like printf(). + Raises RuntimeError. The _fmt_ is a format string just like printf(). -void rb_raise(VALUE exception, const char *fmt, ...) :: +void rb_raise(VALUE exception, const char *fmt, ...) :: - Raises a class exception. The fmt is a format string just like printf(). + Raises a class exception. The _fmt_ is a format string just like printf(). -void rb_fatal(const char *fmt, ...) :: +void rb_fatal(const char *fmt, ...) :: Raises a fatal error, terminates the interpreter. No exception handling will be done for fatal errors, but ensure blocks will be executed. -void rb_bug(const char *fmt, ...) :: +void rb_bug(const char *fmt, ...) :: Terminates the interpreter immediately. This function should be called under the situation caused by the bug in the interpreter. No exception handling nor ensure execution will be done. -Note: In the format string, "%"PRIsVALUE can be used for Object#to_s -(or Object#inspect if '+' flag is set) output (and related argument -must be a VALUE). Since it conflicts with "%i", for integers in -format strings, use "%d". +Note: In the format string, "%"PRIsVALUE can be used for Object#to_s +(or Object#inspect if + flag is set) output (and related argument +must be a VALUE). Since it conflicts with "%i", for integers in +format strings, use "%d". === Threading As of Ruby 1.9, Ruby supports native 1:1 threading with one kernel thread per Ruby Thread object. Currently, there is a GVL (Global VM Lock) which prevents simultaneous execution of Ruby code which may be released -by the rb_thread_call_without_gvl and rb_thread_call_without_gvl2 functions. +by the +rb_thread_call_without_gvl+ and +rb_thread_call_without_gvl2+ functions. These functions are tricky-to-use and documented in thread.c; do not use them before reading comments in thread.c. -void rb_thread_schedule(void) :: +void rb_thread_schedule(void) :: Give the scheduler a hint to pass execution to another thread. === Input/Output (IO) on a single file descriptor -int rb_io_wait_readable(int fd) :: +int rb_io_wait_readable(int fd) :: Wait indefinitely for the given FD to become readable, allowing other threads to be scheduled. Returns a true value if a read may be performed, false if there is an unrecoverable error. -int rb_io_wait_writable(int fd) :: +int rb_io_wait_writable(int fd) :: - Like rb_io_wait_readable, but for writability. + Like +rb_io_wait_readable+, but for writability. -int rb_wait_for_single_fd(int fd, int events, struct timeval *timeout) :: +int rb_wait_for_single_fd(int fd, int events, struct timeval *timeout) :: Allows waiting on a single FD for one or multiple events with a specified timeout. - +events+ is a mask of any combination of the following values: + _events_ is a mask of any combination of the following values: - * RB_WAITFD_IN - wait for readability of normal data - * RB_WAITFD_OUT - wait for writability - * RB_WAITFD_PRI - wait for readability of urgent data + +RB_WAITFD_IN+ :: wait for readability of normal data + +RB_WAITFD_OUT+ :: wait for writability + +RB_WAITFD_PRI+ :: wait for readability of urgent data - Use a NULL +timeout+ to wait indefinitely. + Use a NULL _timeout_ to wait indefinitely. === I/O multiplexing @@ -1900,77 +1920,77 @@ provides a good overview on how to use select(2), and the Ruby API has analogous functions and data structures to the well-known select API. Understanding of select(2) is required to understand this section. -typedef struct rb_fdset_t :: +typedef struct rb_fdset_t :: The data structure which wraps the fd_set bitmap used by select(2). This allows Ruby to use FD sets larger than that allowed by historic limitations on modern platforms. -void rb_fd_init(rb_fdset_t *) :: +void rb_fd_init(rb_fdset_t *) :: - Initializes the rb_fdset_t, it must be initialized before other rb_fd_* + Initializes the +rb_fdset_t+, it must be initialized before other rb_fd_* operations. Analogous to calling malloc(3) to allocate an fd_set. -void rb_fd_term(rb_fdset_t *) :: +void rb_fd_term(rb_fdset_t *) :: - Destroys the rb_fdset_t, releasing any memory and resources it used. - It must be reinitialized using rb_fd_init before future use. + Destroys the +rb_fdset_t+, releasing any memory and resources it used. + It must be reinitialized using +rb_fd_init+ before future use. Analogous to calling free(3) to release memory for an fd_set. -void rb_fd_zero(rb_fdset_t *) :: +void rb_fd_zero(rb_fdset_t *) :: - Clears all FDs from the rb_fdset_t, analogous to FD_ZERO(3). + Clears all FDs from the +rb_fdset_t+, analogous to FD_ZERO(3). -void rb_fd_set(int fd, rb_fdset_t *) :: +void rb_fd_set(int fd, rb_fdset_t *) :: - Adds a given FD in the rb_fdset_t, analogous to FD_SET(3). + Adds a given FD in the +rb_fdset_t+, analogous to FD_SET(3). -void rb_fd_clr(int fd, rb_fdset_t *) :: +void rb_fd_clr(int fd, rb_fdset_t *) :: - Removes a given FD from the rb_fdset_t, analogous to FD_CLR(3). + Removes a given FD from the +rb_fdset_t+, analogous to FD_CLR(3). -int rb_fd_isset(int fd, const rb_fdset_t *) :: +int rb_fd_isset(int fd, const rb_fdset_t *) :: - Returns true if a given FD is set in the rb_fdset_t, false if not. + Returns true if a given _fd_ is set in the +rb_fdset_t+, false if not. Analogous to FD_ISSET(3). -int rb_thread_fd_select(int nfds, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout) :: +int rb_thread_fd_select(int nfds, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout) :: Analogous to the select(2) system call, but allows other Ruby threads to be scheduled while waiting. - When only waiting on a single FD, favor rb_io_wait_readable, - rb_io_wait_writable, or rb_wait_for_single_fd functions since + When only waiting on a single FD, favor +rb_io_wait_readable+, + +rb_io_wait_writable+, or +rb_wait_for_single_fd+ functions since they can be optimized for specific platforms (currently, only Linux). === Initialize and start the interpreter The embedding API functions are below (not needed for extension libraries): -void ruby_init() :: +void ruby_init() :: Initializes the interpreter. -void *ruby_options(int argc, char **argv) :: +void *ruby_options(int argc, char **argv) :: Process command line arguments for the interpreter. And compiles the Ruby source to execute. It returns an opaque pointer to the compiled source or an internal special value. -int ruby_run_node(void *n) :: +int ruby_run_node(void *n) :: Runs the given compiled source and exits this process. It returns EXIT_SUCCESS if successfully runs the source. Otherwise, it returns other value. -void ruby_script(char *name) :: +void ruby_script(char *name) :: - Specifies the name of the script ($0). + Specifies the name of the script (_$0_). === Hooks for the interpreter events -void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data) :: +void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data) :: Adds a hook function for the specified interpreter events. events should be OR'ed value of: @@ -1990,23 +2010,23 @@ void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE typedef void (*rb_event_hook_func_t)(rb_event_t event, VALUE data, VALUE self, ID id, VALUE klass) - The third argument `data' to rb_add_event_hook() is passed to the hook + The third argument _data_ to rb_add_event_hook() is passed to the hook function as the second argument, which was the pointer to the current - NODE in 1.8. See RB_EVENT_HOOKS_HAVE_CALLBACK_DATA below. + NODE in 1.8. See +RB_EVENT_HOOKS_HAVE_CALLBACK_DATA+ below. -int rb_remove_event_hook(rb_event_hook_func_t func) :: +int rb_remove_event_hook(rb_event_hook_func_t func) :: Removes the specified hook function. === Memory usage -void rb_gc_adjust_memory_usage(ssize_t diff) :: +void rb_gc_adjust_memory_usage(ssize_t diff) :: Adjusts the amount of registered external memory. You can tell GC how much memory is used by an external library by this function. Calling - this function with positive diff means the memory usage is increased; + this function with positive _diff_ means the memory usage is increased; new memory block is allocated or a block is reallocated as larger - size. Calling this function with negative diff means the memory usage + size. Calling this function with negative _diff_ means the memory usage is decreased; a memory block is freed or a block is reallocated as smaller size. This function may trigger the GC. @@ -2014,43 +2034,43 @@ void rb_gc_adjust_memory_usage(ssize_t diff) :: Some macros to check API compatibilities are available by default. -NORETURN_STYLE_NEW :: ++NORETURN_STYLE_NEW+ :: - Means that NORETURN macro is functional style instead of prefix. + Means that +NORETURN+ macro is functional style instead of prefix. -HAVE_RB_DEFINE_ALLOC_FUNC :: ++HAVE_RB_DEFINE_ALLOC_FUNC+ :: - Means that function rb_define_alloc_func() is provided, that means the + Means that function rb_define_alloc_func() is provided, that means the allocation framework is used. This is the same as the result of - have_func("rb_define_alloc_func", "ruby.h"). + have_func("rb_define_alloc_func", "ruby.h"). -HAVE_RB_REG_NEW_STR :: ++HAVE_RB_REG_NEW_STR+ :: - Means that function rb_reg_new_str() is provided, that creates Regexp + Means that function rb_reg_new_str() is provided, that creates Regexp object from String object. This is the same as the result of - have_func("rb_reg_new_str", "ruby.h"). + have_func("rb_reg_new_str", "ruby.h"). -HAVE_RB_IO_T :: ++HAVE_RB_IO_T+ :: - Means that type rb_io_t is provided. + Means that type +rb_io_t+ is provided. -USE_SYMBOL_AS_METHOD_NAME :: ++USE_SYMBOL_AS_METHOD_NAME+ :: Means that Symbols will be returned as method names, e.g., Module#methods, \#singleton_methods and so on. -HAVE_RUBY_*_H :: +HAVE_RUBY_*_H :: Defined in ruby.h and means corresponding header is available. For - instance, when HAVE_RUBY_ST_H is defined you should use ruby/st.h not + instance, when +HAVE_RUBY_ST_H+ is defined you should use ruby/st.h not mere st.h. Header files corresponding to these macros may be #include directly from extension libraries. -RB_EVENT_HOOKS_HAVE_CALLBACK_DATA :: ++RB_EVENT_HOOKS_HAVE_CALLBACK_DATA+ :: - Means that rb_add_event_hook() takes the third argument `data', to be + Means that rb_add_event_hook() takes the third argument _data_, to be passed to the given event hook function. === Defining backward compatible macros for keyword argument functions @@ -2106,32 +2126,32 @@ Ruby 2.1 introduced a generational garbage collector (called RGenGC). RGenGC (mostly) keeps compatibility. Generally, the use of the technique called write barriers is required in -extension libraries for generational GC -(https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29). +extension libraries for {generational GC +}[https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29]. RGenGC works fine without write barriers in extension libraries. -If your library adheres to the following tips, performance can -be further improved. Especially, the "Don't touch pointers directly" section is -important. +If your library adheres to the following tips, performance can be further +improved. Especially, the "{Don't touch pointers +directly}[rdoc-ref:@Don-27t+touch+pointers+directly]" section is important. === Incompatibility -You can't write RBASIC(obj)->klass field directly because it is const -value now. +You can't write RBASIC(obj)->klass field directly because it is +const value now. Basically you should not write this field because MRI expects it to be an immutable field, but if you want to do it in your extension you can use the following functions: -VALUE rb_obj_hide(VALUE obj) :: +VALUE rb_obj_hide(VALUE obj) :: - Clear RBasic::klass field. The object will be an internal object. + Clear +RBasic::klass+ field. The object will be an internal object. ObjectSpace::each_object can't find this object. -VALUE rb_obj_reveal(VALUE obj, VALUE klass) :: +VALUE rb_obj_reveal(VALUE obj, VALUE klass) :: - Reset RBasic::klass to be klass. - We expect the `klass' is hidden class by rb_obj_hide(). + Reset +RBasic::klass+ to be _klass_. + We expect the _klass_ is hidden class by rb_obj_hide(). === Write barriers @@ -2142,28 +2162,28 @@ RGenGC. Please check the following tips. ==== Don't touch pointers directly In MRI (include/ruby/ruby.h), some macros to acquire pointers to the -internal data structures are supported such as RARRAY_PTR(), -RSTRUCT_PTR() and so on. +internal data structures are supported such as RARRAY_PTR(), +RSTRUCT_PTR() and so on. DO NOT USE THESE MACROS and instead use the corresponding C-APIs such as -rb_ary_aref(), rb_ary_store() and so on. +rb_ary_aref(), rb_ary_store() and so on. ==== Consider whether to insert write barriers You don't need to care about write barriers if you only use built-in types. -If you support T_DATA objects, you may consider using write barriers. +If you support +T_DATA+ objects, you may consider using write barriers. -Inserting write barriers into T_DATA objects only works with the +Inserting write barriers into +T_DATA+ objects only works with the following type objects: (a) long-lived objects, (b) when a huge number of objects are generated and \(c) container-type objects that have references to other objects. If your extension provides such a type of -T_DATA objects, consider inserting write barriers. ++T_DATA+ objects, consider inserting write barriers. -(a): short-lived objects don't become old generation objects. -(b): only a few oldgen objects don't have performance impact. -\(c): only a few references don't have performance impact. +a. short-lived objects don't become old generation objects. +b. only a few oldgen objects don't have performance impact. +c. only a few references don't have performance impact. Inserting write barriers is a very difficult hack, it is easy to introduce critical bugs. And inserting write barriers has several areas @@ -2176,10 +2196,10 @@ Please consider utilizing built-in types. Most built-in types support write barrier, so you can use them to avoid manually inserting write barriers. -For example, if your T_DATA has references to other objects, then you -can move these references to Array. A T_DATA object only has a reference +For example, if your +T_DATA+ has references to other objects, then you +can move these references to Array. A +T_DATA+ object only has a reference to an array object. Or you can also use a Struct object to gather a -T_DATA object (without any references) and an that Array contains ++T_DATA+ object (without any references) and an Array that contains references. With use of such techniques, you don't need to insert write barriers @@ -2199,7 +2219,7 @@ available in include/ruby/ruby.h. An example is available in iseq.c. For a complete guide for RGenGC and write barriers, please refer to . -== Appendix E. RB_GC_GUARD to protect from premature GC +== Appendix E. +RB_GC_GUARD+ to protect from premature GC C Ruby currently uses conservative garbage collection, thus VALUE variables must remain visible on the stack or registers to ensure any @@ -2208,9 +2228,9 @@ with conservative garbage collection in mind, so they may optimize away the original VALUE even if the code depends on data associated with that VALUE. -The following example illustrates the use of RB_GC_GUARD to ensure -the contents of sptr remain valid while the second invocation of -rb_str_new_cstr is running. +The following example illustrates the use of +RB_GC_GUARD+ to ensure +the contents of _sptr_ remain valid while the second invocation of ++rb_str_new_cstr+ is running. VALUE s, w; const char *sptr; @@ -2221,31 +2241,31 @@ rb_str_new_cstr is running. RB_GC_GUARD(s); /* ensure s (and thus sptr) do not get GC-ed */ -In the above example, RB_GC_GUARD must be placed _after_ the last use of -sptr. Placing RB_GC_GUARD before dereferencing sptr would be of no use. -RB_GC_GUARD is only effective on the VALUE data type, not converted C +In the above example, +RB_GC_GUARD+ must be placed *after* the last use of +_sptr_. Placing +RB_GC_GUARD+ before dereferencing _sptr_ would be of no use. ++RB_GC_GUARD+ is only effective on the VALUE data type, not converted C data types. -RB_GC_GUARD would not be necessary at all in the above example if -non-inlined function calls are made on the `s' VALUE after sptr is ++RB_GC_GUARD+ would not be necessary at all in the above example if +non-inlined function calls are made on the _s_ VALUE after _sptr_ is dereferenced. Thus, in the above example, calling any un-inlined -function on `s' such as: +function on _s_ such as: rb_str_modify(s); -Will ensure `s' stays on the stack or register to prevent a +Will ensure _s_ stays on the stack or register to prevent a GC invocation from prematurely freeing it. -Using the RB_GC_GUARD macro is preferable to using the "volatile" -keyword in C. RB_GC_GUARD has the following advantages: +Using the +RB_GC_GUARD+ macro is preferable to using the "volatile" +keyword in C. +RB_GC_GUARD+ has the following advantages: 1. the intent of the macro use is clear -2. RB_GC_GUARD only affects its call site, "volatile" generates some +2. +RB_GC_GUARD+ only affects its call site, "volatile" generates some extra code every time the variable is used, hurting optimization. 3. "volatile" implementations may be buggy/inconsistent in some - compilers and architectures. RB_GC_GUARD is customizable for broken + compilers and architectures. +RB_GC_GUARD+ is customizable for broken systems/compilers without negatively affecting other systems. == Appendix F. Ractor support @@ -2259,9 +2279,9 @@ Ractor safety around C extensions has the following properties: 1. By default, all C extensions are recognized as Ractor-unsafe. 2. Ractor-unsafe C-methods may only be called from the main Ractor. If invoked by a non-main Ractor, then a Ractor::UnsafeError is raised. -3. If an extension desires to be marked as Ractor-safe the extension should - call rb_ext_ractor_safe(true) at the Init_ function for the extension, and - all defined methods will be marked as Ractor-safe. +3. If an extension desires to be marked as Ractor-safe the extension should call + rb_ext_ractor_safe(true) at the +Init_+ function for the extension, + and all defined methods will be marked as Ractor-safe. To make a "Ractor-safe" C extension, we need to check the following points: @@ -2274,14 +2294,15 @@ To make a "Ractor-safe" C extension, we need to check the following points: VALUE set(VALUE self, VALUE v){ return g_var = v; } VALUE get(VALUE self){ return g_var; } - set() and get() pair can share an unshareable objects using g_var, and - it is Ractor-unsafe. + set() and get() pair can share an unshareable objects + using _g_var_, and it is Ractor-unsafe. Not only using global variables directly, some indirect data structure - such as global st_table can share the objects, so please take care. + such as global +st_table+ can share the objects, so please take care. Note that class and module objects are shareable objects, so you can - keep the code "cFoo = rb_define_class(...)" with C's global variables. + keep the code cFoo = rb_define_class(...) with C's global + variables. 2. Check the thread-safety of the extension @@ -2297,7 +2318,7 @@ To make a "Ractor-safe" C extension, we need to check the following points: return ret; } - because g_called global variable should be synchronized by other + because _g_called_ global variable should be synchronized by other ractor's threads. To avoid such data-race, some synchronization should be used. Check include/ruby/thread_native.h and include/ruby/atomic.h. @@ -2309,25 +2330,26 @@ To make a "Ractor-safe" C extension, we need to check the following points: 3. Check the thread-safety of any used library - If the extension relies on an external library, such as a function foo() from - a library libfoo, the function libfoo foo() should be thread safe. + If the extension relies on an external library, such as a function + foo() from a library libfoo, the function libfoo foo() + should be thread safe. 4. Make an object shareable This is not required to make an extension Ractor-safe. - If an extension provides special objects defined by rb_data_type_t, + If an extension provides special objects defined by +rb_data_type_t+, consider these objects can become shareable or not. - RUBY_TYPED_FROZEN_SHAREABLE flag indicates that these objects can be - shareable objects if the object is frozen. This means that if the object - is frozen, the mutation of wrapped data is not allowed. + +RUBY_TYPED_FROZEN_SHAREABLE+ flag indicates that these objects can be + shareable objects if the object is frozen. This means that if the object is + frozen, the mutation of wrapped data is not allowed. 5. Others - There are possibly other points or requirements which must be considered in the - making of a Ractor-safe extension. This document will be extended as they are - discovered. + There are possibly other points or requirements which must be considered in + the making of a Ractor-safe extension. This document will be extended as + they are discovered. == Appendix G. Embedded TypedData @@ -2414,6 +2436,6 @@ Here is an example of how to use +RUBY_TYPED_EMBEDDABLE+:: -- Local variables: -fill-column: 70 +fill-column: 78 end: ++ diff --git a/gc/default/default.c b/gc/default/default.c index 66df18d879a101..5103e5eca42cf5 100644 --- a/gc/default/default.c +++ b/gc/default/default.c @@ -4212,13 +4212,6 @@ gc_sweep_finish(rb_objspace_t *objspace) } } - gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters); -#if RGENGC_ESTIMATE_OLDMALLOC - if (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) { - gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.oldcounters); - } -#endif - rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_END_SWEEP); gc_mode_transition(objspace, gc_mode_none); @@ -6669,6 +6662,7 @@ gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark) gc_prof_set_malloc_info(objspace); { int64_t inc = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.counters); + gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters); size_t old_limit = malloc_limit; /* A net-negative `inc` (more freed than malloc'd since last GC) is @@ -6724,6 +6718,8 @@ gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark) gc_params.oldmalloc_limit_max); } else { + gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.oldcounters); + if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) { objspace->rgengc.oldmalloc_increase_limit = (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1)); diff --git a/lib/prism/translation/ripper.rb b/lib/prism/translation/ripper.rb index f179a149a1df45..826a4e3f87c728 100644 --- a/lib/prism/translation/ripper.rb +++ b/lib/prism/translation/ripper.rb @@ -648,6 +648,16 @@ def parse end end + # Return encoding of the source. + def encoding + result.source.encoding + end + + # Return true if parsed source ended by `__END__`. + def end_seen? + !!result.data_loc + end + ########################################################################## # Visitor methods ########################################################################## diff --git a/lib/yaml/yaml.gemspec b/lib/yaml/yaml.gemspec index 17e1ce89e09423..620393d0c2137e 100644 --- a/lib/yaml/yaml.gemspec +++ b/lib/yaml/yaml.gemspec @@ -24,7 +24,5 @@ Gem::Specification.new do |spec| spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z 2>#{IO::NULL}`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end - spec.bindir = "exe" - spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] end diff --git a/prism/internal/serialize.h b/prism/internal/serialize.h index e611a0374bd4bf..3a6e05ecca83f0 100644 --- a/prism/internal/serialize.h +++ b/prism/internal/serialize.h @@ -14,6 +14,11 @@ * PRISM_EXCLUDE_SERIALIZATION define. */ #ifndef PRISM_EXCLUDE_SERIALIZATION +/* + * Serialize the given list of offsets to the given buffer. + */ +void pm_serialize_line_offset_list(pm_line_offset_list_t *list, pm_buffer_t *buffer); + /* * Serialize the given list of comments to the given buffer. */ diff --git a/prism/prism.c b/prism/prism.c index 1a2cc64596d150..c83573d4d75006 100644 --- a/prism/prism.c +++ b/prism/prism.c @@ -23079,6 +23079,7 @@ pm_serialize_parse_comments(pm_buffer_t *buffer, const uint8_t *source, size_t s pm_serialize_header(buffer); pm_serialize_encoding(parser.encoding, buffer); pm_buffer_append_varsint(buffer, parser.start_line); + pm_serialize_line_offset_list(&parser.line_offsets, buffer); pm_serialize_comment_list(&parser.comment_list, buffer); pm_parser_cleanup(&parser); diff --git a/prism/templates/lib/prism/serialize.rb.erb b/prism/templates/lib/prism/serialize.rb.erb index a676f957af96df..ec6a19ead014a0 100644 --- a/prism/templates/lib/prism/serialize.rb.erb +++ b/prism/templates/lib/prism/serialize.rb.erb @@ -135,8 +135,10 @@ module Prism loader.load_header loader.load_encoding start_line = loader.load_varsint + offsets = loader.load_line_offsets(freeze) source.replace_start_line(start_line) + source.replace_offsets(offsets) result = loader.load_comments(freeze) raise unless loader.eof? diff --git a/prism/templates/src/serialize.c.erb b/prism/templates/src/serialize.c.erb index 3d9811e5db686b..09d80ed1a51882 100644 --- a/prism/templates/src/serialize.c.erb +++ b/prism/templates/src/serialize.c.erb @@ -156,7 +156,10 @@ pm_serialize_node(pm_parser_t *parser, pm_node_t *node, pm_buffer_t *buffer) { } } -static void +/* + * Serialize the given list of offsets to the given buffer. + */ +void pm_serialize_line_offset_list(pm_line_offset_list_t *list, pm_buffer_t *buffer) { uint32_t size = pm_sizet_to_u32(list->size); pm_buffer_append_varuint(buffer, size); diff --git a/test/prism/api/parse_comments_test.rb b/test/prism/api/parse_comments_test.rb index 4dbcca1827f29e..a4f12495bab1a1 100644 --- a/test/prism/api/parse_comments_test.rb +++ b/test/prism/api/parse_comments_test.rb @@ -9,6 +9,8 @@ def test_parse_comments assert_kind_of Array, comments assert_equal 1, comments.length + assert_equal 1, comments[0].location.start_line + assert_equal "# foo", comments[0].slice end def test_parse_file_comments diff --git a/test/prism/ruby/ripper_test.rb b/test/prism/ruby/ripper_test.rb index 4fff630561e7d6..c5aa63aab21e92 100644 --- a/test/prism/ruby/ripper_test.rb +++ b/test/prism/ruby/ripper_test.rb @@ -230,6 +230,28 @@ def test_encoding assert_equal(Ripper.sexp(source), Translation::Ripper.sexp(source)) end + def test_encoding_method + source = "foo" + assert_equal(Ripper.new(source).tap(&:parse).encoding, Prism::Translation::Ripper.new(source).tap(&:parse).encoding) + + source = "foo".b + assert_equal(Ripper.new(source).tap(&:parse).encoding, Prism::Translation::Ripper.new(source).tap(&:parse).encoding) + + source = "# encoding: shift_jis" + assert_equal(Ripper.new(source).tap(&:parse).encoding, Prism::Translation::Ripper.new(source).tap(&:parse).encoding) + + source = "# encoding: shift_jis".b + assert_equal(Ripper.new(source).tap(&:parse).encoding, Prism::Translation::Ripper.new(source).tap(&:parse).encoding) + end + + def test_end_seen + source = "" + assert_equal(Ripper.new(source).tap(&:parse).end_seen?, Prism::Translation::Ripper.new(source).tap(&:parse).end_seen?) + + source = "__END__" + assert_equal(Ripper.new(source).tap(&:parse).end_seen?, Prism::Translation::Ripper.new(source).tap(&:parse).end_seen?) + end + def test_sexp_coercion string_like = Object.new def string_like.to_str diff --git a/test/ruby/test_keyword.rb b/test/ruby/test_keyword.rb index c836abd0c663b4..c5236b065a1256 100644 --- a/test/ruby/test_keyword.rb +++ b/test/ruby/test_keyword.rb @@ -615,7 +615,7 @@ def test_implicit_super_kwsplat sc = Class.new c = sc.new def c.m(*args, **kw) - super(*args, **kw) + super end sc.class_eval do def m(*args)