Class: MiniRuby::AST::IfExpressionNode

Inherits:
ExpressionNode show all
Defined in:
lib/miniruby/ast.rb

Overview

Represents an if expression like ‘if foo; a = 5; end`

Instance Attribute Summary collapse

Attributes inherited from Node

#span

Instance Method Summary collapse

Constructor Details

#initialize(condition:, then_body:, else_body: nil, span: Span::ZERO) ⇒ IfExpressionNode

: (condition: ExpressionNode, then_body: Array, ?else_body: Array?, ?span: Span) -> void



552
553
554
555
556
557
# File 'lib/miniruby/ast.rb', line 552

def initialize(condition:, then_body:, else_body: nil, span: Span::ZERO)
  @span = span
  @condition = condition
  @then_body = then_body
  @else_body = else_body
end

Instance Attribute Details

#conditionObject (readonly)

: ExpressionNode



543
544
545
# File 'lib/miniruby/ast.rb', line 543

def condition
  @condition
end

#else_bodyObject (readonly)

: Array?



549
550
551
# File 'lib/miniruby/ast.rb', line 549

def else_body
  @else_body
end

#then_bodyObject (readonly)

: Array



546
547
548
# File 'lib/miniruby/ast.rb', line 546

def then_body
  @then_body
end

Instance Method Details

#==(other) ⇒ Object

: (Object other) -> bool



560
561
562
563
564
565
566
# File 'lib/miniruby/ast.rb', line 560

def ==(other)
  return false unless other.is_a?(IfExpressionNode)

  @condition == other.condition &&
    @then_body == other.then_body &&
    @else_body == other.else_body
end

#inspect(indent = 0) ⇒ Object

: (?Integer indent) -> String



593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/miniruby/ast.rb', line 593

def inspect(indent = 0)
  buff = String.new
  buff << "#{INDENT_UNIT * indent}(if"

  buff << "\n" << @condition.inspect(indent + 1)

  buff << "\n#{INDENT_UNIT * (indent + 1)}(then"
  @then_body.each do |stmt|
    buff << "\n" << stmt.inspect(indent + 2)
  end
  buff << ')'

  els = @else_body
  if els
    buff << "\n#{INDENT_UNIT * (indent + 1)}(else"
    els.each do |stmt|
      buff << "\n" << stmt.inspect(indent + 2)
    end
    buff << ')'
  end

  buff << ')'
  buff
end

#to_s(indent = 0) ⇒ Object

: (?Integer indent) -> String



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/miniruby/ast.rb', line 570

def to_s(indent = 0)
  buff = String.new
  indent_str = INDENT_UNIT * indent
  buff << "#{indent_str}if #{@condition}\n"

  @then_body.each do |stmt|
    buff << stmt.to_s(indent + 1)
  end

  els = @else_body
  if els
    buff << "#{indent_str}else\n"
    els.each do |stmt|
      buff << stmt.to_s(indent + 1)
    end
  end
  buff << "#{indent_str}end"

  buff
end