Skip to content

Commit

Permalink
Add Parser::Source::Range#line_span
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Jul 26, 2020
1 parent bff5017 commit f07f543
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 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 `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

0 comments on commit f07f543

Please sign in to comment.