Class: UState::Query::Optimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/ustate/query/optimizer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeOptimizer

Returns a new instance of Optimizer.



7
8
# File 'lib/ustate/query/optimizer.rb', line 7

def initialize
end

Class Method Details

.[](node) ⇒ Object



3
4
5
# File 'lib/ustate/query/optimizer.rb', line 3

def self.[](node)
  new.optimize node
end

Instance Method Details

#collapse_boolean_literals(node) ⇒ Object

Remove true and false from and/or



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ustate/query/optimizer.rb', line 11

def collapse_boolean_literals(node)
  map node do |n|
    case n
    when And
      if n.children.any? do |c|
          False === c
      end
        puts "Collapsing and(false)"
        False.new
      else
        n.children.delete_if do |c|
          True === c
        end
        n
      end
    when Or
      if n.children.any? do |c|
          True === c
      end
        puts "Collapsing or(true)"
        True.new
      else
        n.children.delete_if do |c|
          False === c
        end
        n
      end
    else
      n
    end
  end
end

#deref_ands_ors(node) ⇒ Object

Eliminate useless ands/ors



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ustate/query/optimizer.rb', line 45

def deref_ands_ors(node)
  map node do |n|
    case n
    when And
      case n.children.size
      when 0
        True.new
      when 1
        n.children.first
      else
        n
      end
    when Or
      case n.children.size
      when 0
        False.new
      when 1
        n.children.first
      else
        n
      end
    else
      n
    end
  end
end

#map(node, &block) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ustate/query/optimizer.rb', line 83

def map(node, &block)
  # Transform node
  puts "Map #{node}"
  node = block[node] or raise RuntimeError "Mapped to nil"
  puts "Node is now #{node}"

  # Apply map to children
  if node.respond_to? :children
    puts "Node has children"
    node.children.map! do |n|
      map n, &block
    end
  end

  # Return node
  node
end

#optimize(node) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/ustate/query/optimizer.rb', line 72

def optimize(node)
  mass = node.mass + 1
  
  while node.mass < mass
    mass = node.mass
    node = transform node
  end

  node
end

#transform(node) ⇒ Object



108
109
110
111
# File 'lib/ustate/query/optimizer.rb', line 108

def transform(node)
  puts "Transform ------------\n#{node.inspect}"
  deref_ands_ors collapse_boolean_literals node
end

#traverse(node, &block) ⇒ Object



101
102
103
104
105
106
# File 'lib/ustate/query/optimizer.rb', line 101

def traverse(node, &block)
  block[node]
  node.children.each do |child|
    traverse child, &block
  end
end