Ruby  2.0.0p451(2014-02-24revision45167)
iseq.c
Go to the documentation of this file.
00001 /**********************************************************************
00002 
00003   iseq.c -
00004 
00005   $Author: nagachika $
00006   created at: 2006-07-11(Tue) 09:00:03 +0900
00007 
00008   Copyright (C) 2006 Koichi Sasada
00009 
00010 **********************************************************************/
00011 
00012 #include "ruby/ruby.h"
00013 #include "internal.h"
00014 #include "eval_intern.h"
00015 
00016 /* #define RUBY_MARK_FREE_DEBUG 1 */
00017 #include "gc.h"
00018 #include "vm_core.h"
00019 #include "iseq.h"
00020 
00021 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
00022 
00023 #include "insns.inc"
00024 #include "insns_info.inc"
00025 
00026 #define ISEQ_MAJOR_VERSION 2
00027 #define ISEQ_MINOR_VERSION 0
00028 
00029 VALUE rb_cISeq;
00030 
00031 #define hidden_obj_p(obj) (!SPECIAL_CONST_P(obj) && !RBASIC(obj)->klass)
00032 
00033 static inline VALUE
00034 obj_resurrect(VALUE obj)
00035 {
00036     if (hidden_obj_p(obj)) {
00037         switch (BUILTIN_TYPE(obj)) {
00038           case T_STRING:
00039             obj = rb_str_resurrect(obj);
00040             break;
00041           case T_ARRAY:
00042             obj = rb_ary_resurrect(obj);
00043             break;
00044         }
00045     }
00046     return obj;
00047 }
00048 
00049 static void
00050 compile_data_free(struct iseq_compile_data *compile_data)
00051 {
00052     if (compile_data) {
00053         struct iseq_compile_data_storage *cur, *next;
00054         cur = compile_data->storage_head;
00055         while (cur) {
00056             next = cur->next;
00057             ruby_xfree(cur);
00058             cur = next;
00059         }
00060         ruby_xfree(compile_data);
00061     }
00062 }
00063 
00064 static void
00065 iseq_free(void *ptr)
00066 {
00067     rb_iseq_t *iseq;
00068     RUBY_FREE_ENTER("iseq");
00069 
00070     if (ptr) {
00071         iseq = ptr;
00072         if (!iseq->orig) {
00073             /* It's possible that strings are freed */
00074             if (0) {
00075                 RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label),
00076                                           RSTRING_PTR(iseq->location.path));
00077             }
00078 
00079             if (iseq->iseq != iseq->iseq_encoded) {
00080                 RUBY_FREE_UNLESS_NULL(iseq->iseq_encoded);
00081             }
00082 
00083             RUBY_FREE_UNLESS_NULL(iseq->iseq);
00084             RUBY_FREE_UNLESS_NULL(iseq->line_info_table);
00085             RUBY_FREE_UNLESS_NULL(iseq->local_table);
00086             RUBY_FREE_UNLESS_NULL(iseq->ic_entries);
00087             RUBY_FREE_UNLESS_NULL(iseq->callinfo_entries);
00088             RUBY_FREE_UNLESS_NULL(iseq->catch_table);
00089             RUBY_FREE_UNLESS_NULL(iseq->arg_opt_table);
00090             RUBY_FREE_UNLESS_NULL(iseq->arg_keyword_table);
00091             compile_data_free(iseq->compile_data);
00092         }
00093         ruby_xfree(ptr);
00094     }
00095     RUBY_FREE_LEAVE("iseq");
00096 }
00097 
00098 static void
00099 iseq_mark(void *ptr)
00100 {
00101     RUBY_MARK_ENTER("iseq");
00102 
00103     if (ptr) {
00104         rb_iseq_t *iseq = ptr;
00105 
00106         RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
00107         RUBY_MARK_UNLESS_NULL(iseq->mark_ary);
00108 
00109         RUBY_MARK_UNLESS_NULL(iseq->location.label);
00110         RUBY_MARK_UNLESS_NULL(iseq->location.base_label);
00111         RUBY_MARK_UNLESS_NULL(iseq->location.path);
00112         RUBY_MARK_UNLESS_NULL(iseq->location.absolute_path);
00113 
00114         RUBY_MARK_UNLESS_NULL((VALUE)iseq->cref_stack);
00115         RUBY_MARK_UNLESS_NULL(iseq->klass);
00116         RUBY_MARK_UNLESS_NULL(iseq->coverage);
00117 #if 0
00118         RUBY_MARK_UNLESS_NULL((VALUE)iseq->node);
00119         RUBY_MARK_UNLESS_NULL(iseq->cached_special_block);
00120 #endif
00121         RUBY_MARK_UNLESS_NULL(iseq->orig);
00122 
00123         if (iseq->compile_data != 0) {
00124             struct iseq_compile_data *const compile_data = iseq->compile_data;
00125             RUBY_MARK_UNLESS_NULL(compile_data->mark_ary);
00126             RUBY_MARK_UNLESS_NULL(compile_data->err_info);
00127             RUBY_MARK_UNLESS_NULL(compile_data->catch_table_ary);
00128         }
00129     }
00130     RUBY_MARK_LEAVE("iseq");
00131 }
00132 
00133 static size_t
00134 iseq_memsize(const void *ptr)
00135 {
00136     size_t size = sizeof(rb_iseq_t);
00137     const rb_iseq_t *iseq;
00138 
00139     if (ptr) {
00140         iseq = ptr;
00141         if (!iseq->orig) {
00142             if (iseq->iseq != iseq->iseq_encoded) {
00143                 size += iseq->iseq_size * sizeof(VALUE);
00144             }
00145 
00146             size += iseq->iseq_size * sizeof(VALUE);
00147             size += iseq->line_info_size * sizeof(struct iseq_line_info_entry);
00148             size += iseq->local_table_size * sizeof(ID);
00149             size += iseq->catch_table_size * sizeof(struct iseq_catch_table_entry);
00150             size += iseq->arg_opts * sizeof(VALUE);
00151             size += iseq->ic_size * sizeof(struct iseq_inline_cache_entry);
00152             size += iseq->callinfo_size * sizeof(rb_call_info_t);
00153 
00154             if (iseq->compile_data) {
00155                 struct iseq_compile_data_storage *cur;
00156 
00157                 cur = iseq->compile_data->storage_head;
00158                 while (cur) {
00159                     size += cur->size + sizeof(struct iseq_compile_data_storage);
00160                     cur = cur->next;
00161                 }
00162                 size += sizeof(struct iseq_compile_data);
00163             }
00164         }
00165     }
00166 
00167     return size;
00168 }
00169 
00170 static const rb_data_type_t iseq_data_type = {
00171     "iseq",
00172     {
00173         iseq_mark,
00174         iseq_free,
00175         iseq_memsize,
00176     },
00177 };
00178 
00179 static VALUE
00180 iseq_alloc(VALUE klass)
00181 {
00182     rb_iseq_t *iseq;
00183     return TypedData_Make_Struct(klass, rb_iseq_t, &iseq_data_type, iseq);
00184 }
00185 
00186 static rb_iseq_location_t *
00187 iseq_location_setup(rb_iseq_t *iseq, VALUE path, VALUE absolute_path, VALUE name, size_t first_lineno)
00188 {
00189     rb_iseq_location_t *loc = &iseq->location;
00190     loc->path = path;
00191     if (RTEST(absolute_path) && rb_str_cmp(path, absolute_path) == 0)
00192         loc->absolute_path = path;
00193     else
00194         loc->absolute_path = absolute_path;
00195     loc->label = loc->base_label = name;
00196     loc->first_lineno = first_lineno;
00197     return loc;
00198 }
00199 
00200 static void
00201 set_relation(rb_iseq_t *iseq, const VALUE parent)
00202 {
00203     const VALUE type = iseq->type;
00204     rb_thread_t *th = GET_THREAD();
00205     rb_iseq_t *piseq;
00206 
00207     /* set class nest stack */
00208     if (type == ISEQ_TYPE_TOP) {
00209         /* toplevel is private */
00210         iseq->cref_stack = NEW_CREF(rb_cObject);
00211         iseq->cref_stack->nd_refinements = Qnil;
00212         iseq->cref_stack->nd_visi = NOEX_PRIVATE;
00213         if (th->top_wrapper) {
00214             NODE *cref = NEW_CREF(th->top_wrapper);
00215             cref->nd_refinements = Qnil;
00216             cref->nd_visi = NOEX_PRIVATE;
00217             cref->nd_next = iseq->cref_stack;
00218             iseq->cref_stack = cref;
00219         }
00220         iseq->local_iseq = iseq;
00221     }
00222     else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) {
00223         iseq->cref_stack = NEW_CREF(0); /* place holder */
00224         iseq->cref_stack->nd_refinements = Qnil;
00225         iseq->local_iseq = iseq;
00226     }
00227     else if (RTEST(parent)) {
00228         GetISeqPtr(parent, piseq);
00229         iseq->cref_stack = piseq->cref_stack;
00230         iseq->local_iseq = piseq->local_iseq;
00231     }
00232 
00233     if (RTEST(parent)) {
00234         GetISeqPtr(parent, piseq);
00235         iseq->parent_iseq = piseq;
00236     }
00237 
00238     if (type == ISEQ_TYPE_MAIN) {
00239         iseq->local_iseq = iseq;
00240     }
00241 }
00242 
00243 void
00244 rb_iseq_add_mark_object(rb_iseq_t *iseq, VALUE obj)
00245 {
00246     if (!RTEST(iseq->mark_ary)) {
00247         iseq->mark_ary = rb_ary_tmp_new(3);
00248         OBJ_UNTRUST(iseq->mark_ary);
00249         RBASIC(iseq->mark_ary)->klass = 0;
00250     }
00251     rb_ary_push(iseq->mark_ary, obj);
00252 }
00253 
00254 static VALUE
00255 prepare_iseq_build(rb_iseq_t *iseq,
00256                    VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
00257                    VALUE parent, enum iseq_type type, VALUE block_opt,
00258                    const rb_compile_option_t *option)
00259 {
00260     iseq->type = type;
00261     iseq->arg_rest = -1;
00262     iseq->arg_block = -1;
00263     iseq->arg_keyword = -1;
00264     iseq->klass = 0;
00265     set_relation(iseq, parent);
00266 
00267     OBJ_FREEZE(name);
00268     OBJ_FREEZE(path);
00269 
00270     iseq_location_setup(iseq, path, absolute_path, name, first_lineno);
00271     if (iseq != iseq->local_iseq) {
00272         iseq->location.base_label = iseq->local_iseq->location.label;
00273     }
00274 
00275     iseq->defined_method_id = 0;
00276     iseq->mark_ary = 0;
00277 
00278 
00279     /*
00280      * iseq->special_block_builder = GC_GUARDED_PTR_REF(block_opt);
00281      * iseq->cached_special_block_builder = 0;
00282      * iseq->cached_special_block = 0;
00283      */
00284 
00285     iseq->compile_data = ALLOC(struct iseq_compile_data);
00286     MEMZERO(iseq->compile_data, struct iseq_compile_data, 1);
00287     iseq->compile_data->err_info = Qnil;
00288     iseq->compile_data->mark_ary = rb_ary_tmp_new(3);
00289 
00290     iseq->compile_data->storage_head = iseq->compile_data->storage_current =
00291       (struct iseq_compile_data_storage *)
00292         ALLOC_N(char, INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE +
00293                 sizeof(struct iseq_compile_data_storage));
00294 
00295     iseq->compile_data->catch_table_ary = rb_ary_new();
00296     iseq->compile_data->storage_head->pos = 0;
00297     iseq->compile_data->storage_head->next = 0;
00298     iseq->compile_data->storage_head->size =
00299       INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE;
00300     iseq->compile_data->storage_head->buff =
00301       (char *)(&iseq->compile_data->storage_head->buff + 1);
00302     iseq->compile_data->option = option;
00303     iseq->compile_data->last_coverable_line = -1;
00304 
00305     iseq->coverage = Qfalse;
00306     if (!GET_THREAD()->parse_in_eval) {
00307         VALUE coverages = rb_get_coverages();
00308         if (RTEST(coverages)) {
00309             iseq->coverage = rb_hash_lookup(coverages, path);
00310             if (NIL_P(iseq->coverage)) iseq->coverage = Qfalse;
00311         }
00312     }
00313 
00314     return Qtrue;
00315 }
00316 
00317 static VALUE
00318 cleanup_iseq_build(rb_iseq_t *iseq)
00319 {
00320     struct iseq_compile_data *data = iseq->compile_data;
00321     VALUE err = data->err_info;
00322     iseq->compile_data = 0;
00323     compile_data_free(data);
00324 
00325     if (RTEST(err)) {
00326         rb_funcall2(err, rb_intern("set_backtrace"), 1, &iseq->location.path);
00327         rb_exc_raise(err);
00328     }
00329     return Qtrue;
00330 }
00331 
00332 static rb_compile_option_t COMPILE_OPTION_DEFAULT = {
00333     OPT_INLINE_CONST_CACHE, /* int inline_const_cache; */
00334     OPT_PEEPHOLE_OPTIMIZATION, /* int peephole_optimization; */
00335     OPT_TAILCALL_OPTIMIZATION, /* int tailcall_optimization */
00336     OPT_SPECIALISED_INSTRUCTION, /* int specialized_instruction; */
00337     OPT_OPERANDS_UNIFICATION, /* int operands_unification; */
00338     OPT_INSTRUCTIONS_UNIFICATION, /* int instructions_unification; */
00339     OPT_STACK_CACHING, /* int stack_caching; */
00340     OPT_TRACE_INSTRUCTION, /* int trace_instruction */
00341 };
00342 static const rb_compile_option_t COMPILE_OPTION_FALSE = {0};
00343 
00344 static void
00345 make_compile_option(rb_compile_option_t *option, VALUE opt)
00346 {
00347     if (opt == Qnil) {
00348         *option = COMPILE_OPTION_DEFAULT;
00349     }
00350     else if (opt == Qfalse) {
00351         *option = COMPILE_OPTION_FALSE;
00352     }
00353     else if (opt == Qtrue) {
00354         memset(option, 1, sizeof(rb_compile_option_t));
00355     }
00356     else if (CLASS_OF(opt) == rb_cHash) {
00357         *option = COMPILE_OPTION_DEFAULT;
00358 
00359 #define SET_COMPILE_OPTION(o, h, mem) \
00360   { VALUE flag = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \
00361       if (flag == Qtrue)  { (o)->mem = 1; } \
00362       else if (flag == Qfalse)  { (o)->mem = 0; } \
00363   }
00364 #define SET_COMPILE_OPTION_NUM(o, h, mem) \
00365   { VALUE num = rb_hash_aref(opt, ID2SYM(rb_intern(#mem))); \
00366       if (!NIL_P(num)) (o)->mem = NUM2INT(num); \
00367   }
00368         SET_COMPILE_OPTION(option, opt, inline_const_cache);
00369         SET_COMPILE_OPTION(option, opt, peephole_optimization);
00370         SET_COMPILE_OPTION(option, opt, tailcall_optimization);
00371         SET_COMPILE_OPTION(option, opt, specialized_instruction);
00372         SET_COMPILE_OPTION(option, opt, operands_unification);
00373         SET_COMPILE_OPTION(option, opt, instructions_unification);
00374         SET_COMPILE_OPTION(option, opt, stack_caching);
00375         SET_COMPILE_OPTION(option, opt, trace_instruction);
00376         SET_COMPILE_OPTION_NUM(option, opt, debug_level);
00377 #undef SET_COMPILE_OPTION
00378 #undef SET_COMPILE_OPTION_NUM
00379     }
00380     else {
00381         rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil");
00382     }
00383 }
00384 
00385 static VALUE
00386 make_compile_option_value(rb_compile_option_t *option)
00387 {
00388     VALUE opt = rb_hash_new();
00389 #define SET_COMPILE_OPTION(o, h, mem) \
00390   rb_hash_aset((h), ID2SYM(rb_intern(#mem)), (o)->mem ? Qtrue : Qfalse)
00391 #define SET_COMPILE_OPTION_NUM(o, h, mem) \
00392   rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem))
00393     {
00394         SET_COMPILE_OPTION(option, opt, inline_const_cache);
00395         SET_COMPILE_OPTION(option, opt, peephole_optimization);
00396         SET_COMPILE_OPTION(option, opt, tailcall_optimization);
00397         SET_COMPILE_OPTION(option, opt, specialized_instruction);
00398         SET_COMPILE_OPTION(option, opt, operands_unification);
00399         SET_COMPILE_OPTION(option, opt, instructions_unification);
00400         SET_COMPILE_OPTION(option, opt, stack_caching);
00401         SET_COMPILE_OPTION(option, opt, trace_instruction);
00402         SET_COMPILE_OPTION_NUM(option, opt, debug_level);
00403     }
00404 #undef SET_COMPILE_OPTION
00405 #undef SET_COMPILE_OPTION_NUM
00406     return opt;
00407 }
00408 
00409 VALUE
00410 rb_iseq_new(NODE *node, VALUE name, VALUE path, VALUE absolute_path,
00411             VALUE parent, enum iseq_type type)
00412 {
00413     return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, type,
00414                                 &COMPILE_OPTION_DEFAULT);
00415 }
00416 
00417 VALUE
00418 rb_iseq_new_top(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE parent)
00419 {
00420     return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, ISEQ_TYPE_TOP,
00421                                 &COMPILE_OPTION_DEFAULT);
00422 }
00423 
00424 VALUE
00425 rb_iseq_new_main(NODE *node, VALUE path, VALUE absolute_path)
00426 {
00427     rb_thread_t *th = GET_THREAD();
00428     VALUE parent = th->base_block->iseq->self;
00429     return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), path, absolute_path, INT2FIX(0),
00430                                 parent, ISEQ_TYPE_MAIN, &COMPILE_OPTION_DEFAULT);
00431 }
00432 
00433 static VALUE
00434 rb_iseq_new_with_bopt_and_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
00435                                 VALUE parent, enum iseq_type type, VALUE bopt,
00436                                 const rb_compile_option_t *option)
00437 {
00438     rb_iseq_t *iseq;
00439     VALUE self = iseq_alloc(rb_cISeq);
00440 
00441     GetISeqPtr(self, iseq);
00442     iseq->self = self;
00443 
00444     prepare_iseq_build(iseq, name, path, absolute_path, first_lineno, parent, type, bopt, option);
00445     rb_iseq_compile_node(self, node);
00446     cleanup_iseq_build(iseq);
00447     return self;
00448 }
00449 
00450 VALUE
00451 rb_iseq_new_with_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
00452                      VALUE parent, enum iseq_type type,
00453                      const rb_compile_option_t *option)
00454 {
00455     /* TODO: argument check */
00456     return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
00457                                            Qfalse, option);
00458 }
00459 
00460 VALUE
00461 rb_iseq_new_with_bopt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
00462                        VALUE parent, enum iseq_type type, VALUE bopt)
00463 {
00464     /* TODO: argument check */
00465     return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
00466                                            bopt, &COMPILE_OPTION_DEFAULT);
00467 }
00468 
00469 #define CHECK_ARRAY(v)   rb_convert_type((v), T_ARRAY, "Array", "to_ary")
00470 #define CHECK_STRING(v)  rb_convert_type((v), T_STRING, "String", "to_str")
00471 #define CHECK_SYMBOL(v)  rb_convert_type((v), T_SYMBOL, "Symbol", "to_sym")
00472 static inline VALUE CHECK_INTEGER(VALUE v) {(void)NUM2LONG(v); return v;}
00473 static VALUE
00474 iseq_load(VALUE self, VALUE data, VALUE parent, VALUE opt)
00475 {
00476     VALUE iseqval = iseq_alloc(self);
00477 
00478     VALUE magic, version1, version2, format_type, misc;
00479     VALUE name, path, absolute_path, first_lineno;
00480     VALUE type, body, locals, args, exception;
00481 
00482     st_data_t iseq_type;
00483     static struct st_table *type_map_cache = 0;
00484     struct st_table *type_map = 0;
00485     rb_iseq_t *iseq;
00486     rb_compile_option_t option;
00487     int i = 0;
00488 
00489     /* [magic, major_version, minor_version, format_type, misc,
00490      *  label, path, first_lineno,
00491      *  type, locals, args, exception_table, body]
00492      */
00493 
00494     data        = CHECK_ARRAY(data);
00495 
00496     magic       = CHECK_STRING(rb_ary_entry(data, i++));
00497     version1    = CHECK_INTEGER(rb_ary_entry(data, i++));
00498     version2    = CHECK_INTEGER(rb_ary_entry(data, i++));
00499     format_type = CHECK_INTEGER(rb_ary_entry(data, i++));
00500     misc        = rb_ary_entry(data, i++); /* TODO */
00501     ((void)magic, (void)version1, (void)version2, (void)format_type, (void)misc);
00502 
00503     name        = CHECK_STRING(rb_ary_entry(data, i++));
00504     path        = CHECK_STRING(rb_ary_entry(data, i++));
00505     absolute_path = rb_ary_entry(data, i++);
00506     absolute_path = NIL_P(absolute_path) ? Qnil : CHECK_STRING(absolute_path);
00507     first_lineno = CHECK_INTEGER(rb_ary_entry(data, i++));
00508 
00509     type        = CHECK_SYMBOL(rb_ary_entry(data, i++));
00510     locals      = CHECK_ARRAY(rb_ary_entry(data, i++));
00511 
00512     args        = rb_ary_entry(data, i++);
00513     if (FIXNUM_P(args) || (args = CHECK_ARRAY(args))) {
00514         /* */
00515     }
00516 
00517     exception   = CHECK_ARRAY(rb_ary_entry(data, i++));
00518     body        = CHECK_ARRAY(rb_ary_entry(data, i++));
00519 
00520     GetISeqPtr(iseqval, iseq);
00521     iseq->self = iseqval;
00522 
00523     type_map = type_map_cache;
00524     if (type_map == 0) {
00525         struct st_table *cached_map;
00526         type_map = st_init_numtable();
00527         st_insert(type_map, ID2SYM(rb_intern("top")), ISEQ_TYPE_TOP);
00528         st_insert(type_map, ID2SYM(rb_intern("method")), ISEQ_TYPE_METHOD);
00529         st_insert(type_map, ID2SYM(rb_intern("block")), ISEQ_TYPE_BLOCK);
00530         st_insert(type_map, ID2SYM(rb_intern("class")), ISEQ_TYPE_CLASS);
00531         st_insert(type_map, ID2SYM(rb_intern("rescue")), ISEQ_TYPE_RESCUE);
00532         st_insert(type_map, ID2SYM(rb_intern("ensure")), ISEQ_TYPE_ENSURE);
00533         st_insert(type_map, ID2SYM(rb_intern("eval")), ISEQ_TYPE_EVAL);
00534         st_insert(type_map, ID2SYM(rb_intern("main")), ISEQ_TYPE_MAIN);
00535         st_insert(type_map, ID2SYM(rb_intern("defined_guard")), ISEQ_TYPE_DEFINED_GUARD);
00536         cached_map = ATOMIC_PTR_CAS(type_map_cache, (struct st_table *)0, type_map);
00537         if (cached_map) {
00538             st_free_table(type_map);
00539             type_map = cached_map;
00540         }
00541     }
00542 
00543     if (st_lookup(type_map, type, &iseq_type) == 0) {
00544         ID typeid = SYM2ID(type);
00545         VALUE typename = rb_id2str(typeid);
00546         if (typename)
00547             rb_raise(rb_eTypeError, "unsupport type: :%"PRIsVALUE, typename);
00548         else
00549             rb_raise(rb_eTypeError, "unsupport type: %p", (void *)typeid);
00550     }
00551 
00552     if (parent == Qnil) {
00553         parent = 0;
00554     }
00555 
00556     make_compile_option(&option, opt);
00557     prepare_iseq_build(iseq, name, path, absolute_path, first_lineno,
00558                        parent, (enum iseq_type)iseq_type, 0, &option);
00559 
00560     rb_iseq_build_from_ary(iseq, locals, args, exception, body);
00561 
00562     cleanup_iseq_build(iseq);
00563     return iseqval;
00564 }
00565 
00566 /*
00567  * :nodoc:
00568  */
00569 static VALUE
00570 iseq_s_load(int argc, VALUE *argv, VALUE self)
00571 {
00572     VALUE data, opt=Qnil;
00573     rb_scan_args(argc, argv, "11", &data, &opt);
00574 
00575     return iseq_load(self, data, 0, opt);
00576 }
00577 
00578 VALUE
00579 rb_iseq_load(VALUE data, VALUE parent, VALUE opt)
00580 {
00581     return iseq_load(rb_cISeq, data, parent, opt);
00582 }
00583 
00584 static NODE *
00585 parse_string(VALUE str, const char *file, int line)
00586 {
00587     VALUE parser = rb_parser_new();
00588     NODE *node = rb_parser_compile_string(parser, file, str, line);
00589 
00590     if (!node) {
00591         rb_exc_raise(GET_THREAD()->errinfo);    /* TODO: check err */
00592     }
00593     return node;
00594 }
00595 
00596 VALUE
00597 rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE absolute_path, VALUE line, rb_block_t *base_block, VALUE opt)
00598 {
00599     int state;
00600     rb_thread_t *th = GET_THREAD();
00601     rb_block_t *prev_base_block = th->base_block;
00602     VALUE iseqval = Qundef;
00603 
00604     th->base_block = base_block;
00605 
00606     TH_PUSH_TAG(th);
00607     if ((state = EXEC_TAG()) == 0) {
00608         int ln = NUM2INT(line);
00609         const char *fn = StringValueCStr(file);
00610         NODE *node;
00611         rb_compile_option_t option;
00612 
00613         make_compile_option(&option, opt);
00614 
00615         if (RB_TYPE_P((src), T_FILE))
00616             node = rb_compile_file(fn, src, ln);
00617         else
00618             node = parse_string(StringValue(src), fn, ln);
00619 
00620         if (base_block && base_block->iseq) {
00621             iseqval = rb_iseq_new_with_opt(node, base_block->iseq->location.label,
00622                                            file, absolute_path, line, base_block->iseq->self,
00623                                            ISEQ_TYPE_EVAL, &option);
00624         }
00625         else {
00626             iseqval = rb_iseq_new_with_opt(node, rb_str_new2("<compiled>"), file, absolute_path, line, Qfalse,
00627                                            ISEQ_TYPE_TOP, &option);
00628         }
00629     }
00630     TH_POP_TAG();
00631 
00632     th->base_block = prev_base_block;
00633 
00634     if (state) {
00635         JUMP_TAG(state);
00636     }
00637 
00638     return iseqval;
00639 }
00640 
00641 VALUE
00642 rb_iseq_compile(VALUE src, VALUE file, VALUE line)
00643 {
00644     return rb_iseq_compile_with_option(src, file, Qnil, line, 0, Qnil);
00645 }
00646 
00647 VALUE
00648 rb_iseq_compile_on_base(VALUE src, VALUE file, VALUE line, rb_block_t *base_block)
00649 {
00650     return rb_iseq_compile_with_option(src, file, Qnil, line, base_block, Qnil);
00651 }
00652 
00653 /*
00654  *  call-seq:
00655  *     InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq
00656  *     InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq
00657  *
00658  *  Takes +source+, a String of Ruby code and compiles it to an
00659  *  InstructionSequence.
00660  *
00661  *  Optionally takes +file+, +path+, and +line+ which describe the filename,
00662  *  absolute path and first line number of the ruby code in +source+ which are
00663  *  metadata attached to the returned +iseq+.
00664  *
00665  *  +options+, which can be +true+, +false+ or a +Hash+, is used to
00666  *  modify the default behavior of the Ruby iseq compiler.
00667  *
00668  *  For details regarding valid compile options see ::compile_option=.
00669  *
00670  *     RubyVM::InstructionSequence.compile("a = 1 + 2")
00671  *     #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
00672  *
00673  */
00674 static VALUE
00675 iseq_s_compile(int argc, VALUE *argv, VALUE self)
00676 {
00677     VALUE src, file = Qnil, path = Qnil, line = INT2FIX(1), opt = Qnil;
00678 
00679     rb_secure(1);
00680 
00681     rb_scan_args(argc, argv, "14", &src, &file, &path, &line, &opt);
00682     if (NIL_P(file)) file = rb_str_new2("<compiled>");
00683     if (NIL_P(line)) line = INT2FIX(1);
00684 
00685     return rb_iseq_compile_with_option(src, file, path, line, 0, opt);
00686 }
00687 
00688 /*
00689  *  call-seq:
00690  *      InstructionSequence.compile_file(file[, options]) -> iseq
00691  *
00692  *  Takes +file+, a String with the location of a Ruby source file, reads,
00693  *  parses and compiles the file, and returns +iseq+, the compiled
00694  *  InstructionSequence with source location metadata set.
00695  *
00696  *  Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to
00697  *  modify the default behavior of the Ruby iseq compiler.
00698  *
00699  *  For details regarding valid compile options see ::compile_option=.
00700  *
00701  *      # /tmp/hello.rb
00702  *      puts "Hello, world!"
00703  *
00704  *      # elsewhere
00705  *      RubyVM::InstructionSequence.compile_file("/tmp/hello.rb")
00706  *      #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb>
00707  */
00708 static VALUE
00709 iseq_s_compile_file(int argc, VALUE *argv, VALUE self)
00710 {
00711     VALUE file, line = INT2FIX(1), opt = Qnil;
00712     VALUE parser;
00713     VALUE f;
00714     NODE *node;
00715     const char *fname;
00716     rb_compile_option_t option;
00717 
00718     rb_secure(1);
00719     rb_scan_args(argc, argv, "11", &file, &opt);
00720     FilePathValue(file);
00721     fname = StringValueCStr(file);
00722 
00723     f = rb_file_open_str(file, "r");
00724 
00725     parser = rb_parser_new();
00726     node = rb_parser_compile_file(parser, fname, f, NUM2INT(line));
00727     make_compile_option(&option, opt);
00728     return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), file,
00729                                 rb_realpath_internal(Qnil, file, 1), line, Qfalse,
00730                                 ISEQ_TYPE_TOP, &option);
00731 }
00732 
00733 /*
00734  *  call-seq:
00735  *     InstructionSequence.compile_option = options
00736  *
00737  *  Sets the default values for various optimizations in the Ruby iseq
00738  *  compiler.
00739  *
00740  *  Possible values for +options+ include +true+, which enables all options,
00741  *  +false+ which disables all options, and +nil+ which leaves all options
00742  *  unchanged.
00743  *
00744  *  You can also pass a +Hash+ of +options+ that you want to change, any
00745  *  options not present in the hash will be left unchanged.
00746  *
00747  *  Possible option names (which are keys in +options+) which can be set to
00748  *  +true+ or +false+ include:
00749  *
00750  *  * +:inline_const_cache+
00751  *  * +:instructions_unification+
00752  *  * +:operands_unification+
00753  *  * +:peephole_optimization+
00754  *  * +:specialized_instruction+
00755  *  * +:stack_caching+
00756  *  * +:tailcall_optimization+
00757  *  * +:trace_instruction+
00758  *
00759  *  Additionally, +:debug_level+ can be set to an integer.
00760  *
00761  *  These default options can be overwritten for a single run of the iseq
00762  *  compiler by passing any of the above values as the +options+ parameter to
00763  *  ::new, ::compile and ::compile_file.
00764  */
00765 static VALUE
00766 iseq_s_compile_option_set(VALUE self, VALUE opt)
00767 {
00768     rb_compile_option_t option;
00769     rb_secure(1);
00770     make_compile_option(&option, opt);
00771     COMPILE_OPTION_DEFAULT = option;
00772     return opt;
00773 }
00774 
00775 /*
00776  *  call-seq:
00777  *     InstructionSequence.compile_option -> options
00778  *
00779  *  Returns a hash of default options used by the Ruby iseq compiler.
00780  *
00781  *  For details, see InstructionSequence.compile_option=.
00782  */
00783 static VALUE
00784 iseq_s_compile_option_get(VALUE self)
00785 {
00786     return make_compile_option_value(&COMPILE_OPTION_DEFAULT);
00787 }
00788 
00789 static rb_iseq_t *
00790 iseq_check(VALUE val)
00791 {
00792     rb_iseq_t *iseq;
00793     GetISeqPtr(val, iseq);
00794     if (!iseq->location.label) {
00795         rb_raise(rb_eTypeError, "uninitialized InstructionSequence");
00796     }
00797     return iseq;
00798 }
00799 
00800 /*
00801  *  call-seq:
00802  *     iseq.eval -> obj
00803  *
00804  *  Evaluates the instruction sequence and returns the result.
00805  *
00806  *      RubyVM::InstructionSequence.compile("1 + 2").eval #=> 3
00807  */
00808 static VALUE
00809 iseq_eval(VALUE self)
00810 {
00811     rb_secure(1);
00812     return rb_iseq_eval(self);
00813 }
00814 
00815 /*
00816  *  Returns a human-readable string representation of this instruction
00817  *  sequence, including the #label and #path.
00818  */
00819 static VALUE
00820 iseq_inspect(VALUE self)
00821 {
00822     rb_iseq_t *iseq;
00823     GetISeqPtr(self, iseq);
00824     if (!iseq->location.label) {
00825         return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
00826     }
00827 
00828     return rb_sprintf("<%s:%s@%s>",
00829                       rb_obj_classname(self),
00830                       RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
00831 }
00832 
00833 /*
00834  *  Returns the path of this instruction sequence.
00835  *
00836  *  <code><compiled></code> if the iseq was evaluated from a string.
00837  *
00838  *  For example, using irb:
00839  *
00840  *      iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
00841  *      #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
00842  *      iseq.path
00843  *      #=> "<compiled>"
00844  *
00845  *  Using ::compile_file:
00846  *
00847  *      # /tmp/method.rb
00848  *      def hello
00849  *        puts "hello, world"
00850  *      end
00851  *
00852  *      # in irb
00853  *      > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
00854  *      > iseq.path #=> /tmp/method.rb
00855  */
00856 static VALUE
00857 iseq_path(VALUE self)
00858 {
00859     rb_iseq_t *iseq;
00860     GetISeqPtr(self, iseq);
00861     return iseq->location.path;
00862 }
00863 
00864 /*
00865  *  Returns the absolute path of this instruction sequence.
00866  *
00867  *  +nil+ if the iseq was evaluated from a string.
00868  *
00869  *  For example, using ::compile_file:
00870  *
00871  *      # /tmp/method.rb
00872  *      def hello
00873  *        puts "hello, world"
00874  *      end
00875  *
00876  *      # in irb
00877  *      > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
00878  *      > iseq.absolute_path #=> /tmp/method.rb
00879  */
00880 static VALUE
00881 iseq_absolute_path(VALUE self)
00882 {
00883     rb_iseq_t *iseq;
00884     GetISeqPtr(self, iseq);
00885     return iseq->location.absolute_path;
00886 }
00887 
00888 /*  Returns the label of this instruction sequence.
00889  *
00890  *  <code><main></code> if it's at the top level, <code><compiled></code> if it
00891  *  was evaluated from a string.
00892  *
00893  *  For example, using irb:
00894  *
00895  *      iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
00896  *      #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
00897  *      iseq.label
00898  *      #=> "<compiled>"
00899  *
00900  *  Using ::compile_file:
00901  *
00902  *      # /tmp/method.rb
00903  *      def hello
00904  *        puts "hello, world"
00905  *      end
00906  *
00907  *      # in irb
00908  *      > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
00909  *      > iseq.label #=> <main>
00910  */
00911 static VALUE
00912 iseq_label(VALUE self)
00913 {
00914     rb_iseq_t *iseq;
00915     GetISeqPtr(self, iseq);
00916     return iseq->location.label;
00917 }
00918 
00919 /*  Returns the base label of this instruction sequence.
00920  *
00921  *  For example, using irb:
00922  *
00923  *      iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
00924  *      #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
00925  *      iseq.base_label
00926  *      #=> "<compiled>"
00927  *
00928  *  Using ::compile_file:
00929  *
00930  *      # /tmp/method.rb
00931  *      def hello
00932  *        puts "hello, world"
00933  *      end
00934  *
00935  *      # in irb
00936  *      > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
00937  *      > iseq.base_label #=> <main>
00938  */
00939 static VALUE
00940 iseq_base_label(VALUE self)
00941 {
00942     rb_iseq_t *iseq;
00943     GetISeqPtr(self, iseq);
00944     return iseq->location.base_label;
00945 }
00946 
00947 /*  Returns the number of the first source line where the instruction sequence
00948  *  was loaded from.
00949  *
00950  *  For example, using irb:
00951  *
00952  *      iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
00953  *      #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
00954  *      iseq.first_lineno
00955  *      #=> 1
00956  */
00957 static VALUE
00958 iseq_first_lineno(VALUE self)
00959 {
00960     rb_iseq_t *iseq;
00961     GetISeqPtr(self, iseq);
00962     return iseq->location.first_lineno;
00963 }
00964 
00965 static
00966 VALUE iseq_data_to_ary(rb_iseq_t *iseq);
00967 
00968 /*
00969  *  call-seq:
00970  *     iseq.to_a -> ary
00971  *
00972  *  Returns an Array with 14 elements representing the instruction sequence
00973  *  with the following data:
00974  *
00975  *  [magic]
00976  *    A string identifying the data format. <b>Always
00977  *    +YARVInstructionSequence/SimpleDataFormat+.</b>
00978  *
00979  *  [major_version]
00980  *    The major version of the instruction sequence.
00981  *
00982  *  [minor_version]
00983  *    The minor version of the instruction sequence.
00984  *
00985  *  [format_type]
00986  *    A number identifying the data format. <b>Always 1</b>.
00987  *
00988  *  [misc]
00989  *    A hash containing:
00990  *
00991  *    [+:arg_size+]
00992  *      the total number of arguments taken by the method or the block (0 if
00993  *      _iseq_ doesn't represent a method or block)
00994  *    [+:local_size+]
00995  *      the number of local variables + 1
00996  *    [+:stack_max+]
00997  *      used in calculating the stack depth at which a SystemStackError is
00998  *      thrown.
00999  *
01000  *  [#label]
01001  *    The name of the context (block, method, class, module, etc.) that this
01002  *    instruction sequence belongs to.
01003  *
01004  *    <code><main></code> if it's at the top level, <code><compiled></code> if
01005  *    it was evaluated from a string.
01006  *
01007  *  [#path]
01008  *    The relative path to the Ruby file where the instruction sequence was
01009  *    loaded from.
01010  *
01011  *    <code><compiled></code> if the iseq was evaluated from a string.
01012  *
01013  *  [#absolute_path]
01014  *    The absolute path to the Ruby file where the instruction sequence was
01015  *    loaded from.
01016  *
01017  *    +nil+ if the iseq was evaluated from a string.
01018  *
01019  *  [#first_lineno]
01020  *    The number of the first source line where the instruction sequence was
01021  *    loaded from.
01022  *
01023  *  [type]
01024  *    The type of the instruction sequence.
01025  *
01026  *    Valid values are +:top+, +:method+, +:block+, +:class+, +:rescue+,
01027  *    +:ensure+, +:eval+, +:main+, and +:defined_guard+.
01028  *
01029  *  [locals]
01030  *    An array containing the names of all arguments and local variables as
01031  *    symbols.
01032  *
01033  *  [args]
01034  *    The arity if the method or block only has required arguments.
01035  *
01036  *    Otherwise an array of:
01037  *
01038  *      [required_argc, [optional_arg_labels, ...],
01039  *       splat_index, post_splat_argc, post_splat_index,
01040  *       block_index, simple]
01041  *
01042  *    More info about these values can be found in +vm_core.h+.
01043  *
01044  *  [catch_table]
01045  *    A list of exceptions and control flow operators (rescue, next, redo,
01046  *    break, etc.).
01047  *
01048  *  [bytecode]
01049  *    An array of arrays containing the instruction names and operands that
01050  *    make up the body of the instruction sequence.
01051  *
01052  */
01053 static VALUE
01054 iseq_to_a(VALUE self)
01055 {
01056     rb_iseq_t *iseq = iseq_check(self);
01057     rb_secure(1);
01058     return iseq_data_to_ary(iseq);
01059 }
01060 
01061 int
01062 rb_iseq_first_lineno(const rb_iseq_t *iseq)
01063 {
01064     return FIX2INT(iseq->location.first_lineno);
01065 }
01066 
01067 /* TODO: search algorithm is brute force.
01068          this should be binary search or so. */
01069 
01070 static struct iseq_line_info_entry *
01071 get_line_info(const rb_iseq_t *iseq, size_t pos)
01072 {
01073     size_t i = 0, size = iseq->line_info_size;
01074     struct iseq_line_info_entry *table = iseq->line_info_table;
01075     const int debug = 0;
01076 
01077     if (debug) {
01078         printf("size: %"PRIdSIZE"\n", size);
01079         printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
01080                i, table[i].position, table[i].line_no, pos);
01081     }
01082 
01083     if (size == 0) {
01084         return 0;
01085     }
01086     else if (size == 1) {
01087         return &table[0];
01088     }
01089     else {
01090         for (i=1; i<size; i++) {
01091             if (debug) printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
01092                               i, table[i].position, table[i].line_no, pos);
01093 
01094             if (table[i].position == pos) {
01095                 return &table[i];
01096             }
01097             if (table[i].position > pos) {
01098                 return &table[i-1];
01099             }
01100         }
01101     }
01102     return &table[i-1];
01103 }
01104 
01105 static unsigned int
01106 find_line_no(const rb_iseq_t *iseq, size_t pos)
01107 {
01108     struct iseq_line_info_entry *entry = get_line_info(iseq, pos);
01109     if (entry) {
01110         return entry->line_no;
01111     }
01112     else {
01113         return 0;
01114     }
01115 }
01116 
01117 unsigned int
01118 rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos)
01119 {
01120     if (pos == 0) {
01121         return find_line_no(iseq, pos);
01122     }
01123     else {
01124         return find_line_no(iseq, pos - 1);
01125     }
01126 }
01127 
01128 static VALUE
01129 id_to_name(ID id, VALUE default_value)
01130 {
01131     VALUE str = rb_id2str(id);
01132     if (!str) {
01133         str = default_value;
01134     }
01135     else if (!rb_str_symname_p(str)) {
01136         str = rb_str_inspect(str);
01137     }
01138     return str;
01139 }
01140 
01141 VALUE
01142 insn_operand_intern(rb_iseq_t *iseq,
01143                     VALUE insn, int op_no, VALUE op,
01144                     int len, size_t pos, VALUE *pnop, VALUE child)
01145 {
01146     const char *types = insn_op_types(insn);
01147     char type = types[op_no];
01148     VALUE ret;
01149 
01150     switch (type) {
01151       case TS_OFFSET:           /* LONG */
01152         ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op));
01153         break;
01154 
01155       case TS_NUM:              /* ULONG */
01156         ret = rb_sprintf("%"PRIuVALUE, op);
01157         break;
01158 
01159       case TS_LINDEX:{
01160         if (insn == BIN(getlocal) || insn == BIN(setlocal)) {
01161             if (pnop) {
01162                 rb_iseq_t *diseq = iseq;
01163                 VALUE level = *pnop, i;
01164 
01165                 for (i = 0; i < level; i++) {
01166                     diseq = diseq->parent_iseq;
01167                 }
01168                 ret = id_to_name(diseq->local_table[diseq->local_size - op], INT2FIX('*'));
01169             }
01170             else {
01171                 ret = rb_sprintf("%"PRIuVALUE, op);
01172             }
01173         }
01174         else {
01175             ret = rb_inspect(INT2FIX(op));
01176         }
01177         break;
01178       }
01179       case TS_ID:               /* ID (symbol) */
01180         op = ID2SYM(op);
01181 
01182       case TS_VALUE:            /* VALUE */
01183         op = obj_resurrect(op);
01184         ret = rb_inspect(op);
01185         if (CLASS_OF(op) == rb_cISeq) {
01186             if (child) {
01187                 rb_ary_push(child, op);
01188             }
01189         }
01190         break;
01191 
01192       case TS_ISEQ:             /* iseq */
01193         {
01194             rb_iseq_t *iseq = (rb_iseq_t *)op;
01195             if (iseq) {
01196                 ret = iseq->location.label;
01197                 if (child) {
01198                     rb_ary_push(child, iseq->self);
01199                 }
01200             }
01201             else {
01202                 ret = rb_str_new2("nil");
01203             }
01204             break;
01205         }
01206       case TS_GENTRY:
01207         {
01208             struct rb_global_entry *entry = (struct rb_global_entry *)op;
01209             ret = rb_str_dup(rb_id2str(entry->id));
01210         }
01211         break;
01212 
01213       case TS_IC:
01214         ret = rb_sprintf("<ic:%"PRIdPTRDIFF">", (struct iseq_inline_cache_entry *)op - iseq->ic_entries);
01215         break;
01216 
01217       case TS_CALLINFO:
01218         {
01219             rb_call_info_t *ci = (rb_call_info_t *)op;
01220             VALUE ary = rb_ary_new();
01221 
01222             if (ci->mid) {
01223                 rb_ary_push(ary, rb_sprintf("mid:%s", rb_id2name(ci->mid)));
01224             }
01225 
01226             rb_ary_push(ary, rb_sprintf("argc:%d", ci->orig_argc));
01227 
01228             if (ci->blockiseq) {
01229                 if (child) {
01230                     rb_ary_push(child, ci->blockiseq->self);
01231                 }
01232                 rb_ary_push(ary, rb_sprintf("block:%"PRIsVALUE, ci->blockiseq->location.label));
01233             }
01234 
01235             if (ci->flag) {
01236                 VALUE flags = rb_ary_new();
01237                 if (ci->flag & VM_CALL_ARGS_SPLAT) rb_ary_push(flags, rb_str_new2("ARGS_SPLAT"));
01238                 if (ci->flag & VM_CALL_ARGS_BLOCKARG) rb_ary_push(flags, rb_str_new2("ARGS_BLOCKARG"));
01239                 if (ci->flag & VM_CALL_FCALL) rb_ary_push(flags, rb_str_new2("FCALL"));
01240                 if (ci->flag & VM_CALL_VCALL) rb_ary_push(flags, rb_str_new2("VCALL"));
01241                 if (ci->flag & VM_CALL_TAILCALL) rb_ary_push(flags, rb_str_new2("TAILCALL"));
01242                 if (ci->flag & VM_CALL_SUPER) rb_ary_push(flags, rb_str_new2("SUPER"));
01243                 if (ci->flag & VM_CALL_OPT_SEND) rb_ary_push(flags, rb_str_new2("SNED")); /* maybe not reachable */
01244                 if (ci->flag & VM_CALL_ARGS_SKIP_SETUP) rb_ary_push(flags, rb_str_new2("ARGS_SKIP")); /* maybe not reachable */
01245                 rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|")));
01246             }
01247             ret = rb_sprintf("<callinfo!%"PRIsVALUE">", rb_ary_join(ary, rb_str_new2(", ")));
01248         }
01249         break;
01250 
01251       case TS_CDHASH:
01252         ret = rb_str_new2("<cdhash>");
01253         break;
01254 
01255       case TS_FUNCPTR:
01256         ret = rb_str_new2("<funcptr>");
01257         break;
01258 
01259       default:
01260         rb_bug("insn_operand_intern: unknown operand type: %c", type);
01261     }
01262     return ret;
01263 }
01264 
01269 int
01270 rb_iseq_disasm_insn(VALUE ret, VALUE *iseq, size_t pos,
01271                     rb_iseq_t *iseqdat, VALUE child)
01272 {
01273     VALUE insn = iseq[pos];
01274     int len = insn_len(insn);
01275     int j;
01276     const char *types = insn_op_types(insn);
01277     VALUE str = rb_str_new(0, 0);
01278     const char *insn_name_buff;
01279 
01280     insn_name_buff = insn_name(insn);
01281     if (1) {
01282         rb_str_catf(str, "%04"PRIdSIZE" %-16s ", pos, insn_name_buff);
01283     }
01284     else {
01285         rb_str_catf(str, "%04"PRIdSIZE" %-16.*s ", pos,
01286                     (int)strcspn(insn_name_buff, "_"), insn_name_buff);
01287     }
01288 
01289     for (j = 0; types[j]; j++) {
01290         const char *types = insn_op_types(insn);
01291         VALUE opstr = insn_operand_intern(iseqdat, insn, j, iseq[pos + j + 1],
01292                                           len, pos, &iseq[pos + j + 2],
01293                                           child);
01294         rb_str_concat(str, opstr);
01295 
01296         if (types[j + 1]) {
01297             rb_str_cat2(str, ", ");
01298         }
01299     }
01300 
01301     {
01302         unsigned int line_no = find_line_no(iseqdat, pos);
01303         unsigned int prev = pos == 0 ? 0 : find_line_no(iseqdat, pos - 1);
01304         if (line_no && line_no != prev) {
01305             long slen = RSTRING_LEN(str);
01306             slen = (slen > 70) ? 0 : (70 - slen);
01307             str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no);
01308         }
01309     }
01310 
01311     if (ret) {
01312         rb_str_cat2(str, "\n");
01313         rb_str_concat(ret, str);
01314     }
01315     else {
01316         printf("%s\n", RSTRING_PTR(str));
01317     }
01318     return len;
01319 }
01320 
01321 static const char *
01322 catch_type(int type)
01323 {
01324     switch (type) {
01325       case CATCH_TYPE_RESCUE:
01326         return "rescue";
01327       case CATCH_TYPE_ENSURE:
01328         return "ensure";
01329       case CATCH_TYPE_RETRY:
01330         return "retry";
01331       case CATCH_TYPE_BREAK:
01332         return "break";
01333       case CATCH_TYPE_REDO:
01334         return "redo";
01335       case CATCH_TYPE_NEXT:
01336         return "next";
01337       default:
01338         rb_bug("unknown catch type (%d)", type);
01339         return 0;
01340     }
01341 }
01342 
01343 /*
01344  *  call-seq:
01345  *     iseq.disasm -> str
01346  *     iseq.disassemble -> str
01347  *
01348  *  Returns the instruction sequence as a +String+ in human readable form.
01349  *
01350  *    puts RubyVM::InstructionSequence.compile('1 + 2').disasm
01351  *
01352  *  Produces:
01353  *
01354  *    == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
01355  *    0000 trace            1                                               (   1)
01356  *    0002 putobject        1
01357  *    0004 putobject        2
01358  *    0006 opt_plus         <ic:1>
01359  *    0008 leave
01360  */
01361 VALUE
01362 rb_iseq_disasm(VALUE self)
01363 {
01364     rb_iseq_t *iseqdat = iseq_check(self);
01365     VALUE *iseq;
01366     VALUE str = rb_str_new(0, 0);
01367     VALUE child = rb_ary_new();
01368     unsigned long size;
01369     int i;
01370     long l;
01371     ID *tbl;
01372     size_t n;
01373     enum {header_minlen = 72};
01374 
01375     rb_secure(1);
01376 
01377     iseq = iseqdat->iseq;
01378     size = iseqdat->iseq_size;
01379 
01380     rb_str_cat2(str, "== disasm: ");
01381 
01382     rb_str_concat(str, iseq_inspect(iseqdat->self));
01383     if ((l = RSTRING_LEN(str)) < header_minlen) {
01384         rb_str_resize(str, header_minlen);
01385         memset(RSTRING_PTR(str) + l, '=', header_minlen - l);
01386     }
01387     rb_str_cat2(str, "\n");
01388 
01389     /* show catch table information */
01390     if (iseqdat->catch_table_size != 0) {
01391         rb_str_cat2(str, "== catch table\n");
01392     }
01393     for (i = 0; i < iseqdat->catch_table_size; i++) {
01394         struct iseq_catch_table_entry *entry = &iseqdat->catch_table[i];
01395         rb_str_catf(str,
01396                     "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n",
01397                     catch_type((int)entry->type), (int)entry->start,
01398                     (int)entry->end, (int)entry->sp, (int)entry->cont);
01399         if (entry->iseq) {
01400             rb_str_concat(str, rb_iseq_disasm(entry->iseq));
01401         }
01402     }
01403     if (iseqdat->catch_table_size != 0) {
01404         rb_str_cat2(str, "|-------------------------------------"
01405                     "-----------------------------------\n");
01406     }
01407 
01408     /* show local table information */
01409     tbl = iseqdat->local_table;
01410 
01411     if (tbl) {
01412         rb_str_catf(str,
01413                     "local table (size: %d, argc: %d "
01414                     "[opts: %d, rest: %d, post: %d, block: %d] s%d)\n",
01415                     iseqdat->local_size, iseqdat->argc,
01416                     iseqdat->arg_opts, iseqdat->arg_rest,
01417                     iseqdat->arg_post_len, iseqdat->arg_block,
01418                     iseqdat->arg_simple);
01419 
01420         for (i = 0; i < iseqdat->local_table_size; i++) {
01421             long width;
01422             VALUE name = id_to_name(tbl[i], 0);
01423             char argi[0x100] = "";
01424             char opti[0x100] = "";
01425 
01426             if (iseqdat->arg_opts) {
01427                 int argc = iseqdat->argc;
01428                 int opts = iseqdat->arg_opts;
01429                 if (i >= argc && i < argc + opts - 1) {
01430                     snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE,
01431                              iseqdat->arg_opt_table[i - argc]);
01432                 }
01433             }
01434 
01435             snprintf(argi, sizeof(argi), "%s%s%s%s%s",  /* arg, opts, rest, post  block */
01436                      iseqdat->argc > i ? "Arg" : "",
01437                      opti,
01438                      iseqdat->arg_rest == i ? "Rest" : "",
01439                      (iseqdat->arg_post_start <= i &&
01440                       i < iseqdat->arg_post_start + iseqdat->arg_post_len) ? "Post" : "",
01441                      iseqdat->arg_block == i ? "Block" : "");
01442 
01443             rb_str_catf(str, "[%2d] ", iseqdat->local_size - i);
01444             width = RSTRING_LEN(str) + 11;
01445             if (name)
01446                 rb_str_append(str, name);
01447             else
01448                 rb_str_cat2(str, "?");
01449             if (*argi) rb_str_catf(str, "<%s>", argi);
01450             if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, "");
01451         }
01452         rb_str_cat2(str, "\n");
01453     }
01454 
01455     /* show each line */
01456     for (n = 0; n < size;) {
01457         n += rb_iseq_disasm_insn(str, iseq, n, iseqdat, child);
01458     }
01459 
01460     for (i = 0; i < RARRAY_LEN(child); i++) {
01461         VALUE isv = rb_ary_entry(child, i);
01462         rb_str_concat(str, rb_iseq_disasm(isv));
01463     }
01464 
01465     return str;
01466 }
01467 
01468 /*
01469  *  Returns the instruction sequence containing the given proc or method.
01470  *
01471  *  For example, using irb:
01472  *
01473  *      # a proc
01474  *      > p = proc { num = 1 + 2 }
01475  *      > RubyVM::InstructionSequence.of(p)
01476  *      > #=> <RubyVM::InstructionSequence:block in irb_binding@(irb)>
01477  *
01478  *      # for a method
01479  *      > def foo(bar); puts bar; end
01480  *      > RubyVM::InstructionSequence.of(method(:foo))
01481  *      > #=> <RubyVM::InstructionSequence:foo@(irb)>
01482  *
01483  *  Using ::compile_file:
01484  *
01485  *      # /tmp/iseq_of.rb
01486  *      def hello
01487  *        puts "hello, world"
01488  *      end
01489  *
01490  *      $a_global_proc = proc { str = 'a' + 'b' }
01491  *
01492  *      # in irb
01493  *      > require '/tmp/iseq_of.rb'
01494  *
01495  *      # first the method hello
01496  *      > RubyVM::InstructionSequence.of(method(:hello))
01497  *      > #=> #<RubyVM::InstructionSequence:0x007fb73d7cb1d0>
01498  *
01499  *      # then the global proc
01500  *      > RubyVM::InstructionSequence.of($a_global_proc)
01501  *      > #=> #<RubyVM::InstructionSequence:0x007fb73d7caf78>
01502  */
01503 static VALUE
01504 iseq_s_of(VALUE klass, VALUE body)
01505 {
01506     VALUE ret = Qnil;
01507     rb_iseq_t *iseq;
01508 
01509     rb_secure(1);
01510 
01511     if (rb_obj_is_proc(body)) {
01512         rb_proc_t *proc;
01513         GetProcPtr(body, proc);
01514         iseq = proc->block.iseq;
01515         if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
01516             ret = iseq->self;
01517         }
01518     }
01519     else if ((iseq = rb_method_get_iseq(body)) != 0) {
01520         ret = iseq->self;
01521     }
01522     return ret;
01523 }
01524 
01525 /*
01526  *  call-seq:
01527  *     InstructionSequence.disasm(body) -> str
01528  *     InstructionSequence.disassemble(body) -> str
01529  *
01530  *  Takes +body+, a Method or Proc object, and returns a String with the
01531  *  human readable instructions for +body+.
01532  *
01533  *  For a Method object:
01534  *
01535  *    # /tmp/method.rb
01536  *    def hello
01537  *      puts "hello, world"
01538  *    end
01539  *
01540  *    puts RubyVM::InstructionSequence.disasm(method(:hello))
01541  *
01542  *  Produces:
01543  *
01544  *    == disasm: <RubyVM::InstructionSequence:hello@/tmp/method.rb>============
01545  *    0000 trace            8                                               (   1)
01546  *    0002 trace            1                                               (   2)
01547  *    0004 putself
01548  *    0005 putstring        "hello, world"
01549  *    0007 send             :puts, 1, nil, 8, <ic:0>
01550  *    0013 trace            16                                              (   3)
01551  *    0015 leave                                                            (   2)
01552  *
01553  *  For a Proc:
01554  *
01555  *    # /tmp/proc.rb
01556  *    p = proc { num = 1 + 2 }
01557  *    puts RubyVM::InstructionSequence.disasm(p)
01558  *
01559  *  Produces:
01560  *
01561  *    == disasm: <RubyVM::InstructionSequence:block in <main>@/tmp/proc.rb>===
01562  *    == catch table
01563  *    | catch type: redo   st: 0000 ed: 0012 sp: 0000 cont: 0000
01564  *    | catch type: next   st: 0000 ed: 0012 sp: 0000 cont: 0012
01565  *    |------------------------------------------------------------------------
01566  *    local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
01567  *    [ 2] num
01568  *    0000 trace            1                                               (   1)
01569  *    0002 putobject        1
01570  *    0004 putobject        2
01571  *    0006 opt_plus         <ic:1>
01572  *    0008 dup
01573  *    0009 setlocal         num, 0
01574  *    0012 leave
01575  *
01576  */
01577 
01578 static VALUE
01579 iseq_s_disasm(VALUE klass, VALUE body)
01580 {
01581     VALUE iseqval = iseq_s_of(klass, body);
01582     return NIL_P(iseqval) ? Qnil : rb_iseq_disasm(iseqval);
01583 }
01584 
01585 const char *
01586 ruby_node_name(int node)
01587 {
01588     switch (node) {
01589 #include "node_name.inc"
01590       default:
01591         rb_bug("unknown node (%d)", node);
01592         return 0;
01593     }
01594 }
01595 
01596 #define DECL_SYMBOL(name) \
01597   static VALUE sym_##name
01598 
01599 #define INIT_SYMBOL(name) \
01600   sym_##name = ID2SYM(rb_intern(#name))
01601 
01602 static VALUE
01603 register_label(struct st_table *table, unsigned long idx)
01604 {
01605     VALUE sym;
01606     char buff[8 + (sizeof(idx) * CHAR_BIT * 32 / 100)];
01607 
01608     snprintf(buff, sizeof(buff), "label_%lu", idx);
01609     sym = ID2SYM(rb_intern(buff));
01610     st_insert(table, idx, sym);
01611     return sym;
01612 }
01613 
01614 static VALUE
01615 exception_type2symbol(VALUE type)
01616 {
01617     ID id;
01618     switch (type) {
01619       case CATCH_TYPE_RESCUE: CONST_ID(id, "rescue"); break;
01620       case CATCH_TYPE_ENSURE: CONST_ID(id, "ensure"); break;
01621       case CATCH_TYPE_RETRY:  CONST_ID(id, "retry");  break;
01622       case CATCH_TYPE_BREAK:  CONST_ID(id, "break");  break;
01623       case CATCH_TYPE_REDO:   CONST_ID(id, "redo");   break;
01624       case CATCH_TYPE_NEXT:   CONST_ID(id, "next");   break;
01625       default:
01626         rb_bug("...");
01627     }
01628     return ID2SYM(id);
01629 }
01630 
01631 static int
01632 cdhash_each(VALUE key, VALUE value, VALUE ary)
01633 {
01634     rb_ary_push(ary, obj_resurrect(key));
01635     rb_ary_push(ary, value);
01636     return ST_CONTINUE;
01637 }
01638 
01639 static VALUE
01640 iseq_data_to_ary(rb_iseq_t *iseq)
01641 {
01642     long i;
01643     size_t ti;
01644     unsigned int pos;
01645     unsigned int line = 0;
01646     VALUE *seq;
01647 
01648     VALUE val = rb_ary_new();
01649     VALUE type; /* Symbol */
01650     VALUE locals = rb_ary_new();
01651     VALUE args = rb_ary_new();
01652     VALUE body = rb_ary_new(); /* [[:insn1, ...], ...] */
01653     VALUE nbody;
01654     VALUE exception = rb_ary_new(); /* [[....]] */
01655     VALUE misc = rb_hash_new();
01656 
01657     static VALUE insn_syms[VM_INSTRUCTION_SIZE];
01658     struct st_table *labels_table = st_init_numtable();
01659 
01660     DECL_SYMBOL(top);
01661     DECL_SYMBOL(method);
01662     DECL_SYMBOL(block);
01663     DECL_SYMBOL(class);
01664     DECL_SYMBOL(rescue);
01665     DECL_SYMBOL(ensure);
01666     DECL_SYMBOL(eval);
01667     DECL_SYMBOL(main);
01668     DECL_SYMBOL(defined_guard);
01669 
01670     if (sym_top == 0) {
01671         int i;
01672         for (i=0; i<VM_INSTRUCTION_SIZE; i++) {
01673             insn_syms[i] = ID2SYM(rb_intern(insn_name(i)));
01674         }
01675         INIT_SYMBOL(top);
01676         INIT_SYMBOL(method);
01677         INIT_SYMBOL(block);
01678         INIT_SYMBOL(class);
01679         INIT_SYMBOL(rescue);
01680         INIT_SYMBOL(ensure);
01681         INIT_SYMBOL(eval);
01682         INIT_SYMBOL(main);
01683         INIT_SYMBOL(defined_guard);
01684     }
01685 
01686     /* type */
01687     switch (iseq->type) {
01688       case ISEQ_TYPE_TOP:    type = sym_top;    break;
01689       case ISEQ_TYPE_METHOD: type = sym_method; break;
01690       case ISEQ_TYPE_BLOCK:  type = sym_block;  break;
01691       case ISEQ_TYPE_CLASS:  type = sym_class;  break;
01692       case ISEQ_TYPE_RESCUE: type = sym_rescue; break;
01693       case ISEQ_TYPE_ENSURE: type = sym_ensure; break;
01694       case ISEQ_TYPE_EVAL:   type = sym_eval;   break;
01695       case ISEQ_TYPE_MAIN:   type = sym_main;   break;
01696       case ISEQ_TYPE_DEFINED_GUARD: type = sym_defined_guard; break;
01697       default: rb_bug("unsupported iseq type");
01698     };
01699 
01700     /* locals */
01701     for (i=0; i<iseq->local_table_size; i++) {
01702         ID lid = iseq->local_table[i];
01703         if (lid) {
01704             if (rb_id2str(lid)) rb_ary_push(locals, ID2SYM(lid));
01705         }
01706         else {
01707             rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest")));
01708         }
01709     }
01710 
01711     /* args */
01712     {
01713         /*
01714          * [argc,                 # argc
01715          *  [label1, label2, ...] # opts
01716          *  rest index,
01717          *  post_len
01718          *  post_start
01719          *  block index,
01720          *  simple,
01721          * ]
01722          */
01723         VALUE arg_opt_labels = rb_ary_new();
01724         int j;
01725 
01726         for (j=0; j<iseq->arg_opts; j++) {
01727             rb_ary_push(arg_opt_labels,
01728                         register_label(labels_table, iseq->arg_opt_table[j]));
01729         }
01730 
01731         /* commit */
01732         if (iseq->arg_simple == 1) {
01733             args = INT2FIX(iseq->argc);
01734         }
01735         else {
01736             rb_ary_push(args, INT2FIX(iseq->argc));
01737             rb_ary_push(args, arg_opt_labels);
01738             rb_ary_push(args, INT2FIX(iseq->arg_post_len));
01739             rb_ary_push(args, INT2FIX(iseq->arg_post_start));
01740             rb_ary_push(args, INT2FIX(iseq->arg_rest));
01741             rb_ary_push(args, INT2FIX(iseq->arg_block));
01742             rb_ary_push(args, INT2FIX(iseq->arg_simple));
01743         }
01744     }
01745 
01746     /* body */
01747     for (seq = iseq->iseq; seq < iseq->iseq + iseq->iseq_size; ) {
01748         VALUE insn = *seq++;
01749         int j, len = insn_len(insn);
01750         VALUE *nseq = seq + len - 1;
01751         VALUE ary = rb_ary_new2(len);
01752 
01753         rb_ary_push(ary, insn_syms[insn]);
01754         for (j=0; j<len-1; j++, seq++) {
01755             switch (insn_op_type(insn, j)) {
01756               case TS_OFFSET: {
01757                 unsigned long idx = nseq - iseq->iseq + *seq;
01758                 rb_ary_push(ary, register_label(labels_table, idx));
01759                 break;
01760               }
01761               case TS_LINDEX:
01762               case TS_NUM:
01763                 rb_ary_push(ary, INT2FIX(*seq));
01764                 break;
01765               case TS_VALUE:
01766                 rb_ary_push(ary, obj_resurrect(*seq));
01767                 break;
01768               case TS_ISEQ:
01769                 {
01770                     rb_iseq_t *iseq = (rb_iseq_t *)*seq;
01771                     if (iseq) {
01772                         VALUE val = iseq_data_to_ary(iseq);
01773                         rb_ary_push(ary, val);
01774                     }
01775                     else {
01776                         rb_ary_push(ary, Qnil);
01777                     }
01778                 }
01779                 break;
01780               case TS_GENTRY:
01781                 {
01782                     struct rb_global_entry *entry = (struct rb_global_entry *)*seq;
01783                     rb_ary_push(ary, ID2SYM(entry->id));
01784                 }
01785                 break;
01786               case TS_IC: {
01787                   struct iseq_inline_cache_entry *ic = (struct iseq_inline_cache_entry *)*seq;
01788                     rb_ary_push(ary, INT2FIX(ic - iseq->ic_entries));
01789                 }
01790                 break;
01791               case TS_CALLINFO:
01792                 {
01793                     rb_call_info_t *ci = (rb_call_info_t *)*seq;
01794                     VALUE e = rb_hash_new();
01795                     rb_hash_aset(e, ID2SYM(rb_intern("mid")), ci->mid ? ID2SYM(ci->mid) : Qnil);
01796                     rb_hash_aset(e, ID2SYM(rb_intern("flag")), ULONG2NUM(ci->flag));
01797                     rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), INT2FIX(ci->orig_argc));
01798                     rb_hash_aset(e, ID2SYM(rb_intern("blockptr")), ci->blockiseq ? iseq_data_to_ary(ci->blockiseq) : Qnil);
01799                     rb_ary_push(ary, e);
01800                 }
01801                 break;
01802               case TS_ID:
01803                 rb_ary_push(ary, ID2SYM(*seq));
01804                 break;
01805               case TS_CDHASH:
01806                 {
01807                     VALUE hash = *seq;
01808                     VALUE val = rb_ary_new();
01809                     int i;
01810 
01811                     rb_hash_foreach(hash, cdhash_each, val);
01812 
01813                     for (i=0; i<RARRAY_LEN(val); i+=2) {
01814                         VALUE pos = FIX2INT(rb_ary_entry(val, i+1));
01815                         unsigned long idx = nseq - iseq->iseq + pos;
01816 
01817                         rb_ary_store(val, i+1,
01818                                      register_label(labels_table, idx));
01819                     }
01820                     rb_ary_push(ary, val);
01821                 }
01822                 break;
01823               default:
01824                 rb_bug("unknown operand: %c", insn_op_type(insn, j));
01825             }
01826         }
01827         rb_ary_push(body, ary);
01828     }
01829 
01830     nbody = body;
01831 
01832     /* exception */
01833     for (i=0; i<iseq->catch_table_size; i++) {
01834         VALUE ary = rb_ary_new();
01835         struct iseq_catch_table_entry *entry = &iseq->catch_table[i];
01836         rb_ary_push(ary, exception_type2symbol(entry->type));
01837         if (entry->iseq) {
01838             rb_iseq_t *eiseq;
01839             GetISeqPtr(entry->iseq, eiseq);
01840             rb_ary_push(ary, iseq_data_to_ary(eiseq));
01841         }
01842         else {
01843             rb_ary_push(ary, Qnil);
01844         }
01845         rb_ary_push(ary, register_label(labels_table, entry->start));
01846         rb_ary_push(ary, register_label(labels_table, entry->end));
01847         rb_ary_push(ary, register_label(labels_table, entry->cont));
01848         rb_ary_push(ary, INT2FIX(entry->sp));
01849         rb_ary_push(exception, ary);
01850     }
01851 
01852     /* make body with labels and insert line number */
01853     body = rb_ary_new();
01854     ti = 0;
01855 
01856     for (i=0, pos=0; i<RARRAY_LEN(nbody); i++) {
01857         VALUE ary = RARRAY_PTR(nbody)[i];
01858         st_data_t label;
01859 
01860         if (st_lookup(labels_table, pos, &label)) {
01861             rb_ary_push(body, (VALUE)label);
01862         }
01863 
01864         if (ti < iseq->line_info_size && iseq->line_info_table[ti].position == pos) {
01865             line = iseq->line_info_table[ti].line_no;
01866             rb_ary_push(body, INT2FIX(line));
01867             ti++;
01868         }
01869 
01870         rb_ary_push(body, ary);
01871         pos += RARRAY_LENINT(ary); /* reject too huge data */
01872     }
01873 
01874     st_free_table(labels_table);
01875 
01876     rb_hash_aset(misc, ID2SYM(rb_intern("arg_size")), INT2FIX(iseq->arg_size));
01877     rb_hash_aset(misc, ID2SYM(rb_intern("local_size")), INT2FIX(iseq->local_size));
01878     rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq->stack_max));
01879 
01880     /* TODO: compatibility issue */
01881     /*
01882      * [:magic, :major_version, :minor_version, :format_type, :misc,
01883      *  :name, :path, :absolute_path, :start_lineno, :type, :locals, :args,
01884      *  :catch_table, :bytecode]
01885      */
01886     rb_ary_push(val, rb_str_new2("YARVInstructionSequence/SimpleDataFormat"));
01887     rb_ary_push(val, INT2FIX(ISEQ_MAJOR_VERSION)); /* major */
01888     rb_ary_push(val, INT2FIX(ISEQ_MINOR_VERSION)); /* minor */
01889     rb_ary_push(val, INT2FIX(1));
01890     rb_ary_push(val, misc);
01891     rb_ary_push(val, iseq->location.label);
01892     rb_ary_push(val, iseq->location.path);
01893     rb_ary_push(val, iseq->location.absolute_path);
01894     rb_ary_push(val, iseq->location.first_lineno);
01895     rb_ary_push(val, type);
01896     rb_ary_push(val, locals);
01897     rb_ary_push(val, args);
01898     rb_ary_push(val, exception);
01899     rb_ary_push(val, body);
01900     return val;
01901 }
01902 
01903 VALUE
01904 rb_iseq_clone(VALUE iseqval, VALUE newcbase)
01905 {
01906     VALUE newiseq = iseq_alloc(rb_cISeq);
01907     rb_iseq_t *iseq0, *iseq1;
01908 
01909     GetISeqPtr(iseqval, iseq0);
01910     GetISeqPtr(newiseq, iseq1);
01911 
01912     *iseq1 = *iseq0;
01913     iseq1->self = newiseq;
01914     if (!iseq1->orig) {
01915         iseq1->orig = iseqval;
01916     }
01917     if (iseq0->local_iseq == iseq0) {
01918         iseq1->local_iseq = iseq1;
01919     }
01920     if (newcbase) {
01921         iseq1->cref_stack = NEW_CREF(newcbase);
01922         iseq1->cref_stack->nd_refinements = iseq0->cref_stack->nd_refinements;
01923         iseq1->cref_stack->nd_visi = iseq0->cref_stack->nd_visi;
01924         if (iseq0->cref_stack->nd_next) {
01925             iseq1->cref_stack->nd_next = iseq0->cref_stack->nd_next;
01926         }
01927         iseq1->klass = newcbase;
01928     }
01929 
01930     return newiseq;
01931 }
01932 
01933 VALUE
01934 rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc)
01935 {
01936     int i, r;
01937     VALUE a, args = rb_ary_new2(iseq->arg_size);
01938     ID req, opt, rest, block, key, keyrest;
01939 #define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type))
01940 #define PARAM_ID(i) iseq->local_table[(i)]
01941 #define PARAM(i, type) (                      \
01942         PARAM_TYPE(type),                     \
01943         rb_id2str(PARAM_ID(i)) ?              \
01944         rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \
01945         a)
01946 
01947     CONST_ID(req, "req");
01948     CONST_ID(opt, "opt");
01949     if (is_proc) {
01950         for (i = 0; i < iseq->argc; i++) {
01951             PARAM_TYPE(opt);
01952             rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
01953             rb_ary_push(args, a);
01954         }
01955     }
01956     else {
01957         for (i = 0; i < iseq->argc; i++) {
01958             rb_ary_push(args, PARAM(i, req));
01959         }
01960     }
01961     r = iseq->argc + iseq->arg_opts - 1;
01962     for (; i < r; i++) {
01963         PARAM_TYPE(opt);
01964         if (rb_id2str(PARAM_ID(i))) {
01965             rb_ary_push(a, ID2SYM(PARAM_ID(i)));
01966         }
01967         rb_ary_push(args, a);
01968     }
01969     if (iseq->arg_rest != -1) {
01970         CONST_ID(rest, "rest");
01971         rb_ary_push(args, PARAM(iseq->arg_rest, rest));
01972     }
01973     r = iseq->arg_post_start + iseq->arg_post_len;
01974     if (is_proc) {
01975         for (i = iseq->arg_post_start; i < r; i++) {
01976             PARAM_TYPE(opt);
01977             rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
01978             rb_ary_push(args, a);
01979         }
01980     }
01981     else {
01982         for (i = iseq->arg_post_start; i < r; i++) {
01983             rb_ary_push(args, PARAM(i, req));
01984         }
01985     }
01986     if (iseq->arg_keyword != -1) {
01987         CONST_ID(key, "key");
01988         for (i = 0; i < iseq->arg_keywords; i++) {
01989             PARAM_TYPE(key);
01990             if (rb_id2str(iseq->arg_keyword_table[i])) {
01991                 rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i]));
01992             }
01993             rb_ary_push(args, a);
01994         }
01995         if (rb_id2str(iseq->local_table[iseq->arg_keyword])) {
01996             CONST_ID(keyrest, "keyrest");
01997             rb_ary_push(args, PARAM(iseq->arg_keyword, keyrest));
01998         }
01999     }
02000     if (iseq->arg_block != -1) {
02001         CONST_ID(block, "block");
02002         rb_ary_push(args, PARAM(iseq->arg_block, block));
02003     }
02004     return args;
02005 }
02006 
02007 VALUE
02008 rb_iseq_defined_string(enum defined_type type)
02009 {
02010     static const char expr_names[][18] = {
02011         "nil",
02012         "instance-variable",
02013         "local-variable",
02014         "global-variable",
02015         "class variable",
02016         "constant",
02017         "method",
02018         "yield",
02019         "super",
02020         "self",
02021         "true",
02022         "false",
02023         "assignment",
02024         "expression",
02025     };
02026     const char *estr;
02027     VALUE *defs, str;
02028 
02029     if ((unsigned)(type - 1) >= (unsigned)numberof(expr_names)) return 0;
02030     estr = expr_names[type - 1];
02031     if (!estr[0]) return 0;
02032     defs = GET_VM()->defined_strings;
02033     if (!defs) {
02034         defs = ruby_xcalloc(numberof(expr_names), sizeof(VALUE));
02035         GET_VM()->defined_strings = defs;
02036     }
02037     str = defs[type-1];
02038     if (!str) {
02039         str = rb_str_new_cstr(estr);;
02040         OBJ_FREEZE(str);
02041         defs[type-1] = str;
02042     }
02043     return str;
02044 }
02045 
02046 /* ruby2cext */
02047 
02048 VALUE
02049 rb_iseq_build_for_ruby2cext(
02050     const rb_iseq_t *iseq_template,
02051     const rb_insn_func_t *func,
02052     const struct iseq_line_info_entry *line_info_table,
02053     const char **local_table,
02054     const VALUE *arg_opt_table,
02055     const struct iseq_catch_table_entry *catch_table,
02056     const char *name,
02057     const char *path,
02058     const unsigned short first_lineno)
02059 {
02060     unsigned long i;
02061     VALUE iseqval = iseq_alloc(rb_cISeq);
02062     rb_iseq_t *iseq;
02063     GetISeqPtr(iseqval, iseq);
02064 
02065     /* copy iseq */
02066     *iseq = *iseq_template;
02067     iseq->location.label = rb_str_new2(name);
02068     iseq->location.path = rb_str_new2(path);
02069     iseq->location.first_lineno = first_lineno;
02070     iseq->mark_ary = 0;
02071     iseq->self = iseqval;
02072 
02073     iseq->iseq = ALLOC_N(VALUE, iseq->iseq_size);
02074 
02075     for (i=0; i<iseq->iseq_size; i+=2) {
02076         iseq->iseq[i] = BIN(opt_call_c_function);
02077         iseq->iseq[i+1] = (VALUE)func;
02078     }
02079 
02080     rb_iseq_translate_threaded_code(iseq);
02081 
02082 #define ALLOC_AND_COPY(dst, src, type, size) do { \
02083   if (size) { \
02084       (dst) = ALLOC_N(type, (size)); \
02085       MEMCPY((dst), (src), type, (size)); \
02086   } \
02087 } while (0)
02088 
02089     ALLOC_AND_COPY(iseq->line_info_table, line_info_table,
02090                    struct iseq_line_info_entry, iseq->line_info_size);
02091 
02092     ALLOC_AND_COPY(iseq->catch_table, catch_table,
02093                    struct iseq_catch_table_entry, iseq->catch_table_size);
02094 
02095     ALLOC_AND_COPY(iseq->arg_opt_table, arg_opt_table,
02096                    VALUE, iseq->arg_opts);
02097 
02098     set_relation(iseq, 0);
02099 
02100     return iseqval;
02101 }
02102 
02103 /* Experimental tracing support: trace(line) -> trace(specified_line)
02104  * MRI Specific.
02105  */
02106 
02107 int
02108 rb_iseq_line_trace_each(VALUE iseqval, int (*func)(int line, rb_event_flag_t *events_ptr, void *d), void *data)
02109 {
02110     int trace_num = 0;
02111     size_t pos, insn;
02112     rb_iseq_t *iseq;
02113     int cont = 1;
02114     GetISeqPtr(iseqval, iseq);
02115 
02116     for (pos = 0; cont && pos < iseq->iseq_size; pos += insn_len(insn)) {
02117         insn = iseq->iseq[pos];
02118 
02119         if (insn == BIN(trace)) {
02120             rb_event_flag_t current_events = (VALUE)iseq->iseq[pos+1];
02121 
02122             if (current_events & RUBY_EVENT_LINE) {
02123                 rb_event_flag_t events = current_events & RUBY_EVENT_SPECIFIED_LINE;
02124                 trace_num++;
02125 
02126                 if (func) {
02127                     int line = find_line_no(iseq, pos);
02128                     /* printf("line: %d\n", line); */
02129                     cont = (*func)(line, &events, data);
02130                     if (current_events != events) {
02131                         iseq->iseq[pos+1] = iseq->iseq_encoded[pos+1] =
02132                           (VALUE)(current_events | (events & RUBY_EVENT_SPECIFIED_LINE));
02133                     }
02134                 }
02135             }
02136         }
02137     }
02138     return trace_num;
02139 }
02140 
02141 static int
02142 collect_trace(int line, rb_event_flag_t *events_ptr, void *ptr)
02143 {
02144     VALUE result = (VALUE)ptr;
02145     rb_ary_push(result, INT2NUM(line));
02146     return 1;
02147 }
02148 
02149 /*
02150  * <b>Experimental MRI specific feature, only available as C level api.</b>
02151  *
02152  * Returns all +specified_line+ events.
02153  */
02154 VALUE
02155 rb_iseq_line_trace_all(VALUE iseqval)
02156 {
02157     VALUE result = rb_ary_new();
02158     rb_iseq_line_trace_each(iseqval, collect_trace, (void *)result);
02159     return result;
02160 }
02161 
02162 struct set_specifc_data {
02163     int pos;
02164     int set;
02165     int prev; /* 1: set, 2: unset, 0: not found */
02166 };
02167 
02168 static int
02169 line_trace_specify(int line, rb_event_flag_t *events_ptr, void *ptr)
02170 {
02171     struct set_specifc_data *data = (struct set_specifc_data *)ptr;
02172 
02173     if (data->pos == 0) {
02174         data->prev = *events_ptr & RUBY_EVENT_SPECIFIED_LINE ? 1 : 2;
02175         if (data->set) {
02176             *events_ptr = *events_ptr | RUBY_EVENT_SPECIFIED_LINE;
02177         }
02178         else {
02179             *events_ptr = *events_ptr & ~RUBY_EVENT_SPECIFIED_LINE;
02180         }
02181         return 0; /* found */
02182     }
02183     else {
02184         data->pos--;
02185         return 1;
02186     }
02187 }
02188 
02189 /*
02190  * <b>Experimental MRI specific feature, only available as C level api.</b>
02191  *
02192  * Set a +specified_line+ event at the given line position, if the +set+
02193  * parameter is +true+.
02194  *
02195  * This method is useful for building a debugger breakpoint at a specific line.
02196  *
02197  * A TypeError is raised if +set+ is not boolean.
02198  *
02199  * If +pos+ is a negative integer a TypeError exception is raised.
02200  */
02201 VALUE
02202 rb_iseq_line_trace_specify(VALUE iseqval, VALUE pos, VALUE set)
02203 {
02204     struct set_specifc_data data;
02205 
02206     data.prev = 0;
02207     data.pos = NUM2INT(pos);
02208     if (data.pos < 0) rb_raise(rb_eTypeError, "`pos' is negative");
02209 
02210     switch (set) {
02211       case Qtrue:  data.set = 1; break;
02212       case Qfalse: data.set = 0; break;
02213       default:
02214         rb_raise(rb_eTypeError, "`set' should be true/false");
02215     }
02216 
02217     rb_iseq_line_trace_each(iseqval, line_trace_specify, (void *)&data);
02218 
02219     if (data.prev == 0) {
02220         rb_raise(rb_eTypeError, "`pos' is out of range.");
02221     }
02222     return data.prev == 1 ? Qtrue : Qfalse;
02223 }
02224 
02225 /*
02226  *  Document-class: RubyVM::InstructionSequence
02227  *
02228  *  The InstructionSequence class represents a compiled sequence of
02229  *  instructions for the Ruby Virtual Machine.
02230  *
02231  *  With it, you can get a handle to the instructions that make up a method or
02232  *  a proc, compile strings of Ruby code down to VM instructions, and
02233  *  disassemble instruction sequences to strings for easy inspection. It is
02234  *  mostly useful if you want to learn how the Ruby VM works, but it also lets
02235  *  you control various settings for the Ruby iseq compiler.
02236  *
02237  *  You can find the source for the VM instructions in +insns.def+ in the Ruby
02238  *  source.
02239  *
02240  *  The instruction sequence results will almost certainly change as Ruby
02241  *  changes, so example output in this documentation may be different from what
02242  *  you see.
02243  */
02244 
02245 void
02246 Init_ISeq(void)
02247 {
02248     /* declare ::RubyVM::InstructionSequence */
02249     rb_cISeq = rb_define_class_under(rb_cRubyVM, "InstructionSequence", rb_cObject);
02250     rb_define_alloc_func(rb_cISeq, iseq_alloc);
02251     rb_define_method(rb_cISeq, "inspect", iseq_inspect, 0);
02252     rb_define_method(rb_cISeq, "disasm", rb_iseq_disasm, 0);
02253     rb_define_method(rb_cISeq, "disassemble", rb_iseq_disasm, 0);
02254     rb_define_method(rb_cISeq, "to_a", iseq_to_a, 0);
02255     rb_define_method(rb_cISeq, "eval", iseq_eval, 0);
02256 
02257     /* location APIs */
02258     rb_define_method(rb_cISeq, "path", iseq_path, 0);
02259     rb_define_method(rb_cISeq, "absolute_path", iseq_absolute_path, 0);
02260     rb_define_method(rb_cISeq, "label", iseq_label, 0);
02261     rb_define_method(rb_cISeq, "base_label", iseq_base_label, 0);
02262     rb_define_method(rb_cISeq, "first_lineno", iseq_first_lineno, 0);
02263 
02264 #if 0
02265     /* Now, it is experimental. No discussions, no tests. */
02266     /* They can be used from C level. Please give us feedback. */
02267     rb_define_method(rb_cISeq, "line_trace_all", rb_iseq_line_trace_all, 0);
02268     rb_define_method(rb_cISeq, "line_trace_specify", rb_iseq_line_trace_specify, 2);
02269 #else
02270     (void)rb_iseq_line_trace_all;
02271     (void)rb_iseq_line_trace_specify;
02272 #endif
02273 
02274 #if 0 /* TBD */
02275     rb_define_private_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0);
02276     rb_define_private_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1);
02277 #endif
02278 
02279     /* disable this feature because there is no verifier. */
02280     /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */
02281     (void)iseq_s_load;
02282 
02283     rb_define_singleton_method(rb_cISeq, "compile", iseq_s_compile, -1);
02284     rb_define_singleton_method(rb_cISeq, "new", iseq_s_compile, -1);
02285     rb_define_singleton_method(rb_cISeq, "compile_file", iseq_s_compile_file, -1);
02286     rb_define_singleton_method(rb_cISeq, "compile_option", iseq_s_compile_option_get, 0);
02287     rb_define_singleton_method(rb_cISeq, "compile_option=", iseq_s_compile_option_set, 1);
02288     rb_define_singleton_method(rb_cISeq, "disasm", iseq_s_disasm, 1);
02289     rb_define_singleton_method(rb_cISeq, "disassemble", iseq_s_disasm, 1);
02290     rb_define_singleton_method(rb_cISeq, "of", iseq_s_of, 1);
02291 }
02292