From 1ad366134ded1667745dd9fa70919051869f8d6c Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Thu, 22 Feb 2024 22:25:12 +0900 Subject: [PATCH] [Feature #20293] Add `Warning.categories` --- error.c | 21 +++++++++++++++++++++ test/ruby/test_rubyoptions.rb | 3 ++- tool/lib/envutil.rb | 4 +++- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/error.c b/error.c index 5d1cbcc8da..9c5b70d1d6 100644 --- a/error.c +++ b/error.c @@ -252,6 +252,26 @@ rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag) return flag; } +/* + * call-seq: + * categories -> array + * + * Returns a list of the supported category symbols. + */ + +static VALUE +rb_warning_s_categories(VALUE mod) +{ + st_index_t num = warning_categories.id2enum->num_entries; + ID *ids = ALLOCA_N(ID, num); + num = st_keys(warning_categories.id2enum, ids, num); + VALUE ary = rb_ary_new_capa(num); + for (st_index_t i = 0; i < num; ++i) { + rb_ary_push(ary, ID2SYM(ids[i])); + } + return rb_ary_freeze(ary); +} + /* * call-seq: * warn(msg, category: nil) -> nil @@ -3413,6 +3433,7 @@ Init_Exception(void) rb_mWarning = rb_define_module("Warning"); rb_define_singleton_method(rb_mWarning, "[]", rb_warning_s_aref, 1); rb_define_singleton_method(rb_mWarning, "[]=", rb_warning_s_aset, 2); + rb_define_singleton_method(rb_mWarning, "categories", rb_warning_s_categories, 0); rb_define_method(rb_mWarning, "warn", rb_warning_s_warn, -1); rb_extend_object(rb_mWarning, rb_mWarning); diff --git a/test/ruby/test_rubyoptions.rb b/test/ruby/test_rubyoptions.rb index d5626a1a94..29810d5dd7 100644 --- a/test/ruby/test_rubyoptions.rb +++ b/test/ruby/test_rubyoptions.rb @@ -112,7 +112,8 @@ class TestRubyOptions < Test::Unit::TestCase assert_in_out_err(%w(-We) + ['p $-W'], "", %w(2), []) assert_in_out_err(%w(-w -W0 -e) + ['p $-W'], "", %w(0), []) - categories = {"deprecated"=>1, "experimental"=>0, "performance"=>2} + categories = {deprecated: 1, experimental: 0, performance: 2} + assert_equal categories.keys.sort, Warning.categories.sort categories.each do |category, level| assert_in_out_err(["-W:#{category}", "-e", "p Warning[:#{category}]"], "", %w(true), []) diff --git a/tool/lib/envutil.rb b/tool/lib/envutil.rb index a2ddf74052..642965047f 100644 --- a/tool/lib/envutil.rb +++ b/tool/lib/envutil.rb @@ -53,7 +53,9 @@ module EnvUtil @original_external_encoding = Encoding.default_external @original_verbose = $VERBOSE @original_warning = - if defined?(Warning.[]) # 2.7+ + if defined?(Warning.categories) + Warning.categories.to_h {|i| [i, Warning[i]]} + elsif defined?(Warning.[]) # 2.7+ %i[deprecated experimental performance].to_h do |i| [i, begin Warning[i]; rescue ArgumentError; end] end.compact