Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ast.rb: RubyVM::AST.parse and .of accepts save_script_lines: true #4581

Merged
merged 2 commits into from
Jun 17, 2021

Conversation

mame
Copy link
Member

@mame mame commented Jun 17, 2021

Synopsis:

node = RubyVM::AbstractSyntaxTree.parse(<<END, save_script_lines: true)
puts 'Hello', 'world'
__END__
foobar
END

p node.script_lines #=> ["puts 'Hello', 'world'\n", "__END__\n"]

p node.source                                            #=> "puts 'Hello', 'world'"
p node.children.last.children.last.source                #=> "'Hello', 'world'"
p node.children.last.children.last.children.first.source #=> "'Hello'"

This option makes the parser keep the original source as an array of
the original code lines. This feature exploits the mechanism of
SCRIPT_LINES__ but records only the specified code that is passed to
RubyVM::AST.of or .parse, instead of recording all parsed program texts.

RubyVM::AST::Node instances created with save_script_lines: true
option respond to #script_lines and #source. The former returns
the whole original source code as an array of the lines. The latter returns
the code fragment that corresponds to this AST.
Note that RubyVM::AST is just for ruby internal use, so the compatibility
of the methods is never guaranteed.

This changeset is approved by @matz .

This option makes the parser keep the original source as an array of
the original code lines. This feature exploits the mechanism of
`SCRIPT_LINES__` but records only the specified code that is passed to
RubyVM::AST.of or .parse, instead of recording all parsed program texts.
@mame mame force-pushed the ruby-ast-save_script_lines branch from 72414b4 to 48a5a83 Compare June 17, 2021 16:00
by merging `rb_ast_body_t#line_count` and `#script_lines`.

Fortunately `line_count == RARRAY_LEN(script_lines)` was always
satisfied. When script_lines is saved, it has an array of lines, and
when not saved, it has a Fixnum that represents the old line_count.
@mame mame force-pushed the ruby-ast-save_script_lines branch from 6ab154b to 869eff8 Compare June 17, 2021 16:43
@mame mame merged commit fb01411 into ruby:master Jun 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant