ref: d8fadd0cb30377c98f5f69b5c3603b436149a45d fastpeg/internal/bootstrap/scanner/scanner.go -rw-r--r-- 9.4 KiB View raw
                                                                                
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
// Package scanner implements a scanner for fastpeg input. It takes a
// []byte as source which can then be tokenized through repeated calls
// to the Scan method.
//
// Heavily based on the stdlib's go/scanner package.
package scanner

import (
	"fmt"
	"go/scanner"
	"unicode"
	"unicode/utf8"

	"git.sr.ht/~mna/fastpeg/internal/bootstrap/token"
)

const (
	// byte order mark, only permitted as very first character
	bom = 0xFEFF
	// rune representing EOF
	eof = -1
)

// ErrorList is a list of errors.
type ErrorList = scanner.ErrorList

// A Scanner holds the scanner's internal state while processing a
// given input. It can be allocated as part of another data structure
// but must be initialized via Init before use.
type Scanner struct {
	// immutable fields outside of Init calls
	file *token.File
	src  []byte
	errs *ErrorList

	// mutable state
	rn      rune // current rune
	curpos  int  // start index of current rune (rn)
	nextpos int  // start index of next rune
	linepos int  // current line index
}

// Init prepares the scanner s to tokenize the input src by setting
// the scanner at the beginning of src. The scanner uses the file set
// file for position information and it adds line information for each
// line. Init causes a panic if the file size does not match the src
// size.
func (s *Scanner) Init(file *token.File, src []byte) {
	if file.Size() != len(src) {
		panic(fmt.Sprintf("%s: file size does not match input size: %d bytes vs %d bytes", file.Name(), file.Size(), len(src)))
	}

	s.file = file
	s.src = src
	if s.errs == nil {
		// TODO: probably needs to be passed by the parser
		s.errs = new(ErrorList)
	}

	s.rn = 0
	s.curpos = 0
	s.nextpos = 0
	s.linepos = 0

	s.advance()
	if s.rn == bom {
		// ignore BOM at start of input
		s.advance()
	}
}

// Err returns the error(s) registered in the error list of the
// scanner if any, or nil.
func (s *Scanner) Err() error {
	return s.errs.Err()
}

// advance the scanner to the next rn in the src.
// rn == -1 on EOF.
func (s *Scanner) advance() {
	if s.nextpos >= len(s.src) {
		s.curpos = len(s.src)
		if s.rn == '\n' {
			s.linepos = s.curpos
			s.file.AddLine(s.linepos)
		}
		s.rn = eof
		return
	}

	s.curpos = s.nextpos
	if s.rn == '\n' {
		s.linepos = s.curpos
		s.file.AddLine(s.linepos)
	}

	rn, sz := rune(s.src[s.nextpos]), 1
	switch {
	case rn == 0:
		// Note that this wouldn't be an error case in the parser with byte
		// option, but this bootstrap parser only has to parse the fastpeg
		// language with is rune-based (even ascii-based, but anyway).
		s.error(s.curpos, "illegal character NUL")
	case rn >= utf8.RuneSelf:
		// not ascii
		rn, sz = utf8.DecodeRune(s.src[s.nextpos:])
		if rn == utf8.RuneError && sz == 1 {
			s.error(s.curpos, "illegal UTF-8 encoding")
		} else if rn == bom && s.curpos > 0 {
			s.error(s.curpos, "illegal byte-order mark")
		}
	}

	s.nextpos += sz
	s.rn = rn
}

func (s *Scanner) error(offset int, msg string) {
	fpos := s.file.Position(s.file.Pos(offset))
	s.errs.Add(fpos, msg)
}

func (s *Scanner) skipWhitespace() {
	for s.rn == ' ' || s.rn == '\t' || s.rn == '\n' || s.rn == '\r' {
		s.advance()
	}
}

// Scan scans the next token and returns the token position, the token,
// and its literal string if applicable. The source end is indicated
// by token.EOF.
//
// If the returned token is a literal, the literal string has the
// corresponding value. If the returned token is token.Illegal, the
// literal string is the offending character.  In all other cases,
// Scan returns an empty literal string.
//
// Scan adds line information to the file added to the file set with
// Init. Token positions are relative to that file and thus relative
// to the file set.
func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) {
	s.skipWhitespace()

	pos = s.file.Pos(s.curpos)
	switch rn := s.rn; {
	case isLetter(rn):
		tok = token.Identifier
		lit = s.scanIdentifier()

	default:
		s.advance()

		switch rn {
		case eof:
			tok = token.EOF

		case '"', '\'':
			tok = token.Literal
			lit = s.scanLiteral(rn)

		case '[':
			tok = token.CharClass
			lit = s.scanCharClass()

		case '<':
			if s.rn != '-' {
				s.error(s.curpos-1, fmt.Sprintf("incomplete arrow symbol: illegal character %#U", s.rn))
				break
			}
			s.advance()
			lit = "<-"
			fallthrough
		case '←', '⟵', '=':
			tok = token.Arrow
			if lit == "" {
				lit = string(rn)
			}

		case '|', '/':
			tok = token.Separator
			lit = string(rn)

		case '&':
			if s.rn != '{' {
				tok = token.Ampersand
				break
			}
			tok = token.PredCoderef
			lit = s.scanCoderef()

		case '$':
			if s.rn != '{' {
				s.error(s.curpos-1, fmt.Sprintf("invalid state coderef: illegal character %#U", s.rn))
				break
			}
			tok = token.StateCoderef
			lit = s.scanCoderef()

		case '@':
			if s.rn != '{' {
				s.error(s.curpos-1, fmt.Sprintf("invalid state coderef: illegal character %#U", s.rn))
				break
			}
			tok = token.ActionCoderef
			lit = s.scanCoderef()

		case '.', ':', ';', '!', '?', '*', '+', '(', ')':
			tok = token.FromString(string(rn))

		default:
			// s.advance already reports bom, ignore it here
			if rn != bom {
				s.error(s.file.Offset(pos), fmt.Sprintf("illegal character %#U", rn))
			}
			tok = token.Illegal
			lit = string(rn)
		}
	}

	return pos, tok, lit
}

func (s *Scanner) scanIdentifier() string {
	// when called, s.rn is on the start of the identifier
	start := s.curpos
	for isLetter(s.rn) || isDigit(s.rn) {
		s.advance()
	}
	return string(s.src[start:s.curpos])
}

func (s *Scanner) scanLiteral(quote rune) string {
	// when called, the opening quote is already consumed
	start := s.curpos - 1
	for {
		rn := s.rn
		if rn == '\n' || rn == eof {
			s.error(start, "literal not terminated")
			break
		}
		s.advance()
		if rn == quote {
			break
		}
		if rn == '\\' {
			s.scanLiteralEsc(quote)
		}
	}
	return string(s.src[start:s.curpos])
}

func (s *Scanner) scanCharClass() string {
	// when called, the '[' is already consumed
	start := s.curpos - 1
	for {
		rn := s.rn
		if rn == '\n' || rn == eof {
			s.error(start, "character class not terminated")
			break
		}
		s.advance()
		if rn == ']' {
			break
		}

		// the character range is separated by '-', but there's no
		// special handling required to parse this, if there is no pair
		// of chars around the '-', then it matches the minus symbol
		// itself and is not the "range separator". Meaning:
		//
		// [-] matches '-'
		// [^-] is "not '-'"
		// [^-a] is "not '-' nor 'a'" because '^' at first position always negates
		// [--/] is "from '-' to '/'"
		// [---] is probably invalid, but in the parser, not scanner
		// [a-] is 'a' and '-'
		// [ab-] is 'a', 'b' and '-'
		// [a-b] is "from 'a' to 'b'
		// [ab-c] is 'a' then from 'b' to 'c'

		if rn == '\\' {
			s.scanCharClassEsc()
		}
	}
	return string(s.src[start:s.curpos])
}

func (s *Scanner) scanCharClassEsc() {
	// when called, the '\\' is already consumed
	switch s.rn {
	case '[', '-', '^':
		s.advance()
		return

	case 'p', 'P':
		s.advance()
		switch s.rn {
		case 'C', 'L', 'M', 'N', 'P', 'S', 'Z':
			s.advance()
			return

		case '{':
			s.advance()
			// must be followed by an identifier
			if !isLetter(s.rn) {
				msg := "invalid Unicode class"
				if s.rn < 0 {
					msg = "escape sequence not terminated"
				}
				s.error(s.curpos, msg)
				return
			}
			s.scanIdentifier()
			if s.rn != '}' {
				s.error(s.curpos, "escape sequence not terminated")
				return
			}
			s.advance()
			return

		default:
			msg := "invalid Unicode class"
			if s.rn < 0 {
				msg = "escape sequence not terminated"
			}
			s.error(s.curpos, msg)
		}

	default:
		s.scanLiteralEsc(']')
	}
}

func (s *Scanner) scanLiteralEsc(quote rune) {
	// when called, the '\\' is already consumed
	switch s.rn {
	case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote:
		s.advance()
		return

	case 'x':
		s.advance()
		s.scanHexValue(2, 255)
	case 'u':
		s.advance()
		s.scanHexValue(4, unicode.MaxRune)
	case 'U':
		s.advance()
		s.scanHexValue(8, unicode.MaxRune)

	default:
		msg := "unknown escape sequence"
		if s.rn < 0 {
			msg = "escape sequence not terminated"
		}
		s.error(s.curpos, msg)
	}
}

func (s *Scanner) scanHexValue(digits int, max uint32) {
	const base = 16

	escStart := s.curpos - 1 // i.e. after '\\', at the 'x', 'u' or 'U'
	var val uint32
	for digits > 0 {
		d := uint32(digitVal(s.rn))
		if d >= base {
			msg := fmt.Sprintf("illegal character %#U in escape sequence", s.rn)
			if s.rn < 0 {
				msg = "escape sequence not terminated"
			}
			s.error(s.curpos, msg)
			return
		}

		val = val*base + d
		s.advance()
		digits--
	}

	if val > max || 0xD800 <= val && val < 0xE000 {
		s.error(escStart, "escape sequence is invalid Unicode code point")
	}
}

func (s *Scanner) scanCoderef() string {
	// when called, s.rn is on the start '{'
	start := s.curpos
	s.advance()

	s.skipWhitespace()
	ident := s.scanIdentifier()
	s.skipWhitespace()

	if s.rn == '}' {
		s.advance()
	} else {
		s.error(start, "coderef not terminated")
	}
	if ident == "" {
		s.error(start, "coderef missing identifier")
	}
	return ident
}

func digitVal(rn rune) int {
	switch {
	case '0' <= rn && rn <= '9':
		return int(rn - '0')
	case 'a' <= rn && rn <= 'f':
		return int(rn - 'a' + 10)
	case 'A' <= rn && rn <= 'F':
		return int(rn - 'A' + 10)
	}
	return 16
}

func isLetter(rn rune) bool {
	return 'a' <= rn && rn <= 'z' || 'A' <= rn && rn <= 'Z' || rn == '_' || rn >= utf8.RuneSelf && unicode.IsLetter(rn)
}

func isDigit(rn rune) bool {
	return '0' <= rn && rn <= '9' || rn == '-' || rn >= utf8.RuneSelf && unicode.IsDigit(rn)
}