Class: TRuby::IR::CodeGenerator
Overview
Code Generator - Converts IR to Ruby code
Instance Attribute Summary collapse
Instance Method Summary
collapse
Methods inherited from Visitor
#visit, #visit_children, #visit_default
Constructor Details
Returns a new instance of CodeGenerator.
874
875
876
877
|
# File 'lib/t_ruby/ir.rb', line 874
def initialize
@output = []
@indent = 0
end
|
Instance Attribute Details
#output ⇒ Object
Returns the value of attribute output.
872
873
874
|
# File 'lib/t_ruby/ir.rb', line 872
def output
@output
end
|
Instance Method Details
#generate(program) ⇒ Object
879
880
881
882
883
|
# File 'lib/t_ruby/ir.rb', line 879
def generate(program)
@output = []
visit(program)
@output.join("\n")
end
|
#visit_assignment(node) ⇒ Object
923
924
925
|
# File 'lib/t_ruby/ir.rb', line 923
def visit_assignment(node)
emit("#{node.target} = #{generate_expression(node.value)}")
end
|
#visit_block(node) ⇒ Object
919
920
921
|
# File 'lib/t_ruby/ir.rb', line 919
def visit_block(node)
node.statements.each { |stmt| visit(stmt) }
end
|
#visit_conditional(node) ⇒ Object
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
|
# File 'lib/t_ruby/ir.rb', line 935
def visit_conditional(node)
keyword = node.kind == :unless ? "unless" : "if"
emit("#{keyword} #{generate_expression(node.condition)}")
@indent += 1
visit(node.then_branch) if node.then_branch
@indent -= 1
if node.else_branch
emit("else")
@indent += 1
visit(node.else_branch)
@indent -= 1
end
emit("end")
end
|
#visit_interface(node) ⇒ Object
897
898
899
900
901
902
903
904
|
# File 'lib/t_ruby/ir.rb', line 897
def visit_interface(node)
("interface #{node.name}")
node.members.each do |member|
(" #{member.name}: #{member.type_signature.to_trb}")
end
("end")
end
|
#visit_method_def(node) ⇒ Object
906
907
908
909
910
911
912
913
914
915
916
917
|
# File 'lib/t_ruby/ir.rb', line 906
def visit_method_def(node)
params_str = node.params.map(&:name).join(", ")
emit("def #{node.name}(#{params_str})")
@indent += 1
if node.body
visit(node.body)
end
@indent -= 1
emit("end")
end
|
#visit_program(node) ⇒ Object
885
886
887
888
889
890
|
# File 'lib/t_ruby/ir.rb', line 885
def visit_program(node)
node.declarations.each do |decl|
visit(decl)
@output << ""
end
end
|
#visit_raw_code(node) ⇒ Object
952
953
954
955
956
|
# File 'lib/t_ruby/ir.rb', line 952
def visit_raw_code(node)
node.code.each_line do |line|
emit(line.rstrip)
end
end
|
#visit_return(node) ⇒ Object
927
928
929
930
931
932
933
|
# File 'lib/t_ruby/ir.rb', line 927
def visit_return(node)
if node.value
emit("return #{generate_expression(node.value)}")
else
emit("return")
end
end
|
#visit_type_alias(node) ⇒ Object
892
893
894
895
|
# File 'lib/t_ruby/ir.rb', line 892
def visit_type_alias(node)
("type #{node.name} = #{node.definition.to_trb}")
end
|