-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.go
309 lines (286 loc) · 7.32 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
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
package synta
import (
"errors"
"fmt"
"regexp"
"strings"
)
// ParseSynta attempts to parse a file's contents into a Synta internal
// representation. If an error is encountered the parsing is aborted and the
// error returned
func ParseSynta(contents string) (s Synta, err error) {
lines := strings.Split(contents, "\n")
// remove blank lines
for i := 0; i < len(lines); i++ {
lines[i] = strings.TrimSpace(lines[i])
if lines[i] == "" {
lines = append(lines[:i], lines[i+1:]...)
}
}
var (
consumed = 0
id = Identifier("")
def = Definition{}
definitionLines = []string{}
filenameLine = ""
)
if len(lines) > 1 {
definitionLines = lines[:len(lines)-1]
filenameLine = lines[len(lines)-1]
} else if len(lines) == 1 {
err = errors.New("Missing either the filename or defintions")
} else {
err = errors.New("Empty file provided")
return
}
s.Definitions = map[Identifier]Definition{}
for len(definitionLines) > 0 {
consumed, id, def, err = parseFirstDefinition(definitionLines)
definitionLines = definitionLines[consumed:]
if err != nil {
return
}
if _, ok := s.Definitions[id]; ok {
err = fmt.Errorf("Defintion for `%s` is provided twice", id)
return
} else if err == nil {
s.Definitions[id] = def
}
}
s.Filename.Segments, s.Filename.Extension, err = parseFilename(filenameLine)
if err != nil {
return
}
requiredIdentifiers := getRequiredIdentifiers(s.Filename.Segments)
requiredIdentifiers = append(requiredIdentifiers, s.Filename.Extension)
for _, id := range requiredIdentifiers {
if _, ok := s.Definitions[id]; !ok {
err = fmt.Errorf("Missing definition for `%s`", id)
return
}
}
return
}
func getRequiredIdentifiers(segments []Segment) (requiredIdentifiers []Identifier) {
for _, seg := range segments {
if seg.Kind == SegmentTypeOptional {
requiredIdentifiers = append(requiredIdentifiers, getRequiredIdentifiers(seg.Subsegments)...)
} else {
requiredIdentifiers = append(requiredIdentifiers, *seg.Value)
}
}
return
}
func MustSynta(contents string) Synta {
s, err := ParseSynta(contents)
if err != nil {
panic(err)
}
return s
}
// ParseNextDefinition loops from the start line, until a definition is found.
// All the lines from start to the defintion must be comments. If the defintion
// identifier is not valid, we return an error, otherwise, the definition index,
// the definition identifier and the definition itself are returned.
func parseFirstDefinition(lines []string) (consumed int, id Identifier, def Definition, err error) {
for _, line := range lines {
consumed++
if line[0] == ';' {
def.Comments = append(def.Comments, strings.TrimSpace(line[1:]))
} else {
parsed_line := strings.Split(line, " = ")
raw_id, expr := parsed_line[0], parsed_line[1]
if !IdentifierRegexp.Match([]byte(raw_id)) {
err = fmt.Errorf("Invalid identifier: %s", raw_id)
return
}
id = Identifier(raw_id)
def.Regexp, err = regexp.Compile(expr)
return
}
}
err = errors.New("No next definition")
return
}
type State uint8
const (
State0 State = iota
State1
State2
State3
State4
State5
State6
State7
State8
)
func isLetter(c byte) bool {
return c >= 'a' && c <= 'z'
}
func concat(seg *Segment, c byte) {
val := Identifier(string(*seg.Value) + string(c))
seg.Value = &val
}
func clear(seg *Segment) {
emptyValue := Identifier("")
seg.Value = &emptyValue
seg.Kind = SegmentTypeIdentifier
}
func push(segments []Segment, seg *Segment, depth int) (updatedSegments []Segment) {
backup := segments
for i := 0; i < depth-1; i++ {
segments = segments[len(segments)-1].Subsegments
}
if depth > 0 {
segments[len(segments)-1].Subsegments = append(segments[len(segments)-1].Subsegments, *seg)
} else {
backup = append(backup, *seg)
}
updatedSegments = backup
clear(seg)
return
}
func generateOptional(segments []Segment, depth int) (updatedSegments []Segment) {
backup := segments
newOptional := Segment{SegmentTypeOptional, nil, []Segment{}}
for i := 0; i < depth-1; i++ {
segments = segments[len(segments)-1].Subsegments
}
if depth > 0 {
segments[len(segments)-1].Subsegments = append(segments[len(segments)-1].Subsegments, newOptional)
} else {
backup = append(backup, newOptional)
}
updatedSegments = backup
return
}
// parseFilename checks if the line starts with "> ", or errors otherwise.
// Then, it parses a list of segments from the line using a DFA. If an invalid
// char is found, an error is returned, otherwise the result is the list of
// prased defintions.
func parseFilename(line string) (def []Segment, ext Identifier, err error) {
if len(line) < 2 || line[:2] != "> " {
err = errors.New("Not a Filename")
return
}
line = line[2:]
state := State0
depth := 0
seg := Segment{}
clear(&seg)
col := 0
for col = 0; err == nil && col < len(line); col++ {
c := line[col]
switch state {
case State0:
if isLetter(c) {
concat(&seg, c)
state = State1
} else if c == '(' {
def = generateOptional(def, depth)
depth++
state = State2
} else {
err = errors.New("Expected either a char or a (")
}
case State1:
if isLetter(c) {
concat(&seg, c)
} else if c == '-' {
def = push(def, &seg, depth)
state = State0
} else if c == '(' {
def = push(def, &seg, depth)
def = generateOptional(def, depth)
depth++
state = State2
} else if c == '.' {
if depth == 0 {
def = push(def, &seg, depth)
state = State7
} else {
err = errors.New("Depth is not 0, you must close the optional segment")
}
} else {
err = errors.New("Expected either a char, or a -, or a ( or a .")
}
case State2:
if c == '-' {
state = State3
} else {
err = errors.New("Expected a -")
}
case State3:
if isLetter(c) {
concat(&seg, c)
state = State4
} else {
err = errors.New("Expected a char")
}
case State4:
if isLetter(c) {
concat(&seg, c)
} else if c == ')' {
def = push(def, &seg, depth)
depth--
state = State5
} else if c == '(' {
def = push(def, &seg, depth)
def = generateOptional(def, depth)
depth++
state = State2
} else {
err = errors.New("Expected a char, or a ( or a )")
}
case State5:
if c == '?' {
state = State6
} else {
err = errors.New("Expected a ?")
}
case State6:
if c == '-' {
state = State0
} else if c == '.' {
if depth == 0 {
state = State7
} else {
err = errors.New("Depth is not 0, you must close the optional segment")
}
} else if c == '(' {
def = generateOptional(def, depth)
depth++
state = State2
} else if c == ')' {
depth--
state = State5
} else {
err = errors.New("Expected either a - or a . or a ( or a )")
}
case State7:
if isLetter(c) {
concat(&seg, c)
state = State8
} else {
err = errors.New("Expected a char")
}
case State8:
if isLetter(c) {
concat(&seg, c)
} else {
err = errors.New("Expected a char")
}
}
}
// ensure that we stop on an accepting state
if err == nil && state != State8 {
err = fmt.Errorf("Stopped at a non-accepting state (was %d, expected 8)", state)
}
// handle the filename extension
ext = *seg.Value
// add debug information to the error string
if err != nil {
err = fmt.Errorf("Invalid char at column %d:\n%s\n%s\n%v", col, line, strings.Repeat(" ", col-1)+"^", err)
}
return
}