Skip to content

Commit

Permalink
NodePattern: Allow comments
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Aug 1, 2020
1 parent 3b373c3 commit 076c11b
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -6,6 +6,7 @@

* [#70](https://github.com/rubocop-hq/rubocop-ast/pull/70): Add `NextNode` ([@marcandre][])
* [#85](https://github.com/rubocop-hq/rubocop-ast/pull/85): Add `IntNode#value` and `FloatNode#value`. ([@fatkodima][])
* [#82](https://github.com/rubocop-hq/rubocop-ast/pull/82): `NodePattern`: Allow comments ([@marcandre][])

### Bug fixes

Expand Down
16 changes: 16 additions & 0 deletions docs/modules/ROOT/pages/node_pattern.adoc
Expand Up @@ -477,6 +477,22 @@ def_node_matcher :interesting_call?, '(send _ %SOME_CALLS ...)'

Constants as arguments to custom methods are also supported.

== Comments

You may have comments in node patterns at the end of lines
by preceeding them with `'# '`:

[source,ruby]
----
def_node_matcher :complex_stuff, <<~PATTERN
(send
{#global_const?(:Kernel) nil?} # check for explicit call like Kernel.p too
{:p :pp} # let's consider `pp` also
$... # capture all arguments
)
PATTERN
----

== `nil` or `nil?`

Take a special attention to nil behavior:
Expand Down
5 changes: 4 additions & 1 deletion lib/rubocop/ast/node_pattern.rb
Expand Up @@ -99,6 +99,7 @@ module AST
# # These arguments can be patterns themselves, in
# # which case a matcher responding to === will be
# # passed.
# '# comment' # comments are accepted at the end of lines
#
# You can nest arbitrarily deep:
#
Expand All @@ -122,6 +123,8 @@ class NodePattern
class Compiler
SYMBOL = %r{:(?:[\w+@*/?!<>=~|%^-]+|\[\]=?)}.freeze
IDENTIFIER = /[a-zA-Z_][a-zA-Z0-9_-]*/.freeze
COMMENT = /#\s.*$/.freeze

META = Regexp.union(
%w"( ) { } [ ] $< < > $... $ ! ^ ` ... + * ?"
).freeze
Expand Down Expand Up @@ -788,7 +791,7 @@ def substitute_cur_node(code, cur_node, first_cur_node: cur_node)
end

def self.tokens(pattern)
pattern.scan(TOKEN).grep_v(ONLY_SEPARATOR)
pattern.gsub(COMMENT, '').scan(TOKEN).grep_v(ONLY_SEPARATOR)
end

# This method minimizes the closure for our method
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/ast/node_pattern_spec.rb
Expand Up @@ -1889,6 +1889,14 @@ def withargs(foo, bar, qux)
end
end

describe 'comments' do
let(:pattern) { "(int # We want an int\n$_) # Let's capture the value" }
let(:ruby) { '42' }
let(:captured_val) { 42 }

it_behaves_like 'single capture'
end

describe '.descend' do
let(:ruby) { '[[1, 2], 3]' }

Expand Down

0 comments on commit 076c11b

Please sign in to comment.