aboutsummaryrefslogtreecommitdiff
path: root/tokenizer/tokenizer.go
blob: 78616c682da224984d548cf0135b77d4afec24f2 (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
package tokenizer

import (
	"bufio"
	goerr "errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"unicode"

	"usebox.net/lang/errors"
	"usebox.net/lang/tokens"
)

type rTokenIdMap map[rune]tokens.TokenId
type sTokenIdMap map[string]tokens.TokenId

var (
	keywords = sTokenIdMap{
		"true":     tokens.True,
		"false":    tokens.False,
		"var":      tokens.Var,
		"const":    tokens.Const,
		"def":      tokens.Def,
		"return":   tokens.Return,
		"number":   tokens.TNumber,
		"bool":     tokens.TBool,
		"string":   tokens.TString,
		"func":     tokens.TFunc,
		"if":       tokens.If,
		"else":     tokens.Else,
		"for":      tokens.For,
		"in":       tokens.In,
		"continue": tokens.Continue,
		"break":    tokens.Break,
	}

	doubleChar = map[rune]struct {
		second rTokenIdMap
	}{
		'|': {rTokenIdMap{'|': tokens.Or}},
		'&': {rTokenIdMap{'&': tokens.And}},
		'=': {rTokenIdMap{'=': tokens.Eq}},
		'!': {rTokenIdMap{'=': tokens.Ne, '?': tokens.TagE}},
		'>': {rTokenIdMap{'=': tokens.Ge, '>': tokens.BitShr}},
		'<': {rTokenIdMap{'=': tokens.Le, '<': tokens.BitShl}},
	}

	singleChar = rTokenIdMap{
		'(': tokens.LParen,
		')': tokens.RParen,
		'+': tokens.Add,
		'-': tokens.Sub,
		'*': tokens.Mul,
		'%': tokens.Mod,
		'/': tokens.Div,
		'>': tokens.Gt,
		'<': tokens.Lt,
		'!': tokens.Not,
		'~': tokens.Neg,
		'|': tokens.BitOr,
		'&': tokens.BitAnd,
		'^': tokens.BitXor,
		'=': tokens.Assign,
		'.': tokens.Dot,
		';': tokens.Semicolon,
		',': tokens.Comma,
		'{': tokens.LBrace,
		'}': tokens.RBrace,
		'[': tokens.LBracket,
		']': tokens.RBracket,
		'?': tokens.TestE,
	}
)

type Tokenizer struct {
	input bufio.Reader

	loc tokens.Location
}

func NewTokenizer(filename string, input io.Reader) *Tokenizer {
	return &Tokenizer{input: *bufio.NewReader(input), loc: tokens.Location{File: filename, Line: 1, Column: 1}}
}

func (t *Tokenizer) peek() (rune, error) {
	r, _, err := t.input.ReadRune()
	if err != nil {
		t.input.UnreadRune()
		return rune(0), err
	}
	if err := t.input.UnreadRune(); err != nil {
		return rune(0), err
	}
	return r, nil
}

func (t *Tokenizer) read() (rune, error) {
	r, _, err := t.input.ReadRune()
	if err != nil {
		return rune(0), err
	}
	return r, nil
}

func (t *Tokenizer) unread() error {
	return t.input.UnreadRune()
}

func (t *Tokenizer) skipWhitespace() (rune, error) {
	var r rune
	var err error
loop:
	for {
		r, err = t.read()
		if err != nil {
			break
		}
		switch {
		case !unicode.IsSpace(r):
			break loop
		case r == '\n':
			t.loc.Eol()
		default:
			t.loc.Inc()
		}
	}
	return r, err
}

func (t *Tokenizer) extract(filter func(rune) bool) (string, error) {
	var buf strings.Builder
	for {
		r, err := t.peek()
		// EOF, error or end of extraction
		if err == io.EOF || !filter(r) {
			t.loc.Add(buf.Len())
			return buf.String(), nil
		} else if err != nil {
			return "", err
		} else {
			t.read()
		}
		if _, err = buf.WriteRune(r); err != nil {
			return "", err
		}
	}
}

func (t *Tokenizer) extractEscaped(end rune) (string, error) {
	var buf strings.Builder
	for {
		r, err := t.read()
		t.loc.Inc()
		if r == end {
			return buf.String(), nil
		} else if err == io.EOF {
			return "", fmt.Errorf("EOF found before closing '%c'", end)
		} else if err != nil {
			return "", err
		} else {
			if r == '\\' {
				r, err = t.read()
				if err == io.EOF {
					return "", goerr.New("EOF found before completing escape sequence")
				} else if err != nil {
					return "", err
				}
				switch r {
				case 'n':
					r = '\n'
				case 't':
					r = '\t'
				case '\\', end:
				case 'x':
					count := 0
					value, err := t.extract(func(r rune) bool {
						defer func() {
							count++
						}()
						return unicode.In(r, unicode.ASCII_Hex_Digit) && count != 2
					})
					if err != nil {
						return "", err
					}
					if len(value) != 2 {
						return "", goerr.New("invalid escape sequence")
					}
					nval, err := strconv.ParseInt(value, 16, 8)
					if err != nil {
						return "", goerr.New("invalid escape sequence")
					}
					r = rune(byte(nval))
				default:
					return "", goerr.New("invalid escape sequence")
				}
				t.loc.Inc()
			}
		}
		if _, err = buf.WriteRune(r); err != nil {
			return "", err
		}
	}
}

func (t *Tokenizer) token() (tokens.Token, error) {
	var tok tokens.Token
	var r rune
	var err error
	var loc tokens.Location

	for {
		r, err = t.skipWhitespace()
		loc = t.loc
		if err == io.EOF {
			return tokens.Token{Id: tokens.Eof, Loc: loc}, nil
		} else if err != nil {
			return tok, err
		}

		// comments
		if r == '/' {
			if p, err := t.peek(); err == nil && p == '/' {
				for {
					r, err = t.read()
					if err != nil {
						// could be EOF
						break
					}
					if r == '\n' {
						t.loc.Eol()
						break
					}
				}
				// check for whitespace
				continue
			}
		}
		// not a comment, skipped whitespace,
		// now process this token
		break
	}

	// identifier or keywords
	if unicode.IsLetter(r) || r == '_' {
		t.unread()
		value, err := t.extract(func(r rune) bool {
			return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
		})
		if err != nil {
			return tok, errors.NewErrorWrap(errors.SyntaxError, t.loc, err, err.Error())
		}
		// match keywords
		if tokenId, ok := keywords[value]; ok {
			return tokens.Token{Id: tokenId, Loc: loc, Value: value}, nil
		}
		// otherwise is an identitier
		return tokens.Token{Id: tokens.Ident, Loc: loc, Value: value}, nil
	}

	// character literal
	if r == '\'' {
		t.loc.Inc()
		value, err := t.extractEscaped('\'')
		if err != nil {
			return tok, errors.NewErrorWrap(errors.SyntaxError, t.loc, err, err.Error())
		}
		if len(value) != 1 {
			return tok, errors.NewError(errors.SyntaxError, t.loc, "invalid character literal")
		}
		return tokens.Token{Id: tokens.Char, Loc: loc, Value: value}, nil
	}

	// numeric literal
	if unicode.IsDigit(r) {
		t.unread()
		pos := 0
		hex := false
		bin := false
		value, err := t.extract(func(r rune) bool {
			if pos == 1 && r == 'x' {
				hex = true
				pos++
				return true
			}
			if pos == 1 && r == 'b' {
				bin = true
				pos++
				return true
			}
			if hex && unicode.In(r, unicode.ASCII_Hex_Digit) {
				pos++
				return true
			}
			if bin && r != '0' && r != '1' {
				return false
			}
			pos++
			return unicode.IsDigit(r)
		})
		if (hex || bin) && len(value) == 2 {
			err = fmt.Errorf("invalid numeric format '%s'", value)
		}
		if err != nil {
			return tok, errors.NewErrorWrap(errors.SyntaxError, t.loc, err, err.Error())
		}
		return tokens.Token{Id: tokens.Number, Loc: loc, Value: value}, nil
	}

	// string literal
	if r == '"' {
		t.loc.Inc()
		value, err := t.extractEscaped('"')
		if err != nil {
			return tok, errors.NewErrorWrap(errors.SyntaxError, t.loc, err, err.Error())
		}
		return tokens.Token{Id: tokens.String, Loc: loc, Value: value}, nil
	}

	// two character symbols
	if d, ok := doubleChar[r]; ok {
		if p, err := t.peek(); err == nil {
			if second, ok := d.second[p]; ok {
				t.read()
				t.loc.Add(2)
				// FIXME: value
				return tokens.Token{Id: second, Loc: loc, Value: string(r) + string(p)}, nil
			}
		}
	}

	// single character symbols
	if tokenId, ok := singleChar[r]; ok {
		t.loc.Inc()
		return tokens.Token{Id: tokenId, Loc: loc, Value: string(r)}, nil
	}

	// invalid token
	return tok, errors.NewError(errors.SyntaxError, t.loc, "invalid character:", fmt.Sprintf("'%c'", r))
}

func (t *Tokenizer) Scan() ([]tokens.Token, error) {
	var ts []tokens.Token

	for {
		token, err := t.token()
		if err != nil {
			return nil, err
		}
		ts = append(ts, token)
		if token.Id == tokens.Eof {
			return ts, nil
		}
	}
}