Class: SyntaxTree::WhileMod

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

Overview

WhileMod represents the modifier form of a while loop.

expression while predicate

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#pretty_print, #to_json

Constructor Details

#initialize(statement:, predicate:, location:, comments: []) ⇒ WhileMod

Returns a new instance of WhileMod.



9564
9565
9566
9567
9568
9569
# File 'lib/syntax_tree/node.rb', line 9564

def initialize(statement:, predicate:, location:, comments: [])
  @statement = statement
  @predicate = predicate
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



9562
9563
9564
# File 'lib/syntax_tree/node.rb', line 9562

def comments
  @comments
end

#predicateObject (readonly)

untyped

the expression to be checked



9559
9560
9561
# File 'lib/syntax_tree/node.rb', line 9559

def predicate
  @predicate
end

#statementObject (readonly)

untyped

the expression to be executed



9556
9557
9558
# File 'lib/syntax_tree/node.rb', line 9556

def statement
  @statement
end

Instance Method Details

#accept(visitor) ⇒ Object



9571
9572
9573
# File 'lib/syntax_tree/node.rb', line 9571

def accept(visitor)
  visitor.visit_while_mod(self)
end

#child_nodesObject Also known as: deconstruct



9575
9576
9577
# File 'lib/syntax_tree/node.rb', line 9575

def child_nodes
  [statement, predicate]
end

#deconstruct_keys(keys) ⇒ Object



9581
9582
9583
9584
9585
9586
9587
9588
# File 'lib/syntax_tree/node.rb', line 9581

def deconstruct_keys(keys)
  {
    statement: statement,
    predicate: predicate,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
# File 'lib/syntax_tree/node.rb', line 9590

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 statement.is_a?(Begin) || ContainsAssignment.call(statement)
    q.format(statement)
    q.text(" while ")
    q.format(predicate)
  else
    LoopFormatter.new("while", self, statement).format(q)
  end
end