Skip to content

Commit

Permalink
Add doc and spec for empty-else node
Browse files Browse the repository at this point in the history
Follow whitequark/parser#652.

This PR adds doc and spec for `empty-else` node.

Below is a description of `empty-else` node.

> Empty `else` differs from the missing (or _implicit_) `else` for pattern
> matching, since
> the latter one raises a `NoMatchingPattern` exception. Thus, we need a
> way to distinguish this two cases in the resulting AST.

https://github.com/whitequark/parser/blob/v3.0.1.1/doc/AST_FORMAT.md#with-empty-else

Below are the differences between each AST (`empty-else` only appears in the last case).

```console
% ruby-parse -e 'case foo; when bar; end'
(case
  (send nil :foo)
  (when
    (send nil :bar) nil) nil)

% ruby-parse -e 'case foo; when bar; else; end'
(case
  (send nil :foo)
  (when
    (send nil :bar) nil) nil)

% ruby-parse -e 'case foo; in bar; end'
(case-match
  (send nil :foo)
  (in-pattern
    (match-var :bar) nil nil) nil)

% ruby-parse -e 'case foo; in bar; else; end'
(case-match
  (send nil :foo)
  (in-pattern
    (match-var :bar) nil nil)
  (empty-else))
```

This PR has also added a spec for `CaseNode` to clarify the difference in behavior.
  • Loading branch information
koic authored and marcandre committed Jul 17, 2021
1 parent f6b6075 commit dc23581
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/rubocop/ast/node/case_match_node.rb
Expand Up @@ -47,6 +47,7 @@ def branches
# Returns the else branch of the `case` statement, if any.
#
# @return [Node] the else branch node of the `case` statement
# @return [EmptyElse] the empty else branch node of the `case` statement
# @return [nil] if the case statement does not have an else branch.
def else_branch
node_parts[-1]
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/ast/case_match_node_spec.rb
Expand Up @@ -125,6 +125,19 @@

it { expect(case_match_node.else_branch).to be_sym_type }
end

context 'with an empty else statement' do
let(:source) do
<<~RUBY
case expr
in pattern
else
end
RUBY
end

it { expect(case_match_node.else_branch).to be_empty_else_type }
end
end
end

Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/ast/case_node_spec.rb
Expand Up @@ -104,6 +104,19 @@

it { expect(case_node.else_branch).to be_sym_type }
end

context 'with an empty else statement' do
let(:source) do
<<~RUBY
case
when :foo then :bar
else
end
RUBY
end

it { expect(case_node.else_branch).to be_nil }
end
end
end

Expand Down

0 comments on commit dc23581

Please sign in to comment.