Skip to content

Commit

Permalink
Add ProcessedSource#comment_at_line. Optimize line_with_comment?
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Jul 26, 2020
1 parent 7ac9d0f commit 216c306
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,7 @@
### New features

* [#70](https://github.com/rubocop-hq/rubocop-ast/pull/70): Add `NextNode` ([@marcandre][])
* [#83](https://github.com/rubocop-hq/rubocop-ast/pull/83): Add `ProcessedSource#comment_at_line` ([@marcandre][])

### Bug fixes

Expand Down
15 changes: 11 additions & 4 deletions lib/rubocop/ast/processed_source.rb
Expand Up @@ -76,7 +76,7 @@ def each_comment
comments.each { |comment| yield comment }
end

# @deprecated Use `comments.find`
# @deprecated Use `comments.find` or `comment_at_line`
def find_comment
comments.find { |comment| yield comment }
end
Expand All @@ -99,9 +99,14 @@ def blank?
ast.nil?
end

# @return [Comment, nil] the comment at that line, if any.
def comment_at_line(line)
comment_index[line]
end

# @return [Boolean] if the given line number has a comment.
def line_with_comment?(line)
comment_lines.include?(line)
comment_index.include?(line)
end

# @return [Boolean] if any of the lines in the given `source_range` has a comment.
Expand Down Expand Up @@ -144,8 +149,10 @@ def line_indentation(line_number)

private

def comment_lines
@comment_lines ||= comments.map { |c| c.location.line }
def comment_index
@comment_index ||= {}.tap do |hash|
comments.each { |c| hash[c.location.line] = c }
end
end

def parse(source, ruby_version)
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/ast/processed_source_spec.rb
Expand Up @@ -257,6 +257,17 @@ def some_method
end
end

describe '#comment_at_line' do
it 'returns the comment at the given line number' do
expect(processed_source.comment_at_line(1).text).to eq '# comment one'
expect(processed_source.comment_at_line(4).text).to eq '# comment two'
end

it 'returns nil if line has no comment' do
expect(processed_source.comment_at_line(3)).to be nil
end
end

describe '#line_with_comment?' do
it 'returns true for lines with comments' do
expect(processed_source.line_with_comment?(1)).to be true
Expand Down
9 changes: 9 additions & 0 deletions tasks/compile.rake
@@ -0,0 +1,9 @@
# frozen_string_literal: true

desc 'Sompile [pattern] to Ruby code'
task :compile, [:pattern] do |_task, args|
require_relative '../lib/rubocop/ast'
pattern = args.fetch(:pattern) { $stdin.gets }
require 'pry'
puts RuboCop::AST::NodePattern.const_get(:Compiler).new(pattern).emit_method_code
end

0 comments on commit 216c306

Please sign in to comment.