Skip to content

Commit

Permalink
Merge pull request #1495 from dduugg/heredoc-conversion
Browse files Browse the repository at this point in the history
Fix heredoc-to-string conversion
  • Loading branch information
lsegal committed Aug 26, 2024
2 parents d1bc910 + 8f14413 commit 714e850
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
23 changes: 19 additions & 4 deletions lib/yard/parser/ruby/legacy/ruby_lex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ def lex_init()
if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
(@lex_state != EXPR_ARG || @space_seen)
c = peek(0)
tk = identify_here_document if /[-\w\"\'\`]/ =~ c
tk = identify_here_document if /[-~\w\"\'\`]/ =~ c
end
if !tk
@lex_state = EXPR_BEG
Expand Down Expand Up @@ -1063,6 +1063,8 @@ def identify_here_document
ch = getc
if ch == "-"
ch = getc
elsif ch == "~"
ch = getc
indent = true
end
if /['"`]/ =~ ch # '
Expand Down Expand Up @@ -1096,9 +1098,12 @@ def identify_here_document
str = String.new
while (l = gets)
l.chomp!
l.strip! if indent
break if l == quoted
str << l.chomp << "\n"
if l == quoted
str = dedent(str) if indent
break
else
str << l.chomp << "\n"
end
end

@reader.divert_read_from(reserve)
Expand All @@ -1108,6 +1113,16 @@ def identify_here_document
Token(Ltype2Token[lt], str).set_text(str.dump)
end

def dedent(str)
lines = str.split("\n", -1)
dedent_amt = lines.map do |line|
line =~ /\S/ ? line.match(/^ */).offset(0)[1] : nil
end.compact.min || 0
return str if dedent_amt.zero?

lines.map { |line| line =~ /\S/ ? line.gsub(/^ {#{dedent_amt}}/, "") : line }.join("\n")
end

def identify_quotation(initial_char)
ch = getc
if lt = PERCENT_LTYPE[ch]
Expand Down
8 changes: 7 additions & 1 deletion spec/parser/ruby/legacy/statement_list_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,12 @@ class B; end
it "converts heredoc to string" do
src = "<<-XML\n foo\n\nXML"
s = stmt(src)
expect(s.source).to eq '"foo\n\n"'
expect(s.source).to eq '" foo\n\n"'
end

it "converts squiggly heredoc to string" do
src = "<<~XML\n bar\n\nXML"
s = stmt(src)
expect(s.source).to eq '"bar\n\n"'
end
end

0 comments on commit 714e850

Please sign in to comment.