Class: SyntaxTree::While

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

Overview

While represents a while loop.

while predicate
end

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#pretty_print, #to_json

Constructor Details

#initialize(predicate:, statements:, location:, comments: []) ⇒ While

Returns a new instance of While.



9508
9509
9510
9511
9512
9513
# File 'lib/syntax_tree/node.rb', line 9508

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

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



9506
9507
9508
# File 'lib/syntax_tree/node.rb', line 9506

def comments
  @comments
end

#predicateObject (readonly)

untyped

the expression to be checked



9500
9501
9502
# File 'lib/syntax_tree/node.rb', line 9500

def predicate
  @predicate
end

#statementsObject (readonly)

Statements

the expressions to be executed



9503
9504
9505
# File 'lib/syntax_tree/node.rb', line 9503

def statements
  @statements
end

Instance Method Details

#accept(visitor) ⇒ Object



9515
9516
9517
# File 'lib/syntax_tree/node.rb', line 9515

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

#child_nodesObject Also known as: deconstruct



9519
9520
9521
# File 'lib/syntax_tree/node.rb', line 9519

def child_nodes
  [predicate, statements]
end

#deconstruct_keys(keys) ⇒ Object



9525
9526
9527
9528
9529
9530
9531
9532
# File 'lib/syntax_tree/node.rb', line 9525

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

#format(q) ⇒ Object



9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
# File 'lib/syntax_tree/node.rb', line 9534

def format(q)
  if statements.empty?
    keyword = "while "

    q.group do
      q.text(keyword)
      q.nest(keyword.length) { q.format(predicate) }
      q.breakable(force: true)
      q.text("end")
    end
  else
    LoopFormatter.new("while", self, statements).format(q)
  end
end