<- Back to shtanton's homepage
aboutsummaryrefslogtreecommitdiff
path: root/subex/parse.go
blob: 9a7a75c5183de8c2b595ea1ee15475355975e028 (plain)
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package subex

import (
	"fmt"
	"main/walk"
	"strconv"
	"strings"
)

type Type int
const (
	AnyType Type = iota
	ValueType
	RuneType
)

func resolveTypes(t1 Type, t2 Type) Type {
	if t1 == AnyType {
		return t2
	}

	if t2 == AnyType {
		return t1
	}

	if t1 == t2 {
		return t1
	}

	panic("Types don't match in parser")
}

type Structure int
const (
	NoneStructure Structure = iota
	StringStructure
	ArrayStructure
	ArrayValuesStructure
	MapStructure
)
func (s Structure) String() string {
	switch s {
	case NoneStructure:
		return "-"
	case StringStructure:
		return "~"
	case ArrayStructure:
		return "@"
	case ArrayValuesStructure:
		return ":"
	case MapStructure:
		return "#"
	default:
		panic("Invalid structure")
	}
}

type DestructureMethod int
const (
	Normal DestructureMethod = iota
	Iterate
)

type RuneReader interface {
	Next() rune
	Rewind()
}

func accept(l RuneReader, chars string) bool {
	r := l.Next()
	for _, char := range chars {
		if char == r {
			return true
		}
	}
	l.Rewind()
	return false
}

func isNumericRune(r rune) bool {
	return '0' <= r && r <= '9' || r == '.'
}

// Having just parsed a `, read until the next ` and parse the contents into a list of non-string atoms
func parseScalarLiteral(l RuneReader) (walk.Scalar, bool) {
	r := l.Next()
	if isNumericRune(r) {
		var builder strings.Builder
		builder.WriteRune(r)
		for {
			r := l.Next()
			if !isNumericRune(r) {
				l.Rewind()
				break
			}
			builder.WriteRune(r)
		}
		numberString := builder.String()
		number, err := strconv.ParseFloat(numberString, 64)
		if err != nil {
			panic("Invalid number literal")
		}
		return walk.NumberValue(number), true
	}
	switch r {
		case 'n':
			if accept(l, "u") && accept(l, "l") && accept(l, "l") {
				return walk.NullValue{}, true
			} else {
				panic("Invalid literal")
			}
		case 't':
			if accept(l, "r") && accept(l, "u") && accept(l, "e") {
				return walk.BoolValue(true), true
			} else {
				panic("Invalid literal")
			}
		case 'f':
			if accept(l, "a") && accept(l, "l") && accept(l, "s") && accept(l, "e") {
				return walk.BoolValue(false), true
			} else {
				panic("Invalid literal")
			}
		default:
			fmt.Printf("%c\n", r)
			panic("Invalid literal")
	}
}

func charIsDigit(c rune) bool {
	return '0' <= c && c <= '9'
}

// Parse a positive integer, reads digits 0-9 and stops at the first non-digit
func parseInt(l RuneReader) (output int) {
	for {
		char := l.Next()
		if charIsDigit(char) {
			output = output * 10 + int(char - '0')
		} else {
			break
		}
	}
	l.Rewind()
	return output
}

// Having just read {, read in and parse the range contents
func parseRepeatRange(l RuneReader) (output []ConvexRange) {
	loop: for {
		var start, end int
		char := l.Next()
		l.Rewind()
		if char == '-' {
			start = -1
		} else {
			start = parseInt(l)
		}
		switch l.Next() {
			case ',':
				output = append(output, ConvexRange{start, start})
				continue loop
			case '-':
				char := l.Next()
				if charIsDigit(char) {
					l.Rewind()
					end = parseInt(l)
				} else {
					l.Rewind()
					end = -1
				}
			case '}':
				output = append(output, ConvexRange{start, start})
				break loop
			default:
				panic("Invalid character in repeat specifier")
		}
		switch l.Next() {
			case ',':
				output = append(output, ConvexRange{start, end})
				continue loop
			case '}':
				output = append(output, ConvexRange{start, end})
				break loop
			default:
				panic("Invalid character in repeat specifier")
		}
	}
	return output
}

func parseValueReplacement(l RuneReader, end rune) (output SubexAST) {
	output = SubexASTEmpty{}
	// TODO escaping
	// TODO add arrays, maps and strings
	loop: for {
		r := l.Next()
		switch r {
		case eof:
			panic("Missing closing `")
		case ' ':
		case end:
			break loop
		case '$':
			slot := l.Next()
			if slot == eof {
				panic("Missing slot character")
			}
			output = SubexASTConcat {
				First: output,
				Second: SubexASTOutputValueLoad {
					slot: slot,
				},
			}
		// TODO: destructures
		case '#':
			if !accept(l, "(") {
				panic("Missing ( after #")
			}
			output = SubexASTConcat {
				First: output,
				Second: SubexASTDestructure {
					Destructure: NoneStructure,
					Structure: MapStructure,
					Content: parseValueReplacement(l, ')'),
				},
			}
			if !accept(l, "#") {
				panic("Missing # after )")
			}
		case '"':
			output = SubexASTConcat {
				First: output,
				Second: SubexASTDestructure {
					Destructure: NoneStructure,
					Structure: StringStructure,
					Content: parseRuneReplacement(l, '"'),
				},
			}
		default:
			l.Rewind()
			scalar, ok := parseScalarLiteral(l)
			if !ok {
				panic("Invalid scalar literal")
			}
			output = SubexASTConcat {
				First: output,
				Second: SubexASTOutputValueLiteral {
					literal: scalar,
				},
			}
		}
	}
	return output
}

func parseRuneReplacement(l RuneReader, end rune) (output SubexAST) {
	output = SubexASTEmpty{}
	// TODO escaping
	loop: for {
		r := l.Next()
		switch r {
		case eof:
			panic("Missing closing `")
		case end:
			break loop
		case '$':
			slot := l.Next()
			if slot == eof {
				panic("Missing slot character")
			}
			output = SubexASTConcat {
				First: output,
				Second: SubexASTOutputRuneLoad {
					slot: slot,
				},
			}
		default:
			output = SubexASTConcat {
				First: output,
				Second: SubexASTOutputRuneLiteral {
					literal: r,
				},
			}
		}
	}
	return output
}

// Parse the contents of a range subex [] into a map
// func parseRangeSubex(l RuneReader) map[walk.AtomOLD]walk.AtomOLD {
// 	// TODO escaping
// 	parts := make(map[walk.AtomOLD]walk.AtomOLD)
// 	var froms []walk.AtomOLD
// 	var hasTo bool
// 	for {
// 		fromsStart := l.Next()
// 		if fromsStart == ']' {
// 			hasTo = false
// 			break
// 		} else if fromsStart == '=' {
// 			hasTo = true
// 			break
// 		} else if fromsStart == '`' {
// 			literals := parseNonStringLiteral(l)
// 			froms = append(froms, literals...)
// 			continue
// 		} else if fromsStart == '"' {
// 			froms = append(froms, walk.NewAtomStringTerminal())
// 			continue
// 		}
// 		if accept(l, "-") {
// 			fromsEnd := l.Next()
// 			if fromsEnd == ']' || fromsEnd == '=' {
// 				l.Rewind()
// 				fromsEnd = fromsStart
// 			}
// 			for i := fromsStart; i <= fromsEnd; i += 1 {
// 				froms = append(froms, walk.NewAtomStringRune(i))
// 			}
// 		} else {
// 			froms = append(froms, walk.NewAtomStringRune(fromsStart))
// 		}
// 	}
// 	if len(froms) == 0 {
// 		panic("Missing from part of range expression")
// 	}

// 	var tos []walk.AtomOLD
// 	if hasTo {
// 		for {
// 			tosStart := l.Next()
// 			if tosStart == ']' {
// 				break
// 			} else if tosStart == '`' {
// 				literals := parseNonStringLiteral(l)
// 				tos = append(tos, literals...)
// 				continue
// 			} else if tosStart == '"' {
// 				tos = append(tos, walk.NewAtomStringTerminal())
// 				continue
// 			}
// 			if accept(l, "-") {
// 				tosEnd := l.Next()
// 				if tosEnd == ']' {
// 					l.Rewind()
// 					tosEnd = tosStart
// 				}
// 				for i := tosStart; i <= tosEnd; i += 1 {
// 					tos = append(tos, walk.NewAtomStringRune(i))
// 				}
// 			} else {
// 				tos = append(tos, walk.NewAtomStringRune(tosStart))
// 			}
// 		}
// 	} else {
// 		tos = froms
// 	}
// 	if len(tos) == 0 {
// 		panic("Missing to part of range expression")
// 	}
	
// 	for i, from := range froms {
// 		parts[from] = tos[i % len(tos)]
// 	}
// 	return parts
// }

func parseDestructure(l RuneReader, destructure Structure, inType Type) (lhs SubexAST, outType Type) {
	var method rune
	switch l.Next() {
	case '(':
		method = ')'
	case '[':
		method = ']'
	default:
		panic("Missing ( or [ after destructure start")
	}

	var innerInType Type
	var expectedInType Type
	switch destructure {
	case NoneStructure:
		innerInType = inType
		expectedInType = inType
	case StringStructure:
		innerInType = RuneType
		expectedInType = ValueType
	case ArrayStructure:
		innerInType = ValueType
		expectedInType = ValueType
	case ArrayValuesStructure:
		innerInType = ValueType
		expectedInType = ValueType
	case MapStructure:
		innerInType = ValueType
		expectedInType = ValueType
	default:
		panic("Invalid structure")
	}

	resolveTypes(inType, expectedInType)

	lhs, innerOutType := parseSubex(l, 0, innerInType)
	if !accept(l, string(method)) {
		panic("Missing matching ) or ]")
	}

	switch method {
	case ')':
	case ']':
		lhs = SubexASTRepeat {
			Content: lhs,
			Acceptable: []ConvexRange{{
				Start: -1,
				End: 0,
			}},
		}
	default:
		panic("Invalid method")
	}

	var structure Structure
	var expectedInnerOutType Type
	r := l.Next()
	switch r {
	case '-':
		structure = NoneStructure
		expectedInnerOutType = innerOutType
	case '~':
		structure = StringStructure
		expectedInnerOutType = RuneType
	case '@':
		structure = ArrayStructure
		expectedInnerOutType = ValueType
	case ':':
		structure = ArrayValuesStructure
		expectedInnerOutType = ValueType
	case '#':
		structure = MapStructure
		expectedInnerOutType = ValueType
	default:
		panic("Missing matching destructure")
	}

	innerOutType = resolveTypes(innerOutType, expectedInnerOutType)

	switch structure {
	case NoneStructure:
		outType = innerOutType
	case StringStructure:
		outType = ValueType
	case ArrayStructure:
		outType = ValueType
	case ArrayValuesStructure:
		outType = ValueType
	case MapStructure:
		outType = ValueType
	}

	lhs = SubexASTDestructure {
		Destructure: destructure,
		Structure: structure,
		Content: lhs,
	}

	return lhs, outType
}

func parseSubex(l RuneReader, minPower int, inType Type) (lhs SubexAST, outType Type) {
	start:
	r := l.Next()
	switch r {
		case eof:
			return nil, inType
		case '(':
			lhs, outType = parseSubex(l, 0, inType)
			if !accept(l, ")") {
				panic("Missing matching )")
			}
		case '-':
			lhs, outType = parseDestructure(l, NoneStructure, inType)
		case '~':
			lhs, outType = parseDestructure(l, StringStructure, inType)
		case '@':
			lhs, outType = parseDestructure(l, ArrayStructure, inType)
		case ':':
			lhs, outType = parseDestructure(l, ArrayValuesStructure, inType)
		case '#':
			lhs, outType = parseDestructure(l, MapStructure, inType)
		case '"':
			if inType == ValueType {
				var innerOutType Type
				lhs, innerOutType = parseSubex(l, 0, RuneType)
				if !accept(l, "\"") {
					panic("Missing matching \"")
				}
				resolveTypes(innerOutType, RuneType)
				lhs = SubexASTDestructure {
					Destructure: StringStructure,
					Structure: StringStructure,
					Content: lhs,
				}
				outType = ValueType
			} else {
				l.Rewind()
				return SubexASTEmpty{}, inType
			}
		// TODO
		// case '[':
		// 	rangeParts := parseRangeSubex(l)
		// 	lhs = SubexASTRange {rangeParts}
		case ')', ']', '|', ';', '{', '+', '*', '/', '!', '=', '$':
			l.Rewind()
			return SubexASTEmpty{}, inType
		case '.':
			outType = inType
			if inType == RuneType {
				lhs = SubexASTCopyAnyRune{}
			} else {
				lhs = SubexASTCopyAnyValue{}
			}
		case '?':
			outType = inType
			lhs = SubexASTCopyBool{}
		case '%':
			outType = inType
			lhs = SubexASTCopyNumber{}
		case '`':
			outType = inType
			switch inType {
			case ValueType:
				lhs = parseValueReplacement(l, '`')
			case RuneType:
				lhs = parseRuneReplacement(l, '`')
			default:
				panic("Invalid inType")
			}
		case ' ':
			if inType == RuneType {
				outType = RuneType
				lhs = SubexASTCopyRune {' '}
			} else {
				goto start
			}
		default:
			outType = inType
			if inType == RuneType {
				lhs = SubexASTCopyRune {r}
			} else {
				l.Rewind()
				scalar, ok := parseScalarLiteral(l)
				if !ok {
					panic("Invalid subex")
				}
				lhs = SubexASTCopyScalar {scalar}
			}
	}
	loop: for {
		if minPower <= 20 {
			next, outType2 := parseSubex(l, 21, inType)
			// TODO: next might legitimately be SubexASTEmpty, e.g. ``
			if next != nil && (next != SubexASTEmpty{}) {
				outType = resolveTypes(outType, outType2)
				lhs = SubexASTConcat{lhs, next}
				continue loop
			}
		}
		r := l.Next()
		switch {
			case r == '{' && minPower <= 4:
				lhs = SubexASTRepeat {
					Content: lhs,
					Acceptable: parseRepeatRange(l),
				}
			case r == '+' && minPower <= 4:
				lhs = SubexASTSum {lhs}
				resolveTypes(inType, ValueType)
				outType = resolveTypes(outType, ValueType)
			case r == '*' && minPower <= 4:
				lhs = SubexASTProduct {lhs}
				resolveTypes(inType, ValueType)
				outType = resolveTypes(outType, ValueType)
			case r == '!' && minPower <= 4:
				lhs = SubexASTNot {lhs}
				resolveTypes(inType, ValueType)
				outType = resolveTypes(outType, ValueType)
			case r == '$' && minPower <= 4:
				slot := l.Next()
				if slot == eof {
					panic("Missing slot character")
				}
				if slot == '_' {
					lhs = SubexASTDiscard {
						Content: lhs,
						InnerOutType: outType,
					}
				} else {
					if inType == ValueType {
						lhs = SubexASTStoreValues {
							Match: lhs,
							Slot: slot,
						}
					} else {
						lhs = SubexASTStoreRunes {
							Match: lhs,
							Slot: slot,
						}
					}
				}
				outType = AnyType
			case r == '|' && minPower <= 8:
				rhs, outType2 := parseSubex(l, 9, inType)
				outType = resolveTypes(outType, outType2)
				if rhs == nil {
					panic("Missing subex after |")
				}
				lhs = SubexASTOr{lhs, rhs}
			default:
				l.Rewind()
				break loop
		}
	}
	return lhs, outType
}

func Parse(l RuneReader) SubexAST {
	ast, outType := parseSubex(l, 0, ValueType)
	outType = resolveTypes(outType, ValueType)
	if ast == nil {
		return SubexASTEmpty{}
	}
	return ast
}