Debian Codegraph @

selector/lexer/token.go

raw symbols SCIP
1 package lexer
2
3 import (
4 "fmt"
5 "slices"
6 )
7
8 type TokenKind int
9
10 func TokenKinds(tk ...TokenKind) []TokenKind {
11 return tk
12 }
13
14 const (
15 EOF TokenKind = iota
16 Symbol
17 Comma
18 Colon
19 OpenBracket // [
20 CloseBracket // ]
21 OpenCurly
22 CloseCurly
23 OpenParen
24 CloseParen
25 Equal // ==
26 Equals // =
27 NotEqual // !=
28 And
29 Or
30 Like // =~
31 NotLike // !~
32 String
33 Number
34 Bool
35 Plus
36 Increment
37 IncrementBy
38 Dash
39 Decrement
40 DecrementBy
41 Star
42 Slash
43 Percent
44 Dot
45 Spread // ...
46 RecursiveDescent // ..
47 Dollar
48 Variable
49 GreaterThan
50 GreaterThanOrEqual
51 LessThan
52 LessThanOrEqual
53 Exclamation
54 Null
55 If
56 Else
57 ElseIf
58 Branch
59 Map
60 Each
61 Filter
62 Search
63 RegexPattern
64 SortBy
65 GroupBy
66 Reduce
67 MapValues
68 Any
69 All
70 Count
71 Asc
72 Desc
73 QuestionMark
74 DoubleQuestionMark
75 Semicolon
76 )
77
78 type Tokens []Token
79
80 func (tt Tokens) Split(kind TokenKind) []Tokens {
81 var res []Tokens
82 var cur Tokens
83 for _, t := range tt {
84 if t.Kind == kind {
85 if len(cur) > 0 {
86 res = append(res, cur)
87 }
88 cur = nil
89 continue
90 }
91 cur = append(cur, t)
92 }
93 if len(cur) > 0 {
94 res = append(res, cur)
95 }
96 return res
97 }
98
99 type Token struct {
100 Kind TokenKind
101 Value string
102 Pos int
103 Len int
104 }
105
106 func NewToken(kind TokenKind, value string, pos int, len int) Token {
107 return Token{
108 Kind: kind,
109 Value: value,
110 Pos: pos,
111 Len: len,
112 }
113 }
114
115 func (t Token) IsKind(kind ...TokenKind) bool {
116 return slices.Contains(kind, t.Kind)
117 }
118
119 type UnexpectedTokenError struct {
120 Pos int
121 Token rune
122 }
123
124 func (e *UnexpectedTokenError) Error() string {
125 return fmt.Sprintf("failed to tokenize: unexpected token: %s at position %d.", string(e.Token), e.Pos)
126 }
127
128 type UnexpectedEOFError struct {
129 Pos int
130 }
131
132 func (e *UnexpectedEOFError) Error() string {
133 return fmt.Sprintf("failed to tokenize: unexpected EOF at position %d.", e.Pos)
134 }