Module: FastRuby::IterTranslator

Defined in:
lib/fastruby/translator/modules/iter.rb

Instance Method Summary collapse

Instance Method Details

#to_c_iter(tree, result_var = nil) ⇒ Object



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
689
690
691
# File 'lib/fastruby/translator/modules/iter.rb', line 26

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
      value_cast = ( ["VALUE"]*(call_tree[3].size) ).join(",") + ", VALUE, VALUE"
      strargs = "," + (0..call_args_tree.size-2).map{|i| "arg#{i}"}.join(",")
    else
      value_cast = "VALUE,VALUE,VALUE"
      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_cast}))#{encoded_address})(recv, (VALUE)&block, (VALUE)&call_frame #{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