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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFormatter

Returns a new instance of Formatter.



118
119
120
121
122
# File 'lib/syntax_tree.rb', line 118

def initialize(*)
  super
  @stack = []
  @quote = "\""
end

Instance Attribute Details

#quoteObject (readonly)

Returns the value of attribute quote.



116
117
118
# File 'lib/syntax_tree.rb', line 116

def quote
  @quote
end

#stackObject (readonly)

Returns the value of attribute stack.



116
117
118
# File 'lib/syntax_tree.rb', line 116

def stack
  @stack
end

Instance Method Details

#format(node) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/syntax_tree.rb', line 124

def format(node)
  stack << node
  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

    doc = node.format(self)

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

  stack.pop
  doc
end

#format_each(nodes) ⇒ Object



157
158
159
# File 'lib/syntax_tree.rb', line 157

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

#parentObject



161
162
163
# File 'lib/syntax_tree.rb', line 161

def parent
  stack[-2]
end

#parentsObject



165
166
167
# File 'lib/syntax_tree.rb', line 165

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