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.



2347
2348
2349
2350
2351
2352
2353
# File 'lib/syntax_tree.rb', line 2347

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



2345
2346
2347
# File 'lib/syntax_tree.rb', line 2345

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



2333
2334
2335
# File 'lib/syntax_tree.rb', line 2333

def left
  @left
end

#locationObject (readonly)

Location

the location of this node



2342
2343
2344
# File 'lib/syntax_tree.rb', line 2342

def location
  @location
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



2336
2337
2338
# File 'lib/syntax_tree.rb', line 2336

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



2339
2340
2341
# File 'lib/syntax_tree.rb', line 2339

def right
  @right
end

Instance Method Details

#child_nodesObject



2355
2356
2357
# File 'lib/syntax_tree.rb', line 2355

def child_nodes
  [left, right]
end

#format(q) ⇒ Object



2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
# File 'lib/syntax_tree.rb', line 2359

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



2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
# File 'lib/syntax_tree.rb', line 2377

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



2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
# File 'lib/syntax_tree.rb', line 2394

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