Class: Alf::Support::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/alf/support/tree.rb

Constant Summary collapse

EMPTY_CHILDREN =
[].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Tree

Returns a new instance of Tree


7
8
9
# File 'lib/alf/support/tree.rb', line 7

def initialize(root)
  @root = root
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root


10
11
12
# File 'lib/alf/support/tree.rb', line 10

def root
  @root
end

Instance Method Details

#children(node) ⇒ Object


24
25
26
27
28
29
30
31
32
33
# File 'lib/alf/support/tree.rb', line 24

def children(node)
  case node
  when Sexpr             then node.sexpr_body
  when Relvar            then [node.expr]
  when Algebra::Operator then node.operands
  when Algebra::Operand  then EMPTY_CHILDREN
  when Engine::Cog       then node.children
  else EMPTY_CHILDREN
  end
end

#label(node) ⇒ Object


12
13
14
15
16
17
18
19
20
21
22
# File 'lib/alf/support/tree.rb', line 12

def label(node)
  case node
  when Sexpr                   then node.first.to_s
  when Algebra::Operand::Proxy then label(node.subject)
  when Relation::DUM           then "DUM"
  when Relation::DEE           then "DEE"
  when Relation                then "Relation(...)"
  when Relvar                  then "#{node.class} ..."
  else node.to_s
  end
end

#to_text(buffer = '', node = root, depth = 0, open = []) ⇒ Object Also known as: to_s


35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/alf/support/tree.rb', line 35

def to_text(buffer = '', node = root, depth = 0, open = [])
  depth.times do |i|
    buffer << ((i==depth-1) ? "+-- " : (open[i] ? "|  " : '   '))
  end
  buffer << label(node) << "\n"
  children = children(node)
  children.each_with_index do |child, index|
    open[depth] = (index != children.size-1)
    to_text(buffer, child, depth+1, open)
  end
  buffer
end