Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Parser::Source::Range#line_span #84

Merged
merged 1 commit into from Aug 1, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -9,6 +9,7 @@
* [#82](https://github.com/rubocop-hq/rubocop-ast/pull/82): `NodePattern`: Allow comments ([@marcandre][])
* [#83](https://github.com/rubocop-hq/rubocop-ast/pull/83): Add `ProcessedSource#comment_at_line` ([@marcandre][])
* [#83](https://github.com/rubocop-hq/rubocop-ast/pull/83): Add `ProcessedSource#each_comment_in_lines` ([@marcandre][])
* [#84](https://github.com/rubocop-hq/rubocop-ast/pull/84): Add `Source::Range#line_span` ([@marcandre][])

### Bug fixes

Expand Down
1 change: 1 addition & 0 deletions lib/rubocop/ast.rb
Expand Up @@ -4,6 +4,7 @@
require 'forwardable'
require 'set'

require_relative 'ast/ext/range'
require_relative 'ast/node_pattern'
require_relative 'ast/sexp'
require_relative 'ast/node'
Expand Down
28 changes: 28 additions & 0 deletions lib/rubocop/ast/ext/range.rb
@@ -0,0 +1,28 @@
# frozen_string_literal: true

module RuboCop
module AST
module Ext
# Extensions to Parser::AST::Range
module Range
# @return [Range] the range of line numbers for the node
# If `exclude_end` is `true`, then the range will be exclusive.
#
# Assume that `node` corresponds to the following array literal:
#
# [
# :foo,
# :bar
# ]
#
# node.loc.begin.line_span # => 1..1
# node.loc.expression.line_span(exclude_end: true) # => 1...4
def line_span(exclude_end: false)
::Range.new(first_line, last_line, exclude_end)
end
end
end
end
end

::Parser::Source::Range.include ::RuboCop::AST::Ext::Range
22 changes: 22 additions & 0 deletions spec/rubocop/ast/ext/range_spec.rb
@@ -0,0 +1,22 @@
# frozen_string_literal: true

RSpec.describe RuboCop::AST::Ext::Range do
let(:source) { <<~RUBY }
[
1,
2
]
RUBY

let(:node) { parse_source(source).ast }

describe '#line_span' do
it 'returns the range of lines a range occupies' do
expect(node.loc.begin.line_span).to eq 1..1
end

it 'accepts an `exclude_end` keyword argument' do
expect(node.loc.expression.line_span(exclude_end: true)).to eq 1...4
end
end
end