Class: SyntaxTree::Formatter

Inherits:
PP
  • Object
show all
Defined in:
lib/syntax_tree/formatter.rb

Overview

A slightly enhanced PP that knows how to format recursively including comments.

Constant Summary collapse

COMMENT_PRIORITY =
1
HEREDOC_PRIORITY =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Formatter

Returns a new instance of Formatter.



12
13
14
15
16
17
18
# File 'lib/syntax_tree/formatter.rb', line 12

def initialize(source, ...)
  super(...)

  @source = source
  @stack = []
  @quote = "\""
end

Instance Attribute Details

#quoteObject (readonly)

Returns the value of attribute quote.



10
11
12
# File 'lib/syntax_tree/formatter.rb', line 10

def quote
  @quote
end

#sourceObject (readonly)

Returns the value of attribute source.



10
11
12
# File 'lib/syntax_tree/formatter.rb', line 10

def source
  @source
end

#stackObject (readonly)

Returns the value of attribute stack.



10
11
12
# File 'lib/syntax_tree/formatter.rb', line 10

def stack
  @stack
end

Instance Method Details

#format(node, stackable: true) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/syntax_tree/formatter.rb', line 20

def format(node, stackable: true)
  stack << node if stackable
  doc = nil

  # If there are comments, then we're going to format them around the node
  # so that they get printed properly.
  if node.comments.any?
    leading, trailing = node.comments.partition(&:leading?)

    # Print all comments that were found before the node.
    leading.each do |comment|
      comment.format(self)
      breakable(force: true)
    end

    # If the node has a stree-ignore comment right before it, then we're
    # going to just print out the node as it was seen in the source.
    if leading.last&.ignore?
      doc = text(source[node.location.start_char...node.location.end_char])
    else
      doc = node.format(self)
    end

    # Print all comments that were found after the node.
    trailing.each do |comment|
      line_suffix(priority: COMMENT_PRIORITY) do
        text(" ")
        comment.format(self)
        break_parent
      end
    end
  else
    doc = node.format(self)
  end

  stack.pop if stackable
  doc
end

#format_each(nodes) ⇒ Object



59
60
61
# File 'lib/syntax_tree/formatter.rb', line 59

def format_each(nodes)
  nodes.each { |node| format(node) }
end

#parentObject



63
64
65
# File 'lib/syntax_tree/formatter.rb', line 63

def parent
  stack[-2]
end

#parentsObject



67
68
69
# File 'lib/syntax_tree/formatter.rb', line 67

def parents
  stack[0...-1].reverse_each
end