From dc23581d65e1c094f119ca7e00a131927da21594 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 10 Jul 2021 01:53:35 +0900 Subject: [PATCH] Add doc and spec for `empty-else` node Follow https://github.com/whitequark/parser/pull/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. --- lib/rubocop/ast/node/case_match_node.rb | 1 + spec/rubocop/ast/case_match_node_spec.rb | 13 +++++++++++++ spec/rubocop/ast/case_node_spec.rb | 13 +++++++++++++ 3 files changed, 27 insertions(+) diff --git a/lib/rubocop/ast/node/case_match_node.rb b/lib/rubocop/ast/node/case_match_node.rb index 393a5b8d2..cd6cf8782 100644 --- a/lib/rubocop/ast/node/case_match_node.rb +++ b/lib/rubocop/ast/node/case_match_node.rb @@ -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] diff --git a/spec/rubocop/ast/case_match_node_spec.rb b/spec/rubocop/ast/case_match_node_spec.rb index 81af40541..b2255f14a 100644 --- a/spec/rubocop/ast/case_match_node_spec.rb +++ b/spec/rubocop/ast/case_match_node_spec.rb @@ -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 diff --git a/spec/rubocop/ast/case_node_spec.rb b/spec/rubocop/ast/case_node_spec.rb index fd49cc883..8f5af4ac2 100644 --- a/spec/rubocop/ast/case_node_spec.rb +++ b/spec/rubocop/ast/case_node_spec.rb @@ -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