Class: SyntaxTree::Binary

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

Overview

Binary represents any expression that involves two sub-expressions with an operator in between. This can be something that looks like a mathematical operation:

1 + 1

but can also be something like pushing a value onto an array:

array << value

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(left:, operator:, right:, location:, comments: []) ⇒ Binary

Returns a new instance of Binary.



1616
1617
1618
1619
1620
1621
1622
# File 'lib/syntax_tree/node.rb', line 1616

def initialize(left:, operator:, right:, location:, comments: [])
  @left = left
  @operator = operator
  @right = right
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



1614
1615
1616
# File 'lib/syntax_tree/node.rb', line 1614

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



1605
1606
1607
# File 'lib/syntax_tree/node.rb', line 1605

def left
  @left
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



1608
1609
1610
# File 'lib/syntax_tree/node.rb', line 1608

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



1611
1612
1613
# File 'lib/syntax_tree/node.rb', line 1611

def right
  @right
end

Instance Method Details

#accept(visitor) ⇒ Object



1624
1625
1626
# File 'lib/syntax_tree/node.rb', line 1624

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

#child_nodesObject Also known as: deconstruct



1628
1629
1630
# File 'lib/syntax_tree/node.rb', line 1628

def child_nodes
  [left, right]
end

#deconstruct_keys(_keys) ⇒ Object



1634
1635
1636
1637
1638
1639
1640
1641
1642
# File 'lib/syntax_tree/node.rb', line 1634

def deconstruct_keys(_keys)
  {
    left: left,
    operator: operator,
    right: right,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
# File 'lib/syntax_tree/node.rb', line 1644

def format(q)
  power = operator == :**

  q.group do
    q.group { q.format(left) }
    q.text(" ") unless power

    if operator == :<<
      q.text(operator.to_s)
      q.text(" ")
      q.format(right)
    else
      q.group do
        q.text(operator.to_s)

        q.indent do
          q.breakable(power ? "" : " ")
          q.format(right)
        end
      end
    end
  end
end