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

#construct_keys, #pretty_print, #to_json

Constructor Details

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

Returns a new instance of WhileMod.



9799
9800
9801
9802
9803
9804
# File 'lib/syntax_tree/node.rb', line 9799

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

Instance Attribute Details

#comments ⇒ Object (readonly)

[Array[ Comment | EmbDoc ]] the comments attached to this node



9797
9798
9799
# File 'lib/syntax_tree/node.rb', line 9797

def comments
  @comments
end

#predicate ⇒ Object (readonly)

[untyped] the expression to be checked



9794
9795
9796
# File 'lib/syntax_tree/node.rb', line 9794

def predicate
  @predicate
end

#statement ⇒ Object (readonly)

[untyped] the expression to be executed



9791
9792
9793
# File 'lib/syntax_tree/node.rb', line 9791

def statement
  @statement
end

Instance Method Details

#accept(visitor) ⇒ Object



9806
9807
9808
# File 'lib/syntax_tree/node.rb', line 9806

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

#child_nodes ⇒ Object Also known as: deconstruct



9810
9811
9812
# File 'lib/syntax_tree/node.rb', line 9810

def child_nodes
  [statement, predicate]
end

#deconstruct_keys(_keys) ⇒ Object



9816
9817
9818
9819
9820
9821
9822
9823
# File 'lib/syntax_tree/node.rb', line 9816

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

#format(q) ⇒ Object



9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
# File 'lib/syntax_tree/node.rb', line 9825

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