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.
870
871
872
873
|
# File 'lib/t_ruby/ir.rb', line 870
def initialize
@output = []
@indent = 0
end
|
Instance Attribute Details
#output ⇒ Object
Returns the value of attribute output.
868
869
870
|
# File 'lib/t_ruby/ir.rb', line 868
def output
@output
end
|
Instance Method Details
#generate(program) ⇒ Object
875
876
877
878
879
|
# File 'lib/t_ruby/ir.rb', line 875
def generate(program)
@output = []
visit(program)
@output.join("\n")
end
|
#visit_assignment(node) ⇒ Object
919
920
921
|
# File 'lib/t_ruby/ir.rb', line 919
def visit_assignment(node)
emit("#{node.target} = #{generate_expression(node.value)}")
end
|
#visit_block(node) ⇒ Object
915
916
917
|
# File 'lib/t_ruby/ir.rb', line 915
def visit_block(node)
node.statements.each { |stmt| visit(stmt) }
end
|
#visit_conditional(node) ⇒ Object
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
|
# File 'lib/t_ruby/ir.rb', line 931
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
893
894
895
896
897
898
899
900
|
# File 'lib/t_ruby/ir.rb', line 893
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
902
903
904
905
906
907
908
909
910
911
912
913
|
# File 'lib/t_ruby/ir.rb', line 902
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
881
882
883
884
885
886
|
# File 'lib/t_ruby/ir.rb', line 881
def visit_program(node)
node.declarations.each do |decl|
visit(decl)
@output << ""
end
end
|
#visit_raw_code(node) ⇒ Object
948
949
950
951
952
|
# File 'lib/t_ruby/ir.rb', line 948
def visit_raw_code(node)
node.code.each_line do |line|
emit(line.rstrip)
end
end
|
#visit_return(node) ⇒ Object
923
924
925
926
927
928
929
|
# File 'lib/t_ruby/ir.rb', line 923
def visit_return(node)
if node.value
emit("return #{generate_expression(node.value)}")
else
emit("return")
end
end
|
#visit_type_alias(node) ⇒ Object
888
889
890
891
|
# File 'lib/t_ruby/ir.rb', line 888
def visit_type_alias(node)
("type #{node.name} = #{node.definition.to_trb}")
end
|