Class: SyntaxTree::Case

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree.rb

Overview

Case represents the beginning of a case chain.

case value
when 1
  "one"
when 2
  "two"
else
  "number"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keyword:, value:, consequent:, location:, comments: []) ⇒ Case

Returns a new instance of Case.



3455
3456
3457
3458
3459
3460
3461
# File 'lib/syntax_tree.rb', line 3455

def initialize(keyword:, value:, consequent:, location:, comments: [])
  @keyword = keyword
  @value = value
  @consequent = consequent
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



3453
3454
3455
# File 'lib/syntax_tree.rb', line 3453

def comments
  @comments
end

#consequentObject (readonly)

In | When

the next clause in the chain



3447
3448
3449
# File 'lib/syntax_tree.rb', line 3447

def consequent
  @consequent
end

#keywordObject (readonly)

Kw

the keyword that opens this expression



3441
3442
3443
# File 'lib/syntax_tree.rb', line 3441

def keyword
  @keyword
end

#locationObject (readonly)

Location

the location of this node



3450
3451
3452
# File 'lib/syntax_tree.rb', line 3450

def location
  @location
end

#valueObject (readonly)

nil | untyped

optional value being switched on



3444
3445
3446
# File 'lib/syntax_tree.rb', line 3444

def value
  @value
end

Instance Method Details

#child_nodesObject



3463
3464
3465
# File 'lib/syntax_tree.rb', line 3463

def child_nodes
  [keyword, value, consequent]
end

#format(q) ⇒ Object



3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
# File 'lib/syntax_tree.rb', line 3467

def format(q)
  q.group do
    q.format(keyword)

    if value
      q.text(" ")
      q.format(value)
    end

    q.breakable(force: true)
    q.format(consequent)
    q.breakable(force: true)

    q.text("end")
  end
end

#pretty_print(q) ⇒ Object



3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
# File 'lib/syntax_tree.rb', line 3484

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

    q.breakable
    q.pp(keyword)

    if value
      q.breakable
      q.pp(value)
    end

    q.breakable
    q.pp(consequent)

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

#to_json(*opts) ⇒ Object



3503
3504
3505
3506
3507
3508
3509
3510
3511
# File 'lib/syntax_tree.rb', line 3503

def to_json(*opts)
  {
    type: :case,
    value: value,
    cons: consequent,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end