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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
# File 'lib/rvm/languages/math/tree.rb', line 24
def Tree.generate tokens
output = []
dbgoutput = []
stack = []
dbgstack = []
while not tokens.empty?
token = tokens.shift
case token[1]
when :function
fun = token[0]
stack << {:type => :function, :op => fun}
output << {:type => :function_end}
dbgoutput << ')'
dbgstack << fun
when :function_sep
while stack.last && (stack.last[:type] != :function)
output << stack.pop
dbgoutput << dbgstack.pop
end
when :paren_open
op = token[0]
stack << {:type => :op, :op => op}
dbgstack << op
when :paren_close
while stack.last && (stack.last[:op] != '(')
output << stack.pop
dbgoutput << dbgstack.pop
end
stack.pop
dbgstack.pop
when :number
output << {:type => :number, :number => token[0]}
dbgoutput << token[0]
when :ident
output << {:type => :ident, :ident => token[0]}
dbgoutput << token[0]
when :opperator
op = token[0]
ass = ASSOSICATIONS[op]
o1p = PRIORITIES[op]
while stack.last && (stack.last[:type] != :function) &&
(((ass == :left) && (o1p <= PRIORITIES[stack.last[:op]])) ||
((ass == :right) && (o1p < PRIORITIES[stack.last[:op]])))
output << stack.pop
dbgoutput << dbgstack.pop
end
stack << {:type => :op, :op => op}
dbgstack << op
else
raise "Unknown element in parser tree: #{token.inspect}"
end
p(dbgstack) if $DEBUG
p(dbgoutput) if $DEBUG
end
while not stack.empty?
output << stack.pop
end
gen_tree output
end
|