-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rb
More file actions
67 lines (58 loc) · 1.11 KB
/
parser.rb
File metadata and controls
67 lines (58 loc) · 1.11 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
require "./tokenizer"
class Parser
attr_accessor :index, :tokens, :node
def initialize(index, tokens)
@index = index
@tokens = tokens
@node = []
end
def node_type
@index = 0
case @tokens[@index][:type]
when :LPAREN then :LPAREN
when :RPAREN then :RPAREN
when :OPERATOR then :OPERATOR
when :NUMBER then :NUMBER
else :Unknown
end
end
def curr
@tokens[@index]
end
def parse_expr
op = curr
@index+=1
nums = []
while @tokens[@index][:type] == :NUMBER do
nums.push(parse_num)
end
parse
p "#{parse}"
{type: :Exprr, val: op, children: nums}
end
def parse_num
tok = curr
return nil if tok.nil?
if tok[:type] == :LPAREN
parse
else
@index+=1
{type: :NumberNode, val: tok}
end
end
def parse
c = @tokens[@index]
if c[:type] == :LPAREN then
@index+=1
@node.push parse_expr
elsif c[:type] == :NUMBER then
@node.push parse_num
elsif c[:type] == :RPAREN then
"RPARENです"
else
"error #{c}"
end
end
def evaluate
end
end