nrk (owner)

Fork Of

Revisions

gist: 191370 Download_button fork
public
Public Clone URL: git://gist.github.com/191370.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
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
43
44
45
46
47
48
49
50
51
52
53
54
#
# [{:op=>"and"},
# [{:op=>"="}, [{:path=>"hello"}, {:lit=>":ivan"}]],
# [{:op => "or"},
# [{:op=>"="}, [{:path=>"test"}, {:lit=>":ivan"}]],
# [{:op => ">"}, [:path => "test3", {:list => ":ivan"}]]]]
#
# hello = :ivan and (test = :ivan or test3 = :ivan)
 
class Parser
  def initialize(where_clause, binding)
    @binding = binding
    @tokens = where_clause.scan(/\(|\)|>=|<=|<>|=|>|<|[:?\w\.\*]+/)
    @stack = @top = @current_stack = []
    @previous = nil
  end
  
  def ast
    @tokens.each do |token|
      p token
 
      return nil unless token
      case token
      when "("
        @current_stack << []
        @previous = @current_stack
        @previous_top = @top
        @top = @current_stack = @current_stack.last
      when ")"
        @current_stack = @previous
        @top = @previous_top
      when "or", "and"
        @top.unshift [{:op => token}, @current_stack, []]
      when ">", "<", "<>", "=", ">=", "<="
        first = @current_stack.pop
        @current_stack.push(:op => token)
        @current_stack << []
        @previous = @current_stack
        @current_stack = @current_stack.last
        @current_stack.push first
      when /:[\w\.\*]+/
        @current_stack.push :lit => token
        @current_stack = @previous
      when /[\w\.\*]+/
        @current_stack.push(:path => token)
      end
 
      
    end
    #@stack.push(@current_stack)
    #@current_stack = []
    @stack
  end
end