rubyx/lib/sof/node.rb

54 lines
1.1 KiB
Ruby
Raw Normal View History

# We transform objects into a tree of nodes
module Sof
2014-08-16 11:34:25 +02:00
#abstract base class for nodes in the tree
# may be referenced (should be a simple name or number)
class Node
def initialize referenced
@referenced = referenced
end
2014-08-18 12:01:52 +02:00
include Util
2014-08-16 11:34:25 +02:00
# must be able to output to a stream
def out io ,level
io.write "&#{referenced} " if referenced
2014-08-16 11:34:25 +02:00
end
attr_reader :referenced
2014-08-16 11:34:25 +02:00
end
class SimpleNode < Node
def initialize data , ref = nil
super(ref)
2014-08-16 14:16:07 +02:00
@data = data
end
2014-08-18 12:01:52 +02:00
attr_reader :data
def out io , level
super
io.write(data)
end
end
class ObjectNode < Node
def initialize data , ref
super(ref)
@data = data
@children = []
end
2014-08-18 12:01:52 +02:00
attr_reader :children , :data
def add k , v
@children << [k,v]
end
def out io , level = 0
super
io.write(@data)
2014-08-18 11:49:38 +02:00
indent = " " * (level + 1)
@children.each_with_index do |child , i|
k , v = child
2014-08-18 11:49:38 +02:00
io.write "\n#{indent}"
k.out(io , level + 2)
io.write " "
v.out(io , level + 2)
end
end
end
end