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.



11385
11386
11387
11388
# File 'lib/syntax_tree/node.rb', line 11385

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

Instance Attribute Details

#keywordObject (readonly)

String

the name of the keyword used for this loop



11380
11381
11382
# File 'lib/syntax_tree/node.rb', line 11380

def keyword
  @keyword
end

#nodeObject (readonly)

Until | While

the node that is being formatted



11383
11384
11385
# File 'lib/syntax_tree/node.rb', line 11383

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
# File 'lib/syntax_tree/node.rb', line 11390

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