Bug #22629
closedTracePoint :class / :end events are not fired for class << self when compiled with Prism
Description
When code is compiled with Prism (the default since Ruby 3.4), entering and leaving a singleton class body (class << obj ... end) does not fire the :class and :end TracePoint events. The parse.y compiler does fire them.
Reproduction¶
events = []
tp = TracePoint.new(:class, :end) { |t| events << [t.event, t.self] }
tp.enable do
class Foo
class << self
def bar; end
end
end
end
events.each { |event, mod| puts "#{event} #{mod.inspect}" }
puts RUBY_DESCRIPTION
Expected (--parser=parse.y)¶
Actual (--parser=prism, the default)¶
Affected versions¶
| version | parse.y | prism |
|---|---|---|
| 3.3.6 | 4 events | 0 events (the Prism compiler was experimental then and fired no :class/:end at all) |
| 3.4.10 | 4 events | 2 events |
| 4.0.10 | 4 events | 2 events |
| master (bf888872d4) | 4 events | 2 events |
Cause¶
compile.c emits RUBY_EVENT_CLASS and RUBY_EVENT_END for every ISEQ_TYPE_CLASS iseq. That covers class, module and singleton class bodies. pm_compile_scope_node in prism_compile.c keys these events on the AST node type instead. It checks only PM_CLASS_NODE and PM_MODULE_NODE and leaves out PM_SINGLETON_CLASS_NODE. This looks like a gap left by the fix for https://github.com/ruby/prism/issues/2662.
Fix¶
Adding PM_SINGLETON_CLASS_NODE to both conditions makes the events and their lineno values match parse.y. A patch with a regression test in test/ruby/test_settracefunc.rb is attached and will also be submitted as a pull request.
- if (PM_NODE_TYPE_P(scope_node->ast_node, PM_CLASS_NODE) || PM_NODE_TYPE_P(scope_node->ast_node, PM_MODULE_NODE)) {
+ if (PM_NODE_TYPE_P(scope_node->ast_node, PM_CLASS_NODE) || PM_NODE_TYPE_P(scope_node->ast_node, PM_MODULE_NODE) || PM_NODE_TYPE_P(scope_node->ast_node, PM_SINGLETON_CLASS_NODE)) {
(The same change applies to both the RUBY_EVENT_CLASS site and the RUBY_EVENT_END site.)
Files
Updated by divide (Rafał Rzepecki) 5 days ago
· Edited
The pull request is at https://github.com/ruby/ruby/pull/20095
Note I can't seem to be able to edit the backports field, but I'd appreciate a backport to 3.4 and 4.0 because it makes some traces unreliable in an instrumentation project I'm working on, which people could use with multiple versions of Ruby.
Updated by divide (Rafał Rzepecki) 5 days ago
- Status changed from Open to Closed
Applied in changeset git|e9ce844bbb4ffc0f28395c36b7cc84e038551dd2.
[Bug #22629] Fire :class/:end TracePoint events for class << obj with Prism
The parse.y-based compiler emits RUBY_EVENT_CLASS and RUBY_EVENT_END
for every ISEQ_TYPE_CLASS iseq, which includes singleton class bodies.
The Prism compiler instead keys these events on the AST node type and
only handled PM_CLASS_NODE and PM_MODULE_NODE, so class << obj
bodies never fired :class or :end.
Also handle PM_SINGLETON_CLASS_NODE so both compilers agree.