-
Notifications
You must be signed in to change notification settings - Fork 3
/
parser.go
240 lines (210 loc) · 5.55 KB
/
parser.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
(c) 2019 Launix, Inh. Carl-Philip Hänsch
Author: Tim Kluge
Dual licensed with custom aggreements or GPLv3
*/
package packrat
import (
"fmt"
"strconv"
"strings"
"unicode"
)
type Parser[T any] interface {
Match(s *Scanner[T]) (Node[T], bool)
}
func (s *Scanner[T]) applyRule(rule Parser[T]) (Node[T], bool) {
startPosition := s.position
memmap, memmapExists := s.memoization[startPosition]
if !memmapExists {
memmap = make(map[Parser[T]]*MemoEntry[T])
s.memoization[startPosition] = memmap
}
m := s.Recall(rule, startPosition)
if m == nil {
lr := &s.invocationStack[s.invocationStackIdx]
lr.seedOk = false
lr.rule = rule
lr.head = nil
s.invocationStackIdx++
m := &MemoEntry[T]{Lr: lr, Position: startPosition}
memmap[rule] = m
ans, ok := rule.Match(s)
s.invocationStackIdx--
m.Position = s.position // update Lr position
if lr.head != nil {
lr.seed = ans
lr.seedOk = ok
return s.LrAnswer(rule, startPosition, m)
}
m.Lr = nil
m.Ans = ans
m.Ok = ok
return ans, ok
}
s.setPosition(m.Position)
if m.Lr != nil {
s.SetupLr(rule, m.Lr)
return m.Lr.seed, m.Lr.seedOk
}
return m.Ans, m.Ok
}
var emptyString = ""
type Node[T any] struct {
Payload T
}
type ParserError[T any] struct {
Parser Parser[T]
Line int
Column int
Position int
FailedParsers []Parser[T]
Input string
}
func (e *ParserError[T]) Error() string {
linestartpos := e.Position - 30
startpos := linestartpos
if startpos < 0 {
startpos = 0
}
endpos := e.Position + 10
if endpos >= len(e.Input) {
endpos = len(e.Input)
if endpos < 0 {
endpos = 0
}
}
atomParsers := make(map[*AtomParser[T]]bool)
regexParsers := make(map[*RegexParser[T]]bool)
eofParser := false
allskipws := true
for _, p := range e.FailedParsers {
switch pa := p.(type) {
case *AtomParser[T]:
atomParsers[pa] = true
if !pa.skipWs {
allskipws = false
}
case *RegexParser[T]:
regexParsers[pa] = true
if !pa.skipWs {
allskipws = false
}
case *EndParser[T]:
eofParser = true
}
}
expected := strings.Builder{}
count := 0
for r := range atomParsers {
if count >= 5 {
break
}
expected.WriteString("- " + r.atom)
if r.skipWs {
expected.WriteString(" (with leading whitespace)")
}
expected.WriteString("\r\n")
count++
}
for r := range regexParsers {
if count >= 5 {
break
}
expected.WriteString("- Regex: " + r.rs)
if r.skipWs {
expected.WriteString(" (with leading whitespace)")
}
expected.WriteString("\r\n")
count++
}
if eofParser && count < 5 {
expected.WriteString("- End of input\r\n")
}
epos := e.Position
for allskipws && epos < len(e.Input)-1 && unicode.IsSpace(rune(e.Input[epos])) {
epos++
}
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("Parser failed at line %d, column %d (position %d of input string).", e.Line, e.Column, e.Position+1))
replacer := strings.NewReplacer("\r\n", "\\n", "\n", "\\n", "\t", " ")
builder.WriteString("\r\n" + replacer.Replace(e.Input[startpos:endpos]))
builder.WriteString("\r\n")
runes := []rune(e.Input)
for i := startpos; i < epos && i < len(runes); i++ {
c := runes[i]
switch c {
case '\n':
builder.WriteString(" ")
case '\t':
builder.WriteString(" ")
default:
builder.WriteRune(' ')
}
}
builder.WriteString("^\r\n")
builder.WriteString("Expected one of " + strconv.Itoa(len(atomParsers)+len(regexParsers)) + " alternatives:\r\n" + expected.String() + "Found: " + strings.ReplaceAll(e.Input[e.Position:endpos], "\n", "\\n"))
return builder.String()
}
func ParsePartial[T any](p Parser[T], originalScanner *Scanner[T]) (Node[T], *ParserError[T]) {
node, ok := originalScanner.applyRule(p)
if ok {
return node, nil
}
maxPos := 0
var failedParsers []Parser[T]
for index := len(originalScanner.input) - 1; index >= 0; index-- {
m, mExists := originalScanner.memoization[index]
if mExists && len(m) > 0 {
maxPos = index
for k := range m {
failedParsers = append(failedParsers, k)
}
break
}
}
consumed := originalScanner.input[:maxPos]
line := strings.Count(consumed, "\n") + 1
lastBreak := strings.LastIndex(consumed, "\n")
if lastBreak < 0 {
lastBreak = 0
}
column := maxPos - lastBreak + 1
e := &ParserError[T]{FailedParsers: failedParsers, Parser: p, Line: line, Column: column, Position: maxPos, Input: originalScanner.input}
return Node[T]{}, e
}
func Parse[T any](p Parser[T], originalScanner *Scanner[T]) (Node[T], *ParserError[T]) {
node, ok := originalScanner.applyRule(p)
if ok {
originalScanner.Skip()
if len(originalScanner.remainingInput) > 0 {
consumed := originalScanner.input[:originalScanner.position]
line := strings.Count(consumed, "\n") + 1
column := originalScanner.position - strings.LastIndex(consumed, "\n") + 1
e := &ParserError[T]{Parser: p, Line: line, Column: column, Position: originalScanner.position, Input: originalScanner.input}
return Node[T]{}, e
}
return node, nil
}
maxPos := 0
var failedParsers []Parser[T]
for index := len(originalScanner.input) - 1; index >= 0; index-- {
m := originalScanner.memoization[index]
if len(m) > 0 {
maxPos = index
for k := range m {
failedParsers = append(failedParsers, k)
}
break
}
}
consumed := originalScanner.input[:maxPos]
line := strings.Count(consumed, "\n") + 1
lastBreak := strings.LastIndex(consumed, "\n")
if lastBreak < 0 {
lastBreak = 0
}
column := maxPos - lastBreak + 1
e := &ParserError[T]{FailedParsers: failedParsers, Parser: p, Line: line, Column: column, Position: maxPos, Input: originalScanner.input}
return Node[T]{}, e
}