Use IO in print_visitor, and add to_s method.

This commit is contained in:
Danila Fedorin 2018-07-25 14:04:27 -07:00
parent df2a00fd66
commit fbb0da9e44
3 changed files with 17 additions and 11 deletions

View File

@ -7,6 +7,6 @@ module Chalk
tokens = lexer.lex(File.read("test.txt")) tokens = lexer.lex(File.read("test.txt"))
trees = parser.parse?(tokens) trees = parser.parse?(tokens)
trees.try do |trees| trees.try do |trees|
trees.each &.accept(PrintVisitor.new) trees.each { |tree| puts tree }
end end
end end

View File

@ -2,30 +2,30 @@ require "./tree.cr"
module Chalk module Chalk
class PrintVisitor < Visitor class PrintVisitor < Visitor
def initialize def initialize(@stream : IO)
@indent = 0 @indent = 0
end end
def print_indent def print_indent
@indent.times do @indent.times do
STDOUT << " " @stream << " "
end end
end end
def visit(id : TreeId) def visit(id : TreeId)
print_indent print_indent
puts id.id @stream << id.id << "\n"
end end
def visit(lit : TreeLit) def visit(lit : TreeLit)
print_indent print_indent
puts lit.lit @stream << lit.lit << "\n"
end end
def visit(op : TreeOp) def visit(op : TreeOp)
print_indent print_indent
STDOUT << "[op] " @stream << "[op] "
puts op.op @stream << op.op << "\n"
@indent += 1 @indent += 1
end end
@ -35,11 +35,11 @@ module Chalk
def visit(function : TreeFunction) def visit(function : TreeFunction)
print_indent print_indent
STDOUT << "[function] " << function.name << "( " @stream << "[function] " << function.name << "( "
function.params.each do |param| function.params.each do |param|
STDOUT << param << " " @stream << param << " "
end end
puts ")" @stream << ")" << "\n"
@indent += 1 @indent += 1
end end
@ -50,7 +50,7 @@ module Chalk
macro forward(text, type) macro forward(text, type)
def visit(tree : {{type}}) def visit(tree : {{type}})
print_indent print_indent
puts {{text}} @stream << {{text}} << "\n"
@indent += 1 @indent += 1
end end

View File

@ -1,3 +1,5 @@
require "./print_visitor.cr"
module Chalk module Chalk
class Visitor class Visitor
def visit(tree : Tree) def visit(tree : Tree)
@ -12,6 +14,10 @@ module Chalk
v.visit(self) v.visit(self)
v.finish(self) v.finish(self)
end end
def to_s(io)
accept(PrintVisitor.new io)
end
end end
class TreeId < Tree class TreeId < Tree