From 7c527ee52c17236f4574bdfd0227e4ebc2bf9b82 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 8 Aug 2019 09:55:33 -0700 Subject: [PATCH] Do not allow Module#include to insert modules before the origin in the lookup chain Module#include should only be able to insert modules after the origin, otherwise it ends up working like Module#prepend. This fixes the case where one of the modules in the included module chain is included in a module that is already prepended to the receiver. Fixes [Bug #7844] --- class.c | 7 ++++++- test/ruby/test_module.rb | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/class.c b/class.c index 243f8c4610..7bc76b1749 100644 --- a/class.c +++ b/class.c @@ -895,9 +895,12 @@ include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super) struct rb_id_table *const klass_m_tbl = RCLASS_M_TBL(RCLASS_ORIGIN(klass)); while (module) { + int origin_seen = FALSE; int superclass_seen = FALSE; struct rb_id_table *tbl; + if (klass == c) + origin_seen = TRUE; if (RCLASS_ORIGIN(module) != module) goto skip; if (klass_m_tbl && klass_m_tbl == RCLASS_M_TBL(module)) @@ -905,9 +908,11 @@ include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super) /* ignore if the module included already in superclasses */ for (p = RCLASS_SUPER(klass); p; p = RCLASS_SUPER(p)) { int type = BUILTIN_TYPE(p); + if (c == p) + origin_seen = TRUE; if (type == T_ICLASS) { if (RCLASS_M_TBL(p) == RCLASS_M_TBL(module)) { - if (!superclass_seen) { + if (!superclass_seen && origin_seen) { c = p; /* move insertion point */ } goto skip; diff --git a/test/ruby/test_module.rb b/test/ruby/test_module.rb index cf50db3374..accee9ca1a 100644 --- a/test/ruby/test_module.rb +++ b/test/ruby/test_module.rb @@ -469,6 +469,16 @@ def test_included_modules assert_equal([Comparable, Kernel], String.included_modules - mixins) end + def test_include_with_prepend + c = Class.new{def m; [:c] end} + p = Module.new{def m; [:p] + super end} + q = Module.new{def m; [:q] + super end; include p} + r = Module.new{def m; [:r] + super end; prepend q} + s = Module.new{def m; [:s] + super end; include r} + a = Class.new(c){def m; [:a] + super end; prepend p; include s} + assert_equal([:p, :a, :s, :q, :r, :c], a.new.m) + end + def test_instance_methods assert_equal([:user, :user2], User.instance_methods(false).sort) assert_equal([:user, :user2, :mixin].sort, User.instance_methods(true).sort) -- 2.21.0