Class: Prism::Merge::Comment::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/prism/merge/comment/parser.rb

Overview

Ruby-specific comment parser.

Produces Prism::Merge::Comment::Line and Prism::Merge::Comment::Block
nodes instead of the generic Ast::Merge::Comment::* classes, enabling
Ruby-specific features like magic comment detection.

Examples:

lines = ["# frozen_string_literal: true", "", "# A comment"]
nodes = Parser.parse(lines)
nodes.first.contains_magic_comment? #=> true

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lines) ⇒ Parser

Initialize a new Ruby comment Parser.

Parameters:

  • lines (Array<String>)

    Source lines



28
29
30
# File 'lib/prism/merge/comment/parser.rb', line 28

def initialize(lines)
  @lines = lines || []
end

Instance Attribute Details

#linesArray<String> (readonly)

Returns The source lines.

Returns:

  • (Array<String>)

    The source lines



23
24
25
# File 'lib/prism/merge/comment/parser.rb', line 23

def lines
  @lines
end

Class Method Details

.parse(lines) ⇒ Array<Ast::Merge::AstNode>

Class method for convenient one-shot parsing.

Parameters:

  • lines (Array<String>)

    Source lines

Returns:

  • (Array<Ast::Merge::AstNode>)

    Parsed nodes



86
87
88
# File 'lib/prism/merge/comment/parser.rb', line 86

def parse(lines)
  new(lines).parse
end

Instance Method Details

#parseArray<Ast::Merge::AstNode>

Parse the lines into Ruby-specific comment AST.

Returns:

  • (Array<Ast::Merge::AstNode>)

    Parsed nodes



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/prism/merge/comment/parser.rb', line 35

def parse
  return [] if lines.empty?

  nodes = []
  current_block = []

  lines.each_with_index do |line, idx|
    line_number = idx + 1
    stripped = line.to_s.rstrip

    if stripped.empty?
      # Blank line - flush current block and add Empty
      if current_block.any?
        nodes << build_block(current_block)
        current_block = []
      end
      nodes << Ast::Merge::Comment::Empty.new(line_number: line_number, text: line.to_s)
    elsif stripped.start_with?("#")
      # Ruby comment line
      current_block << Line.new(
        text: stripped,
        line_number: line_number,
      )
    else
      # Non-comment content (shouldn't happen in comment-only files)
      if current_block.any?
        nodes << build_block(current_block)
        current_block = []
      end
      # Add as generic line
      nodes << Ast::Merge::Comment::Line.new(
        text: stripped,
        line_number: line_number,
        style: :hash_comment,
      )
    end
  end

  # Flush remaining block
  if current_block.any?
    nodes << build_block(current_block)
  end

  nodes
end