Skip to content

Commit 714e850

Browse files
authored
Merge pull request #1495 from dduugg/heredoc-conversion
Fix heredoc-to-string conversion
2 parents d1bc910 + 8f14413 commit 714e850

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

lib/yard/parser/ruby/legacy/ruby_lex.rb

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -656,7 +656,7 @@ def lex_init()
656656
if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
657657
(@lex_state != EXPR_ARG || @space_seen)
658658
c = peek(0)
659-
tk = identify_here_document if /[-\w\"\'\`]/ =~ c
659+
tk = identify_here_document if /[-~\w\"\'\`]/ =~ c
660660
end
661661
if !tk
662662
@lex_state = EXPR_BEG
@@ -1063,6 +1063,8 @@ def identify_here_document
10631063
ch = getc
10641064
if ch == "-"
10651065
ch = getc
1066+
elsif ch == "~"
1067+
ch = getc
10661068
indent = true
10671069
end
10681070
if /['"`]/ =~ ch # '
@@ -1096,9 +1098,12 @@ def identify_here_document
10961098
str = String.new
10971099
while (l = gets)
10981100
l.chomp!
1099-
l.strip! if indent
1100-
break if l == quoted
1101-
str << l.chomp << "\n"
1101+
if l == quoted
1102+
str = dedent(str) if indent
1103+
break
1104+
else
1105+
str << l.chomp << "\n"
1106+
end
11021107
end
11031108

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

1116+
def dedent(str)
1117+
lines = str.split("\n", -1)
1118+
dedent_amt = lines.map do |line|
1119+
line =~ /\S/ ? line.match(/^ */).offset(0)[1] : nil
1120+
end.compact.min || 0
1121+
return str if dedent_amt.zero?
1122+
1123+
lines.map { |line| line =~ /\S/ ? line.gsub(/^ {#{dedent_amt}}/, "") : line }.join("\n")
1124+
end
1125+
11111126
def identify_quotation(initial_char)
11121127
ch = getc
11131128
if lt = PERCENT_LTYPE[ch]

spec/parser/ruby/legacy/statement_list_spec.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,12 @@ class B; end
294294
it "converts heredoc to string" do
295295
src = "<<-XML\n foo\n\nXML"
296296
s = stmt(src)
297-
expect(s.source).to eq '"foo\n\n"'
297+
expect(s.source).to eq '" foo\n\n"'
298+
end
299+
300+
it "converts squiggly heredoc to string" do
301+
src = "<<~XML\n bar\n\nXML"
302+
s = stmt(src)
303+
expect(s.source).to eq '"bar\n\n"'
298304
end
299305
end

0 commit comments

Comments
 (0)