From 2186dc33696e2aa5e74de7634f15c8701e7956e5 Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Wed, 30 Sep 2020 00:10:04 -0400 Subject: [PATCH] [Fixes #117] Future-proof `Traversal` by detecting unknown Node types --- .../fix_futureproof_traversal_by_detecting.md | 1 + lib/rubocop/ast/traversal.rb | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 changelog/fix_futureproof_traversal_by_detecting.md diff --git a/changelog/fix_futureproof_traversal_by_detecting.md b/changelog/fix_futureproof_traversal_by_detecting.md new file mode 100644 index 000000000..0f1bdd1b6 --- /dev/null +++ b/changelog/fix_futureproof_traversal_by_detecting.md @@ -0,0 +1 @@ +* [#117](https://github.com/rubocop-hq/rubocop-ast/pull/117): Future-proof `AST::Traversal` by detecting unknown `Node` types. ([@marcandre][]) diff --git a/lib/rubocop/ast/traversal.rb b/lib/rubocop/ast/traversal.rb index 0e02d8e5b..2df9e39b0 100644 --- a/lib/rubocop/ast/traversal.rb +++ b/lib/rubocop/ast/traversal.rb @@ -201,6 +201,27 @@ def on_numblock(node) send(TYPE_TO_METHOD[child.type], child) end + + defined = instance_methods(false) + .grep(/^on_/) + .map { |s| s.to_s[3..-1].to_sym } # :on_foo => :foo + + to_define = ::Parser::Meta::NODE_TYPES.to_a + to_define -= defined + to_define -= %i[numargs ident] # transient + to_define -= %i[blockarg_expr restarg_expr] # obsolete + to_define -= %i[objc_kwarg objc_restarg objc_varargs] # mac_ruby + to_define.each do |type| + module_eval(<<~RUBY, __FILE__, __LINE__ + 1) + def on_#{type}(node) + node.children.each do |child| + next unless child.class == Node + send(TYPE_TO_METHOD[child.type], child) + end + nil + end + RUBY + end end end end