Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/variable.c
Original file line number Diff line number Diff line change
Expand Up @@ -1747,15 +1747,20 @@ const_missing(mrb_state *mrb, struct RClass *base, mrb_sym sym)
return mrb_funcall_argv(mrb, mod, MRB_SYM(const_missing), 1, &name);
}

/* *cachep, unless NULL, is cleared when the constant is deprecated */
/* *cachep, unless NULL, is cleared when the constant is deprecated, or
when const_missing answers for it: the hook is called for each read, as
in CRuby, and what it gives is not the constant */
static mrb_value
const_get(mrb_state *mrb, struct RClass *base, mrb_sym sym, mrb_bool skip, mrb_bool *cachep)
{
struct RClass *owner;
mrb_value v = const_get_nohook(mrb, base, sym, skip, TRUE, &owner);

/* call const_missing hook */
if (mrb_undef_p(v)) return const_missing(mrb, base, sym);
if (mrb_undef_p(v)) {
if (cachep) *cachep = FALSE;
return const_missing(mrb, base, sym);
}
if (const_warn_deprecated(mrb, owner, sym, v) && cachep) *cachep = FALSE;
return v;
}
Expand Down Expand Up @@ -1844,7 +1849,7 @@ lexical_scope_p(mrb_state *mrb, const struct RProc *proc)
}

/* the constant `sym` a lexical read finds; *cachep is cleared when it is
deprecated, so that each read warns */
deprecated, so that each read warns, or when const_missing gives it */
mrb_value
mrb_vm_const_get(mrb_state *mrb, mrb_sym sym, mrb_bool *cachep)
{
Expand Down
3 changes: 2 additions & 1 deletion src/vm.c
Original file line number Diff line number Diff line change
Expand Up @@ -3721,7 +3721,8 @@ mrb_vm_exec(mrb_state *mrb, const struct RProc *begin_proc, const mrb_code *iseq
ci = mrb->c->ci;
regs[a] = v;
#ifndef MRB_NO_CONST_CACHE
/* a deprecated constant is not cached, so each read warns */
/* neither a deprecated constant, so that each read warns, nor what
const_missing gives, so that each read calls it, is cached */
if (cache) {
cc->irep = irep;
cc->sym = sym;
Expand Down
14 changes: 14 additions & 0 deletions test/t/module.rb
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,20 @@ def self.const_missing(sym)
assert_equal 42, Test4ConstMissing.const_get(:ConstDoesntExist)
end

assert('Module#const_missing is called for each lexical read') do
module Test4ConstMissingEach
@n = 0
def self.const_missing(sym) = (@n += 1)
def self.read = Missing
end

assert_equal 1, Test4ConstMissingEach.read
assert_equal 2, Test4ConstMissingEach.read
# and the constant, once it is set, is what the read gives
Test4ConstMissingEach.const_set(:Missing, :set)
assert_equal :set, Test4ConstMissingEach.read
end

assert('Module#include', '15.2.2.4.27') do
module Test4Include
Const4Include = 42
Expand Down
Loading