-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.rb
89 lines (74 loc) · 1.48 KB
/
parser.rb
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!macruby
# coding: utf-8
#
# parser.rb
#
# Created by Erik Österlund on 1/14/10.
# Copyright 2010 Växjö Universitet. All rights reserved.
#
require 'singleton'
require 'utilities'
module LALR
class Parser
def initialize(actions, gotos, rules)
@actions, @gotos, @rules = actions, gotos, rules
end
def parse(str)
@inp = str
init_parsing
while not @accepted and not @error
parse_loop
end
@out
end
private
def init_parsing
@out = []
@stack = []
@pos = 0
@accepted = false
@error = nil
shift 0
end
private
def next_token
result = @inp[@pos]
@pos += 1
return result unless result.nil?
EOF.instance
end
private
def parse_loop
action = @actions[@stack.last][@token]
if action == nil
error
else
action.exec self
end
end
private
def shift(state)
@stack << state
@token = next_token
end
private
def reduce(rule_number)
state = @stack.last
@out << rule_number
rule = @rules[rule_number]
@stack.slice!(-rule.productions.length..-1)
state = @stack.last
@stack << @gotos[state][rule.name]
end
private
def accept()
@accepted = true
p "Succeeded."
end
private
def error()
@error = "Something didn't work out"
p "Error: " + @error
end
end
end