Class: FastRuby::Context

Inherits:
Object show all
Defined in:
lib/fastruby/translator/translator.rb,
lib/fastruby/translator/modules/call.rb,
lib/fastruby/translator/modules/defn.rb,
lib/fastruby/translator/modules/flow.rb,
lib/fastruby/translator/modules/iter.rb,
lib/fastruby/translator/modules/block.rb,
lib/fastruby/translator/modules/static.rb,
lib/fastruby/translator/modules/literal.rb,
lib/fastruby/translator/modules/logical.rb,
lib/fastruby/translator/modules/nonlocal.rb,
lib/fastruby/translator/modules/variable.rb,
lib/fastruby/translator/modules/directive.rb,
lib/fastruby/translator/modules/exceptions.rb,
lib/fastruby/translator/modules/method_group.rb

Defined Under Namespace

Classes: Value

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(common_func = true) ⇒ Context

Returns a new instance of Context.



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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
# File 'lib/fastruby/translator/translator.rb', line 110

def initialize(common_func = true)
  initialize_to_c
  
  @catch_blocks = []
  @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 = "
    unless $LOAD_PATH.include? #{FastRuby.fastruby_load_path.inspect}
      $LOAD_PATH << #{FastRuby.fastruby_load_path.inspect}
    end
    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.



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

def alt_method_name
  @alt_method_name
end

#extra_codeObject (readonly)

Returns the value of attribute extra_code.



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

def extra_code
  @extra_code
end

#infer_lvar_mapObject

Returns the value of attribute infer_lvar_map.



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

def infer_lvar_map
  @infer_lvar_map
end

#infer_selfObject

Returns the value of attribute infer_self.



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

def infer_self
  @infer_self
end

#init_extraObject (readonly)

Returns the value of attribute init_extra.



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

def init_extra
  @init_extra
end

#localsObject

Returns the value of attribute locals.



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

def locals
  @locals
end

#no_cacheObject (readonly)

Returns the value of attribute no_cache.



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

def no_cache
  @no_cache
end

#optionsObject

Returns the value of attribute options.



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

def options
  @options
end

#snippet_hashObject

Returns the value of attribute snippet_hash.



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

def snippet_hash
  @snippet_hash
end

Class Method Details

.define_translator_for(ntype, options = {}, &blk) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fastruby/translator/translator.rb', line 48

def self.define_translator_for(ntype, options = {}, &blk)
  condition_blk = proc do |*x|
    tree = x.first; tree.node_type == ntype
  end
  
  if options[:arity]
    if options[:arity] == 1
      condition_blk = proc do |*x|
        tree = x.first; x.size == 1 and tree.node_type == ntype
      end
    end
  end
  
  define_method_handler(:to_c, options, &blk).condition &condition_blk
end

Instance Method Details

#_raise(class_tree, message_tree = nil) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/fastruby/translator/translator.rb', line 255

def _raise(class_tree, message_tree = nil)
  class_tree = to_c class_tree unless class_tree.instance_of? String

  if message_tree.instance_of? String
    message_tree = "rb_str_new2(#{message_tree.inspect})"
  else
    message_tree = to_c message_tree
  end

  if message_tree
    return inline_block("
        pframe->thread_data->exception = rb_funcall(#{class_tree}, #{intern_num :exception},1,#{message_tree});
        longjmp(pframe->jmp, FASTRUBY_TAG_RAISE);
        return Qnil;
        ")
  else
    return inline_block("
        pframe->thread_data->exception = rb_funcall(#{class_tree}, #{intern_num :exception},0);
        longjmp(pframe->jmp, FASTRUBY_TAG_RAISE);
        return Qnil;
        ")
  end

end

#add_global_name(ctype, default) ⇒ Object



1532
1533
1534
1535
1536
1537
1538
1539
# File 'lib/fastruby/translator/translator.rb', line 1532

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

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

#add_mainObject



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/fastruby/translator/translator.rb', line 356

def add_main
  if options[:main]

    extra_code << "
      static VALUE #{@alt_method_name}(VALUE self__);
      static VALUE main_proc_call(VALUE self__, VALUE signature, 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, 2);
        rb_gv_set(\"$last_obj_proc\", newproc);
        }
      "
  end
end

#anonymous_function(*x) ⇒ Object



280
281
282
283
284
285
286
# File 'lib/fastruby/translator/translator.rb', line 280

def anonymous_function(*x)

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

  name
end

#c_escape(str) ⇒ Object



1105
1106
1107
# File 'lib/fastruby/translator/translator.rb', line 1105

def c_escape(str)
  str.inspect
end

#catch_block(*catchs) ⇒ Object



100
101
102
103
104
105
106
107
108
# File 'lib/fastruby/translator/translator.rb', line 100

def catch_block(*catchs)
    old_catch_blocks = @catch_blocks.dup
  begin
    catchs.each &@catch_blocks.method(:<<)
    return yield
  ensure
    @catch_blocks = old_catch_blocks
  end
end

#catch_on_throwObject



871
872
873
874
875
876
877
878
879
880
881
# File 'lib/fastruby/translator/translator.rb', line 871

def catch_on_throw
  old_catch_jmp_on_throw = @catch_jmp_on_throw || false
  @catch_jmp_on_throw = true
  begin
    ret = yield
  ensure
    @catch_jmp_on_throw = old_catch_jmp_on_throw
  end
  
  ret
end

#define_method_at_init(method_name, size, signature) ⇒ Object



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
# File 'lib/fastruby/translator/translator.rb', line 378

def define_method_at_init(method_name, size, signature)
  extra_code << "
    static VALUE main_proc_call(VALUE self__, VALUE signature, VALUE class_self_) {
      VALUE method_name = rb_funcall(
            #{literal_value FastRuby},
            #{intern_num :make_str_signature},
            2,
            #{literal_value method_name},
            signature
            );

      ID id = rb_intern(RSTRING_PTR(method_name));
      
      rb_funcall(
            #{literal_value FastRuby},
            #{intern_num :set_builder_module},
            1,
            class_self_
            );
      
      VALUE rb_method_hash;
      void** address = 0;
      rb_method_hash = rb_funcall(class_self_, #{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(
          class_self_,
          #{intern_num :register_method_value}, 
          3,
          #{literal_value method_name},
          PTR2NUM(id),
          PTR2NUM(address)
          );
          
          return Qnil;
    }
  "
  
  init_extra << "
        {
        VALUE newproc = rb_funcall(rb_cObject,#{intern_num :new},0);
        rb_define_singleton_method(newproc, \"call\", main_proc_call, 2);
        rb_gv_set(\"$last_obj_proc\", newproc);
        }
      "
end

#directive(tree) ⇒ Object



809
810
811
812
813
814
815
816
817
818
819
820
821
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
# File 'lib/fastruby/translator/translator.rb', line 809

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



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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
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
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# File 'lib/fastruby/translator/translator.rb', line 1184

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, int argc, VALUE* argv){
      #{@frame_struct}* pframe = frame;
      VALUE method_arguments[3];
      
      method_arguments[0] = (VALUE)argc;
      method_arguments[1] = (VALUE)argv;
      method_arguments[2] = (VALUE)self;
      
      return #{
        protected_block "last_expression = rb_funcall2(((VALUE*)method_arguments)[2], #{intern_num mname.to_sym}, ((int*)method_arguments)[0], ((VALUE**)method_arguments)[1]);", false, "method_arguments"
        };
    }
  "
  }
  
  generic_wrapper = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE self,void* block,void* frame, int argc, VALUE* argv){
    
      #{@frame_struct}* pframe = frame;
      VALUE method_arguments[4];
      
      method_arguments[0] = (VALUE)argc;
      method_arguments[1] = (VALUE)argv;
      method_arguments[2] = (VALUE)self;
      method_arguments[3] = (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 (fptr == 0) {
          fptr = *#{cfunc_address_name};
          if (fptr != 0) {
            return ( (VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*) ) (fptr) )(self,(VALUE)block,(VALUE)frame, argc, argv);  
          }
        }

      if (fptr == 0) {
        if (block==0) {
          return #{
            protected_block "last_expression = rb_funcall2(((VALUE*)method_arguments)[2], #{intern_num mname.to_sym}, ((int*)method_arguments)[0], ((VALUE**)method_arguments)[1]);", false, "method_arguments"
            };

        } else {
          return #{
              protected_block "
                    #{@block_struct} *pblock;
                    pblock = (typeof(pblock))( ((VALUE*)method_arguments)[3] );
                    last_expression = rb_iterate(
                    #{anonymous_function{|name|
                      "
                        static VALUE #{name} (VALUE data) {
                          VALUE* method_arguments = (VALUE*)data;
                          return rb_funcall2(((VALUE*)method_arguments)[2], #{intern_num mname.to_sym}, ((int*)method_arguments)[0], ((VALUE**)method_arguments)[1]);
                        }
                      "
                    }},
                      (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,argc,argv);  
      }
    }
    "
  }


  cfuncall1inprocargs = (0..args_tree.size-2).map{|x| "argv[#{x}]"}.join(",")
  cfuncall1inprocargs = ","+cfuncall1inprocargs if cfuncall1inprocargs != ""
  
  cfunc_value_cast = (["VALUE"]*args_tree.size).join(",")
  cfunc_wrapper = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE self, void* block,void* frame, int argc, VALUE* argv){
        return ( (VALUE(*)(#{cfunc_value_cast})) (#{cfunc_real_address_name}) )(self#{cfuncall1inprocargs});
    }
    "
  }
  
  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 self, void* block,void* frame, int argc, VALUE* argv){
        return ( (VALUE(*)(int, VALUE*, VALUE)) (#{cfunc_real_address_name}) )(argc,argv,self);
    }
    "
  }

  cfunc_wrapper_2 = anonymous_function{ |funcname| "
    static VALUE #{funcname}(VALUE self, void* block,void* frame, int argc, VALUE* argv){
        VALUE args = rb_ary_new3(argc, argv);
        return ( (VALUE(*)(VALUE,VALUE)) (#{cfunc_real_address_name}) )(self,args);
    }
    "
  }

  update_cfunc_method = anonymous_function{ |funcname| "
      static VALUE #{funcname}(){
            void** default_address = (void**)#{cfunc_address_name};
            ID default_id = rb_intern(\"default\");
            VALUE recvtype = #{recvdump};

            if (1) {
              *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)
                    );
              }
            }
          return Qnil;
      }
    "
  }
    
    

  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;
        }
        #{cfunc_address_name} = default_address;
        
        #{update_cfunc_method}();
        rb_iterate(#{anonymous_function{|funcname|
          "static VALUE #{funcname}(VALUE recv) {
            return rb_funcall(recv, #{intern_num :observe}, 1, #{literal_value(alt_method_name + "#" + cfunc_address_name)});
          }
          "
        }},fastruby_method,#{update_cfunc_method},Qnil);

        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;
        #{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



1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
# File 'lib/fastruby/translator/translator.rb', line 1552

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



288
289
290
291
292
293
294
295
296
297
298
299
300
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
# File 'lib/fastruby/translator/translator.rb', line 288

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

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



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
1037
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
# File 'lib/fastruby/translator/translator.rb', line 968

def generate_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
    "
      #{return_err_struct} str;
      
      str.state = 0;
      str.last_error = Qnil;
      
      pframe->last_error = Qnil;
      VALUE result = #{rescue_code};

      #{wrapper_code}

      return result;
    "
  else
    "
      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;
    "
  end
end

#global_entry(glbname) ⇒ Object



1541
1542
1543
1544
1545
1546
1547
1548
1549
# File 'lib/fastruby/translator/translator.rb', line 1541

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



785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/fastruby/translator/translator.rb', line 785

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



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/fastruby/translator/translator.rb', line 340

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(*args) ⇒ Object



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
# File 'lib/fastruby/translator/translator.rb', line 883

def inline_block(*args)
  
  unless block_given?
    code = args.first
    return inline_block(*args[1..-1]) {
        code
      }
  end
  
  repass_var = args[0]
  nolocals = args[1] || false
  
  code = catch_on_throw{ yield }

  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;


#{@catch_blocks.map { |cb|
  "#{cb.to_s}_end:

   plocals->return_value = last_expression;
   plocals->targetted = 1;
   longjmp(pframe->jmp, #{intern_num( cb.to_s + "_end")});

   #{cb.to_s}_start:
  
   plocals->return_value = last_expression;
   plocals->targetted = 1;
   longjmp(pframe->jmp, #{intern_num( cb.to_s + "_start")});
  
  "

}.join("\n")
}
      #{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



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'lib/fastruby/translator/translator.rb', line 848

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



948
949
950
# File 'lib/fastruby/translator/translator.rb', line 948

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

#intern_num(symbol) ⇒ Object



1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/fastruby/translator/translator.rb', line 1516

def intern_num(symbol)
  symbol = symbol.to_sym
  @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



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
# File 'lib/fastruby/translator/translator.rb', line 1109

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



755
756
757
# File 'lib/fastruby/translator/translator.rb', line 755

def locals_accessor
  "plocals->"
end

#locals_scope(locals) ⇒ Object



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

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



801
802
803
804
805
806
807
# File 'lib/fastruby/translator/translator.rb', line 801

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

#protected_block(*args) ⇒ Object



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/fastruby/translator/translator.rb', line 952

def protected_block(*args)
  unless block_given?
    inner_code = args.first
    return protected_block(*args[1..-1]) {
      inner_code
    }
  end
  
  repass_var = args[1]
  nolocals = args[2] || false
  
  inline_block(repass_var, nolocals) do
    generate_protected_block(yield, *args)
  end
end

#to_c_and(tree, return_var = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/fastruby/translator/modules/logical.rb', line 25

def to_c_and(tree, return_var = nil)
  if return_var
    "
      {
        VALUE op1 = Qnil;
        VALUE op2 = Qnil;
        #{to_c tree[1], "op1"};
        #{to_c tree[2], "op2"};
        #{return_var} = (RTEST(op1) && RTEST(op2)) ? Qtrue : Qfalse;
      }
    "
  else
    "(RTEST(#{to_c tree[1]}) && RTEST(#{to_c tree[2]})) ? Qtrue : Qfalse"
  end
  
end

#to_c_array(tree, result_var = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/literal.rb', line 75

def to_c_array(tree, result_var = nil)
  if tree.size > 1
    if result_var
      prefix = "_array_element_" + rand(10000000).to_s + "_"
      "
      {
        #{ 
          (0..tree.size-2).map{|x|
            "VALUE #{prefix}#{x};"
          }.join("\n");
        }
        
        #{
          (0..tree.size-2).map{|x|
            to_c(tree[x+1], prefix+x.to_s)
          }.join("\n");
        }
        
        #{result_var} = rb_ary_new3(#{tree.size-1}, #{(0..tree.size-2).map{|x| prefix+x.to_s}.join(",")} );
      }
      "
    else
      strargs = tree[1..-1].map{|subtree| to_c subtree}.join(",")
      "rb_ary_new3(#{tree.size-1}, #{strargs})"
    end
  else
    if result_var
    "#{result_var} = rb_ary_new3(0);"
    else
    "rb_ary_new3(0)"
    end
  end
end

#to_c_attrasgn(tree) ⇒ Object



319
320
321
# File 'lib/fastruby/translator/modules/call.rb', line 319

def to_c_attrasgn(tree)
  to_c_call(tree)
end

#to_c_block(tree, result_variable = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/block.rb', line 97

def to_c_block(tree, result_variable = nil)
  if tree.size == 1
    return inline_block("return Qnil;")
  end

  code = proc{
    
    str = tree[1..-2].map{ |subtree|
      to_c(subtree,"last_expression")
    }.join(";")
  
    if tree[-1]
        str = str + ";#{to_c(tree[-1],"last_expression")};"
    end
  
    if result_variable
      str << "#{result_variable} = last_expression;"
    else
      str << "return last_expression;"
    end
    str
  }
  
  if result_variable
    code.call
  else
    inline_block &code
  end
end

#to_c_break(tree, result_var = nil) ⇒ Object



40
41
42
43
44
45
46
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
# File 'lib/fastruby/translator/modules/nonlocal.rb', line 40

def to_c_break(tree, result_var = nil)
  
    value_tmp_var = "value_" + rand(10000000).to_s
  
    code = proc{"

      {
     VALUE #{value_tmp_var} = Qnil; 
     #{
     if tree[1]
       to_c(tree[1], value_tmp_var)
     end
     };

     typeof(pframe) target_frame_;
     target_frame_ = (void*)plocals->call_frame;

     if (target_frame_ == 0) {
        #{_raise("rb_eLocalJumpError","illegal break")};
     }

     plocals->call_frame = 0;

     target_frame_->return_value = #{value_tmp_var};
     target_frame_->targetted = 1;
     pframe->thread_data->exception = Qnil;
     longjmp(pframe->jmp,FASTRUBY_TAG_BREAK);
     
     }
     "}
     
     if result_var
       code.call
     else
       inline_block code
     end
end

#to_c_call(tree, result_var = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/fastruby/translator/modules/call.rb', line 25

def to_c_call(tree, result_var = nil)
  repass_var = @repass_var

  recv = tree[1]
  mname = tree[2]
  args = tree[3]
  args_tree = tree[3]
  
  # search block_pass on arguments
  block_pass_arg = args.find{|arg| if arg == :arglist
        false
      else
      arg[0] == :block_pass
        end} 

  if block_pass_arg
    args_tree = args_tree.dup.reject{|st| 
      if st.respond_to? :node_type
        st.node_type == :block_pass
      else 
        false
      end
     }
    args = args_tree
  end
 
  mname = :require_fastruby if mname == :require

  argnum = args.size - 1

  recv = recv || s(:self)

  recvtype = infer_type(recv)
  
  if args.size > 1
    if (not recvtype) or args.last[0] == :splat
      if block_pass_arg
        call_tree = tree.dup
        call_tree[3] = args.select{|arg| if arg == :arglist 
            true
            else
              arg[0] != :block_pass
              end
              }
        
        block_arguments_tree = s(:masgn, s(:array, s(:splat, s(:lasgn, :__xblock_arguments))))
        block_tree = s(:call, s(:lvar, :__x_proc), :call, s(:arglist, s(:splat, s(:lvar, :__xblock_arguments))))
        
        replace_iter_tree = s(:block,
            s(:lasgn, :__x_proc, s(:call, block_pass_arg[1], :to_proc, s(:arglist))),
            s(:iter, call_tree, block_arguments_tree, block_tree)
            ).to_fastruby_sexp
      
        if result_var  
          return to_c(replace_iter_tree,result_var)
        else
          return to_c(replace_iter_tree)
        end
      end
    end

    if args.last[0] == :splat
      aux_varname = "_aux_" + rand(1000000).to_s
      code = protected_block(
        "
        
        VALUE array = Qnil;
        
        #{to_c args.last[1], "array"};
        
        if (TYPE(array) != T_ARRAY) {
          array = rb_ary_new4(1,&array);
        }
        
        int argc = #{args.size-2};
        VALUE argv[#{args.size} + _RARRAY_LEN(array)];
        VALUE #{aux_varname} = Qnil;
        #{
          i = -1
          args[1..-2].map {|arg|
            i = i + 1
            "#{to_c arg, aux_varname};
            argv[#{i}] = #{aux_varname};
            "
          }.join(";\n")
        };
        
        VALUE recv = Qnil;
        
        #{to_c recv, "recv"};
        
        int array_len = _RARRAY_LEN(array);
        
        int i;
        for (i=0; i<array_len;i++) {
          argv[argc] = rb_ary_entry(array,i);
          argc++; 
        }
        
        last_expression = rb_funcall2(recv, #{intern_num tree[2]}, argc, argv);
        ", true, repass_var)
        
      if result_var
       return "#{result_var} = #{code};\n"
      else
       return code
      end
    end
  end

  if recvtype

    address = nil
    mobject = nil

    inference_complete = true
    signature = [recvtype]

    args[1..-1].each do |arg|
      argtype = infer_type(arg)
      signature << argtype
      unless argtype
        inference_complete = false
      end
    end

    if repass_var
      extraargs = ","+repass_var
      extraargs_signature = ",VALUE " + repass_var
    else
      extraargs = ""
      extraargs_signature = ""
    end

      block_proc_tree = s(:call, block_pass_arg[1], :to_proc, s(:arglist)) if block_pass_arg

      block_wrapping_proc = proc { |name| "
        static VALUE #{name}(int argc, VALUE* argv, VALUE _locals, VALUE _parent_frame) {
          return rb_proc_call(_locals, rb_ary_new4(argc, argv)); 
        }
      "
      }
 
      if argnum == 0
        value_cast = "VALUE,VALUE,VALUE"


          if block_pass_arg or result_var
            code = proc{ "
            {
            VALUE recv = Qnil;
            #{to_c recv, "recv"};

            #{@block_struct} block, *pblock = Qfalse;

            #{if block_pass_arg
            "
            VALUE proc = Qnil;
            #{to_c(block_proc_tree, "proc") }

            VALUE block_address_value = rb_ivar_get(proc, #{intern_num "__block_address"});

            if (block_address_value != Qnil) {
              block.block_function_address = NUM2PTR(block_address_value);
              block.block_function_param = NUM2PTR(rb_ivar_get(proc, #{intern_num "__block_param"}));
              block.proc = proc;
              pblock = &block;
            } else {
              // create a block from a proc
              block.block_function_address = ((void*)#{anonymous_function(&block_wrapping_proc)});
              block.block_function_param = (void*)proc;
              block.proc = proc;
              pblock = &block;
            }

            "
            end
            }

            #{if result_var
            "
            #{result_var} = ((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(recv, (VALUE)pblock, (VALUE)pframe, 0, (VALUE[]){});
            "
            else
            "
            ((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(recv, (VALUE)pblock, (VALUE)pframe, 0, (VALUE[]){});
            "
            end
            }
            }
            "
            }
          
            result_var ? code.call : inline_block(&code)
          else
             "((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(#{to_c recv}, Qfalse, (VALUE)pframe, 0, (VALUE[]){})"               
          end          

      else
        value_cast = ( ["VALUE"]*(args.size) ).join(",") + ",VALUE,VALUE"
        suffix = "_" + rand(1000000).to_s+"_"

            strargs = (0..args_tree.size-2).map{|i| "#{suffix}arg#{i}"}.join(",")
          if block_pass_arg or result_var
            code = proc{ "
            {
            VALUE recv = Qnil;
            
            #{
            (0..args_tree.size-2).map{ |x|
              "VALUE #{suffix}arg#{x};"
            }.join("\n")
            }

            #{
            (0..args_tree.size-2).map{ |x|
              to_c(args_tree[x+1], "#{suffix}arg#{x}") + ";"
            }.join("\n")
            }
            
            #{to_c recv, "recv"};

            #{@block_struct} block, *pblock = Qfalse;

            #{if block_pass_arg
            "
            VALUE proc = Qnil;
            #{to_c(block_proc_tree, "proc") }
            VALUE block_address_value = rb_ivar_get(proc, #{intern_num "__block_address"});
            if (block_address_value != Qnil) {
              block.block_function_address = NUM2PTR(block_address_value);
              block.block_function_param = NUM2PTR(rb_ivar_get(proc, #{intern_num "__block_param"}));
              block.proc = proc;
              pblock = &block;
            } else {
              // create a block from a proc
              block.block_function_address = ((void*)#{anonymous_function(&block_wrapping_proc)});
              block.block_function_param = (void*)proc;
              block.proc = proc;
              pblock = &block;
            }

            "
            end
            }

            #{if result_var
            "
            #{result_var} = ((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(recv, (VALUE)pblock, (VALUE)pframe, #{args.size-1}, (VALUE[]){#{strargs}});
            "
            else
            "
            ((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(recv, (VALUE)pblock, (VALUE)pframe, #{args.size-1}, (VALUE[]){#{strargs}});
            "
            end
            }

            
            }
            "
            }
            
            result_var ? code.call : inline_block(&code)
          else
            strargs = args[1..-1].map{|arg| to_c arg}.join(",")
            "((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encode_address(recvtype,signature,mname,tree,inference_complete)})(#{to_c recv}, Qfalse, (VALUE)pframe, #{args.size-1}, (VALUE[]){#{strargs}})"
          end
      end

  else # else recvtype
    if argnum == 0
      code = protected_block("last_expression = rb_funcall(#{to_c recv}, #{intern_num tree[2]}, 0)", true, repass_var)
      if result_var
      "
        #{result_var} = #{code};
      "
      else
        code
      end
    else
      strargs = args[1..-1].map{|arg| to_c arg}.join(",")
      code = protected_block("last_expression = rb_funcall(#{to_c recv}, #{intern_num tree[2]}, #{argnum}, #{strargs} )", true, repass_var)
      if result_var
      "
        #{result_var} = #{code};
      "
      else
        code
      end
    end
  end # if recvtype
end

#to_c_cdecl(tree, result_var_ = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/variable.rb', line 99

def to_c_cdecl(tree, result_var_ = nil)
  
  result_var = result_var_ || "value"
  
  if tree[1].instance_of? Symbol
    code = proc{"
      {
        // set constant #{tree[1].to_s}
        #{to_c tree[2], result_var};
        rb_const_set(rb_cObject, #{intern_num tree[1]}, #{result_var});
      }
      "}
  elsif tree[1].instance_of? FastRuby::FastRubySexp

    if tree[1].node_type == :colon2
      code = proc{"
        {
          // set constant #{tree[1].to_s}
          #{to_c tree[2], result_var};
          VALUE klass = Qnil;
          #{to_c tree[1][1], "klass"};
          rb_const_set(klass, #{intern_num tree[1][2]}, #{result_var});
        }
        "}
    elsif tree[1].node_type == :colon3
      code = proc{"
        {
        // set constant #{tree[1].to_s}
        #{to_c tree[2], result_var};
        rb_const_set(rb_cObject, #{intern_num tree[1][1]}, #{result_var});
        }
        "}
    end
  end

    if result_var_
      code.call
    else
       inline_block{"VALUE #{result_var} = Qnil;\n" + code.call + "
        return #{result_var};
       "}
    end
end

#to_c_class(tree, result_var = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fastruby/translator/modules/method_group.rb', line 25

def to_c_class(tree, result_var = nil)
  str_class_name = get_class_name(tree[1])
  container_tree = get_container_tree(tree[1])

  if container_tree == s(:self)
    method_group("
                VALUE superklass = rb_cObject;
                #{
                if tree[2] 
                  to_c tree[2], "superklass"
                end
                };
                VALUE tmpklass = rb_define_class(
                  #{str_class_name.inspect},
                  superklass
              );
    ", tree[3], result_var)
  else
    method_group("
                VALUE container_klass = Qnil;
                VALUE superklass = rb_cObject;
                
                #{
                if tree[2] 
                  to_c tree[2], "superklass"
                end
                };
                
                #{to_c(container_tree, "container_klass")};
                VALUE tmpklass = rb_define_class_under(
                  container_klass,
                  #{str_class_name.inspect},
                  superklass
              );
    ", tree[3], result_var)
  end
end

#to_c_colon2(tree, result_var = nil) ⇒ Object



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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/fastruby/translator/modules/variable.rb', line 149

def to_c_colon2(tree, result_var = nil)
  code = proc{ "
    {
    VALUE klass = Qnil;
    
    #{to_c tree[1],"klass"};
        #{
        if result_var
          "#{result_var} = Qnil;"
        end
      }

  if (rb_is_const_id(#{intern_num tree[2]})) {
    switch (TYPE(klass)) {
      case T_CLASS:
      case T_MODULE:
        #{
        if result_var
          "#{result_var} = rb_const_get_from(klass, #{intern_num tree[2]});"
        else
          "return rb_const_get_from(klass, #{intern_num tree[2]});"
        end
        }
        break;
      default:
        #{_raise("rb_eTypeError","not a class/module")};
        break;
    }
  }
  else {
        #{
        if result_var
          "#{result_var} = rb_funcall(klass, #{intern_num tree[2]}, 0, 0);"
        else
          "return rb_funcall(klass, #{intern_num tree[2]}, 0, 0);"
        end
        }
  }
    
        #{
        unless result_var
          "return Qnil;"
        end
        }
    }
  "}
  
  if result_var
    code.call
  else
    inline_block &code
  end
end

#to_c_colon3(tree) ⇒ Object



144
145
146
# File 'lib/fastruby/translator/modules/variable.rb', line 144

def to_c_colon3(tree)
  "rb_const_get_from(rb_cObject, #{intern_num tree[1]})"
end

#to_c_cvar(tree) ⇒ Object



24
25
26
# File 'lib/fastruby/translator/modules/variable.rb', line 24

def to_c_cvar(tree)
  "rb_cvar_get(CLASS_OF(plocals->self) != rb_cClass ? CLASS_OF(plocals->self) : plocals->self,#{intern_num tree[1]})"
end

#to_c_cvasgn(tree, result_var = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/fastruby/translator/modules/variable.rb', line 29

def to_c_cvasgn(tree, result_var = nil)
  if result_var
    "
      {
        VALUE recv = CLASS_OF(plocals->self) != rb_cClass ? CLASS_OF(plocals->self) : plocals->self;

        #{to_c tree[2], result_var};
        
        #{if RUBY_VERSION =~ /^1\.9/
          "rb_cvar_set(recv,#{intern_num tree[1]},#{result_var});"
          elsif RUBY_VERSION =~ /^1\.8/
          "rb_cvar_set(recv,#{intern_num tree[1]},#{result_var},Qfalse);"
          else
            raise RuntimeError, "unsupported ruby version #{RUBY_VERSION}"
          end 
        }
      }
   "
  else
  "__rb_cvar_set(CLASS_OF(plocals->self) != rb_cClass ? CLASS_OF(plocals->self) : plocals->self,#{intern_num tree[1]},#{to_c tree[2]},Qfalse)"
  end
end

#to_c_defined(tree) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/fastruby/translator/modules/variable.rb', line 260

def to_c_defined(tree)
  nt = tree[1].node_type

  if nt == :self
  'rb_str_new2("self")'
  elsif nt == :true
  'rb_str_new2("true")'
  elsif nt == :false
  'rb_str_new2("false")'
  elsif nt == :nil
  'rb_str_new2("nil")'
  elsif nt == :lvar
  'rb_str_new2("local-variable")'
  elsif nt == :gvar
  "rb_gvar_defined((struct global_entry*)#{global_entry(tree[1][1])}) ? #{literal_value "global-variable"} : Qnil"
  elsif nt == :const
  "rb_const_defined(rb_cObject, #{intern_num tree[1][1]}) ? #{literal_value "constant"} : Qnil"
  elsif nt == :call
    if RUBY_VERSION =~ /^1\.8/
    "rb_method_node(CLASS_OF(#{to_c tree[1][1]}), #{intern_num tree[1][2]}) ? #{literal_value "method"} : Qnil"
    else
    "rb_method_entry(CLASS_OF(#{to_c tree[1][1]}), #{intern_num tree[1][2]}) ? #{literal_value "method"} : Qnil"
    end
  elsif nt == :yield
    "rb_block_given_p() ? #{literal_value "yield"} : Qnil"
  elsif nt == :ivar
  "rb_ivar_defined(plocals->self,#{intern_num tree[1][1]}) ? #{literal_value "instance-variable"} : Qnil"
  elsif nt == :attrset or
        nt == :op_asgn1 or
        nt == :op_asgn2 or
        nt == :op_asgn_or or
        nt == :op_asgn_and or
        nt == :op_asgn_masgn or
        nt == :masgn or
        nt == :lasgn or
        nt == :dasgn or
        nt == :dasgn_curr or
        nt == :gasgn or
        nt == :iasgn or
        nt == :cdecl or
        nt == :cvdecl or
        nt == :cvasgn
    literal_value "assignment"
  else
    literal_value "expression"
  end
end

#to_c_defn(tree, result_var = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/fastruby/translator/modules/defn.rb', line 25

def to_c_defn(tree, result_var = nil)

  method_name = tree[1]
  args_tree = tree[2].select{|x| x.to_s[0] != ?&}
  
  global_klass_variable = add_global_name("VALUE", "Qnil");

  hash = Hash.new
  value_cast = ( ["VALUE"]*(args_tree.size+2) ).join(",")
  
  strmethodargs = "self,block,(VALUE)&frame"
  
  anonymous_method_name = anonymous_dispatcher(global_klass_variable, method_name)
  alt_options = options.dup

  alt_options.delete(:self)
  alt_options.delete(:main)

  code = "
  
  
    if (rb_obj_is_kind_of(plocals->self, rb_cClass) || rb_obj_is_kind_of(plocals->self, rb_cModule)) {
      rb_define_method(plocals->self, #{method_name.to_s.inspect}, #{anonymous_method_name}, -1);
      
      #{global_klass_variable} = plocals->self;
      // set tree
      rb_funcall(#{literal_value FastRuby}, #{intern_num :set_tree}, 5,
              #{global_klass_variable},
              rb_str_new2(#{method_name.to_s.inspect}),
              #{literal_value tree},
              #{literal_value snippet_hash},
              #{literal_value alt_options}
  
              );
      
    } else {
      VALUE obj = plocals->self;
      rb_define_singleton_method(obj, #{method_name.to_s.inspect}, #{anonymous_method_name}, -1 );
      
      #{global_klass_variable} = CLASS_OF(obj);
      // set tree
      rb_funcall(#{literal_value FastRuby}, #{intern_num :set_tree}, 5,
              #{global_klass_variable},
              rb_str_new2(#{method_name.to_s.inspect}),
              #{literal_value tree},
              #{literal_value snippet_hash},
              #{literal_value alt_options}
  
              );
    }
    
    "

  if result_var
    code + "\n#{result_var} = Qnil;"
  else
    inline_block code + "\nreturn Qnil;\n"
  end
end

#to_c_defs(tree, result_var = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/defn.rb', line 86

def to_c_defs(tree, result_var = nil)
  method_name = tree[2]
  args_tree = tree[3].select{|x| x.to_s[0] != ?&}
  
  global_klass_variable = add_global_name("VALUE", "Qnil");

  hash = Hash.new
  value_cast = ( ["VALUE"]*(args_tree.size+2) ).join(",")
  
  strmethodargs = "self,block,(VALUE)&frame"
  
  anonymous_method_name = anonymous_dispatcher(global_klass_variable, method_name)

  alt_options = options.dup

  alt_options.delete(:self)
  alt_options.delete(:main)

  code = "
  
    VALUE obj = Qnil;
    #{to_c tree[1], "obj"};
    rb_define_singleton_method(obj, #{method_name.to_s.inspect}, #{anonymous_method_name}, -1 );
    
    #{global_klass_variable} = CLASS_OF(obj);
    // set tree
    rb_funcall(#{literal_value FastRuby}, #{intern_num :set_tree}, 5,
            #{global_klass_variable},
            rb_str_new2(#{method_name.to_s.inspect}),
            #{literal_value tree},
            #{literal_value snippet_hash},
            #{literal_value alt_options}

            );

    "

  if result_var
    code + "\n#{result_var} = Qnil;"
  else
    inline_block code + "\nreturn Qnil;\n"
  end
    
end

#to_c_dot2(tree, result_var = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/literal.rb', line 114

def to_c_dot2(tree, result_var = nil)
  
  begin_var = "_begin"+rand(10000000).to_s
  end_var = "_end"+rand(10000000).to_s
  
  if result_var
    "
    {
      VALUE #{begin_var} = Qnil;
      VALUE #{end_var} = Qnil;
      
      #{to_c tree[1], begin_var};
      #{to_c tree[2], end_var};
      
      #{result_var} = rb_range_new(#{begin_var}, #{end_var},0);
    }
    "
  else
    if result_var
    "
      {
      VALUE #{begin_var} = Qnil;
      VALUE #{end_var} = Qnil;
      #{to_c tree[1], begin_var};
      #{to_c tree[2], end_var};
      
      #{result_var} = rb_range_new(#{begin_var}, #{end_var},0)
      }
    "
    else
    "rb_range_new(#{to_c tree[1]}, #{to_c tree[2]},0)"
    end
  end
end

#to_c_ensure(tree) ⇒ Object



99
100
101
102
103
104
105
106
107
108
# File 'lib/fastruby/translator/modules/exceptions.rb', line 99

def to_c_ensure(tree)
  if tree.size == 2
    to_c tree[1]
  else
    ensured_code = to_c tree[2]
    inline_block {
      "#{frame(to_c(tree[1]),ensured_code,ensured_code,1)};"
    }
  end
end

#to_c_gasgn(tree, result_var = nil) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/fastruby/translator/modules/variable.rb', line 62

def to_c_gasgn(tree, result_var = nil)
  if result_var
      "
      {
      #{to_c tree[2], result_var}; 
      rb_gvar_set((void*)#{global_entry(tree[1])},#{result_var});
      }
      "
  else
  "_rb_gvar_set((void*)#{global_entry(tree[1])}, #{to_c tree[2]})"
  end
end

#to_c_gvar(tree) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/fastruby/translator/modules/variable.rb', line 53

def to_c_gvar(tree)
  if (tree[1] == :$!)
    "pframe->thread_data->exception"
  else
    "rb_gvar_get((struct global_entry*)#{global_entry(tree[1])})"
  end
end

#to_c_hash(tree, result_var = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/fastruby/translator/modules/literal.rb', line 29

def to_c_hash(tree, result_var = nil)
  
  hash_tmp_var = "_hash_"+rand(1000000).to_s
  key_tmp_var = "_key_"+rand(1000000).to_s
  value_tmp_var = "_value_"+rand(1000000).to_s

  code = proc{ 
  hash_aset_code = ""
  (0..(tree.size-3)/2).each do |i|
    strkey = to_c tree[1 + i * 2]
    strvalue = to_c tree[2 + i * 2]
    hash_aset_code << "
      {
        VALUE #{key_tmp_var} = Qnil;
        VALUE #{value_tmp_var} = Qnil;
        
        #{to_c tree[1 + i * 2], key_tmp_var};
        #{to_c tree[2 + i * 2], value_tmp_var};
        
        rb_hash_aset(#{hash_tmp_var}, #{key_tmp_var}, #{value_tmp_var});
      }
    "
  end
  
      "
      {
      VALUE #{hash_tmp_var} = rb_hash_new();
      #{hash_aset_code};
      #{
      if result_var
        "#{result_var} = #{hash_tmp_var}"
      else
        "return #{hash_tmp_var}"
      end
      };
      }
    "}
    
  if result_var
    code.call
  else
    inline_block &code
  end
end

#to_c_iasgn(tree, result_var = nil) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/fastruby/translator/modules/variable.rb', line 81

def to_c_iasgn(tree, result_var = nil)
  if result_var
      "
      {
      #{to_c tree[2], result_var}; 
      rb_ivar_set(#{locals_accessor}self,#{intern_num tree[1]},#{result_var});
      }
      "
  else
    "_rb_ivar_set(#{locals_accessor}self,#{intern_num tree[1]},#{to_c tree[2]})"
  end
end

#to_c_if(tree, result_variable_ = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/fastruby/translator/modules/flow.rb', line 24

def to_c_if(tree, result_variable_ = nil)
  condition_tree = tree[1]
  impl_tree = tree[2]
  else_tree = tree[3]
  
  result_variable = result_variable_ || "last_expression"
  
  infered_value = infer_value(condition_tree)
  unless infered_value
    
    code = proc{"
      {
        VALUE condition_result;
        #{to_c condition_tree, "condition_result"};
        if (RTEST(condition_result)) {
          #{to_c impl_tree, result_variable};
        }#{else_tree ?
          " else {
          #{to_c else_tree, result_variable};
          }
          " : ""
        }
      }
    "}
  
    if result_variable_
      code.call
    else
      inline_block { code.call + "; return last_expression;" }
    end
  else
    if infered_value.value
      to_c(impl_tree, result_variable_)
    else
      if else_tree
        to_c(else_tree, result_variable_)
      else
        to_c(s(:nil), result_variable_)
      end
    end
  end
end

#to_c_iter(tree, result_var = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
348
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/fastruby/translator/modules/iter.rb', line 25

def to_c_iter(tree, result_var = nil)

  call_tree = tree[1]
  args_tree = tree[2]
  recv_tree = call_tree[1]

  directive_code = directive(call_tree)
  if directive_code
    if result_var
      return "#{result_var} = #{directive_code};\n"
    else
      return directive_code
    end
  end

  other_call_tree = call_tree.dup
  other_call_tree[1] = s(:lvar, :arg)

  mname = call_tree[2]

  call_args_tree = call_tree[3]

  caller_code = nil

  recvtype = infer_type(recv_tree || s(:self))

  address = nil
  mobject = nil
  len = nil

  if recvtype

    inference_complete = true
    signature = [recvtype]

    call_args_tree[1..-1].each do |arg|
      argtype = infer_type(arg)
      if argtype
        signature << argtype
      else
        inference_complete = false
      end
    end
  end

  anonymous_impl = tree[3]

  str_lvar_initialization = "#{@frame_struct} *pframe;
                             #{@locals_struct} *plocals;
                            pframe = (void*)param;
                            plocals = (void*)pframe->plocals;
                            "

  str_arg_initialization = ""

  str_impl = ""
  on_block do
    str_impl = to_c(anonymous_impl, "last_expression")
  end     

    if not args_tree
    elsif args_tree.first == :lasgn
      if RUBY_VERSION =~ /^1\.8/
        str_arg_initialization << "plocals->#{args_tree[1]} = arg;"
      elsif RUBY_VERSION =~ /^1\.9/
        str_arg_initialization << "
          if (TYPE(arg) != T_ARRAY) {
            plocals->#{args_tree[1]} = arg;
          } else {
            plocals->#{args_tree[1]} = rb_ary_entry(arg,0);
          }
          "
      end
    elsif args_tree.first == :masgn
      
      if RUBY_VERSION =~ /^1\.8/
        str_arg_initialization << "
            {
              if (TYPE(arg) != T_ARRAY) {
                if (arg != Qnil) {
                  arg = rb_ary_new4(1,&arg);
                } else {
                  arg = rb_ary_new2(0);
                }
              } else if (_RARRAY_LEN(arg) <= 1) {
                arg = rb_ary_new4(1,&arg);
              }
            }
            "
      elsif RUBY_VERSION =~ /^1\.9/
        str_arg_initialization << "
            {
            }
            "
      end
      
      arguments = args_tree[1][1..-1]
      
      (0..arguments.size-1).each do |i|
        arg = arguments[i]
        if arg[0] == :lasgn 
          str_arg_initialization << "plocals->#{arguments[i].last} = rb_ary_entry(arg,#{i});\n"
        elsif arg[0] == :splat
          str_arg_initialization << "plocals->#{arg.last.last} = rb_ary_new2(_RARRAY_LEN(arg)-#{i});\n
          
            int i;
            for (i=#{i};i<_RARRAY_LEN(arg);i++){
              rb_ary_store(plocals->#{arg.last.last},i-#{i},rb_ary_entry(arg,i));
            }
           "
        end
      end
    end
      str_recv = "pframe->next_recv"
      str_recv = "plocals->self" unless recv_tree

      strargs = if call_args_tree.size > 1
                  "," + (0..call_args_tree.size-2).map{|i| "arg#{i}"}.join(",")
              else
                ""
              end
      
      str_evaluate_args = ""

        rb_funcall_caller_code = proc { |name, call_type| "
          static VALUE #{name}(VALUE param) {
            // call to #{call_tree[2]}
             VALUE last_expression = Qnil;
  
            #{str_lvar_initialization}
            #{str_evaluate_args};
            
          VALUE ret = rb_funcall(#{str_recv}, #{intern_num call_tree[2]}, #{call_args_tree.size-1} #{strargs});
            #{
            if call_type == :lambda
          "

          // freeze all stacks
          struct FASTRUBYTHREADDATA* thread_data = rb_current_thread_data();

          if (thread_data != 0) {
            VALUE rb_stack_chunk = thread_data->rb_stack_chunk;

            // add reference to stack chunk to lambda object
            rb_ivar_set(ret,#{intern_num :_fastruby_stack_chunk},rb_stack_chunk);

            // freeze the complete chain of stack chunks
            while (rb_stack_chunk != Qnil) {
              struct STACKCHUNK* stack_chunk;
              Data_Get_Struct(rb_stack_chunk,struct STACKCHUNK,stack_chunk);

              stack_chunk_freeze(stack_chunk);

              rb_stack_chunk = rb_ivar_get(rb_stack_chunk,#{intern_num :_parent_stack_chunk});
            }
          }
          "
          end
        }
          return ret;
          }
        "
        }


      if call_args_tree.size > 1
        if call_args_tree.last[0] == :splat
          rb_funcall_caller_code = proc { |name,call_type| "
            static VALUE #{name}(VALUE param) {
              // call to #{call_tree[2]}
  
              VALUE last_expression = Qnil;
              #{str_lvar_initialization}
              
              VALUE array = Qnil;
              
              #{to_c call_args_tree.last[1], "array"};
              
              if (TYPE(array) != T_ARRAY) {
                array = rb_ary_new4(1,&array);
              }
              
              int argc = #{call_args_tree.size-2};
              VALUE argv[#{call_args_tree.size} + _RARRAY_LEN(array)];
              
              VALUE aux_ = Qnil;;
              #{
                i = -1
                call_args_tree[1..-2].map {|arg|
                  i = i + 1
                  "
                  #{to_c arg, "aux_"};
                  argv[#{i}] = aux_;
                  "
                }.join(";\n")
              };
              
              int array_len = _RARRAY_LEN(array);
              
              int i;
              for (i=0; i<array_len;i++) {
                argv[argc] = rb_ary_entry(array,i);
                argc++; 
              }
              
              return rb_funcall2(#{str_recv}, #{intern_num call_tree[2]}, argc, argv);
            }
          "
          }   
        else
          str_evaluate_args = "
              #{
                (0..call_args_tree.size-2).map{|i|
                  "VALUE arg#{i} = Qnil;"
                }.join("\n")
              }
              
              #{
                (0..call_args_tree.size-2).map{|i|
                  to_c(call_args_tree[i+1], "arg#{i}")+";"
                }.join("\n")
              }
          "
        end
      end

    argument_array_read = "
        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
        }
    "
    
    rb_funcall_block_code = proc { |name,call_type| "
      static VALUE #{name}(VALUE arg_, VALUE _plocals, int argc, VALUE* argv) {
        // block for call to #{call_tree[2]}
        #{argument_array_read}

        volatile VALUE last_expression = Qnil;

        #{@frame_struct} frame;
        #{@frame_struct} * volatile pframe = (void*)&frame;
        #{@locals_struct} * volatile plocals = (void*)_plocals;

        frame.plocals = plocals;
        frame.parent_frame = 0;
        frame.return_value = Qnil;
        frame.rescue = 0;
        frame.targetted = 0;
        frame.thread_data = rb_current_thread_data();

        #{str_arg_initialization}

        #{
        if call_type == :lambda or call_type == :proc_new
        "
          void* volatile old_call_frame = ((typeof(plocals))(pframe->plocals))->call_frame;
          ((typeof(plocals))(pframe->plocals))->call_frame = pframe;
        "
        end
        }

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

            if (aux == FASTRUBY_TAG_NEXT) {
              last_expression = pframe->thread_data->accumulator;
              goto fastruby_local_next;
            } else if (aux == FASTRUBY_TAG_REDO) {
              // do nothing and let execute the block again
#{
if call_type == :lambda
"

            } else if (aux == FASTRUBY_TAG_BREAK) {
              last_expression = frame.return_value;
              goto fastruby_local_next;
"
end
}
#{
if call_type == :lambda or call_type == :proc_new
"
            } else if (aux == FASTRUBY_TAG_RAISE) {
               rb_funcall(((typeof(plocals))(pframe->plocals))->self, #{intern_num :raise}, 1, frame.thread_data->exception);
               return Qnil;
"
end
}
            } else {
#{
case call_type
when :proc_new
"
_local_return:
                  if (plocals->targetted == 1) {
                    if (plocals->active == Qfalse) {
                      rb_raise(rb_eLocalJumpError,\"return from proc-closure\");
                    } else {
                      ((typeof(plocals))(pframe->plocals))->call_frame = old_call_frame;
                      frb_jump_tag(aux);
                    }
                  } else {
                    rb_raise(rb_eLocalJumpError, \"unexpected return\");
                  }
"
when :lambda
"
              if (aux == FASTRUBY_TAG_RETURN) {
                if (plocals->targetted == 1) {
                  last_expression = ((typeof(plocals))(pframe->plocals))->return_value;
                  goto fastruby_local_next;

                } else {
                  rb_raise(rb_eLocalJumpError, \"unexpected return\");
                }
              } else {
                rb_raise(rb_eLocalJumpError, \"unexpected return\");
              }
"
else
  "
              frb_jump_tag(aux);
              return frame.return_value;
  "
end
}

            }
        }

      #{
      if call_type == :callcc
      "
        if (rb_obj_is_kind_of(arg, rb_const_get(rb_cObject, #{intern_num :Continuation}))) {
          struct FASTRUBYTHREADDATA* thread_data = frame.thread_data;
          rb_ivar_set(arg,#{intern_num :__stack_chunk},thread_data->rb_stack_chunk);
        }
      "
      end
      }

fastruby_local_redo:
        #{str_impl};

#{
case call_type
when :proc_new
"
        return last_expression;
local_return:
        aux = FASTRUBY_TAG_RETURN;
        plocals->return_value = last_expression;
        plocals->targetted = 1;
        goto _local_return;
"
when :lambda
"
local_return:
"
else
" 
        return last_expression;
local_return:            
        plocals->return_value = last_expression;
        plocals->targetted = 1;
        frb_jump_tag(FASTRUBY_TAG_RETURN);
"
end
}


fastruby_local_next:
#{
if call_type == :proc_new or call_type == :lambda
"
  ((typeof(plocals))(pframe->plocals))->call_frame = old_call_frame;
"
end
}
        return last_expression;          
        }
    "
    }

    fastruby_str_arg_initialization = ""

    if not args_tree
      fastruby_str_arg_initialization = ""
    elsif args_tree.first == :lasgn
      fastruby_str_arg_initialization = "plocals->#{args_tree[1]} = argv[0];"
    elsif args_tree.first == :masgn
      arguments = args_tree[1][1..-1]
      
      (0..arguments.size-1).each do |i|
        arg = arguments[i]
        if arg[0] == :lasgn 
          fastruby_str_arg_initialization << "plocals->#{arg.last} = #{i} < argc ? argv[#{i}] : Qnil;\n"
        elsif arg[0] == :splat
          fastruby_str_arg_initialization << "plocals->#{arg.last.last} = rb_ary_new2(#{arguments.size-1-i});\n
          {
            int i;
            for (i=#{i};i<argc;i++){
              rb_ary_store(plocals->#{arg.last.last},i-#{i},argv[i]);
            }
          }
           "
        end 
      end
    end

    block_code = proc { |name| "
      static VALUE #{name}(int argc, VALUE* argv, VALUE _locals, VALUE _parent_frame) {
        // block for call to #{call_tree[2]}
        volatile VALUE last_expression = Qnil;
        #{@frame_struct} frame;
        #{@frame_struct} * volatile pframe = (void*)&frame;
        #{@frame_struct} * volatile parent_frame = (void*)_parent_frame;
        #{@locals_struct} * volatile plocals;

        frame.plocals = (void*)_locals;
        frame.parent_frame = parent_frame;
        frame.return_value = Qnil;
        frame.rescue = 0;
        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;

        #{fastruby_str_arg_initialization}

        int aux = setjmp(frame.jmp);
        if (aux != 0) {
            if (pframe->targetted == 0) {
              if (aux == FASTRUBY_TAG_NEXT) {
                return pframe->thread_data->accumulator;
              } else if (aux == FASTRUBY_TAG_REDO) {
                // do nothing and let execute the block again
              } else {
                longjmp(((typeof(pframe))_parent_frame)->jmp,aux);
              }
            }

        }

fastruby_local_redo:
        #{str_impl};

        return last_expression;
local_return:
        plocals->return_value = last_expression;
        plocals->targetted = 1;
        longjmp(pframe->jmp, FASTRUBY_TAG_RETURN);
fastruby_local_next:
        return last_expression;          }
    "
    }

    caller_code = nil
    convention_global_name = add_global_name("int",0)
    
      precode = "
          struct FASTRUBYTHREADDATA* thread_data = 0;
          VALUE saved_rb_stack_chunk = Qnil;
          
          VALUE next_recv = plocals->self;
          
          #{
            if recv_tree
              to_c recv_tree, "next_recv"
            end
          };

          pframe->next_recv = next_recv;
#ifdef RUBY_1_8
          NODE* node = rb_method_node(CLASS_OF(pframe->next_recv), #{intern_num mname});
#endif              
#ifdef RUBY_1_9
          void* node = rb_method_entry(CLASS_OF(pframe->next_recv), #{intern_num mname});
#endif              

          if (node == #{@callcc_node_gvar}) {
            
            // freeze all stacks
            thread_data = rb_current_thread_data();
  
            if (thread_data != 0) {
              VALUE rb_stack_chunk = thread_data->rb_stack_chunk;
              saved_rb_stack_chunk = rb_stack_chunk;

              // freeze the complete chain of stack chunks
              while (rb_stack_chunk != Qnil) {
                struct STACKCHUNK* stack_chunk;
                Data_Get_Struct(rb_stack_chunk,struct STACKCHUNK,stack_chunk);
  
                stack_chunk_freeze(stack_chunk);
  
                rb_stack_chunk = rb_ivar_get(rb_stack_chunk,#{intern_num :_parent_stack_chunk});
              }
            }
          }
        "
      
      postcode = "
          if (node == #{@callcc_node_gvar}) {
            thread_data->rb_stack_chunk = saved_rb_stack_chunk;  
          }
      "              
      
    
      funcall_call_code = "
      #{
        frame_call(
          "ret = " + protected_block("
          
          void* caller_func;
          void* block_func;
          typeof(plocals) current_plocals;
          
          if (pframe->thread_data == 0) pframe->thread_data = rb_current_thread_data();
          void* last_plocals = pframe->thread_data->last_plocals;

#ifdef RUBY_1_8
          NODE* node = rb_method_node(CLASS_OF(pframe->next_recv), #{intern_num mname});
#endif
#ifdef RUBY_1_9
          void* node = rb_method_entry(CLASS_OF(pframe->next_recv), #{intern_num mname});
#endif

          if (
            node == #{@proc_node_gvar} ||
            node == #{@lambda_node_gvar}
            )  {

            caller_func = #{anonymous_function(:lambda,&rb_funcall_caller_code)};
            block_func = #{anonymous_function(:lambda,&rb_funcall_block_code)};
          } else if (node == #{@procnew_node_gvar} && pframe->next_recv == rb_cProc) {
            caller_func = #{anonymous_function(:lambda,&rb_funcall_caller_code)};
            block_func = #{anonymous_function(:proc_new,&rb_funcall_block_code)};
          } else if (node == #{@callcc_node_gvar}) {
            caller_func = #{anonymous_function(:normal,&rb_funcall_caller_code)};
            block_func = #{anonymous_function(:callcc,&rb_funcall_block_code)};
          } else {
            caller_func = #{anonymous_function(:normal,&rb_funcall_caller_code)};
            block_func = #{anonymous_function(:normal,&rb_funcall_block_code)};
          }
          

          last_expression = rb_iterate(
            caller_func,
            (VALUE)pframe,
            block_func,
            (VALUE)plocals);

          if (node == #{@callcc_node_gvar}) {
  
            // remove active flags of abandoned stack
            current_plocals = pframe->thread_data->last_plocals;
            while (current_plocals) {
              current_plocals->active = Qfalse;
              current_plocals = (typeof(current_plocals))(current_plocals->parent_locals); 
            }
            
            // restore last_plocals
            pframe->thread_data->last_plocals = last_plocals;
            
            // mark all scopes as active
            current_plocals = last_plocals;
            
            while (current_plocals) {
              current_plocals->active = Qtrue;
              current_plocals = (typeof(current_plocals))(current_plocals->parent_locals); 
            }
          }
          ", true), precode, postcode
        )
      };
      "        

  recvtype = nil if call_args_tree.size > 1 ? call_args_tree.last[0] == :splat : false
  unless recvtype
    if result_var
      "#{result_var} = #{funcall_call_code};"
    else
      funcall_call_code
    end
  else
    encoded_address = encode_address(recvtype,signature,mname,call_tree,inference_complete,convention_global_name)

    if call_args_tree.size > 1
      strargs = (0..call_args_tree.size-2).map{|i| "arg#{i}"}.join(",")
    else
      strargs = ""
    end

    fastruby_call_code = "
            // call to #{call_tree[2]}
            #{
            if call_args_tree.size > 1
              str_evaluate_args
            end
            };
            
            VALUE recv = plocals->self;
            
            #{
            if recv_tree
             to_c recv_tree, "recv" 
            end
            } 

            ret = ((VALUE(*)(VALUE,VALUE,VALUE,int,VALUE*))#{encoded_address})(recv, (VALUE)&block, (VALUE)&call_frame, #{call_args_tree.size-1}, (VALUE[]){#{strargs}});
        "
    
    code = "
      if (#{@last_address_name} == 0) {
        return #{funcall_call_code};
      } else {
        #{if recvtype and inference_complete
          "if (*#{@last_address_name} == 0) {
            rb_funcall(#{literal_value recvtype},#{intern_num :build}, 2, #{literal_value signature}, #{literal_value mname});
          }
          "
        end
        }
        if (*#{@last_address_name} == 0) {
          return #{funcall_call_code};
        } else {
          #{fastruby_call_code}
        }
      }
    "
    
    fastruby_precode = "                 #{@block_struct} block;

            block.block_function_address = ((void*)#{anonymous_function(&block_code)});
            block.block_function_param = ((void*)plocals);
            block.proc = Qnil;                
            "
    
    if result_var
      "#{result_var} = #{frame_call(code,fastruby_precode,"")}"
    else
      frame_call(code,fastruby_precode,"")
    end
    
  end
end

#to_c_ivar(tree) ⇒ Object



76
77
78
# File 'lib/fastruby/translator/modules/variable.rb', line 76

def to_c_ivar(tree)
  "rb_ivar_get(#{locals_accessor}self,#{intern_num tree[1]})"
end

#to_c_lasgn(tree, result_var = nil) ⇒ Object



204
205
206
207
208
209
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
# File 'lib/fastruby/translator/modules/variable.rb', line 204

def to_c_lasgn(tree, result_var = nil)
  code = "
      {
        #{to_c tree[2], result_var};
        #{locals_accessor}#{tree[1]} = #{result_var};
       }
       "

  if result_var
    if options[:validate_lvar_types]
      klass = @infer_lvar_map[tree[1]]
      if klass
        "
        {
          #{to_c tree[2], result_var};
          if (CLASS_OF(#{result_var})!=#{literal_value klass}) {
            #{_raise(literal_value(FastRuby::TypeMismatchAssignmentException), "Illegal assignment at runtime (type mismatch)")};
          }
          #{locals_accessor}#{tree[1]} = #{result_var};
        }
       "
      else
        code
      end
    else
      code
    end
  else
    if options[:validate_lvar_types]
      klass = @infer_lvar_map[tree[1]]
      if klass
        verify_type_function = proc { |name| "
          static VALUE #{name}(VALUE arg, void* pframe ) {
            if (CLASS_OF(arg)!=#{literal_value klass}) {
              #{_raise(literal_value(FastRuby::TypeMismatchAssignmentException), "Illegal assignment at runtime (type mismatch)")};
            }
            return arg;
          }
        "
        }
        
        "_lvar_assing(&#{locals_accessor}#{tree[1]}, #{anonymous_function(&verify_type_function)}(#{to_c tree[2]},pframe))"
      else
        "_lvar_assing(&#{locals_accessor}#{tree[1]},#{to_c tree[2]})"
      end
    else
      "_lvar_assing(&#{locals_accessor}#{tree[1]},#{to_c tree[2]})"
    end
  end
end

#to_c_method(tree, signature = nil) ⇒ Object



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
667
668
669
670
671
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
# File 'lib/fastruby/translator/translator.rb', line 436

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

#to_c_module(tree, result_var = nil) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/fastruby/translator/modules/method_group.rb', line 64

def to_c_module(tree, result_var = nil)
  str_class_name = get_class_name(tree[1])
  container_tree = get_container_tree(tree[1])

  if container_tree == s(:self)
    method_group("
                  VALUE tmpklass = rb_define_module(#{str_class_name.inspect});
    ", tree[2], result_var)
  else
    method_group("
                  VALUE container_klass = Qnil;
                  
                  #{to_c(container_tree, "container_klass")};
                  VALUE tmpklass = rb_define_module_under(container_klass,#{str_class_name.inspect});
    ", tree[2], result_var)
  end
end

#to_c_next(tree, result_var = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/nonlocal.rb', line 118

def to_c_next(tree, result_var = nil)
  tmp_varname = "_acc_" + rand(10000000).to_s
  if @on_block
   code =proc {"
    {
      last_expression = Qnil;
      
      #{
      if tree[1]
        to_c(tree[1],"last_expression")
      end
      }
    pframe->thread_data->accumulator = last_expression;
    goto fastruby_local_next;
    }
    "}
    
    if result_var
      code.call
    else
      inline_block &code
    end
  else
    _raise("rb_eLocalJumpError","illegal next");
  end
end

#to_c_not(tree, return_var = nil) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/fastruby/translator/modules/logical.rb', line 60

def to_c_not(tree, return_var = nil)
  if return_var
    "
      {
        VALUE op1 = Qnil;
        #{to_c tree[1], "op1"};
        #{return_var} = (RTEST(op1)) ? Qfalse: Qtrue;
      }
    "
  else
    "RTEST(#{to_c tree[1]}) ? Qfalse : Qtrue"
  end
end

#to_c_or(tree, return_var = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fastruby/translator/modules/logical.rb', line 43

def to_c_or(tree, return_var = nil)
  if return_var
    "
      {
        VALUE op1 = Qnil;
        VALUE op2 = Qnil;
        #{to_c tree[1], "op1"};
        #{to_c tree[2], "op2"};
        #{return_var} = (RTEST(op1) || RTEST(op2)) ? Qtrue : Qfalse;
      }
    "
  else
  "(RTEST(#{to_c tree[1]}) || RTEST(#{to_c tree[2]})) ? Qtrue : Qfalse"
  end
end

#to_c_redo(tree, result_var = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/fastruby/translator/modules/nonlocal.rb', line 101

def to_c_redo(tree, result_var = nil)
  if @on_block
     code = "
        goto fastruby_local_redo;
      "
      
      if result_var
        code
      else
        inline_block code
      end
  else
      _raise("rb_eLocalJumpError","illegal redo");
  end
end

#to_c_rescue(tree) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/fastruby/translator/modules/exceptions.rb', line 25

def to_c_rescue(tree)
  catch_on_throw do
    if tree[1][0] == :resbody
      else_tree = tree[2]
  
      if else_tree
        to_c else_tree
      else
        "Qnil"
      end
    else
      resbody_tree = tree[2]
      else_tree = nil
      if tree[-1]
        if tree[-1][0] != :resbody
          else_tree = tree[-1]
        end
      end
  
      catch_condition_array = []
      lasgn_code = ""
      resbody_code = to_c(resbody_tree[2])
  
      rescue_code = ""
  
      tree[1..-1].each do |resbody_tree|
        next if resbody_tree[0] != :resbody
  
        if resbody_tree[1].size == 1
          resbody_tree[1][1] = s(:const, :Exception)
        end
  
        if resbody_tree[1].last[0] == :lasgn
          lasgn_code = to_c(resbody_tree[1].last)
        end
  
        resbody_tree[1][1..-1].each do |xtree|
          if xtree[0] != :lasgn
            trapcode = "rb_eException";
  
            if xtree
              trapcode = to_c(xtree)
            end
  
            catch_condition_array << "(rb_obj_is_kind_of(frame.thread_data->exception,#{trapcode}) == Qtrue)"
          end
        end
  
        rescue_code << "
          if (aux == FASTRUBY_TAG_RAISE) {
            if (#{catch_condition_array.join(" || ")})
            {
              // trap exception
              frame.targetted = 1;
  
              #{lasgn_code};
  
               #{resbody_code};
            }
          }
        "
      end
  
      frame_call(
        "ret = " + frame(to_c(tree[1])+";","
          #{rescue_code}
        ", else_tree ? to_c(else_tree) : nil, 1)
  
        )
    end
  end
end

#to_c_retry(tree, result_var = nil) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/fastruby/translator/modules/nonlocal.rb', line 79

def to_c_retry(tree, result_var = nil)
    code = "
      {
     typeof(pframe) target_frame_;
     target_frame_ = (void*)plocals->call_frame;

     if (target_frame_ == 0) {
        #{_raise("rb_eLocalJumpError","illegal retry")};
     }

     target_frame_->targetted = 1;
     longjmp(pframe->jmp,FASTRUBY_TAG_RETRY);
     }
     "
   if result_var
     code
   else
     inline_block code
   end
end

#to_c_return(tree, return_variable = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/fastruby/translator/modules/nonlocal.rb', line 25

def to_c_return(tree, return_variable = nil)
  code = proc{"
    #{to_c(tree[1],"last_expression")};
    goto local_return;
    return Qnil;
    "}
    
  if return_variable
    code.call
  else
    inline_block &code
  end
end

#to_c_scope(tree, result_var = nil) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/fastruby/translator/modules/defn.rb', line 132

def to_c_scope(tree, result_var = nil)
  if tree[1]
    if result_var
      to_c(tree[1], result_var)
    else
      to_c(tree[1])
    end
  else
    "Qnil"
  end
end

#to_c_while(tree, result_var = nil) ⇒ Object



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
# File 'lib/fastruby/translator/modules/flow.rb', line 68

def to_c_while(tree, result_var = nil)
  
  begin_while = "begin_while_"+rand(10000000).to_s
  end_while = "end_while_"+rand(10000000).to_s
  aux_varname = "_aux_" + rand(10000000).to_s
  code = proc{ "
    {
      VALUE while_condition;
      VALUE #{aux_varname};
      
#{begin_while}:
      #{to_c tree[1], "while_condition"};
      if (!RTEST(while_condition)) goto #{end_while}; 
      #{to_c tree[2], aux_varname};
      goto #{begin_while};
#{end_while}:
      
      #{
      if result_var
        "#{result_var} = Qnil;"
      else
        "return Qnil;"
      end
      }
    }
  "}
  
  if result_var
    code.call
  else
    inline_block &code
  end
  
end

#to_c_yield(tree) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/fastruby/translator/modules/block.rb', line 25

def to_c_yield(tree)

  block_code = proc { |name| "
    static VALUE #{name}(VALUE frame_param, VALUE* block_args, int size) {

      #{@locals_struct} *plocals;
      #{@frame_struct} *pframe;
      pframe = (void*)frame_param;
      plocals = (void*)pframe->plocals;

      if ((plocals->block_function_address) == 0) {
        #{_raise("rb_eLocalJumpError", "no block given")};
      } else {
        return ((VALUE(*)(int,VALUE*,VALUE,VALUE))(plocals->block_function_address))(size, block_args, (VALUE)(plocals->block_function_param), (VALUE)pframe);
      }
    }
  "
  }

  splat_arg = tree.find{|x| x == :yield ? false : x[0] == :splat}

  protected_block(false) do
    if splat_arg
      "
        VALUE splat_array = Qnil;
        VALUE block_aux = Qnil;
         #{to_c(splat_arg[1], "splat_array")};
        
        if (CLASS_OF(splat_array) == rb_cArray) {
          VALUE block_args[_RARRAY_LEN(splat_array) + #{tree.size}];
          int i;
          #{ 
            (0..tree.size-3).map{|i|
              "
              #{to_c(tree[i+1], "block_aux")};
              block_args[#{i}] = block_aux;
              "
            }.join(";\n")
          };
          
          for (i=0; i<_RARRAY_LEN(splat_array); i++) {
            block_args[i+#{tree.size-2}] = rb_ary_entry(splat_array,i);
          }
          
          last_expression = #{anonymous_function(&block_code)}((VALUE)pframe, block_args, _RARRAY_LEN(splat_array) + #{tree.size-2});
        } else {
          VALUE block_args[1+#{tree.size}];
          #{ 
            (0..tree.size-3).map{|i|
              "
              #{to_c(tree[i+1], "block_aux")};
              block_args[#{i}] = block_aux;
              "
            }.join(";\n")
          };
          
          block_args[#{tree.size-2}] = splat_array;
          last_expression = #{anonymous_function(&block_code)}((VALUE)pframe, block_args, #{tree.size-1});
        }
        
      "
    else
      if tree.size > 1
          "last_expression = " + anonymous_function(&block_code)+"((VALUE)pframe, (VALUE[]){#{tree[1..-1].map{|subtree| to_c subtree}.join(",")}},#{tree.size-1})"
        else
          "last_expression = " + anonymous_function(&block_code)+"((VALUE)pframe, (VALUE[]){}, #{tree.size-1})"
        end
    end
  end
end