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.



3313
3314
3315
3316
3317
3318
3319
# File 'lib/syntax_tree.rb', line 3313

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



3311
3312
3313
# File 'lib/syntax_tree.rb', line 3311

def comments
  @comments
end

#consequentObject (readonly)

In | When

the next clause in the chain



3305
3306
3307
# File 'lib/syntax_tree.rb', line 3305

def consequent
  @consequent
end

#keywordObject (readonly)

Kw

the keyword that opens this expression



3299
3300
3301
# File 'lib/syntax_tree.rb', line 3299

def keyword
  @keyword
end

#locationObject (readonly)

Location

the location of this node



3308
3309
3310
# File 'lib/syntax_tree.rb', line 3308

def location
  @location
end

#valueObject (readonly)

nil | untyped

optional value being switched on



3302
3303
3304
# File 'lib/syntax_tree.rb', line 3302

def value
  @value
end

Instance Method Details

#child_nodesObject



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

def child_nodes
  [keyword, value, consequent]
end

#format(q) ⇒ Object



3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
# File 'lib/syntax_tree.rb', line 3325

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



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

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



3361
3362
3363
3364
3365
3366
3367
3368
3369
# File 'lib/syntax_tree.rb', line 3361

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