Skip to content

Commit a641746

Browse files
authored
Fix undef and alias indent (#838)
1 parent 343b08f commit a641746

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

lib/irb/nesting_parser.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ def self.scan_opens(tokens)
1212
skip = false
1313
last_tok, state, args = opens.last
1414
case state
15+
when :in_alias_undef
16+
skip = t.event == :on_kw
1517
when :in_unquoted_symbol
1618
unless IGNORE_TOKENS.include?(t.event)
1719
opens.pop
@@ -130,6 +132,10 @@ def self.scan_opens(tokens)
130132
opens.pop
131133
opens << [t, nil]
132134
end
135+
when 'alias'
136+
opens << [t, :in_alias_undef, 2]
137+
when 'undef'
138+
opens << [t, :in_alias_undef, 1]
133139
when 'elsif', 'else', 'when'
134140
opens.pop
135141
opens << [t, nil]
@@ -174,6 +180,10 @@ def self.scan_opens(tokens)
174180
pending_heredocs.reverse_each { |t| opens << [t, nil] }
175181
pending_heredocs = []
176182
end
183+
if opens.last && opens.last[1] == :in_alias_undef && !IGNORE_TOKENS.include?(t.event) && t.event != :on_heredoc_end
184+
tok, state, arg = opens.pop
185+
opens << [tok, state, arg - 1] if arg >= 1
186+
end
177187
yield t, opens if block_given?
178188
end
179189
opens.map(&:first) + pending_heredocs.reverse

lib/irb/ruby-lex.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def calc_indent_level(opens)
290290
when :on_embdoc_beg
291291
indent_level = 0
292292
else
293-
indent_level += 1
293+
indent_level += 1 unless t.tok == 'alias' || t.tok == 'undef'
294294
end
295295
end
296296
indent_level

test/irb/test_nesting_parser.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,44 @@ def test_while_until
280280
end
281281
end
282282

283+
def test_undef_alias
284+
codes = [
285+
'undef foo',
286+
'alias foo bar',
287+
'undef !',
288+
'alias + -',
289+
'alias $a $b',
290+
'undef do',
291+
'alias do do',
292+
'undef :do',
293+
'alias :do :do',
294+
'undef :"#{alias do do}"',
295+
'alias :"#{undef do}" do',
296+
'alias do :"#{undef do}"'
297+
]
298+
code_with_comment = <<~EOS
299+
undef #
300+
#
301+
do #
302+
alias #
303+
#
304+
do #
305+
#
306+
do #
307+
EOS
308+
code_with_heredoc = <<~EOS
309+
<<~A; alias
310+
A
311+
:"#{<<~A}"
312+
A
313+
do
314+
EOS
315+
[*codes, code_with_comment, code_with_heredoc].each do |code|
316+
opens = IRB::NestingParser.open_tokens(IRB::RubyLex.ripper_lex_without_warning('(' + code + "\nif"))
317+
assert_equal(%w[( if], opens.map(&:tok))
318+
end
319+
end
320+
283321
def test_case_in
284322
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.7.0')
285323
pend 'This test requires ruby version that supports case-in syntax'

0 commit comments

Comments
 (0)