Skip to Content Skip to Search

When we’ve parsed the source, we have both the syntax tree and the list of comments that we found in the source. This class is responsible for walking the tree and finding the nearest location to attach each comment.

It does this by first finding the nearest locations to each comment. Locations can either come from nodes directly or from location fields on nodes. For example, a ‘ClassNode` has an overall location encompassing the entire class, but it also has a location for the `class` keyword.

Once the nearest locations are found, it determines which one to attach to. If it’s a trailing comment (a comment on the same line as other source code), it will favor attaching to the nearest location that occurs before the comment. Otherwise it will favor attaching to the nearest location that is after the comment.

Methods
A
N

Attributes

[R] parse_result

The parse result that we are attaching comments to.

Class Public methods

new(parse_result)

Create a new Comments object that will attach comments to the given parse result.

# File ruby/lib/prism/parse_result/comments.rb, line 78
def initialize(parse_result)
  @parse_result = parse_result
end

Instance Public methods

attach!()

Attach the comments to their respective locations in the tree by mutating the parse result.

# File ruby/lib/prism/parse_result/comments.rb, line 84
def attach!
  parse_result.comments.each do |comment|
    preceding, enclosing, following = nearest_targets(parse_result.value, comment)
    target =
      if comment.trailing?
        preceding || following || enclosing || NodeTarget.new(parse_result.value)
      else
        # If a comment exists on its own line, prefer a leading comment.
        following || preceding || enclosing || NodeTarget.new(parse_result.value)
      end

    target << comment
  end
end