1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
# frozen_string_literal: true
module Unparser
class Emitter
# Emitter if nodes
class If < self
handle :if
children :condition, :if_branch, :else_branch
def emit_ternary
visit(condition)
write(' ? ')
visit(if_branch)
write(' : ')
visit(else_branch)
end
private
def dispatch
if postcondition?
emit_postcondition
else
emit_normal
end
end
def postcondition?
return false unless if_branch.nil? ^ else_branch.nil?
body = if_branch || else_branch
local_variable_scope.first_assignment_in?(body, condition)
end
def emit_postcondition
visit(if_branch || else_branch)
write(' ', keyword, ' ')
emit_condition
end
def emit_normal
write(keyword, ' ')
emit_condition
emit_if_branch
emit_else_branch
k_end
end
def unless?
!if_branch && else_branch
end
def keyword
unless? ? 'unless' : 'if'
end
def emit_condition
visit(condition)
end
def emit_if_branch
if if_branch
emit_body(if_branch)
end
nl if !if_branch && !else_branch
end
def emit_else_branch
return unless else_branch
write('else') unless unless?
emit_body(else_branch)
end
end # If
end # Emitter
end # Unparser
|