Hi James,

> I just found out about the VM::InstructionSequence.compile method for
> turning Ruby code strings into ruby1.9 bytecode. Is there a standard method
> of de/serializing this bytecode to/from files, and is there a way of running
> bytecode directly? I'm looking at generating bytecode from another language
> to get it to run on Ruby.
>

You can at least load bytecode directly, transform ruby to bytecode and at
the end evaluate everything:

1
2
3
4
5
6
7
8
9
*10*
11
12
13
14
15
16
17
18
19
*20*
iseqFromCode = RubyVM::InstructionSequence.new "a = 1; a += a; puts a"
  # => <RubyVM::InstructionSequence:<compiled>@<compiled>>
iseqFromCode.eval
  # 2
  # => nil
iseqRawArr = iseqFromCode.to_a
  # => ["YARVInstructionSequence/SimpleDataFormat", 1, 1, 1,
  #     {:arg_size=>0, :local_size=>2, :stack_max=>2}, "<compiled>",
  #     "<compiled>", :top, [:a], 0, [], [1, [:trace, 1],
  #     [:putobject, 1], [:setlocal, 2], [:trace, 1], [:getlocal, 2],
  #     [:getlocal, 2], [:opt_plus], [:setlocal, 2], [:trace, 1],
  #     [:putnil], [:getlocal, 2], [:send, :puts, 1, nil, 8, nil],
  #     [:leave]]]
iseqRawArr.class
  # => Array
iseqFromArr = RubyVM::InstructionSequence.load iseqRawArr
  # => <RubyVM::InstructionSequence:<compiled>@<compiled>>
iseqFromArr.eval
  # 2
  # => nil

But for this you have to apply this to the source code:

1
2
3
4
5
6
7
8
9
*10*
11
12
13
14
15
boviAir:src danielbovensiepen$ svn diff iseq.c
Index: iseq.c
===================================================================
--- iseq.c      (revision 21348)
+++ iseq.c      (working copy)
@@ -1451,7 +1451,7 @@
     rb_define_method(rb_cISeq, "eval", iseq_eval, 0);

     /* disable this feature because there is no verifier. */
-    /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */
+    rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1);
     (void)iseq_s_load;

     rb_define_singleton_method(rb_cISeq, "compile", iseq_s_compile, -1);
boviAir:src danielbovensiepen$

Of course, the comments are very clear: you shouldn't do this!


MfG
Daniel