Constant access on `nil`
It is possible to access top-level constants by doing
nil::CONSTANT, which looks like a bug according to Matz. Here are a couple of examples:
$ ruby -ve "Foo = 123; p nil::Foo" ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux] 123
$ ruby -ve "class A; Foo = 456; end; p nil::A::Foo" ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux] 456
Updated by elia (Elia Schito) almost 6 years ago
looks like it's somehow intended behavior
/** @c variable @e Get constant variable id. If klass is Qnil, constants are searched in the current scope. If klass is Qfalse, constants are searched as top level constants. Otherwise, get constant under klass class or module. @j 定数 id の値を得る。 klass が Qnil なら、そのスコープで得られる定数の値を得る。 Qfalse なら、トップレベルスコープを得る。 それ以外なら、klass クラスの下の定数を得る。 */
apparently introduced here: https://github.com/ruby/ruby/commit/d84f9b16946bca06ce0557ebe99152d7d445c9ec to resolve bug #10943
Updated by jeremyevans0 (Jeremy Evans) about 2 years ago
This bug is still present in the master branch. Attached is a patch that fixes it. It adds a second argument to the getconstant instruction. It would probably be better for performance to add a separate instruction for the case where this is needed, but I'm not sure it is worth it. With the patch:
nil::Object # TypeError (nil is not a class/module)
Updated by jeremyevans (Jeremy Evans) about 2 years ago
- Status changed from Open to Closed
Applied in changeset git|fbcd0652944568c43a6ae427960d909d62ce6a8d.
Remove support for nil::Constant
This was an intentional bug added in 1.9.
The approach taken here is to add a second operand to the
getconstant instruction for whether nil should be allowed and
treated as current scope.
Fixes [Bug #11718]