Debian Codegraph @

internal/revision/scanner.go

raw
1 package revision
2
3 import (
4 "bufio"
5 "io"
6 "unicode"
7 )
8
9 // runeCategoryValidator takes a rune as input and
10 // validates it belongs to a rune category
11 type runeCategoryValidator func(r rune) bool
12
13 // tokenizeExpression aggregates a series of runes matching check predicate into a single
14 // string and provides given tokenType as token type
15 func tokenizeExpression(ch rune, tokenType token, check runeCategoryValidator, r *bufio.Reader) (token, string, error) {
16 var data []rune
17 data = append(data, ch)
18
19 for {
20 c, _, err := r.ReadRune()
21
22 if c == zeroRune {
23 break
24 }
25
26 if err != nil {
27 return tokenError, "", err
28 }
29
30 if check(c) {
31 data = append(data, c)
32 } else {
33 err := r.UnreadRune()
34
35 if err != nil {
36 return tokenError, "", err
37 }
38
39 return tokenType, string(data), nil
40 }
41 }
42
43 return tokenType, string(data), nil
44 }
45
46 // maxRevisionLength holds the maximum length that will be parsed for a
47 // revision. Git itself doesn't enforce a max length, but rather leans on
48 // the OS to enforce it via its ARG_MAX.
49 const maxRevisionLength = 128 * 1024 // 128kb
50
51 var zeroRune = rune(0)
52
53 // scanner represents a lexical scanner.
54 type scanner struct {
55 r *bufio.Reader
56 }
57
58 // newScanner returns a new instance of scanner.
59 func newScanner(r io.Reader) *scanner {
60 return &scanner{r: bufio.NewReader(io.LimitReader(r, maxRevisionLength))}
61 }
62
63 // Scan extracts tokens and their strings counterpart
64 // from the reader
65 func (s *scanner) scan() (token, string, error) {
66 ch, _, err := s.r.ReadRune()
67
68 if err != nil && err != io.EOF {
69 return tokenError, "", err
70 }
71
72 switch ch {
73 case zeroRune:
74 return eof, "", nil
75 case ':':
76 return colon, string(ch), nil
77 case '~':
78 return tilde, string(ch), nil
79 case '^':
80 return caret, string(ch), nil
81 case '.':
82 return dot, string(ch), nil
83 case '/':
84 return slash, string(ch), nil
85 case '{':
86 return obrace, string(ch), nil
87 case '}':
88 return cbrace, string(ch), nil
89 case '-':
90 return minus, string(ch), nil
91 case '@':
92 return at, string(ch), nil
93 case '\\':
94 return aslash, string(ch), nil
95 case '?':
96 return qmark, string(ch), nil
97 case '*':
98 return asterisk, string(ch), nil
99 case '[':
100 return obracket, string(ch), nil
101 case '!':
102 return emark, string(ch), nil
103 }
104
105 if unicode.IsSpace(ch) {
106 return space, string(ch), nil
107 }
108
109 if unicode.IsControl(ch) {
110 return control, string(ch), nil
111 }
112
113 if unicode.IsLetter(ch) {
114 return tokenizeExpression(ch, word, unicode.IsLetter, s.r)
115 }
116
117 if unicode.IsNumber(ch) {
118 return tokenizeExpression(ch, number, unicode.IsNumber, s.r)
119 }
120
121 return tokenError, string(ch), nil
122 }