This repository was archived by the owner on Mar 27, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.go
More file actions
356 lines (322 loc) · 8.83 KB
/
base.go
File metadata and controls
356 lines (322 loc) · 8.83 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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package gparselib
import (
"cmp"
"errors"
"fmt"
"slices"
"strconv"
"strings"
)
//
// ---- Data types:
// FeedbackKind is just an enumeration of kinds of feedback.
type FeedbackKind int
// Enumeration of the kinds of feedback we can handle.
const (
FeedbackUnknown = FeedbackKind(iota) // should never be used directly but is default value
FeedbackInfo
FeedbackWarning
FeedbackPotentialProblem
FeedbackError
)
// FeedbackItem is just one item of feedback.
type FeedbackItem struct {
Pos int
Kind FeedbackKind
Msg fmt.Stringer
}
func (fi *FeedbackItem) String() string {
var msg string
switch fi.Kind {
case FeedbackInfo:
msg = "INFO: "
case FeedbackWarning:
msg = "WARNING: "
case FeedbackPotentialProblem:
msg = "PROBLEM?: "
case FeedbackError:
msg = "ERROR: "
default:
msg = "UNKNOWN!!!: "
}
return msg + fi.Msg.String()
}
// ParseResult contains the result of parsing including semantic value and
// feedback.
type ParseResult struct {
Pos int
Text string
Value interface{}
ErrPos int
Feedback []*FeedbackItem
}
// HasError searches the feedback for errors and returns only true if it found
// one.
func (pr *ParseResult) HasError() bool {
for _, fb := range pr.Feedback {
if fb.Kind == FeedbackError {
return true
}
}
return false
}
// AddInfo adds a new parse information to the result feedback.
func (pd *ParseData) AddInfo(pos int, msg string) {
pd.Result.Feedback = append(
pd.Result.Feedback,
&FeedbackItem{
Pos: pos,
Kind: FeedbackInfo,
Msg: newParseMessage(pd, pos, msg),
},
)
}
// AddWarning adds a new parser warning to the result feedback.
func (pd *ParseData) AddWarning(pos int, msg string) {
pd.Result.Feedback = append(
pd.Result.Feedback,
&FeedbackItem{
Pos: pos,
Kind: FeedbackWarning,
Msg: newParseMessage(pd, pos, msg),
},
)
}
// AddError adds a new parse error to the result feedback.
func (pd *ParseData) AddError(pos int, msg string, baseErr error) {
pd.Result.Feedback = append(
pd.Result.Feedback,
&FeedbackItem{
Pos: pos,
Kind: FeedbackError,
Msg: newParseError(pd, pos, msg, baseErr),
},
)
}
// CleanFeedback returns parser errors as a single error and
// additional feedback.
func (pd *ParseData) CleanFeedback(cleanEnd bool) {
if pd.Result.HasError() || len(pd.Result.Feedback) == 0 { // in error case we need all information
return
}
start := pd.Result.Pos
end := start + len(pd.Result.Text) // clean until here
if !cleanEnd {
end--
}
cleanFeedback := make([]*FeedbackItem, 0, len(pd.Result.Feedback))
for _, fb := range pd.Result.Feedback {
if fb.Kind != FeedbackPotentialProblem || fb.Pos < start || fb.Pos > end {
cleanFeedback = append(cleanFeedback, fb)
}
}
pd.Result.Feedback = cleanFeedback
}
// GetFeedback returns parser errors as a single error and
// additional feedback.
func (pd *ParseData) GetFeedback() (string, error) {
slices.SortFunc(pd.Result.Feedback, func(a, b *FeedbackItem) int {
if n := cmp.Compare(a.Pos, b.Pos); n != 0 {
return n
}
// If positions are equal, order by message
return strings.Compare(a.Msg.String(), b.Msg.String())
})
return feedbackInfo(pd.Result), feedbackError(pd.Result)
}
func feedbackError(pr *ParseResult) error {
b := strings.Builder{}
for _, fb := range pr.Feedback {
if fb.Kind == FeedbackError {
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString(fb.String())
}
}
if b.Len() == 0 {
return nil
}
return errors.New(b.String())
}
func feedbackInfo(pr *ParseResult) string {
b := strings.Builder{}
for _, fb := range pr.Feedback {
if fb.Kind != FeedbackError {
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString(fb.String())
}
}
return b.String()
}
// ResetSourcePos resets the source position to an old value.
// This is usually needed when semantic errors occur.
// If the given pos is negative, the position of the current result is used.
func (pd *ParseData) ResetSourcePos(pos int) {
if pos < 0 {
pd.Source.pos = pd.Result.Pos
} else {
pd.Source.pos = pos
}
}
// SourceData contains the name of the source for parsing, its contents and
// unexported stuff.
type SourceData struct {
Name string
content string
pos int
wherePrevNl int
whereLine int
}
// NewSourceData creates a new, completely initialized SourceData.
func NewSourceData(name string, content string) SourceData {
return SourceData{name, content, 0, -1, 1}
}
// Where describes the given integer position in a human-readable way.
func (sd SourceData) Where(pos int) string {
return where(&sd, pos)
}
// ParseData contains all data needed during parsing.
type ParseData struct {
Source SourceData
Result *ParseResult
SubResults []*ParseResult
}
// NewParseData creates a new, completely initialized ParseData.
func NewParseData(name string, content string) *ParseData {
return &ParseData{Source: NewSourceData(name, content)}
}
// parseMessage holds some information from the parser.
type parseMessage struct {
where string
msg string
}
// newParseMessage creates a new, completely initialized parseMessage.
func newParseMessage(pd *ParseData, pos int, msg string) *parseMessage {
return &parseMessage{where: pd.Source.Where(pos), msg: msg}
}
func (i *parseMessage) String() string {
b := &strings.Builder{}
b.WriteString(i.where)
b.WriteString(i.msg)
b.WriteRune('.')
return b.String()
}
// parseError holds information about a parser error.
type parseError struct {
where string
myErr string
baseErr error
}
// newParseError creates a new, completely initialized parseError.
func newParseError(pd *ParseData, pos int, msg string, baseErr error) *parseError {
return &parseError{where: pd.Source.Where(pos), myErr: msg, baseErr: baseErr}
}
func (e *parseError) Error() string {
msg := e.where + e.myErr
if e.baseErr != nil {
msg += ":\n" + e.baseErr.Error()
} else {
msg += "."
}
return msg
}
func (e *parseError) String() string {
return e.Error()
}
// ------- Base for all parsers:
// SubparserOp is a simple filter to the outside and gets the same data as the
// parent parser.
type SubparserOp func(pd *ParseData, ctx interface{}) (*ParseData, interface{})
// SemanticsOp is a simple filter for parser and context data.
type SemanticsOp func(pd *ParseData, ctx interface{}) (*ParseData, interface{})
// handleSemantics calls pluginSemantics if given and no error was detected, and always clears any subresults.
func handleSemantics(pluginSemantics SemanticsOp, pd *ParseData, ctx interface{}) (*ParseData, interface{}) {
if pluginSemantics != nil && pd.Result.ErrPos < 0 {
pd, ctx = pluginSemantics(pd, ctx)
}
pd.SubResults = nil
return pd, ctx
}
//
// ---- Utility functions:
func createMatchedResult(pd *ParseData, n int) {
i := pd.Source.pos
n += i
pd.Result = &ParseResult{
Pos: i,
Text: pd.Source.content[i:n],
Value: nil,
ErrPos: -1,
Feedback: make([]*FeedbackItem, 0, 8),
}
pd.Source.pos = n
}
func createUnmatchedResult(pd *ParseData, i int, msg string, baseErr error) {
i += pd.Source.pos
pd.Result = &ParseResult{pd.Source.pos, "", nil, i, make([]*FeedbackItem, 0, 64)}
pd.AddError(i, msg, baseErr)
}
func where(src *SourceData, pos int) string {
if src.content == "" {
return generateWhereMessage(src.Name, 1, 1, "")
}
if pos >= src.wherePrevNl {
return whereForward(src, pos)
} else if pos <= src.wherePrevNl-pos {
src.whereLine = 1
src.wherePrevNl = -1
return whereForward(src, pos)
} else {
return whereBackward(src, pos)
}
}
func whereForward(src *SourceData, pos int) string {
text := src.content
lineNum := src.whereLine // Line number
prevNl := src.wherePrevNl // Line start (position of preceding newline)
var nextNl int // Position of next newline or end
for {
nextNl = strings.IndexByte(text[prevNl+1:], '\n')
if nextNl < 0 {
nextNl = len(text)
} else {
nextNl += prevNl + 1
}
where, stop := tryWhere(src, prevNl, pos, nextNl, lineNum)
if stop {
return where
}
prevNl = nextNl
lineNum++
}
}
func whereBackward(src *SourceData, pos int) string {
text := src.content
lineNum := src.whereLine // Line number
var prevNl int // Line start (position of preceding newline)
nextNl := src.wherePrevNl // Position of next newline or end
for {
prevNl = strings.LastIndexByte(text[0:nextNl], '\n')
lineNum--
where, stop := tryWhere(src, prevNl, pos, nextNl, lineNum)
if stop {
return where
}
nextNl = prevNl
}
}
func tryWhere(src *SourceData, prevNl int, pos int, nextNl int, lineNum int) (where string, stop bool) {
if prevNl < pos && pos <= nextNl {
src.wherePrevNl = prevNl
src.whereLine = lineNum
return generateWhereMessage(src.Name, lineNum, pos-prevNl, src.content[prevNl+1:nextNl]), true
}
return "", false
}
func generateWhereMessage(name string, line int, col int, srcLine string) string {
return "File '" + name + "', line " + strconv.Itoa(line) +
", column " + strconv.Itoa(col) + ":\n" + srcLine + "\n"
}