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.
912
913
914
915
|
# File 'lib/t_ruby/ir.rb', line 912
def initialize
@output = []
@indent = 0
end
|
Instance Attribute Details
#output ⇒ Object
Returns the value of attribute output.
910
911
912
|
# File 'lib/t_ruby/ir.rb', line 910
def output
@output
end
|
Instance Method Details
#generate(program) ⇒ Object
917
918
919
920
921
|
# File 'lib/t_ruby/ir.rb', line 917
def generate(program)
@output = []
visit(program)
@output.join("\n")
end
|
#visit_assignment(node) ⇒ Object
961
962
963
|
# File 'lib/t_ruby/ir.rb', line 961
def visit_assignment(node)
emit("#{node.target} = #{generate_expression(node.value)}")
end
|
#visit_block(node) ⇒ Object
957
958
959
|
# File 'lib/t_ruby/ir.rb', line 957
def visit_block(node)
node.statements.each { |stmt| visit(stmt) }
end
|
#visit_conditional(node) ⇒ Object
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
|
# File 'lib/t_ruby/ir.rb', line 973
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
935
936
937
938
939
940
941
942
|
# File 'lib/t_ruby/ir.rb', line 935
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
944
945
946
947
948
949
950
951
952
953
954
955
|
# File 'lib/t_ruby/ir.rb', line 944
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
923
924
925
926
927
928
|
# File 'lib/t_ruby/ir.rb', line 923
def visit_program(node)
node.declarations.each do |decl|
visit(decl)
@output << ""
end
end
|
#visit_raw_code(node) ⇒ Object
990
991
992
993
994
|
# File 'lib/t_ruby/ir.rb', line 990
def visit_raw_code(node)
node.code.each_line do |line|
emit(line.rstrip)
end
end
|
#visit_return(node) ⇒ Object
965
966
967
968
969
970
971
|
# File 'lib/t_ruby/ir.rb', line 965
def visit_return(node)
if node.value
emit("return #{generate_expression(node.value)}")
else
emit("return")
end
end
|
#visit_type_alias(node) ⇒ Object
930
931
932
933
|
# File 'lib/t_ruby/ir.rb', line 930
def visit_type_alias(node)
("type #{node.name} = #{node.definition.to_trb}")
end
|