Skip to content

Commit

Permalink
[ruby/irb] Fix crashing when multiple open braces per line
Browse files Browse the repository at this point in the history
ruby/irb#55

If we had put multiple open braces on a line the with no closing brace
spaces_of_nest array keeps getting '0' added to it. This means that when
we pop off of this array we are saying that we should be in position zero
for the next line. This is an issue because we don't always want to be
in position 0 after a closing brace.

Example:
```
[[[
]
]
]
```
In the above example the 'spaces_of_nest' array looks like this after
the first line is entered: [0,0,0]. We really want to be indented 4
spaces for the 1st closing brace 2 for the 2nd and 0 for the 3rd. i.e.
we want it to be: [0,2,4].

We also saw this issue with a heredoc inside of an array.

```
[<<FOO]
hello
FOO
```

ruby/irb@80c69c8272
  • Loading branch information
BenKanouse authored and aycabta committed Jan 14, 2020
1 parent 9994eb8 commit c94025b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/irb/ruby-lex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -368,13 +368,15 @@ def check_corresponding_token_depth
is_first_printable_of_line = true
spaces_of_nest = []
spaces_at_line_head = 0
open_brace_on_line = 0
@tokens.each_with_index do |t, index|
case t[1]
when :on_ignored_nl, :on_nl, :on_comment
corresponding_token_depth = nil
spaces_at_line_head = 0
is_first_spaces_of_line = true
is_first_printable_of_line = true
open_brace_on_line = 0
next
when :on_sp
spaces_at_line_head = t[2].count(' ') if is_first_spaces_of_line
Expand All @@ -383,7 +385,8 @@ def check_corresponding_token_depth
end
case t[1]
when :on_lbracket, :on_lbrace, :on_lparen
spaces_of_nest.push(spaces_at_line_head)
spaces_of_nest.push(spaces_at_line_head + open_brace_on_line * 2)
open_brace_on_line += 1
when :on_rbracket, :on_rbrace, :on_rparen
if is_first_printable_of_line
corresponding_token_depth = spaces_of_nest.pop
Expand Down
19 changes: 19 additions & 0 deletions test/irb/test_ruby_lex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,24 @@ def test_braces_on_thier_own_line
assert_indenting(lines, row.new_line_spaces, true)
end
end

def test_multiple_braces_in_a_line
input_with_correct_indents = [
Row.new(%q([[[), nil, 6),
Row.new(%q( ]), 4, 4),
Row.new(%q( ]), 2, 2),
Row.new(%q(]), 0, 0),
Row.new(%q([<<FOO]), nil, 0),
Row.new(%q(hello), nil, 0),
Row.new(%q(FOO), nil, 0),
]

lines = []
input_with_correct_indents.each do |row|
lines << row.content
assert_indenting(lines, row.current_line_spaces, false)
assert_indenting(lines, row.new_line_spaces, true)
end
end
end
end

0 comments on commit c94025b

Please sign in to comment.