Class: SyntaxTree::LoopFormatter

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

Overview

Formats an Until or While node.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keyword, node) ⇒ LoopFormatter

Returns a new instance of LoopFormatter.



11244
11245
11246
11247
# File 'lib/syntax_tree/node.rb', line 11244

def initialize(keyword, node)
  @keyword = keyword
  @node = node
end

Instance Attribute Details

#keywordObject (readonly)

String

the name of the keyword used for this loop



11239
11240
11241
# File 'lib/syntax_tree/node.rb', line 11239

def keyword
  @keyword
end

#nodeObject (readonly)

Until | While

the node that is being formatted



11242
11243
11244
# File 'lib/syntax_tree/node.rb', line 11242

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
# File 'lib/syntax_tree/node.rb', line 11249

def format(q)
  # If we're in the modifier form and we're modifying a `begin`, then this
  # is a special case where we need to explicitly use the modifier form
  # because otherwise the semantic meaning changes. This looks like:
  #
  #     begin
  #       foo
  #     end while bar
  #
  # Also, if the statement of the modifier includes an assignment, then we
  # can't know for certain that it won't impact the predicate, so we need to
  # force it to stay as it is. This looks like:
  #
  #     foo = bar while foo
  #
  if node.modifier? && (statement = node.statements.body.first) &&
       (statement.is_a?(Begin) || ContainsAssignment.call(statement))
    q.format(statement)
    q.text(" #{keyword} ")
    q.format(node.predicate)
  elsif node.statements.empty?
    q.group do
      q.text("#{keyword} ")
      q.nest(keyword.length + 1) { q.format(node.predicate) }
      q.breakable_force
      q.text("end")
    end
  elsif ContainsAssignment.call(node.predicate)
    format_break(q)
    q.break_parent
  else
    q.group do
      q
        .if_break { format_break(q) }
        .if_flat do
          Parentheses.flat(q) do
            q.format(node.statements)
            q.text(" #{keyword} ")
            q.format(node.predicate)
          end
        end
    end
  end
end