Debian Codegraph @

internal/frontend/scanner/scanner.go

raw symbols SCIP
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // A scanner for Go source text. Takes a []byte as source which can
6 // then be tokenized through repeated calls to the Scan function.
7 // For a sample use of a scanner, see the implementation of Tokenize.
8 package scanner
9
10 import (
11 "bytes"
12 "strconv"
13 "unicode"
14 "unicode/utf8"
15
16 "github.com/goccmack/gocc/internal/frontend/token"
17 )
18
19 // A Scanner holds the scanner's internal state while processing
20 // a given text. It can be allocated as part of another data
21 // structure but must be initialized via Init before use. For
22 // a sample use, see the implementation of Tokenize.
23 type Scanner struct {
24 // immutable state
25 src []byte // source
26 tokenMap *token.TokenMap
27
28 // scanning state
29 pos token.Position // previous reading position (position before ch)
30 offset int // current reading offset (position after ch)
31 ch rune // one char look-ahead
32
33 // public state - ok to modify
34 ErrorCount int // number of errors encountered
35 }
36
37 // Read the next Unicode char into S.ch.
38 // S.ch < 0 means end-of-file.
39 func (S *Scanner) next() {
40 if S.offset < len(S.src) {
41 S.pos.Offset = S.offset
42 S.pos.Column++
43 if S.ch == '\n' {
44 // next character starts a new line
45 S.pos.Line++
46 S.pos.Column = 1
47 }
48 r, w := rune(S.src[S.offset]), 1
49 if r == 0 {
50 S.error(S.pos, "illegal character NUL")
51 } else if r >= 80 {
52 // not ASCII
53 r, w = utf8.DecodeRune(S.src[S.offset:])
54 if r == utf8.RuneError && w == 1 {
55 S.error(S.pos, "illegal UTF-8 encoding")
56 }
57 }
58 S.offset += w
59 S.ch = r
60 } else {
61 S.pos.Offset = len(S.src)
62 S.ch = -1 // eof
63 }
64 }
65
66 // The mode parameter to the Init function is a set of flags (or 0).
67 // They control scanner behavior.
68 const (
69 ScanComments = 1 << iota // return comments as COMMENT tokens
70 AllowIllegalChars // do not report an error for illegal chars
71 InsertSemis // automatically insert semicolons
72 )
73
74 // Init prepares the scanner S to tokenize the text src. Calls to Scan
75 // will use the error handler err if they encounter a syntax error and
76 // err is not nil. Also, for each error encountered, the Scanner field
77 // ErrorCount is incremented by one. The filename parameter is used as
78 // filename in the token.Position returned by Scan for each token. The
79 // mode parameter determines how comments and illegal characters are
80 // handled.
81 func (S *Scanner) Init(src []byte, tokenMap *token.TokenMap) {
82 // Explicitly initialize all fields since a scanner may be reused.
83 S.src = src
84 S.tokenMap = tokenMap
85 S.pos = token.Position{Offset: 0, Line: 1, Column: 0}
86 S.offset = 0
87 S.ErrorCount = 0
88 S.next()
89 }
90
91 func charString(ch rune) string {
92 var s string
93 switch ch {
94 case -1:
95 return "EOF"
96 case '\a':
97 s = "\\a"
98 case '\b':
99 s = "\\b"
100 case '\f':
101 s = "\\f"
102 case '\n':
103 s = "\\n"
104 case '\r':
105 s = "\\r"
106 case '\t':
107 s = "\\t"
108 case '\v':
109 s = "\\v"
110 case '\\':
111 s = "\\\\"
112 case '\'':
113 s = "\\'"
114 default:
115 s = string(ch)
116 }
117 return "'" + s + "' (U+" + strconv.FormatInt(int64(ch), 16) + ")"
118 }
119
120 func (S *Scanner) error(pos token.Position, msg string) {
121 S.ErrorCount++
122 }
123
124 func (S *Scanner) expect(ch rune) {
125 if S.ch != ch {
126 S.error(S.pos, "expected "+charString(ch)+", found "+charString(S.ch))
127 }
128 S.next() // always make progress
129 }
130
131 var prefix = []byte("line ")
132
133 func (S *Scanner) scanComment(pos token.Position) {
134 // first '/' already consumed
135
136 if S.ch == '/' {
137 //-style comment
138 for S.ch >= 0 {
139 S.next()
140 if S.ch == '\n' {
141 // '\n' is not part of the comment for purposes of scanning
142 // (the comment ends on the same line where it started)
143 if pos.Column == 1 {
144 text := S.src[pos.Offset+2 : S.pos.Offset]
145 if bytes.HasPrefix(text, prefix) {
146 // comment starts at beginning of line with "//line ";
147 // get filename and line number, if any
148 i := bytes.Index(text, []byte{':'})
149 if i >= 0 {
150 if line, err := strconv.Atoi(string(text[i+1:])); err == nil && line > 0 {
151 // valid //line filename:line comment;
152 // update scanner position
153 S.pos.Line = line - 1 // -1 since the '\n' has not been consumed yet
154 }
155 }
156 }
157 }
158 return
159 }
160 }
161 } else {
162 // / *-style comment * /
163 S.expect('*')
164 for S.ch >= 0 {
165 ch := S.ch
166 S.next()
167 if ch == '*' && S.ch == '/' {
168 S.next()
169 return
170 }
171 }
172 }
173
174 S.error(pos, "comment not terminated")
175 }
176
177 func (S *Scanner) findNewline(pos token.Position) bool {
178 // first '/' already consumed; assume S.ch == '/' || S.ch == '*'
179
180 // read ahead until a newline or non-comment token is found
181 newline := false
182 for pos1 := pos; S.ch >= 0; {
183 if S.ch == '/' {
184 //-style comment always contains a newline
185 newline = true
186 break
187 }
188 S.scanComment(pos1)
189 if pos1.Line < S.pos.Line {
190 // / *-style comment contained a newline * /
191 newline = true
192 break
193 }
194 S.skipWhitespace() // S.insertSemi is set
195 if S.ch == '\n' {
196 newline = true
197 break
198 }
199 if S.ch != '/' {
200 // non-comment token
201 break
202 }
203 pos1 = S.pos
204 S.next()
205 if S.ch != '/' && S.ch != '*' {
206 // non-comment token
207 break
208 }
209 }
210
211 // reset position to where it was upon calling findNewline
212 S.pos = pos
213 S.offset = pos.Offset + 1
214 S.next()
215
216 return newline
217 }
218
219 func isLetter(ch rune) bool {
220 return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' ||
221 ch >= 0x80 && unicode.IsLetter(ch) || ch == '_'
222 }
223
224 func isDigit(ch rune) bool {
225 return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
226 }
227
228 func digitVal(ch rune) int {
229 switch {
230 case '0' <= ch && ch <= '9':
231 return int(ch) - '0'
232 case 'a' <= ch && ch <= 'f':
233 return int(ch) - 'a' + 10
234 case 'A' <= ch && ch <= 'F':
235 return int(ch) - 'A' + 10
236 }
237 return 16 // larger than any legal digit val
238 }
239
240 func (S *Scanner) scanEscape(quote rune) {
241 pos := S.pos
242
243 var i, base, max uint32
244 switch S.ch {
245 case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote:
246 S.next()
247 return
248 case '0', '1', '2', '3', '4', '5', '6', '7':
249 i, base, max = 3, 8, 255
250 case 'x':
251 S.next()
252 i, base, max = 2, 16, 255
253 case 'u':
254 S.next()
255 i, base, max = 4, 16, unicode.MaxRune
256 case 'U':
257 S.next()
258 i, base, max = 8, 16, unicode.MaxRune
259 default:
260 S.next() // always make progress
261 S.error(pos, "unknown escape sequence")
262 return
263 }
264
265 var x uint32
266 for ; i > 0; i-- {
267 d := uint32(digitVal(S.ch))
268 if d > base {
269 S.error(S.pos, "illegal character in escape sequence")
270 return
271 }
272 x = x*base + d
273 S.next()
274 }
275 if x > max || 0xd800 <= x && x < 0xe000 {
276 S.error(pos, "escape sequence is invalid Unicode code point")
277 }
278 }
279
280 func (S *Scanner) scanChar(pos token.Position) {
281 // '\'' already consumed
282
283 n := 0
284 for S.ch != '\'' {
285 ch := S.ch
286 n++
287 S.next()
288 if ch == '\n' || ch < 0 {
289 S.error(pos, "character literal not terminated")
290 n = 1
291 break
292 }
293 if ch == '\\' {
294 S.scanEscape('\'')
295 }
296 }
297
298 S.next()
299
300 if n != 1 {
301 S.error(pos, "illegal character literal")
302 }
303 }
304
305 func (S *Scanner) scanIdentifier(pos token.Position) token.Type {
306 ch0 := S.ch
307 for isLetter(S.ch) || isDigit(S.ch) || S.ch == '!' {
308 S.next()
309 }
310 switch {
311 case string(S.src[pos.Offset:S.pos.Offset]) == "import":
312 return S.tokenMap.Type("import")
313 case ch0 == '!':
314 return S.tokenMap.Type("ignoredTokId")
315 case ch0 == '_':
316 return S.tokenMap.Type("regDefId")
317 case unicode.IsUpper(ch0):
318 return S.tokenMap.Type("prodId")
319 default:
320 return S.tokenMap.Type("tokId")
321 }
322 }
323
324 var (
325 rw_CharLit = []byte("char_lit")
326 rw_StringLit = []byte("string_lit")
327 )
328
329 func (S *Scanner) isReservedWord(lit []byte) bool {
330 return bytes.Equal(lit, rw_CharLit) || bytes.Equal(lit, rw_StringLit)
331 }
332
333 // func (S *Scanner) scanInteger() {
334 // if !isDigit(S.ch) { S.error(S.pos, "integer index expected") }
335 //
336 //
337 // for S.next(); isDigit(S.ch); S.next() {}
338 // }
339
340 func (S *Scanner) scanNumber() token.Type {
341 if S.ch == '-' {
342 S.next()
343 }
344 for isDigit(S.ch) {
345 S.next()
346 }
347 return S.tokenMap.Type("int_lit")
348 }
349
350 func (S *Scanner) scanSDTLit(pos token.Position) {
351 // '<' already consumed
352 S.next() // consume second <
353 for cmp := false; !cmp; {
354 if S.ch < 0 {
355 S.error(pos, "SDT not terminated")
356 break
357 }
358 if S.ch == '>' {
359 S.next()
360 if S.ch == '>' {
361 break
362 }
363 }
364 S.next()
365 }
366 S.next()
367 }
368
369 func (S *Scanner) scanString(pos token.Position) {
370 // '"' already consumed
371
372 for S.ch != '"' {
373 ch := S.ch
374 S.next()
375 if ch == '\n' || ch < 0 {
376 S.error(pos, "string not terminated")
377 break
378 }
379 if ch == '\\' {
380 S.scanEscape('"')
381 }
382 }
383
384 S.next()
385 }
386
387 func (S *Scanner) scanRawString(pos token.Position) {
388 // '\140' already consumed
389
390 for S.ch != '\140' {
391 ch := S.ch
392 S.next()
393 if ch < 0 {
394 S.error(pos, "string not terminated")
395 break
396 }
397 }
398
399 S.next()
400 }
401
402 func (S *Scanner) skipWhitespace() {
403 for S.ch == ' ' || S.ch == '\t' || S.ch == '\n' || S.ch == '\r' {
404 S.next()
405 }
406 }
407
408 // Helper functions for scanning multi-byte tokens such as >> += >>= .
409 // Different routines recognize different length tok_i based on matches
410 // of ch_i. If a token ends in '=', the result is tok1 or tok3
411 // respectively. Otherwise, the result is tok0 if there was no other
412 // matching character, or tok2 if the matching character was ch2.
413
414 func (S *Scanner) switch2(tok0, tok1 token.Type) token.Type {
415 if S.ch == '=' {
416 S.next()
417 return tok1
418 }
419 return tok0
420 }
421
422 func (S *Scanner) switch3(tok0, tok1 token.Type, ch2 rune, tok2 token.Type) token.Type {
423 if S.ch == '=' {
424 S.next()
425 return tok1
426 }
427 if S.ch == ch2 {
428 S.next()
429 return tok2
430 }
431 return tok0
432 }
433
434 func (S *Scanner) switch4(tok0, tok1 token.Type, ch2 rune, tok2, tok3 token.Type) token.Type {
435 if S.ch == '=' {
436 S.next()
437 return tok1
438 }
439 if S.ch == ch2 {
440 S.next()
441 if S.ch == '=' {
442 S.next()
443 return tok3
444 }
445 return tok2
446 }
447 return tok0
448 }
449
450 var semicolon = []byte{';'}
451
452 // Scan scans the next token and returns the token position pos,
453 // the token tok, and the literal text lit corresponding to the
454 // token. The source end is indicated by token.EOF.
455 //
456 // For more tolerant parsing, Scan will return a valid token if
457 // possible even if a syntax error was encountered. Thus, even
458 // if the resulting token sequence contains no illegal tokens,
459 // a client may not assume that no error occurred. Instead it
460 // must check the scanner's ErrorCount or the number of calls
461 // of the error handler, if there was one installed.
462 func (S *Scanner) Scan() (*token.Token, token.Position) {
463 scanAgain:
464 S.skipWhitespace()
465
466 // current token start
467 pos, tok := S.pos, token.ILLEGAL
468
469 // determine token value
470 switch ch := S.ch; {
471 case ch == '!' || isLetter(ch):
472 tok = S.scanIdentifier(pos)
473 default:
474 S.next() // always make progress
475 switch ch {
476 case -1:
477 tok = S.tokenMap.Type("␚")
478 case '"':
479 tok = S.tokenMap.Type("string_lit")
480 S.scanString(pos)
481 case '\'':
482 tok = S.tokenMap.Type("char_lit")
483 S.scanChar(pos)
484 case '\140':
485 tok = S.tokenMap.Type("string_lit")
486 S.scanRawString(pos)
487 case '-':
488 tok = S.tokenMap.Type("-")
489 case '{':
490 tok = S.tokenMap.Type("{")
491 case '}':
492 tok = S.tokenMap.Type("}")
493 case ':':
494 tok = S.tokenMap.Type(":")
495 case ';':
496 tok = S.tokenMap.Type(";")
497 case ',':
498 tok = S.tokenMap.Type(",")
499 case '[':
500 tok = S.tokenMap.Type("[")
501 case ']':
502 tok = S.tokenMap.Type("]")
503 case '(':
504 tok = S.tokenMap.Type("(")
505 case ')':
506 tok = S.tokenMap.Type(")")
507 case '|':
508 tok = S.tokenMap.Type("|")
509 case '/':
510 if S.ch == '/' || S.ch == '*' {
511 // comment
512 S.scanComment(pos)
513 goto scanAgain
514 } else {
515 tok = S.tokenMap.Type("/")
516 }
517 case '<':
518 switch S.ch {
519 case '<':
520 tok = S.tokenMap.Type("g_sdt_lit")
521 S.scanSDTLit(pos)
522 case '=':
523 tok = S.tokenMap.Type("<=")
524 S.next()
525 default:
526 tok = S.tokenMap.Type("<")
527 }
528 case '.':
529 tok = S.tokenMap.Type(".")
530 default:
531 S.error(pos, "illegal character "+charString(ch))
532 }
533 }
534 return token.NewToken(tok, S.src[pos.Offset:S.pos.Offset]), pos
535 }
536
537 // An implementation of an ErrorHandler may be provided to the Scanner.
538 // If a syntax error is encountered and a handler was installed, Error
539 // is called with a position and an error message. The position points
540 // to the beginning of the offending token.
541 type ErrorHandler interface {
542 Error(pos token.Position, msg string)
543 }
544
545 // Within ErrorVector, an error is represented by an Error node. The
546 // position Pos, if valid, points to the beginning of the offending
547 // token, and the error condition is described by Msg.
548 type Error struct {
549 Pos token.Position
550 Msg string
551 }
552
553 func (e *Error) String() string {
554 if e.Pos.IsValid() {
555 // don't print "<unknown position>"
556 return e.Pos.String() + ": " + e.Msg
557 }
558 return e.Msg
559 }