Class: RBS::Inline::AST::CommentLines

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs/inline/ast/comment_lines.rb

Overview

CommentLines represents consecutive comments, providing a mapping from locations in ‘#string` to a pair of a comment and its offset

The comments construct one String.

“‘ruby # Hello <– Comment1 # World <– Comment2 “`

We want to get a String of comment1 and comment2, ‘“HellonWorld”. And want to translate a location in the string into the location in comment1 and comment2.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(comments) ⇒ CommentLines

Returns a new instance of CommentLines.



22
23
24
# File 'lib/rbs/inline/ast/comment_lines.rb', line 22

def initialize(comments) #: void
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

: Array



19
20
21
# File 'lib/rbs/inline/ast/comment_lines.rb', line 19

def comments
  @comments
end

Instance Method Details

#comment_location(index) ⇒ Object

Translates the cursor index of ‘#string` into the cursor index of a specific comment object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rbs/inline/ast/comment_lines.rb', line 38

def comment_location(index)
  comments.each do |comment|
    comment_length = comment.location.length

    if index + 1 <= comment_length
      return [comment, index + 1]
    else
      index -= comment_length - 1
      index -= 1 # newline
      return if index < 0
    end
  end

  nil
end

#linesObject

: Array



26
27
28
# File 'lib/rbs/inline/ast/comment_lines.rb', line 26

def lines #: Array[String]
  comments.map {|comment| comment.location.slice }
end

#stringObject

: String



30
31
32
# File 'lib/rbs/inline/ast/comment_lines.rb', line 30

def string #: String
  comments.map {|comment| comment.location.slice[1..] || "" }.join("\n")
end