Module: RuboCop::Cop::Style::RbsInline::SourceCodeHelper

Overview

Utility module for accessing processed source code information

Instance Method Summary collapse

Instance Method Details

#annotation_range(annotation) ⇒ Object

Convert RBS::Inline annotation to Parser::Source::Range



62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 62

def annotation_range(annotation) #: Parser::Source::Range?
  comments = annotation.source.comments
  first = comments.first&.location
  last = comments.last&.location
  return unless first && last

  range_between(character_offset(first.start_offset), character_offset(last.end_offset))
end

#blank_line?(line_number) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 38

def blank_line?(line_number) #: bool
  line = processed_source.buffer.source.lines[line_number - 1]
  line.nil? || line.strip.empty?
end

#char_at(pos) ⇒ Object



23
24
25
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 23

def char_at(pos) #: String?
  processed_source.buffer.source[pos]
end

#character_offset(byte_offset) ⇒ Object

Convert byte offset to character offset



14
15
16
17
18
19
20
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 14

def character_offset(byte_offset) #: Integer
  source = processed_source.buffer.source.dup.force_encoding('ASCII')
  text = source[...byte_offset] or raise
  text.force_encoding(processed_source.buffer.source.encoding).size
rescue StandardError
  byte_offset
end

#comment_at(line) ⇒ Object



28
29
30
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 28

def comment_at(line) #: Parser::Source::Comment?
  processed_source.comments.find { _1.location.line == line }
end

#comment_range(comment) ⇒ Object

Convert Prism::Comment to Parser::Source::Range



56
57
58
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 56

def comment_range(comment) #: Parser::Source::Range
  location_to_range(comment.location)
end

#line_range(line_number) ⇒ Object



44
45
46
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 44

def line_range(line_number) #: Parser::Source::Range
  processed_source.buffer.line_range(line_number)
end

#location_to_range(location) ⇒ Object

Convert Prism::Location to Parser::Source::Range



50
51
52
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 50

def location_to_range(location) #: Parser::Source::Range
  range_between(character_offset(location.start_offset), character_offset(location.end_offset))
end

#source_code_at(line_number) ⇒ Object



33
34
35
# File 'lib/rubocop/cop/style/rbs_inline/source_code_helper.rb', line 33

def source_code_at(line_number) #: String
  processed_source.buffer.source.lines[line_number - 1] || ''
end