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.



1504
1505
1506
1507
1508
1509
1510
# File 'lib/syntax_tree/node.rb', line 1504

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



1502
1503
1504
# File 'lib/syntax_tree/node.rb', line 1502

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



1493
1494
1495
# File 'lib/syntax_tree/node.rb', line 1493

def left
  @left
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



1496
1497
1498
# File 'lib/syntax_tree/node.rb', line 1496

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



1499
1500
1501
# File 'lib/syntax_tree/node.rb', line 1499

def right
  @right
end

Instance Method Details

#accept(visitor) ⇒ Object



1512
1513
1514
# File 'lib/syntax_tree/node.rb', line 1512

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

#child_nodesObject Also known as: deconstruct



1516
1517
1518
# File 'lib/syntax_tree/node.rb', line 1516

def child_nodes
  [left, right]
end

#deconstruct_keys(keys) ⇒ Object



1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/syntax_tree/node.rb', line 1522

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

#format(q) ⇒ Object



1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
# File 'lib/syntax_tree/node.rb', line 1532

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

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

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

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