Class: SyntaxTree::Binary

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree.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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Binary.



2463
2464
2465
2466
2467
2468
2469
# File 'lib/syntax_tree.rb', line 2463

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



2461
2462
2463
# File 'lib/syntax_tree.rb', line 2461

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



2449
2450
2451
# File 'lib/syntax_tree.rb', line 2449

def left
  @left
end

#locationObject (readonly)

Location

the location of this node



2458
2459
2460
# File 'lib/syntax_tree.rb', line 2458

def location
  @location
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



2452
2453
2454
# File 'lib/syntax_tree.rb', line 2452

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



2455
2456
2457
# File 'lib/syntax_tree.rb', line 2455

def right
  @right
end

Instance Method Details

#child_nodesObject



2471
2472
2473
# File 'lib/syntax_tree.rb', line 2471

def child_nodes
  [left, right]
end

#format(q) ⇒ Object



2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
# File 'lib/syntax_tree.rb', line 2475

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

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

    q.group do
      q.text(operator)

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

#pretty_print(q) ⇒ Object



2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
# File 'lib/syntax_tree.rb', line 2493

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("binary")

    q.breakable
    q.pp(left)

    q.breakable
    q.text(operator)

    q.breakable
    q.pp(right)

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
# File 'lib/syntax_tree.rb', line 2510

def to_json(*opts)
  {
    type: :binary,
    left: left,
    op: operator,
    right: right,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end