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

#pretty_print, #to_json

Constructor Details

#initialize(left:, operator:, right:, location:, comments: []) ⇒ Binary

Returns a new instance of Binary.



1552
1553
1554
1555
1556
1557
1558
# File 'lib/syntax_tree/node.rb', line 1552

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



1550
1551
1552
# File 'lib/syntax_tree/node.rb', line 1550

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



1541
1542
1543
# File 'lib/syntax_tree/node.rb', line 1541

def left
  @left
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



1544
1545
1546
# File 'lib/syntax_tree/node.rb', line 1544

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



1547
1548
1549
# File 'lib/syntax_tree/node.rb', line 1547

def right
  @right
end

Instance Method Details

#accept(visitor) ⇒ Object



1560
1561
1562
# File 'lib/syntax_tree/node.rb', line 1560

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

#child_nodesObject Also known as: deconstruct



1564
1565
1566
# File 'lib/syntax_tree/node.rb', line 1564

def child_nodes
  [left, right]
end

#deconstruct_keys(keys) ⇒ Object



1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'lib/syntax_tree/node.rb', line 1570

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

#format(q) ⇒ Object



1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
# File 'lib/syntax_tree/node.rb', line 1580

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