Class: FastRuby::Context

Inherits:
Object show all
Defined in:
lib/fastruby/translator/translator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(common_func = true) ⇒ Context

Returns a new instance of Context.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/fastruby/translator/translator.rb', line 47

def initialize(common_func = true)
  @infer_lvar_map = Hash.new
  @no_cache = false
  @extra_code = ""
  @options = {}
  @init_extra = Array.new
  @frame_struct = "struct {
    void* parent_frame;
    void* plocals;
    jmp_buf jmp;
    VALUE return_value;
    int rescue;
    VALUE last_error;
    VALUE next_recv;
    int targetted;
    struct FASTRUBYTHREADDATA* thread_data;
  }"

  @block_struct = "struct {
    void* block_function_address;
    void* block_function_param;
    VALUE proc;
  }"

    extra_code << "
      static void frb_jump_tag(int state) {
        VALUE exception = rb_funcall(#{literal_value FastRuby::JumpTagException}, #{intern_num :new},1,INT2FIX(state)); 
        rb_exc_raise(exception);
      }
    "

  extra_code << "
    #define FASTRUBY_TAG_RETURN 0x80
    #define FASTRUBY_TAG_NEXT 0x81
    #define FASTRUBY_TAG_BREAK 0x82
    #define FASTRUBY_TAG_RAISE 0x83
    #define FASTRUBY_TAG_REDO 0x84
    #define FASTRUBY_TAG_RETRY 0x85
    #define TAG_RAISE 0x6

# define PTR2NUM(x)   (ULONG2NUM((unsigned long)(x)))
# define NUM2PTR(x)   ((void*)(NUM2ULONG(x)))

    #ifndef __INLINE_FASTRUBY_BASE
    #include \"#{FastRuby.fastruby_load_path}/../ext/fastruby_base/fastruby_base.inl\"
    #define __INLINE_FASTRUBY_BASE
    #endif
  "

  ruby_code = "
    $LOAD_PATH << #{FastRuby.fastruby_load_path.inspect}
    require #{FastRuby.fastruby_script_path.inspect}
  "

  init_extra << "
    rb_eval_string(#{ruby_code.inspect});
	"
	
	
  if RUBY_VERSION =~ /^1\.8/

  @lambda_node_gvar = add_global_name("NODE*", 0);
  @proc_node_gvar = add_global_name("NODE*", 0);
  @procnew_node_gvar = add_global_name("NODE*", 0);
  @callcc_node_gvar = add_global_name("NODE*", 0);
  
  init_extra << "
    #{@lambda_node_gvar} = rb_method_node(rb_cObject, #{intern_num :lambda});
    #{@proc_node_gvar} = rb_method_node(rb_cObject, #{intern_num :proc});
    #{@procnew_node_gvar} = rb_method_node(CLASS_OF(rb_cProc), #{intern_num :new});
    #{@callcc_node_gvar} = rb_method_node(rb_mKernel, #{intern_num :callcc});
  "
 elsif RUBY_VERSION =~ /^1\.9/

  @lambda_node_gvar = add_global_name("void*", 0);
  @proc_node_gvar = add_global_name("void*", 0);
  @procnew_node_gvar = add_global_name("void*", 0);
  @callcc_node_gvar = add_global_name("void*", 0);
  
  init_extra << "
    #{@lambda_node_gvar} = rb_method_entry(rb_cObject, #{intern_num :lambda});
    #{@proc_node_gvar} = rb_method_entry(rb_cObject, #{intern_num :proc});
    #{@procnew_node_gvar} = rb_method_entry(CLASS_OF(rb_const_get(rb_cObject, #{intern_num :Proc})), #{intern_num :new});
    #{@callcc_node_gvar} = rb_method_entry(rb_mKernel, #{intern_num :callcc});
  "
end

  @common_func = common_func
  if common_func
    extra_code << "static VALUE _rb_gvar_set(void* ge,VALUE value) {
      rb_gvar_set((struct global_entry*)ge,value);
      return value;
    }
    "

    extra_code << "static VALUE re_yield(int argc, VALUE* argv, VALUE param, VALUE _parent_frame) {
     VALUE yield_args = rb_ary_new4(argc,argv);
     VALUE* yield_args_p = &yield_args;

     #{@frame_struct}* pframe;
     pframe = (typeof(pframe))_parent_frame;

     return #{protected_block("last_expression = rb_yield_splat(*(VALUE*)yield_args_p)",true,"yield_args_p",true)};
    }"

    extra_code << "static VALUE _rb_ivar_set(VALUE recv,ID idvar, VALUE value) {
      rb_ivar_set(recv,idvar,value);
      return value;
    }
    "

    extra_code << "static VALUE __rb_cvar_set(VALUE recv,ID idvar, VALUE value, int warn) {
      #{if RUBY_VERSION =~ /^1\.9/
        "rb_cvar_set(recv,idvar,value);"
        elsif RUBY_VERSION =~ /^1\.8/
        "rb_cvar_set(recv,idvar,value,warn);"
        else
          raise RuntimeError, "unsupported ruby version #{RUBY_VERSION}"
        end 
      }
     
      return value;
    }
    "

    extra_code << "static VALUE _lvar_assing(VALUE* destination,VALUE value) {
      *destination = value;
      return value;
    }

/*
   #{caller.join("\n")}
*/

    "
    
  end
end

Instance Attribute Details

#alt_method_nameObject

Returns the value of attribute alt_method_name.



33
34
35
# File 'lib/fastruby/translator/translator.rb', line 33

def alt_method_name
  @alt_method_name
end

#extra_codeObject (readonly)

Returns the value of attribute extra_code.



40
41
42
# File 'lib/fastruby/translator/translator.rb', line 40

def extra_code
  @extra_code
end

#infer_lvar_mapObject

Returns the value of attribute infer_lvar_map.



32
33
34
# File 'lib/fastruby/translator/translator.rb', line 32

def infer_lvar_map
  @infer_lvar_map
end

#infer_selfObject

Returns the value of attribute infer_self.



36
37
38
# File 'lib/fastruby/translator/translator.rb', line 36

def infer_self
  @infer_self
end

#init_extraObject (readonly)

Returns the value of attribute init_extra.



39
40
41
# File 'lib/fastruby/translator/translator.rb', line 39

def init_extra
  @init_extra
end

#localsObject

Returns the value of attribute locals.



34
35
36
# File 'lib/fastruby/translator/translator.rb', line 34

def locals
  @locals
end

#no_cacheObject (readonly)

Returns the value of attribute no_cache.



38
39
40
# File 'lib/fastruby/translator/translator.rb', line 38

def no_cache
  @no_cache
end

#optionsObject

Returns the value of attribute options.



35
36
37
# File 'lib/fastruby/translator/translator.rb', line 35

def options
  @options
end

#snippet_hashObject

Returns the value of attribute snippet_hash.



37
38
39
# File 'lib/fastruby/translator/translator.rb', line 37

def snippet_hash
  @snippet_hash
end

Instance Method Details

#add_global_name(ctype, default) ⇒ Object



1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/fastruby/translator/translator.rb', line 1364

def add_global_name(ctype, default)
  name = "glb" + rand(1000000000).to_s

  extra_code << "
    static #{ctype} #{name} = #{default};
  "
  name
end

#add_mainObject



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/fastruby/translator/translator.rb', line 278

def add_main
  if options[:main]

    extra_code << "
      static VALUE #{@alt_method_name}(VALUE self__);
      static VALUE main_proc_call(VALUE self__, VALUE class_self_) {
        #{@alt_method_name}(class_self_);
        return Qnil;
      }

    "

    init_extra << "
        {
        VALUE newproc = rb_funcall(rb_cObject,#{intern_num :new},0);
        rb_define_singleton_method(newproc, \"call\", main_proc_call, 1);
        rb_gv_set(\"$last_obj_proc\", newproc);

        }
      "
  end
end

#anonymous_function(*x) ⇒ Object



202
203
204
205
206
207
208
# File 'lib/fastruby/translator/translator.rb', line 202

def anonymous_function(*x)

  name = "anonymous" + rand(10000000).to_s
  extra_code << yield(name,*x)

  name
end

#c_escape(str) ⇒ Object



959
960
961
# File 'lib/fastruby/translator/translator.rb', line 959

def c_escape(str)
  str.inspect
end

#define_method_at_init(klass, method_name, size, signature) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/fastruby/translator/translator.rb', line 301

def define_method_at_init(klass,method_name, size, signature)
  init_extra << "
    {
      VALUE method_name = rb_funcall(
            #{literal_value FastRuby},
            #{intern_num :make_str_signature},
            2,
            #{literal_value method_name},
            #{literal_value signature}
            );

      ID id = rb_intern(RSTRING_PTR(method_name));
      
      rb_funcall(
            #{literal_value FastRuby},
            #{intern_num :set_builder_module},
            1,
            #{literal_value klass}
            );
      
      VALUE rb_method_hash;
      void** address = 0;
      rb_method_hash = rb_funcall(#{literal_value klass}, #{intern_num :method_hash},1,#{literal_value method_name});

      if (rb_method_hash != Qnil) {
        VALUE tmp = rb_hash_aref(rb_method_hash, PTR2NUM(id));
        if (tmp != Qnil) {
            address = (void*)NUM2PTR(tmp);
        }
      }
      
      if (address == 0) {
        address = malloc(sizeof(void*));
      }
      *address = #{alt_method_name};
      
      rb_funcall(
          #{literal_value klass},
          #{intern_num :register_method_value}, 
          3,
          #{literal_value method_name},
          PTR2NUM(id),
          PTR2NUM(address)
          );
    }
  "
end

#directive(tree) ⇒ Object



722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'lib/fastruby/translator/translator.rb', line 722

def directive(tree)
  recv = tree[1]
  mname = tree[2]
  args = tree[3]

  if mname == :infer
    return to_c(recv)
  elsif mname == :lvar_type
    lvar_name = args[1][1] || args[1][2]
    lvar_type = eval(args[2][1].to_s)

    @infer_lvar_map[lvar_name] = lvar_type
    return "Qnil"
  elsif mname == :block_given?
    return "plocals->block_function_address == 0 ? Qfalse : Qtrue"
  elsif mname == :inline_c

    code = args[1][1]

    unless (args[2] == s(:false))
      return anonymous_function{ |name| "
         static VALUE #{name}(VALUE param) {
          #{@frame_struct} *pframe = (void*)param;
          #{@locals_struct} *plocals = (void*)pframe->plocals;
          #{code};

          return Qnil;
        }
       "
      }+"((VALUE)pframe)"
    else
      code
    end

  else
    nil
  end
end

#encode_address(recvtype, signature, mname, call_tree, inference_complete, convention_global_name = nil) ⇒ Object



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# File 'lib/fastruby/translator/translator.rb', line 1038

def encode_address(recvtype,signature,mname,call_tree,inference_complete,convention_global_name = nil)
  name = self.add_global_name("void*", 0);
  address_name = self.add_global_name("void**", 0);
  @last_address_name = address_name
  cfunc_address_name = self.add_global_name("void**", 0);
  cfunc_real_address_name  = self.add_global_name("void*", 0);
  tree_pointer_name = self.add_global_name("VALUE*", 0);
  args_tree = call_tree[3].reject{|st| st.respond_to?(:node_type) ? st[0] == :block_pass : false}
  method_tree = nil

  begin
    method_tree = recvtype.instance_method(@method_name.to_sym).fastruby.tree
  rescue NoMethodError
  end

  strargs_signature = (0..args_tree.size-2).map{|x| "VALUE arg#{x}"}.join(",")
  strargs = (0..args_tree.size-2).map{|x| "arg#{x}"}.join(",")
  inprocstrargs = (1..args_tree.size-1).map{|x| "((VALUE*)method_arguments)[#{x}]"}.join(",")

  if args_tree.size > 1
    strargs_signature = "," + strargs_signature
    toprocstrargs = "self,"+strargs
    strargs = "," + strargs
    inprocstrargs = ","+inprocstrargs
  else
    toprocstrargs = "self"
  end

  value_cast = ( ["VALUE"]*(args_tree.size) ).join(",") + ",VALUE,VALUE"

  recvdump = nil

  begin
     recvdump = literal_value recvtype
  rescue
  end
  
  pureruby_wrapper = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE self,void* block,void* frame#{strargs_signature}){
      #{@frame_struct}* pframe = frame;
      VALUE method_arguments[#{args_tree.size}] = {#{toprocstrargs}};
  
      return #{
        protected_block "last_expression = rb_funcall(((VALUE*)method_arguments)[0], #{intern_num mname.to_sym}, #{args_tree.size-1}#{inprocstrargs});", false, "method_arguments"
        };
    }
  "
  }
  
  generic_wrapper = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE self,void* block,void* frame#{strargs_signature}){
    
      #{@frame_struct}* pframe = frame;
      VALUE method_arguments[#{args_tree.size+1}] = {#{toprocstrargs},(VALUE)block};
      
      void* fptr = 0;
      
      if (*#{address_name} == 0) {
        if (#{tree_pointer_name} != 0) {
          if (*#{tree_pointer_name} != Qnil) {
            VALUE signature = #{literal_value signature};
            VALUE recvtype = #{recvdump};
            VALUE mname = #{literal_value mname};
            
            rb_funcall(recvtype, #{intern_num :build}, 2, signature, mname);
          }
        }
      }
      
      fptr = *#{address_name};
      
      #{
        if args_tree.size < 25
        "
        if (fptr == 0) {
          fptr = *#{cfunc_address_name};
          if (fptr != 0) {
            VALUE params[2] = {self,PTR2NUM(#{args_tree.size-1})};
            return ( (VALUE(*)(#{value_cast})) (fptr) )((VALUE)params,(VALUE)block,(VALUE)frame#{inprocstrargs});  
          }
        }
        "
        end
      } 
      
      if (fptr == 0) {
        if (block==0) {
          return #{
            protected_block "last_expression = rb_funcall(((VALUE*)method_arguments)[0], #{intern_num mname.to_sym}, #{args_tree.size-1}#{inprocstrargs});", false, "method_arguments"
            };

        } else {
          return #{
              protected_block "
                    #{@block_struct} *pblock;
                    pblock = (typeof(pblock))( ((VALUE*)method_arguments)[#{args_tree.size}] );
                    last_expression = rb_iterate(
                    #{anonymous_function{|name|
                      "
                        static VALUE #{name} (VALUE data) {
                          VALUE* method_arguments = (VALUE*)data;
                          return rb_funcall(
                            ((VALUE*)method_arguments)[0], 
                            #{intern_num mname.to_sym}, 
                            #{args_tree.size-1}#{inprocstrargs});
                        }
                      "
                    }},
                      (VALUE)method_arguments,
                      
                    #{anonymous_function{|name|
                      "
                        static VALUE #{name} (VALUE arg_, VALUE param, int argc, VALUE* argv) {

       VALUE arg;
        #{
        # TODO: access directly to argc and argv for optimal execution
        if RUBY_VERSION =~ /^1\.9/ 
          "
            if (TYPE(arg_) == T_ARRAY) {
              if (_RARRAY_LEN(arg_) <= 1) {
                arg = rb_ary_new4(argc,argv);
              } else {
                arg = arg_;
              }
            } else {
              arg = rb_ary_new4(argc,argv);
            }
          "
        else
          "arg = arg_;"
        end
        }
    
                          return rb_proc_call(param, arg);
                        }
                      "
                    }},
                      pblock->proc
                    );
            ", false, "method_arguments"
            };
        }

      } else {
        return ( (VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*)) (fptr) )(self,(VALUE)block,(VALUE)frame,#{args_tree.size-1},method_arguments+1);  
      }
    }
    "
  }


  cfunc_value_cast = (["VALUE"]*args_tree.size).join(",")
  cfunc_wrapper = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE* params, void* block,void* frame#{strargs_signature}){
        VALUE self = params[0];
        VALUE method_arguments[#{args_tree.size}] = {#{toprocstrargs}};
        return ( (VALUE(*)(#{cfunc_value_cast})) (#{cfunc_real_address_name}) )(self#{inprocstrargs});
    }
    "
  }
  
  toprocstrargs = (0..25).map{|x| "arg#{x}"}.join(",")
  strargs_signature = (0..25).map{|x| "VALUE arg#{x}"}.join(",")

  cfunc_wrapper_1 = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE* params, void* block,void* frame, #{strargs_signature}){
        VALUE self = params[0];
        VALUE method_arguments[26] = {#{toprocstrargs}};
        return ( (VALUE(*)(int, VALUE*, VALUE)) (#{cfunc_real_address_name}) )(NUM2ULONG(params[1]),method_arguments,self);
    }
    "
  }

  cfunc_wrapper_2 = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE* params, void* block,void* frame, #{strargs_signature}){
        VALUE self = params[0];
        VALUE args = rb_ary_new3(NUM2ULONG(params[1]),#{toprocstrargs});
        return ( (VALUE(*)(VALUE,VALUE)) (#{cfunc_real_address_name}) )(self,args);
    }
    "
  }

  if recvdump and recvtype
    init_extra << "
      {
        VALUE recvtype = #{recvdump};
        rb_funcall(#{literal_value FastRuby}, #{intern_num :set_builder_module}, 1, recvtype);
        VALUE signature = #{literal_value signature};
        VALUE mname = #{literal_value mname};
        VALUE tree = #{literal_value method_tree};
        VALUE rb_str_signature = rb_funcall(
                                  #{literal_value FastRuby},
                                  #{intern_num :make_str_signature},
                                  2,
                                  mname,
                                  signature);



        VALUE fastruby_method = rb_funcall(recvtype, #{intern_num :fastruby_method}, 1, mname);
        #{tree_pointer_name} = (VALUE*)NUM2PTR(fastruby_method_tree_pointer(fastruby_method));
        
        ID id;
        ID default_id = rb_intern(\"default\");
        VALUE rb_method_hash;
        void** address = 0;
        void** default_address = 0;
        id = rb_intern(RSTRING_PTR(rb_str_signature));
        rb_method_hash = rb_funcall(recvtype, #{intern_num :method_hash},1,mname);

        if (rb_method_hash != Qnil) {
          VALUE tmp = rb_hash_aref(rb_method_hash, PTR2NUM(id));
          if (tmp != Qnil) {
              address = (void*)NUM2PTR(tmp);
          }
          
          tmp = rb_hash_aref(rb_method_hash, PTR2NUM(default_id));
          if (tmp != Qnil) {
             default_address = (void*)NUM2PTR(tmp);
          }
        }
        
        if (default_address==0) {
          default_address = malloc(sizeof(void*));
          *default_address = 0;

#ifdef RUBY_1_8

			// this only works with ruby1.8

          NODE* body = rb_method_node(recvtype,#{intern_num mname});
          if (body != 0) {
            if (nd_type(body) == NODE_CFUNC) {
              if (body->nd_argc == #{args_tree.size-1}) {
                *default_address = #{cfunc_wrapper};
                #{cfunc_real_address_name} = (void*)body->nd_cfnc;
              } else if (body->nd_argc == -1) {
                *default_address = #{cfunc_wrapper_1};
                #{cfunc_real_address_name} = (void*)body->nd_cfnc;
              } else if (body->nd_argc == -2) {
                *default_address = #{cfunc_wrapper_2};
                #{cfunc_real_address_name} = (void*)body->nd_cfnc;
              }
            }
          }
#endif
#ifdef RUBY_1_9
          rb_method_entry_t* me = rb_method_entry(recvtype,#{intern_num mname});
          if (me != 0) {
            rb_method_definition_t* def = me->def;
            
            if (def->type == VM_METHOD_TYPE_CFUNC) {
              if (def->body.cfunc.argc == #{args_tree.size-1}) {
                *default_address = #{cfunc_wrapper};
                #{cfunc_real_address_name} = (void*)def->body.cfunc.func;
              } else if (def->body.cfunc.argc == -1) {
                *default_address = #{cfunc_wrapper_1};
                #{cfunc_real_address_name} = (void*)def->body.cfunc.func;
              } else if (def->body.cfunc.argc == -2) {
                *default_address = #{cfunc_wrapper_2};
                #{cfunc_real_address_name} = (void*)def->body.cfunc.func;
              }
            }
          }
#endif

          if (recvtype != Qnil) { 
            rb_funcall(
                recvtype,
                #{intern_num :register_method_value}, 
                3,
                #{literal_value mname},
                PTR2NUM(default_id),
                PTR2NUM(default_address)
                );
          }
        }

        if (address==0) {
          address = malloc(sizeof(void*));
          
          if (recvtype != Qnil) { 
            rb_funcall(
                recvtype,
                #{intern_num :register_method_value}, 
                3,
                #{literal_value mname},
                PTR2NUM(id),
                PTR2NUM(address)
                );
          }
  
          *address = 0; //(void*)
        }
        
        #{address_name} = address;
        #{cfunc_address_name} = default_address;
        #{name} = (void*)#{generic_wrapper};
      }
    "
  else
    init_extra << "
    // ruby, wrap rb_funcall
    #{name} = (void*)#{pureruby_wrapper};
    "
  end

  name
end

#frame(code, jmp_code, not_jmp_code = "", rescued = nil) ⇒ Object



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
# File 'lib/fastruby/translator/translator.rb', line 1384

def frame(code, jmp_code, not_jmp_code = "", rescued = nil)

  anonymous_function{ |name| "
    static VALUE #{name}(VALUE param) {
      volatile VALUE last_expression = Qnil;
      #{@frame_struct} frame;

      typeof(frame)* volatile pframe;
      typeof(frame)* volatile parent_frame;
      #{@locals_struct}* volatile plocals;

      parent_frame = (void*)param;

      frame.parent_frame = (void*)param;
      frame.plocals = parent_frame->plocals;
      frame.rescue = #{rescued ? rescued : "parent_frame->rescue"};
      frame.targetted = 0;
      frame.thread_data = parent_frame->thread_data;
      if (frame.thread_data == 0) frame.thread_data = rb_current_thread_data();

      plocals = frame.plocals;
      pframe = &frame;

      int aux = setjmp(frame.jmp);
      if (aux != 0) {
        last_expression = pframe->return_value;

        // restore previous frame
        typeof(pframe) original_frame = pframe;
        pframe = parent_frame;

        #{jmp_code};

        if (original_frame->targetted == 0) {
          longjmp(pframe->jmp,aux);
        }

        return last_expression;
      }

      #{code};

      // restore previous frame
      volatile typeof(pframe) original_frame = pframe;
      pframe = parent_frame;
      #{not_jmp_code};

      return last_expression;

      }
    "
  } + "((VALUE)pframe)"
end

#frame_call(inner_code, precode = "", postcode = "") ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/fastruby/translator/translator.rb', line 210

def frame_call(inner_code, precode = "", postcode = "")
  inline_block "

    volatile VALUE ret = Qnil;
    // create a call_frame
    #{@frame_struct} call_frame;
    typeof(call_frame)* volatile old_pframe = (void*)pframe;

    pframe = (typeof(pframe))&call_frame;

    call_frame.parent_frame = (void*)pframe;
    call_frame.plocals = plocals;
    call_frame.return_value = Qnil;
    call_frame.targetted = 0;
    call_frame.thread_data = old_pframe->thread_data;
    if (call_frame.thread_data == 0) call_frame.thread_data = rb_current_thread_data();

    void* volatile old_call_frame = plocals->call_frame;
    plocals->call_frame = &call_frame;

    #{precode}

            int aux = setjmp(call_frame.jmp);
            if (aux != 0) {
              if (call_frame.targetted == 0) {
                #{postcode}
                longjmp(old_pframe->jmp,aux);
              }

              if (aux == FASTRUBY_TAG_BREAK) {
                plocals->call_frame = old_call_frame;
                #{postcode}
                return call_frame.return_value;
              } else if (aux == FASTRUBY_TAG_RETRY ) {
                // do nothing and let the call execute again
              } else {
                plocals->call_frame = old_call_frame;
                #{postcode}
                return call_frame.return_value;
              }
            }
            

    #{inner_code};
    
    #{postcode}
    
    plocals->call_frame = old_call_frame;
    return ret;
  "
end

#global_entry(glbname) ⇒ Object



1373
1374
1375
1376
1377
1378
1379
1380
1381
# File 'lib/fastruby/translator/translator.rb', line 1373

def global_entry(glbname)
  name = add_global_name("struct global_entry*", 0);

  init_extra << "
    #{name} = rb_global_entry(SYM2ID(#{literal_value glbname}));
  "

  name
end

#infer_type(recv) ⇒ Object



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'lib/fastruby/translator/translator.rb', line 698

def infer_type(recv)
  if recv[0] == :call
    if recv[2] == :infer
      eval(recv[3].last.last.to_s)
    end
  elsif recv[0] == :lvar
    @infer_lvar_map[recv[1]]
  elsif recv[0] == :self
    @infer_self
  elsif recv[0] == :str or recv[0] == :lit
    recv[1].class
  else
    nil
  end
end

#initialize_method_structs(args_tree) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/fastruby/translator/translator.rb', line 262

def initialize_method_structs(args_tree)
  @locals_struct = "struct {
    int size;        
    void* call_frame;
    void* parent_locals;
    void* pframe;
    void* block_function_address;
    void* block_function_param;
    VALUE active;
    VALUE targetted;
    VALUE return_value;
    #{@locals.map{|l| "VALUE #{l};\n"}.join}
    }"

end

#inline_block(code, repass_var = nil, nolocals = false) ⇒ Object



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/fastruby/translator/translator.rb', line 784

def inline_block(code, repass_var = nil, nolocals = false)
  anonymous_function{ |name| "
    static VALUE #{name}(VALUE param#{repass_var ? ",void* " + repass_var : "" }) {
      #{@frame_struct} * volatile pframe = (void*)param;

      #{nolocals ? "" : "#{@locals_struct} * volatile plocals = (void*)pframe->plocals;"}
      volatile VALUE last_expression = Qnil;

      #{code}
      return Qnil;

      #{unless nolocals
      "
local_return:
    plocals->return_value = last_expression;
    plocals->targetted = 1;
    longjmp(pframe->jmp, FASTRUBY_TAG_RETURN);
    return last_expression;
    "
    end
      }
fastruby_local_redo:
      longjmp(pframe->jmp,FASTRUBY_TAG_REDO);
      return Qnil;
fastruby_local_next:
      longjmp(pframe->jmp,FASTRUBY_TAG_NEXT);
      return Qnil;


      }
    "
  } + "((VALUE)pframe#{repass_var ? ", " + repass_var : "" })"
end

#inline_block_reference(arg, nolocals = false) ⇒ Object



761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'lib/fastruby/translator/translator.rb', line 761

def inline_block_reference(arg, nolocals = false)
  code = nil

  if arg.instance_of? FastRuby::FastRubySexp
    code = to_c(arg);
  else
    code = arg
  end

  anonymous_function{ |name| "
    static VALUE #{name}(VALUE param) {
      #{@frame_struct} *pframe = (void*)param;

      #{nolocals ? "" : "#{@locals_struct} *plocals = (void*)pframe->plocals;"}
      VALUE last_expression = Qnil;

      #{code};
      return last_expression;
      }
    "
  }
end

#inline_ruby(proced, parameter) ⇒ Object



818
819
820
# File 'lib/fastruby/translator/translator.rb', line 818

def inline_ruby(proced, parameter)
  "rb_funcall(#{proced.__id__}, #{intern_num :call}, 1, #{parameter})"
end

#intern_num(symbol) ⇒ Object



1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
# File 'lib/fastruby/translator/translator.rb', line 1349

def intern_num(symbol)
  @intern_num_hash = Hash.new unless @intern_num_hash
  return @intern_num_hash[symbol] if @intern_num_hash[symbol]

  name = self.add_global_name("ID", 0);

  init_extra << "
    #{name} = rb_intern(\"#{symbol.to_s}\");
  "

  @intern_num_hash[symbol] = name

  name
end

#literal_value(value) ⇒ Object



963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/fastruby/translator/translator.rb', line 963

def literal_value(value)
  @literal_value_hash = Hash.new unless @literal_value_hash
  return @literal_value_hash[value] if @literal_value_hash[value]

  name = self.add_global_name("VALUE", "Qnil");

  begin

    str = Marshal.dump(value)


    if value.instance_of? Module

      container_str = value.to_s.split("::")[0..-2].join("::")

      init_extra << "
        #{name} = rb_define_module_under(
                #{container_str == "" ? "rb_cObject" : literal_value(eval(container_str))}
                ,\"#{value.to_s.split("::").last}\");

        rb_funcall(#{name},#{intern_num :gc_register_object},0);
      "
    elsif value.instance_of? Class
      container_str = value.to_s.split("::")[0..-2].join("::")

      str_class_name = value.to_s.split("::").last

      if (str_class_name == "Object")
        init_extra << "
          #{name} = rb_cObject;
        "
      else
        init_extra << "
          #{name} = rb_define_class_under(
                  #{container_str == "" ? "rb_cObject" : literal_value(eval(container_str))}
                  ,\"#{str_class_name}\"
                  ,#{value.superclass == Object ? "rb_cObject" : literal_value(value.superclass)});

          rb_funcall(#{name},#{intern_num :gc_register_object},0);
        "
      end
    elsif value.instance_of? Array
      init_extra << "
        #{name} = rb_ary_new3(#{value.size}, #{value.map{|x| literal_value x}.join(",")} );
        rb_funcall(#{name},#{intern_num :gc_register_object},0);
      "
    else
      
      require "base64"

      init_extra << "
      
        {
          VALUE encoded_str = rb_str_new2(#{Base64.encode64(str).inspect});
          VALUE str = rb_funcall(rb_cObject, #{intern_num :decode64}, 1, encoded_str);
          #{name} = rb_marshal_load(str);
          
          rb_funcall(#{name},#{intern_num :gc_register_object},0);
        }

      "
    end
  rescue TypeError => e
    @no_cache = true
    FastRuby.logger.info "#{value} disabling cache for extension"
    init_extra << "
      #{name} = rb_funcall(rb_const_get(rb_cObject, #{intern_num :ObjectSpace}), #{intern_num :_id2ref}, 1, INT2FIX(#{value.__id__}));
    "

  end
 @literal_value_hash[value] = name

  name
end

#locals_accessorObject



668
669
670
# File 'lib/fastruby/translator/translator.rb', line 668

def locals_accessor
  "plocals->"
end

#locals_scope(locals) ⇒ Object



672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'lib/fastruby/translator/translator.rb', line 672

def locals_scope(locals)
   old_locals = @locals
   old_locals_struct = @locals_struct

   @locals = locals
    @locals_struct = "struct {
    int size;
    void* call_frame;
    void* parent_locals;
    void* pframe;
    void* block_function_address;
    void* block_function_param;
    VALUE active;
    VALUE targetted;
    VALUE return_value;
    #{@locals.map{|l| "VALUE #{l};\n"}.join}
    }"

  begin
    yield
  ensure
    @locals = old_locals
    @locals_struct = old_locals_struct
  end
end

#on_blockObject



714
715
716
717
718
719
720
# File 'lib/fastruby/translator/translator.rb', line 714

def on_block
  old_on_block = @on_block
  @on_block = true
  return yield
ensure
  @on_block = old_on_block
end

#protected_block(inner_code, always_rescue = false, repass_var = nil, nolocals = false) ⇒ Object



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
# File 'lib/fastruby/translator/translator.rb', line 822

def protected_block(inner_code, always_rescue = false,repass_var = nil, nolocals = false)
  body = nil
  rescue_args = nil

    body =  anonymous_function{ |name| "
      static VALUE #{name}(VALUE param) {

        #{@frame_struct} frame;

        typeof(frame)* volatile pframe;
        
        #{if repass_var
        "typeof(frame)* parent_frame = ((typeof(pframe))((void**)param)[0]);"
        else
        "typeof(frame)* parent_frame = (typeof(pframe))param;"
        end
        }

        frame.parent_frame = 0;
        frame.return_value = Qnil;
        frame.rescue = 0;
        frame.last_error = Qnil;
        frame.targetted = 0;
        frame.thread_data = parent_frame->thread_data;
        frame.next_recv = parent_frame->next_recv;
        if (frame.thread_data == 0) frame.thread_data = rb_current_thread_data();

        pframe = &frame;

        #{
        nolocals ? "frame.plocals = 0;" : "#{@locals_struct}* plocals = parent_frame->plocals;
        frame.plocals = plocals;
        "
        }

        int aux = setjmp(frame.jmp);
        if (aux != 0) {

          if (frame.targetted == 1) {
            return frame.return_value;
          } else {
            frb_jump_tag(aux);
          }
        }

        #{if repass_var 
          "VALUE #{repass_var} = (VALUE)((void**)param)[1];"
        end
        }
          volatile VALUE last_expression = Qnil;
          #{inner_code};
          return last_expression;
        }
      "
    }

  if repass_var
    rescue_args = ""
    rescue_args = "(VALUE)(VALUE[]){(VALUE)pframe,(VALUE)#{repass_var}}"
  else
    rescue_args = "(VALUE)pframe"
  end

  wrapper_code = "
        if (str.state >= 0x80) {
          longjmp(pframe->jmp, str.state);
        } else {
          if (str.last_error != Qnil) {
              // raise emulation
              pframe->thread_data->exception = str.last_error;
              longjmp(pframe->jmp, FASTRUBY_TAG_RAISE);
              return Qnil;
          }
        }
    "
    
    return_err_struct = "struct {
        VALUE last_error;
        int state;
      }
      "

    rescue_body = anonymous_function{ |name| "
      static VALUE #{name}(VALUE param, VALUE err) {
        #{return_err_struct} *pstr = (void*)param;
        
        if (rb_obj_is_instance_of(err, #{literal_value FastRuby::JumpTagException})) {
          pstr->state = FIX2INT(rb_funcall(err, #{intern_num :state}, 0));
        } else {
          pstr->last_error = err;
        }
        
        return Qnil;
      }
    "
  }

  rescue_code = "rb_rescue2(#{body}, #{rescue_args}, #{rescue_body}, (VALUE)&str, rb_eException, (VALUE)0)"

  if always_rescue
    inline_block "
      #{return_err_struct} str;
      
      str.state = 0;
      str.last_error = Qnil;
      
      pframe->last_error = Qnil;
      VALUE result = #{rescue_code};

      #{wrapper_code}

      return result;
    ", repass_var, nolocals
  else
    inline_block "
      VALUE result;
      #{return_err_struct} str;
      
      str.state = 0;
      str.last_error = Qnil;
      
      pframe->last_error = Qnil;

      if (pframe->rescue) {
        result = #{rescue_code};
        #{wrapper_code}
      } else {
        VALUE last_expression = Qnil;
        #{inner_code};
        return last_expression;
      }

      return result;
    ", repass_var, nolocals
  end
end

#to_c(tree, result_variable = nil) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/fastruby/translator/translator.rb', line 186

def to_c(tree, result_variable = nil)
  return "Qnil" unless tree
  
  mname = "to_c_" + tree[0].to_s
  
  if result_variable
    if method(mname).arity == 1
      "#{result_variable} = #{send(mname, tree)};\n"
    else
      send(mname, tree, result_variable)
    end 
  else
    send(mname, tree)
  end
end

#to_c_method(tree, signature = nil) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'lib/fastruby/translator/translator.rb', line 349

def to_c_method(tree, signature = nil)
  
  if tree[0] == :defn
    method_name = tree[1]
    original_args_tree = tree[2]
    block_argument = tree[2].find{|x| x.to_s[0] == ?&}
    impl_tree = tree[3][1]
  elsif tree[0] == :defs
    method_name = tree[2]
    original_args_tree = tree[3]
    block_argument = tree[3].find{|x| x.to_s[0] == ?&}
    impl_tree = tree[4][1]
  end

  args_tree = original_args_tree.select{|x| x.to_s[0] != ?&}

    initialize_method_structs(original_args_tree)
    
    if options[:main] then
      strargs = if args_tree.size > 1
        "VALUE self, VALUE block, VALUE _parent_frame, #{(0..signature.size-1).map{|x| "VALUE arg#{x}"}.join(",")}"
      else
        "VALUE self, VALUE block, VALUE _parent_frame"
      end

    else
      
      strargs = "VALUE self, VALUE block, VALUE _parent_frame, int argc, VALUE* argv"
      
      splat_arg = args_tree[1..-1].find{|x| x.to_s.match(/\*/) }
  
      maxargnum = args_tree[1..-1].count{ |x|
          if x.instance_of? Symbol
            not x.to_s.match(/\*/) and not x.to_s.match(/\&/)
          else
            false
          end
        }
        
      minargnum = maxargnum
        
      args_tree[1..-1].each do |subtree|
        unless subtree.instance_of? Symbol
          if subtree[0] == :block
            minargnum = minargnum - (subtree.size-1)
          end
        end
      end
      
      if args_tree[1..-1].find{|x| x.to_s.match(/\*/)}
        maxargnum = 2147483647
      end
      
      read_arguments_code = ""
  
  
      validate_arguments_code = if signature.size-1 < minargnum
          "
            rb_raise(rb_eArgError, \"wrong number of arguments (#{signature.size-1} for #{minargnum})\");
          "
      elsif signature.size-1 > maxargnum
          "
            rb_raise(rb_eArgError, \"wrong number of arguments (#{signature.size-1} for #{maxargnum})\");
          "
      else
  
          default_block_tree = args_tree[1..-1].find{|subtree|
            unless subtree.instance_of? Symbol
              if subtree[0] == :block
                next true
              end
            end
  
            false
          }
          
          i = -1
  
          normalargsnum = args_tree[1..-1].count{|subtree|
            if subtree.instance_of? Symbol
              unless subtree.to_s.match(/\*/) or subtree.to_s.match(/\&/)
                next true
              end
            end
                  
            false
          }
  
          read_arguments_code = args_tree[1..-1].map { |arg_|
              arg = arg_.to_s
              i = i + 1
  
              if i < normalargsnum
                if i < signature.size-1
                  "plocals->#{arg} = argv[#{i}];\n"
                else
                    
                  if default_block_tree
                    initialize_tree = default_block_tree[1..-1].find{|subtree| subtree[1] == arg_}
                    if initialize_tree
                      to_c(initialize_tree) + ";\n"
                    else
                      ""
                    end
                  else
                      ";\n"
                  end
                end
              else
                ""
              end
            }.join("")
            
          if splat_arg
                if signature.size-1 < normalargsnum then
                  read_arguments_code << "
                    plocals->#{splat_arg.to_s.gsub("*","")} = rb_ary_new3(0);
                    "
                else
                  read_arguments_code << "
                    plocals->#{splat_arg.to_s.gsub("*","")} = rb_ary_new4(
                          #{(signature.size-1) - (normalargsnum)}, argv+#{normalargsnum} 
                          );
                  "
                end
  
          end
        
        
          ""
      end
  
      if block_argument
  
        proc_reyield_block_tree = s(:iter, s(:call, nil, :proc, s(:arglist)), s(:masgn, s(:array, s(:splat, s(:lasgn, :__xproc_arguments)))), s(:yield, s(:splat, s(:lvar, :__xproc_arguments))))
  
        require "fastruby/sexp_extension"
  
        read_arguments_code << "
          if (pblock ? pblock->proc != Qnil : 0) {
            plocals->#{block_argument.to_s.gsub("&","")} = pblock->proc;
          } else {
            plocals->#{block_argument.to_s.gsub("&","")} = #{to_c FastRuby::FastRubySexp.from_sexp(proc_reyield_block_tree)};
          }
        "

        read_arguments_code << "
          if (pblock) {
          rb_ivar_set(plocals->#{block_argument.to_s.gsub("&","")},
                    #{intern_num "__block_address"}, PTR2NUM(pblock->block_function_address)); 
          rb_ivar_set(plocals->#{block_argument.to_s.gsub("&","")},
                    #{intern_num "__block_param"}, PTR2NUM(pblock->block_function_param));            
          }            

        "
      end

    end

    require "fastruby/sexp_extension"       
    scope_mode = FastRuby::ScopeModeHelper.get_scope_mode(tree)

    ret = "VALUE #{@alt_method_name || method_name}(#{options[:main] ? "VALUE self" : strargs}) {
      #{validate_arguments_code}

      #{@frame_struct} frame;
      #{@frame_struct} * volatile pframe;
      
      frame.parent_frame = #{options[:main] ? "0"  : "(void*)_parent_frame"};
      frame.return_value = Qnil;
      frame.rescue = 0;
      frame.targetted = 0;
      frame.thread_data = #{options[:main] ? "0" : "((typeof(pframe))_parent_frame)->thread_data"};
      if (frame.thread_data == 0) frame.thread_data = rb_current_thread_data();

      int stack_chunk_instantiated = 0;
      
#{
if scope_mode == :dag
  " 
      volatile VALUE rb_previous_stack_chunk = Qnil;
      VALUE rb_stack_chunk = frame.thread_data->rb_stack_chunk;
      struct STACKCHUNK* volatile stack_chunk = 0;

      if (rb_stack_chunk != Qnil) {
        Data_Get_Struct(rb_stack_chunk,struct STACKCHUNK,stack_chunk);
      }

      if (stack_chunk == 0 || (stack_chunk == 0 ? 0 : stack_chunk_frozen(stack_chunk)) ) {
        rb_previous_stack_chunk = rb_stack_chunk;
        rb_gc_register_address(&rb_stack_chunk);
        stack_chunk_instantiated = 1;

        rb_stack_chunk = rb_stack_chunk_create(Qnil);
        frame.thread_data->rb_stack_chunk = rb_stack_chunk;

        rb_ivar_set(rb_stack_chunk, #{intern_num :_parent_stack_chunk}, rb_previous_stack_chunk);

        Data_Get_Struct(rb_stack_chunk,struct STACKCHUNK,stack_chunk);
      }

      #{@locals_struct}* volatile plocals;

      volatile int previous_stack_position = stack_chunk_get_current_position(stack_chunk);
      plocals = (typeof(plocals))stack_chunk_alloc(stack_chunk ,sizeof(typeof(*plocals))/sizeof(void*));
      
  "
else
  "
      #{@locals_struct} locals;
      typeof(locals) * volatile plocals = &locals;
  "
end
}

      plocals->parent_locals = (frame.thread_data->last_plocals);
      void* volatile old_parent_locals = frame.thread_data->last_plocals;
      
      #{
      if scope_mode == :dag 
        "frame.thread_data->last_plocals = plocals;\n"
      end
      }
      
      frame.plocals = plocals;
      plocals->active = Qtrue;
      plocals->targetted = Qfalse;
      plocals->pframe = (&frame);
      plocals->call_frame = (0);

      pframe = (void*)&frame;

      #{@block_struct} * volatile pblock;
      volatile VALUE last_expression = Qnil;

      int aux = setjmp(pframe->jmp);
      if (aux != 0) {
        plocals->active = Qfalse;

#{
if scope_mode == :dag
  " 
        stack_chunk_set_current_position(stack_chunk, previous_stack_position);

        if (stack_chunk_instantiated) {
          rb_gc_unregister_address(&rb_stack_chunk);
          frame.thread_data->rb_stack_chunk = rb_previous_stack_chunk;
        }
"
end
}            
        #{
        unless options[:main]
          "
          if (plocals->targetted == Qfalse || aux != FASTRUBY_TAG_RETURN) {
            frame.thread_data->last_plocals = old_parent_locals;
            
            longjmp(((typeof(pframe))_parent_frame)->jmp,aux);
          }
          "
        end
        }

        frame.thread_data->last_plocals = old_parent_locals;
        
        return plocals->return_value;
      }

      plocals->self = self;

      #{
      unless options[:main]
        "
        pblock = (void*)block;
        if (pblock) {
          plocals->block_function_address = pblock->block_function_address;
          plocals->block_function_param = pblock->block_function_param;
        } else {
          plocals->block_function_address = (0);
          plocals->block_function_param = 0;
        }
        "
      end
      }

      #{read_arguments_code}

      #{to_c impl_tree, "last_expression"};
      
local_return:
#{
if scope_mode == :dag
"
      stack_chunk_set_current_position(stack_chunk, previous_stack_position);

      if (stack_chunk_instantiated) {
        rb_gc_unregister_address(&rb_stack_chunk);
        frame.thread_data->rb_stack_chunk = rb_previous_stack_chunk;
      }
"
end
}
      plocals->active = Qfalse;
      
      frame.thread_data->last_plocals = old_parent_locals;
      
      return last_expression;
    }"

    add_main
    extra_code << ret
  
  "
    static VALUE dummy_#{method_name}_#{alt_method_name}_#{rand(1000000000000000000000000000000000)}(VALUE a) {
      return Qnil;
    }
  "
end