From ca2da262ef1dcbda19cb2830d3667c5797e0d9ee Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 22 Oct 2020 19:03:51 +0900 Subject: [PATCH] Make `SendNode#macro?` aware of struct constructor This PR makes `SendNode#macro?` and `RuboCop::AST::Node#class_constructor?` aware of struct constructor and `RuboCop::AST::Node#struct_constructor?` is deprecated. Like class constructor, struct constructor will be recognized as a macro and will be awakened in the following `private` modifier: ```ruby Foo = Struct.new(:foo) do private def private_foo foo end end ``` With this change, this PR aims to resolve the following issue. https://github.com/rubocop-hq/rubocop/issues/8919 --- CHANGELOG.md | 4 ++++ lib/rubocop/ast/node.rb | 5 +++-- spec/rubocop/ast/send_node_spec.rb | 11 +++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd295eb4f..da7a23935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#141](https://github.com/rubocop-hq/rubocop-ast/pull/141): Make `SendNode#macro?` and `RuboCop::AST::Node#class_constructor?` aware of struct constructor and `RuboCop::AST::Node#struct_constructor?` is deprecated. ([@koic][]) + ## 1.0.0 (2020-10-21) ### Changes diff --git a/lib/rubocop/ast/node.rb b/lib/rubocop/ast/node.rb index 996e84e8d..ac33f8848 100644 --- a/lib/rubocop/ast/node.rb +++ b/lib/rubocop/ast/node.rb @@ -484,10 +484,11 @@ def guard_clause? def_node_matcher :global_const?, '(const {nil? cbase} %1)' def_node_matcher :class_constructor?, <<~PATTERN - { (send #global_const?({:Class :Module}) :new ...) - (block (send #global_const?({:Class :Module}) :new ...) ...)} + { (send #global_const?({:Class :Module :Struct}) :new ...) + (block (send #global_const?({:Class :Module :Struct}) :new ...) ...)} PATTERN + # @deprecated Use `:class_constructor?` def_node_matcher :struct_constructor?, <<~PATTERN (block (send #global_const?(:Struct) :new ...) _ $_) PATTERN diff --git a/spec/rubocop/ast/send_node_spec.rb b/spec/rubocop/ast/send_node_spec.rb index b81d4b7a8..c8076e066 100644 --- a/spec/rubocop/ast/send_node_spec.rb +++ b/spec/rubocop/ast/send_node_spec.rb @@ -242,6 +242,17 @@ module Foo it { expect(send_node).to be_macro } end + context 'when parent is a struct constructor' do + let(:source) do + ['Foo = Struct.new do', + '>>bar :baz<<', + ' bar :qux', + 'end'].join("\n") + end + + it { expect(send_node).to be_macro } + end + context 'when parent is a singleton class' do let(:source) do ['class << self',