Ruby 2.0 Bytecode Export / Import

前端 未结 2 2112
囚心锁ツ
囚心锁ツ 2021-02-14 14:32

I\'ve been reading about the new ruby 2.0 features, and found that it will support bytecode import / export:

Ruby 2.0 is expected to make it simple to sav

2条回答
  •  轮回少年
    2021-02-14 15:22

    Until someone with better information looks at this question, I did some research:

    Is this feature already implemented, and if so, how do I use it?

    It is implemented, but it doesn't seem to be exposed (e.g ruby --dump-bytecode doesn't exist). Also there's not very much documentation. As far as I can tell, what you are looking for is something like:

    seq = RubyVM::InstructionSequence.compile_file("./example.rb")
    

    seq.disassemble will give you a nicely formatted string that you could dump to a file, or seq.to_a will generate an an array that looks like:

    ["YARVInstructionSequence/SimpleDataFormat",
     2,
     0,
     1,
     {:arg_size=>0, :local_size=>1, :stack_max=>2},
     "
    ", "./example.rb", "./example.rb", 1, :top, [], 0, [], [[:trace, 1], [:putspecialobject, 3], [:putnil], [:defineclass, :User, ["YARVInstructionSequence/SimpleDataFormat", 2, 0, 1, {:arg_size=>0, :local_size=>1, :stack_max=>6}, "", ....

    If you want to persist this to a file, you can do something like:

    File.write("out.dump", Marshal.dump(seq.to_a))
    

    And then to load again:

    arr = Marshal.load(File.read("out.dump"))
    

    Unfortunately I can't seem to figure out how to create a new InstructionSequence given the array loaded above.

    I'm also wondering about some of the details. Is YARV-bytecode supposed to be platform-independent? Are all gems automatically included in the bytecode?

    In the example above, gems are not included. Your InstructionSequence would include the bytecode equivalent of a require 'active_record' or what have you. I suspect that if dumping and loading of bytecode were provided directly by a ruby executable, this behavior would stay the same.

    If anyone else has more information I'd love to see it!

提交回复
热议问题