From b6390a21eb7f316341bb7bf669a15dc321aa5239 Mon Sep 17 00:00:00 2001 From: Matt Valentine-House Date: Fri, 29 Sep 2023 10:17:10 +0100 Subject: [ci skip] More docs for InstructionSequence.compile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit documents that you can also pass a `File` object to `RubyVM::InstructionSequence.compile`, instead of a string, and this will behave in a similar way to `RubyVM::InstructionSequence.compile_file` e.g. ``` ❯ ./ruby -e "puts RubyVM::InstructionSequence.compile(File.open('test.rb')).disasm" == disasm: #@:1 (1,0)-(2,21)> local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1]) [ 1] name@0 0000 putstring "Ruby" ( 1)[Li] 0002 setlocal_WC_0 name@0 0004 putself ( 2)[Li] 0005 putobject "Hello, " 0007 getlocal_WC_0 name@0 0009 dup 0010 objtostring 0012 anytostring 0013 concatstrings 2 0015 opt_send_without_block 0017 leave ~/git/ruby master* ≡ ⇡ ❯ ./ruby -e "puts RubyVM::InstructionSequence.compile(File.open('test.rb').read).disasm" == disasm: #@:1 (1,0)-(2,21)> local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1]) [ 1] name@0 0000 putstring "Ruby" ( 1)[Li] 0002 setlocal_WC_0 name@0 0004 putself ( 2)[Li] 0005 putobject "Hello, " 0007 getlocal_WC_0 name@0 0009 dup 0010 objtostring 0012 anytostring 0013 concatstrings 2 0015 opt_send_without_block 0017 leave ``` This is explicitly allowed by this code path in `rb_iseq_compile_with_option` so we should document it. ``` if (RB_TYPE_P(src, T_FILE)) { parse = rb_parser_compile_file_path; } else { parse = rb_parser_compile_string_path; StringValue(src); } ``` --- iseq.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/iseq.c b/iseq.c index 5deda19c26..0bd4b2812b 100644 --- a/iseq.c +++ b/iseq.c @@ -1334,8 +1334,8 @@ rb_iseqw_new(const rb_iseq_t *iseq) * InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq * InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq * - * Takes +source+, a String of Ruby code and compiles it to an - * InstructionSequence. + * Takes +source+, which can be a string of Ruby code, or an open +File+ object. + * that contains Ruby source code. * * Optionally takes +file+, +path+, and +line+ which describe the file path, * real path and first line number of the ruby code in +source+ which are @@ -1357,6 +1357,10 @@ rb_iseqw_new(const rb_iseq_t *iseq) * RubyVM::InstructionSequence.compile(File.read(path), path, File.expand_path(path)) * #=> @test.rb:1> * + * file = File.open("test.rb") + * RubyVM::InstructionSequence.compile(file) + * #=> @:1> + * * path = File.expand_path("test.rb") * RubyVM::InstructionSequence.compile(File.read(path), path, path) * #=> @/absolute/path/to/test.rb:1> -- cgit v1.2.3