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.



1680
1681
1682
1683
1684
1685
1686
# File 'lib/syntax_tree/node.rb', line 1680

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



1678
1679
1680
# File 'lib/syntax_tree/node.rb', line 1678

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



1669
1670
1671
# File 'lib/syntax_tree/node.rb', line 1669

def left
  @left
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



1672
1673
1674
# File 'lib/syntax_tree/node.rb', line 1672

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



1675
1676
1677
# File 'lib/syntax_tree/node.rb', line 1675

def right
  @right
end

Instance Method Details

#accept(visitor) ⇒ Object



1688
1689
1690
# File 'lib/syntax_tree/node.rb', line 1688

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

#child_nodesObject Also known as: deconstruct



1692
1693
1694
# File 'lib/syntax_tree/node.rb', line 1692

def child_nodes
  [left, right]
end

#deconstruct_keys(_keys) ⇒ Object



1698
1699
1700
1701
1702
1703
1704
1705
1706
# File 'lib/syntax_tree/node.rb', line 1698

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

#format(q) ⇒ Object



1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
# File 'lib/syntax_tree/node.rb', line 1708

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

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

    if operator == :<<
      q.text("<< ")
      q.format(right)
    else
      q.group do
        q.text(operator.name)
        q.indent do
          power ? q.breakable_empty : q.breakable_space
          q.format(right)
        end
      end
    end
  end
end