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.
826
827
828
829
|
# File 'lib/t_ruby/ir.rb', line 826
def initialize
@output = []
@indent = 0
end
|
Instance Attribute Details
#output ⇒ Object
Returns the value of attribute output.
824
825
826
|
# File 'lib/t_ruby/ir.rb', line 824
def output
@output
end
|
Instance Method Details
#generate(program) ⇒ Object
831
832
833
834
835
|
# File 'lib/t_ruby/ir.rb', line 831
def generate(program)
@output = []
visit(program)
@output.join("\n")
end
|
#visit_assignment(node) ⇒ Object
875
876
877
|
# File 'lib/t_ruby/ir.rb', line 875
def visit_assignment(node)
emit("#{node.target} = #{generate_expression(node.value)}")
end
|
#visit_block(node) ⇒ Object
871
872
873
|
# File 'lib/t_ruby/ir.rb', line 871
def visit_block(node)
node.statements.each { |stmt| visit(stmt) }
end
|
#visit_conditional(node) ⇒ Object
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
|
# File 'lib/t_ruby/ir.rb', line 887
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
849
850
851
852
853
854
855
856
|
# File 'lib/t_ruby/ir.rb', line 849
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
858
859
860
861
862
863
864
865
866
867
868
869
|
# File 'lib/t_ruby/ir.rb', line 858
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
837
838
839
840
841
842
|
# File 'lib/t_ruby/ir.rb', line 837
def visit_program(node)
node.declarations.each do |decl|
visit(decl)
@output << ""
end
end
|
#visit_raw_code(node) ⇒ Object
904
905
906
907
908
|
# File 'lib/t_ruby/ir.rb', line 904
def visit_raw_code(node)
node.code.each_line do |line|
emit(line.rstrip)
end
end
|
#visit_return(node) ⇒ Object
879
880
881
882
883
884
885
|
# File 'lib/t_ruby/ir.rb', line 879
def visit_return(node)
if node.value
emit("return #{generate_expression(node.value)}")
else
emit("return")
end
end
|
#visit_type_alias(node) ⇒ Object
844
845
846
847
|
# File 'lib/t_ruby/ir.rb', line 844
def visit_type_alias(node)
("type #{node.name} = #{node.definition.to_trb}")
end
|