From 37e7b987160ce8688c9a0acf06e0ba96efbe0916 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 17 Oct 2019 15:41:06 -0700 Subject: [PATCH] Refine error message for subclassing a non-class Previously, code such as: ```ruby class C1; end class C2 < C1.new; end ``` Resulted in an error message: ``` TypeError (superclass must be a Class (C1 given)) ``` This may confuse users as C1 is a class. This changes the error message to: ``` TypeError (superclass must be an instance of Class (given an instance of C1)) ``` This makes it clear that the wrong type of of was given. Fixes [Bug #14726] --- class.c | 2 +- spec/ruby/core/class/new_spec.rb | 2 +- vm_insnhelper.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/class.c b/class.c index 010faed3eb..40f21d56cc 100644 --- a/class.c +++ b/class.c @@ -220,7 +220,7 @@ void rb_check_inheritable(VALUE super) { if (!RB_TYPE_P(super, T_CLASS)) { - rb_raise(rb_eTypeError, "superclass must be a Class (%"PRIsVALUE" given)", + rb_raise(rb_eTypeError, "superclass must be an instance of Class (given an instance of %"PRIsVALUE")", rb_obj_class(super)); } if (RBASIC(super)->flags & FL_SINGLETON) { diff --git a/spec/ruby/core/class/new_spec.rb b/spec/ruby/core/class/new_spec.rb index 8191ce6a37..aa9a1881e7 100644 --- a/spec/ruby/core/class/new_spec.rb +++ b/spec/ruby/core/class/new_spec.rb @@ -95,7 +95,7 @@ def message2; "hello"; end end it "raises a TypeError when given a non-Class" do - error_msg = /superclass must be a Class/ + error_msg = /superclass must be a.*Class/ -> { Class.new("") }.should raise_error(TypeError, error_msg) -> { Class.new(1) }.should raise_error(TypeError, error_msg) -> { Class.new(:symbol) }.should raise_error(TypeError, error_msg) diff --git a/vm_insnhelper.c b/vm_insnhelper.c index c7dd213035..437266bce7 100644 --- a/vm_insnhelper.c +++ b/vm_insnhelper.c @@ -3596,7 +3596,7 @@ vm_define_class(ID id, rb_num_t flags, VALUE cbase, VALUE super) if (VM_DEFINECLASS_HAS_SUPERCLASS_P(flags) && !RB_TYPE_P(super, T_CLASS)) { rb_raise(rb_eTypeError, - "superclass must be a Class (%"PRIsVALUE" given)", + "superclass must be an instance of Class (given an instance of %"PRIsVALUE")", rb_obj_class(super)); } -- 2.23.0