From 9180e33ca3a5886fec3f9e0a2f48072b55914e65 Mon Sep 17 00:00:00 2001 From: Koichi Sasada Date: Wed, 27 Mar 2024 07:29:38 +0900 Subject: show warning for unused block With verbopse mode (-w), the interpreter shows a warning if a block is passed to a method which does not use the given block. Warning on: * the invoked method is written in C * the invoked method is not `initialize` * not invoked with `super` * the first time on the call-site with the invoked method (`obj.foo{}` will be warned once if `foo` is same method) [Feature #15554] `Primitive.attr! :use_block` is introduced to declare that primitive functions (written in C) will use passed block. For minitest, test needs some tweak, so use https://github.com/minitest/minitest/commit/ea9caafc0754b1d6236a490d59e624b53209734a for `test-bundled-gems`. --- test/ruby/test_method.rb | 59 ++++++++++++++++++++++++++++++++++++++++++ test/ruby/test_optimization.rb | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) (limited to 'test/ruby') diff --git a/test/ruby/test_method.rb b/test/ruby/test_method.rb index ec06f4c50a..67b3e03e10 100644 --- a/test/ruby/test_method.rb +++ b/test/ruby/test_method.rb @@ -1623,4 +1623,63 @@ class TestMethod < Test::Unit::TestCase end RUBY end + + def test_warn_unused_block + assert_in_out_err '-w', <<-'RUBY' do |_out, err, _status| + def foo = nil + foo{} # warn + send(:foo){} # warn + b = Proc.new{} + foo(&b) # warn + RUBY + assert_equal 3, err.size + err = err.join + assert_match(/-:2: warning/, err) + assert_match(/-:3: warning/, err) + assert_match(/-:5: warning/, err) + end + + assert_in_out_err '-w', <<-'RUBY' do |_out, err, _status| + def foo = nil + 10.times{foo{}} # warn once + RUBY + assert_equal 1, err.size + end + + assert_in_out_err '-w', <<-'RUBY' do |_out, err, _status| + def foo = nil; b = nil + foo(&b) # no warning + 1.object_id{} # no warning because it is written in C + + class C + def initialize + end + end + C.new{} # no warning + + RUBY + assert_equal 0, err.size + end + + assert_in_out_err '-w', <<-'RUBY' do |_out, err, _status| + class C0 + def foo = nil + def bar = nil + def baz = nil + end + + class C1 < C0 + def foo = super + def bar = super() + def baz(&_) = super(&_) + end + + C1.new.foo{} # no warning + C1.new.bar{} # warning + C1.new.baz{} # no warning + RUBY + assert_equal 1, err.size + assert_match(/-:14: warning.+bar/, err.join) + end + end end diff --git a/test/ruby/test_optimization.rb b/test/ruby/test_optimization.rb index 70b6bde6ed..44ec615405 100644 --- a/test/ruby/test_optimization.rb +++ b/test/ruby/test_optimization.rb @@ -577,7 +577,7 @@ class TestRubyOptimization < Test::Unit::TestCase begin; class String undef freeze - def freeze + def freeze(&) block_given? end end -- cgit v1.2.3