summaryrefslogtreecommitdiff
path: root/src/tparse/tokenize.go
blob: 8eab15a940a4e60a06e0c5e8203699997c318032 (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
/*
   Copyright 2020 Kyle Gunger

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package tparse

import (
	"bufio"
	"io"
	"os"
	"strings"
	"unicode"
)

// Read in a number (may be a float)
func numericLiteral(r *bufio.Reader, line int, char *int) Token {
	decimal, base := false, false
	run, _, err := r.ReadRune()
	last := *char
	b := strings.Builder{}

	for ; err == nil; run, _, err = r.ReadRune() {
		if (run == '.') && !decimal && !base {
			decimal = true
		} else if (run == '.') && (decimal || base) {
			break
		} else if !unicode.IsNumber(run) {
			if decimal || checkResRune(run) != -1 || unicode.IsSpace(run) {
				break
			} else if !base {
				base = true
			}
		}
		*char++
		b.WriteRune(run)
	}

	r.UnreadRune()

	return Token{Type: LITERAL, Data: b.String(), Line: line, Char: last}
}

// Parse a string (will escape \" only in this stage)
func stringLiteral(r *bufio.Reader, line, char *int) Token {
	escape := false
	run, _, err := r.ReadRune()
	last := *char

	if run != '"' {
		return Token{Type: LITERAL}
	}

	b := strings.Builder{}
	b.WriteRune(run)
	run, _, err = r.ReadRune()

	for ; err == nil; run, _, err = r.ReadRune() {
		*char++
		b.WriteRune(run)
		if run == '\\' && !escape {
			escape = true
		} else if (run == '"' || run == '\n') && !escape {
			break
		} else if escape {
			if run == '\n' {
				*line++
			}
			escape = false
		}
	}

	return Token{Type: LITERAL, Data: b.String(), Line: *line, Char: last}
}

// Parse a character in (escape \\ or \')
func charLiteral(r *bufio.Reader, line int, char *int) Token {
	escape := false
	run, _, err := r.ReadRune()
	last := *char

	if run != '\'' {
		return Token{Type: LITERAL}
	}

	b := strings.Builder{}
	b.WriteRune(run)
	run, _, err = r.ReadRune()

	for ; err == nil; run, _, err = r.ReadRune() {
		b.WriteRune(run)
		*char++
		if run == '\\' && !escape {
			escape = true
		} else if (run == '\'' && !escape) || run == '\n' {
			break
		} else if escape {
			escape = false
		}
	}

	return Token{Type: LITERAL, Data: b.String(), Line: line, Char: last}
}

// Split reserved runes into rune groups
func splitResRunes(str string, max, line, start int) []Token {
	out := []Token{}

	rs := []rune(str)
	s, e := 0, max

	if max > len(rs) {
		e = len(rs)
	}

	for e <= len(rs) && s < len(rs) {
		if checkRuneGroup(string(rs[s:e])) != -1 || e == s+1 {
			tmp := string(rs[s:e])
			out = append(out, Token{Type: checkRuneGroup(tmp), Data: tmp, Line: line, Char: start + s})
			s = e
			if s+max < len(rs) {
				e = s + max
			} else {
				e = len(rs)
			}
		} else if e != s+1 {
			e--
		}
	}

	return out
}

// Remove block comments
func stripBlockComments(t []Token) []Token {
	out := []Token{}
	bc := false
	for _, tok := range t {

		if tok.Type == DELIMIT {
			ch := ":"
			switch tok.Data {
			case ";#":
				ch = ";"
				fallthrough
			case ":#":
				out = append(out, Token{DELIMIT, ch + "/", tok.Line, tok.Char})
				fallthrough
			case "/#":
				bc = true
				continue
			case "#;":
				ch = ";"
				fallthrough
			case "#:":
				out = append(out, Token{DELIMIT, "/" + ch, tok.Line, tok.Char})
				fallthrough
			case "#/":
				bc = false
				continue
			default:
				if bc {
					continue
				}
			}
		} else if bc {
			continue
		}

		out = append(out, tok)
	}

	return out
}

func endsDef(toks *[]Token) bool {
	for i := range *toks {
		switch (*toks)[i].Data {
		case ":", ";", "/;", "/:", "#;", "#:", ";;", "::":
			return true
		}
	}

	return false
}

func endsPre(toks *[]Token) bool {
	o := false

	for i := range *toks {
		switch (*toks)[i].Data {
		case ":", "/:", "#:", "::":
			o = true
		case ";", "/;", "#;", ";;":
			o = false
		}
	}

	return o
}

// TokenizeFile tries to read a file and turn it into a series of tokens
func TokenizeFile(path string) []Token {
	out := []Token{}

	fd, err := os.Open(path)

	if err != nil {
		return out
	}

	read := bufio.NewReader(fd)

	b := strings.Builder{}

	max := maxResRunes()

	ln, cn, last := int(1), int(-1), int(0)
	sp, pre := false, false

	for r := rune(' '); ; r, _, err = read.ReadRune() {
		cn++
		// If error in stream or EOF, break
		if err != nil {
			if err != io.EOF {
				out = append(out, Token{Type: -1})
			} else if b.String() != "" {
				out = append(out, Token{Type: checkToken(b.String(), pre), Data: b.String(), Line: ln, Char: last})
			}
			break
		}

		// Checking for a space
		if unicode.IsSpace(r) {
			sp = true
			if b.String() != "" {
				out = append(out, Token{Type: checkToken(b.String(), pre), Data: b.String(), Line: ln, Char: last})
				b.Reset()
			}

			// checking for a newline
			if r == '\n' {
				ln++
				cn = -1
				last = 0
			}

			continue
		} else if sp {
			last = cn
			sp = false
		}

		if unicode.IsNumber(r) && b.String() == "" {
			read.UnreadRune()
			out = append(out, numericLiteral(read, ln, &cn))
			sp = true

			continue
		}

		if r == '\'' {
			if b.String() != "" {
				out = append(out, Token{Type: checkToken(b.String(), pre), Data: b.String(), Line: ln, Char: last})
				b.Reset()
			}

			read.UnreadRune()
			out = append(out, charLiteral(read, ln, &cn))
			sp = true

			continue
		}

		if r == '"' {
			if b.String() != "" {
				out = append(out, Token{Type: checkToken(b.String(), pre), Data: b.String()})
				b.Reset()
			}

			read.UnreadRune()
			out = append(out, stringLiteral(read, &ln, &cn))
			sp = true

			continue
		}

		// Checking for a rune group
		if checkResRune(r) != -1 {
			if b.String() != "" {
				out = append(out, Token{Type: checkToken(b.String(), pre), Data: b.String(), Line: ln, Char: last})
				b.Reset()
			}
			last = cn
			for ; err == nil; r, _, err = read.ReadRune() {
				if checkResRune(r) == -1 {
					break
				}
				cn++
				b.WriteRune(r)
			}
			cn--

			read.UnreadRune()

			rgs := splitResRunes(b.String(), max, ln, last)

			// Line Comments
			for i, rg := range rgs {
				if rg.Data == "#" {
					rgs = rgs[:i]
					read.ReadString('\n')
					ln++
					cn = -1
					last = 0
					break
				}
			}

			out = append(out, rgs...)

			b.Reset()

			sp = true

			if endsDef(&rgs) {
				pre = endsPre(&rgs)
			}

			continue
		}

		// Accumulate
		b.WriteRune(r)
	}

	return stripBlockComments(out)
}