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.



9754
9755
9756
9757
9758
9759
# File 'lib/syntax_tree/node.rb', line 9754

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



9752
9753
9754
# File 'lib/syntax_tree/node.rb', line 9752

def comments
  @comments
end

#predicateObject (readonly)

untyped

the expression to be checked



9749
9750
9751
# File 'lib/syntax_tree/node.rb', line 9749

def predicate
  @predicate
end

#statementObject (readonly)

untyped

the expression to be executed



9746
9747
9748
# File 'lib/syntax_tree/node.rb', line 9746

def statement
  @statement
end

Instance Method Details

#accept(visitor) ⇒ Object



9761
9762
9763
# File 'lib/syntax_tree/node.rb', line 9761

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

#child_nodesObject Also known as: deconstruct



9765
9766
9767
# File 'lib/syntax_tree/node.rb', line 9765

def child_nodes
  [statement, predicate]
end

#deconstruct_keys(_keys) ⇒ Object



9771
9772
9773
9774
9775
9776
9777
9778
# File 'lib/syntax_tree/node.rb', line 9771

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

#format(q) ⇒ Object



9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
# File 'lib/syntax_tree/node.rb', line 9780

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