Skip to content

Commit

Permalink
Support Ruby 2.7's pattern matching for Layout/SpaceAroundKeyword
Browse files Browse the repository at this point in the history
This PR supports guard `if` and `unless` syntax keywords of Ruby 2.7's
pattern matching for `Layout/SpaceAroundKeyword`.

```ruby
case 42
in 42 if true
  puts 'hello'
end
```

These nodes are called `if-guard` and `unless-guard` when using guard `if` and `unless`
in pattern matching.

```ruby
% ruby-parse example.rb
(case-match
  (int 42)
  (in-pattern
    (int 42)
    (if-guard
      (true))
    (send nil :puts
      (str "hello"))) nil)
```

See below for this guard semantics:
whitequark/parser#574 (comment)
  • Loading branch information
koic authored and bbatsov committed Jun 1, 2021
1 parent 6dfcb7a commit 40e9f30
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
@@ -0,0 +1 @@
* [#9841](https://github.com/rubocop/rubocop/pull/9841): Support guard `if` and `unless` syntax keywords of Ruby 2.7's pattern matching for `Layout/SpaceAroundKeyword`. ([@koic][])
8 changes: 8 additions & 0 deletions lib/rubocop/cop/layout/space_around_keyword.rb
Expand Up @@ -69,6 +69,10 @@ def on_if(node)
check(node, %i[keyword else begin end].freeze, 'then')
end

def on_if_guard(node)
check(node, [:keyword].freeze)
end

def on_in_pattern(node)
check(node, [:keyword].freeze)
end
Expand Down Expand Up @@ -117,6 +121,10 @@ def on_zsuper(node)
check(node, [:keyword].freeze)
end

def on_unless_guard(node)
check(node, [:keyword].freeze)
end

def on_until(node)
check(node, %i[begin end keyword].freeze)
end
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/layout/space_around_keyword_spec.rb
Expand Up @@ -84,6 +84,15 @@
it_behaves_like 'missing before', 'else', 'case a; in b; ""else end',
'case a; in b; "" else end'
it_behaves_like 'missing after', 'else', 'case a; in b; else"" end', 'case a; in b; else "" end'

it_behaves_like 'missing before', 'if', 'case a; in "pattern"if "condition"; else "" end',
'case a; in "pattern" if "condition"; else "" end'
it_behaves_like 'missing after', 'if', 'case a; in "pattern" if"condition"; else "" end',
'case a; in "pattern" if "condition"; else "" end'
it_behaves_like 'missing before', 'unless', 'case a; in "pattern"unless "condition"; else "" end',
'case a; in "pattern" unless "condition"; else "" end'
it_behaves_like 'missing after', 'unless', 'case a; in "pattern" unless"condition"; else "" end',
'case a; in "pattern" unless "condition"; else "" end'
end

it_behaves_like 'missing before', 'elsif', 'if a; ""elsif b; end', 'if a; "" elsif b; end'
Expand Down

0 comments on commit 40e9f30

Please sign in to comment.