Class: SyntaxTree::Formatter

Inherits:
PP
  • Object
show all
Defined in:
lib/syntax_tree.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.



128
129
130
131
132
133
134
# File 'lib/syntax_tree.rb', line 128

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

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

Instance Attribute Details

#quoteObject (readonly)

Returns the value of attribute quote.



126
127
128
# File 'lib/syntax_tree.rb', line 126

def quote
  @quote
end

#sourceObject (readonly)

Returns the value of attribute source.



126
127
128
# File 'lib/syntax_tree.rb', line 126

def source
  @source
end

#stackObject (readonly)

Returns the value of attribute stack.



126
127
128
# File 'lib/syntax_tree.rb', line 126

def stack
  @stack
end

Instance Method Details

#format(node, stackable: true) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/syntax_tree.rb', line 136

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



175
176
177
# File 'lib/syntax_tree.rb', line 175

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

#parentObject



179
180
181
# File 'lib/syntax_tree.rb', line 179

def parent
  stack[-2]
end

#parentsObject



183
184
185
# File 'lib/syntax_tree.rb', line 183

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