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.



3334
3335
3336
3337
3338
3339
3340
# File 'lib/syntax_tree.rb', line 3334

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



3332
3333
3334
# File 'lib/syntax_tree.rb', line 3332

def comments
  @comments
end

#consequentObject (readonly)

In | When

the next clause in the chain



3326
3327
3328
# File 'lib/syntax_tree.rb', line 3326

def consequent
  @consequent
end

#keywordObject (readonly)

Kw

the keyword that opens this expression



3320
3321
3322
# File 'lib/syntax_tree.rb', line 3320

def keyword
  @keyword
end

#locationObject (readonly)

Location

the location of this node



3329
3330
3331
# File 'lib/syntax_tree.rb', line 3329

def location
  @location
end

#valueObject (readonly)

nil | untyped

optional value being switched on



3323
3324
3325
# File 'lib/syntax_tree.rb', line 3323

def value
  @value
end

Instance Method Details

#child_nodesObject



3342
3343
3344
# File 'lib/syntax_tree.rb', line 3342

def child_nodes
  [keyword, value, consequent]
end

#format(q) ⇒ Object



3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
# File 'lib/syntax_tree.rb', line 3346

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



3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
# File 'lib/syntax_tree.rb', line 3363

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



3382
3383
3384
3385
3386
3387
3388
3389
3390
# File 'lib/syntax_tree.rb', line 3382

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