Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Prism::Translation::Parser::Compiler#visit_heredoc
visit_heredoc(node) { |children, closing_t| ... }
lib/prism/translation/parser/compiler.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/lib/prism/translation/parser/compiler.rb, line 2061
def visit_heredoc(node)
children = Array.new
indented = false
# If this is a dedenting heredoc, then we need to insert the opening
# content into the children as well.
if node.opening.start_with?("<<~") && node.parts.length > 0 && !node.parts.first.is_a?(StringNode)
location = node.parts.first.location
location = location.copy(start_offset: location.start_offset - location.start_line_slice.bytesize)
children << builder.string_internal(token(location))
indented = true
end
node.parts.each do |part|
pushing =
if part.is_a?(StringNode) && part.unescaped.include?("\n")
unescaped = part.unescaped.lines
escaped = part.content.lines
escaped_lengths = []
normalized_lengths = []
if node.opening.end_with?("'")
escaped.each do |line|
escaped_lengths << line.bytesize
normalized_lengths << chomped_bytesize(line)
end
else
escaped
.chunk_while { |before, after| before.match?(/(?<!\\)\\\r?\n$/) }
.each do |lines|
escaped_lengths << lines.sum(&:bytesize)
normalized_lengths << lines.sum { |line| chomped_bytesize(line) }
end
end
start_offset = part.location.start_offset
unescaped.map.with_index do |unescaped_line, index|
inner_part = builder.string_internal([unescaped_line, srange_offsets(start_offset, start_offset + normalized_lengths.fetch(index, 0))])
start_offset += escaped_lengths.fetch(index, 0)
inner_part
end
else
[visit(part)]
end
pushing.each do |child|
if child.type == :str && child.children.last == ""
# nothing
elsif child.type == :str && children.last && children.last.type == :str && !children.last.children.first.end_with?("\n")
appendee = children[-1]
location = appendee.loc
location = location.with_expression(location.expression.join(child.loc.expression))
children[-1] = appendee.updated(:str, [appendee.children.first << child.children.first], location: location)
else
children << child
end
end
end
closing = node.closing
closing_t = [closing.chomp, srange_offsets(node.closing_loc.start_offset, node.closing_loc.end_offset - (closing[/\s+$/]&.length || 0))]
composed = yield children, closing_t
composed = composed.updated(nil, children[1..-1]) if indented
composed
end
Visit a heredoc that can be either a string or an xstring.