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.



2237
2238
2239
2240
2241
2242
2243
# File 'lib/syntax_tree.rb', line 2237

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



2235
2236
2237
# File 'lib/syntax_tree.rb', line 2235

def comments
  @comments
end

#leftObject (readonly)

untyped

the left-hand side of the expression



2223
2224
2225
# File 'lib/syntax_tree.rb', line 2223

def left
  @left
end

#locationObject (readonly)

Location

the location of this node



2232
2233
2234
# File 'lib/syntax_tree.rb', line 2232

def location
  @location
end

#operatorObject (readonly)

Symbol

the operator used between the two expressions



2226
2227
2228
# File 'lib/syntax_tree.rb', line 2226

def operator
  @operator
end

#rightObject (readonly)

untyped

the right-hand side of the expression



2229
2230
2231
# File 'lib/syntax_tree.rb', line 2229

def right
  @right
end

Instance Method Details

#child_nodesObject



2245
2246
2247
# File 'lib/syntax_tree.rb', line 2245

def child_nodes
  [left, right]
end

#format(q) ⇒ Object



2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
# File 'lib/syntax_tree.rb', line 2249

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

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

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

#pretty_print(q) ⇒ Object



2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
# File 'lib/syntax_tree.rb', line 2264

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



2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
# File 'lib/syntax_tree.rb', line 2281

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