vile / lexer / lexer.v
534 lines · 507 sloc · 15.4 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1// R5RS sections 2 and 7.1.1: source text -> tokens. Reading lists, interpreting
2// numbers, decoding escapes, and evaluating expressions belong to later stages.
3module lexer
4
5import encoding.utf8
6import unicode17
7
8// Scanner consumes source incrementally. Its cursor and each returned TokenSpan
9// have constant size; successful next calls do not copy source text or collect
10// tokens. Create one with new_scanner so UTF-8 is checked before scanning.
11@[params]
12pub struct ScannerOptions {
13pub:
14 fold_case bool = true
15}
16
17pub const token_preserve_case = u8(1)
18pub const token_identifier_escaped = u8(2)
19pub const token_identifier_barred = u8(4)
20pub const token_string_extended = u8(8)
21pub const token_identifier_unicode = u8(16)
22
23pub struct Scanner {
24 source string
25mut:
26 no_fold bool
27 unicode_source bool
28 flags u8
29 pos int
30 line int = 1
31 column int = 1
32}
33
34// new_scanner validates UTF-8 once and creates a cursor over the source.
35// Identifiers use the report's ASCII alphabet; strings, comments and character
36// literals accept UTF-8. Letter case is preserved for the reader to normalize.
37// Space, tab, LF, CR, CRLF, vertical tab and form feed separate tokens.
38pub fn new_scanner(source string, options ScannerOptions) !Scanner {
39 valid, ascii := source_properties(source)
40 if !valid {
41 return LexError{
42 line: 1
43 column: 1
44 message: 'source is not valid UTF-8'
45 }
46 }
47 return Scanner{
48 source: source
49 no_fold: !options.fold_case
50 unicode_source: !ascii
51 }
52}
53
54// tokenize collects tokens with owned spellings for callers that need the whole
55// array. Sequential consumers should use new_scanner and next instead.
56pub fn tokenize(source string) ![]Token {
57 mut scanner := new_scanner(source)!
58 mut tokens := []Token{}
59 // No slices exist during collection. Growth may release the old metadata
60 // after copying; token spelling allocations have independent ownership.
61 unsafe { tokens.flags.set(.noslices) }
62 for {
63 token := scanner.next()!
64 tokens << Token{
65 kind: token.kind
66 lexeme: token.text(source)
67 start: token.start
68 end: token.end
69 line: token.line
70 column: token.column
71 }
72 if token.kind == .eof { break }
73 // Use actual progress through the first 32 tokens as a bounded sizing
74 // hint. This adds no lexer pass and never speculates for huge scalar
75 // tokens. The cap limits over-reservation if the rest is mostly trivia.
76 if tokens.len == 32 && token.end > 0 && token.end < source.len {
77 estimate := f64(source.len) * 32 / f64(token.end) + 1
78 capacity := if estimate > 8192 { 8192 } else { int(estimate) }
79 tokens.ensure_cap(capacity)
80 }
81 }
82 // Callers may freely slice the published array using ordinary semantics.
83 unsafe { tokens.flags.clear(.noslices) }
84 return tokens
85}
86
87// next returns one token span, or a located lexical error. After EOF it keeps
88// returning the same EOF span. After an error, discard the scanner.
89pub fn (mut s Scanner) next() !TokenSpan {
90 if s.skip_plain_atmosphere() { s.skip_atmosphere()! }
91 s.flags = if s.no_fold { token_preserve_case } else { u8(0) }
92 start := s.pos
93 line := s.line
94 column := s.column
95 if s.at_end() {
96 return s.token(.eof, start, line, column)
97 }
98 mut kind := TokenKind.identifier
99 match s.source[s.pos] {
100 `(` {
101 s.skip_bytes(1)
102 kind = .lparen
103 }
104 `)` {
105 s.skip_bytes(1)
106 kind = .rparen
107 }
108 `'` {
109 s.skip_bytes(1)
110 kind = .quote
111 }
112 0x60 { // backquote
113 s.skip_bytes(1)
114 kind = .quasiquote
115 }
116 `,` {
117 s.skip_bytes(1)
118 kind = if !s.at_end() && s.source[s.pos] == `@` {
119 s.skip_bytes(1)
120 TokenKind.unquote_splicing
121 } else {
122 TokenKind.unquote
123 }
124 }
125 `|` {
126 s.barred_identifier(start, line, column)!
127 kind = .identifier
128 }
129 `"` {
130 s.scan_string(start, line, column)!
131 kind = .string_literal
132 }
133 `#` {
134 if s.pos + 1 == s.source.len {
135 return s.scan_atom(start, line, column)
136 }
137 if s.source[s.pos + 1] >= `0` && s.source[s.pos + 1] <= `9` {
138 s.skip_bytes(1)
139 for !s.at_end() && s.source[s.pos] >= `0` && s.source[s.pos] <= `9` {
140 s.skip_bytes(1)
141 }
142 if s.at_end() {
143 return s.lexical_error(start, line, column, 'unfinished datum label', true)
144 }
145 if s.source[s.pos] !in [`=`, `#`] {
146 return s.lexical_error(start, line, column, 'datum label needs = or #', false)
147 }
148 kind = if s.source[s.pos] == `=` { .label_definition } else { .label_reference }
149 s.skip_bytes(1)
150 return s.token(kind, start, line, column)
151 }
152 if s.pos + 3 < s.source.len && ascii_lower(s.source[s.pos + 1]) == `u` && s.source[s.pos + 2] == `8` && s.source[s.pos + 3] == `(` {
153 s.skip_bytes(4)
154 return s.token(.bytevector_start, start, line, column)
155 }
156 if s.pos + 4 < s.source.len && ascii_lower(s.source[s.pos + 1]) == `v` && ascii_lower(s.source[s.pos + 2]) == `u` && s.source[s.pos + 3] == `8` && s.source[s.pos + 4] == `(` {
157 s.skip_bytes(5)
158 return s.token(.bytevector_start, start, line, column)
159 }
160 match s.source[s.pos + 1] {
161 `:` {
162 s.skip_bytes(2)
163 kind = .keyword_prefix
164 }
165 `'` {
166 s.skip_bytes(2)
167 kind = .syntax_quote
168 }
169 0x60 {
170 s.skip_bytes(2)
171 kind = .syntax_quasiquote
172 }
173 `,` {
174 s.skip_bytes(2)
175 kind = if !s.at_end() && s.source[s.pos] == `@` {
176 s.skip_bytes(1)
177 TokenKind.syntax_unquote_splicing
178 } else {
179 TokenKind.syntax_unquote
180 }
181 }
182 `;` {
183 s.skip_bytes(2)
184 kind = .datum_comment
185 }
186 `(` {
187 s.skip_bytes(2)
188 kind = .vector_start
189 }
190 `\\` {
191 s.scan_character(start, line, column)!
192 kind = .character
193 }
194 `t`, `T`, `f`, `F` {
195 // Long aliases require a delimiter; preserve old short boolean adjacency.
196 length := if ascii_lower(s.source[s.pos + 1]) == `t` { 5 } else { 6 }
197 expected := if length == 5 { '#true' } else { '#false' }
198 if s.pos + length <= s.source.len && matches_ascii_name(s.source, s.pos, s.pos + length, expected) {
199 if !source_boundary(s.source, s.pos + length) {
200 return s.lexical_error(start, line, column, 'long boolean needs a delimiter', false)
201 }
202 s.skip_bytes(length)
203 return s.token(.boolean, start, line, column)
204 }
205 s.skip_bytes(2)
206 kind = .boolean
207 }
208 else { return s.scan_atom(start, line, column) }
209 }
210 }
211 else {
212 return s.scan_atom(start, line, column)
213 }
214 }
215 return s.token(kind, start, line, column)
216}
217
218fn (s &Scanner) at_end() bool {
219 return s.pos >= s.source.len
220}
221
222// Callers have already established an in-bounds span with no CR or LF.
223@[inline]
224fn (mut s Scanner) skip_bytes(count int) {
225 s.pos += count
226 s.column += count
227}
228
229// Only an in-bounds CR or LF reaches this helper. Other bytes use skip_bytes,
230// so ordinary whitespace and punctuation never repeat newline classification.
231fn (mut s Scanner) advance_line(c u8) {
232 s.pos++
233 if c == `\r` || s.pos < 2 || s.source[s.pos - 2] != `\r` {
234 s.line++
235 }
236 s.column = 1
237}
238
239// Most source needs no fallible atmosphere operation. Stop before extended
240// comments/directives/Unicode whitespace and keep their error result cold.
241fn (mut s Scanner) skip_plain_atmosphere() bool {
242 for !s.at_end() {
243 c := s.source[s.pos]
244 if is_whitespace(c) {
245 if c == `\r` {
246 s.skip_line_ending(line_ending_width(s.source, s.pos))
247 } else if c == `\n` {
248 s.advance_line(c)
249 } else {
250 s.skip_bytes(1)
251 }
252 } else if c == `;` {
253 end := if s.unicode_source {
254 comment_end_unicode(s.source, s.pos)
255 } else {
256 comment_end(s.source, s.pos)
257 }
258 s.column += end - s.pos
259 s.pos = end
260 } else {
261 return c >= 128 || (c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] in [
262 `|`,
263 `!`,
264 ])
265 }
266 }
267 return false
268}
269
270@[noinline]
271fn (mut s Scanner) skip_atmosphere() ! {
272 for !s.at_end() {
273 c := s.source[s.pos]
274 if is_whitespace(c) {
275 width := line_ending_width(s.source, s.pos)
276 if width > 0 { s.skip_line_ending(width) } else { s.skip_bytes(1) }
277 } else if c == `;` {
278 end := if s.unicode_source {
279 comment_end_unicode(s.source, s.pos)
280 } else {
281 comment_end(s.source, s.pos)
282 }
283 s.column += end - s.pos
284 s.pos = end
285 } else if c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] == `|` {
286 s.block_comment(s.pos, s.line, s.column)!
287 } else if c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] == `!` {
288 s.directive(s.pos, s.line, s.column)!
289 } else if c >= 128 {
290 cp, width := utf8.decode_rune_at(s.source, s.pos)
291 if !unicode17.whitespace(cp) { break }
292 line_width := line_ending_width(s.source, s.pos)
293 if line_width > 0 { s.skip_line_ending(line_width) } else { s.skip_bytes(width) }
294 } else {
295 break
296 }
297 }
298}
299
300fn (s &Scanner) token(kind TokenKind, start int, line int, column int) TokenSpan {
301 return TokenSpan{
302 kind: kind
303 start: start
304 end: s.pos
305 line: line
306 column: column
307 }
308}
309
310fn (mut s Scanner) scan_string(start int, line int, column int) ! {
311 s.skip_bytes(1)
312 if s.unicode_source { return s.scan_string_unicode(start, line, column) }
313 return s.scan_string_ascii(start, line, column)
314}
315
316@[noinline]
317fn (mut s Scanner) scan_string_ascii(start int, line int, column int) ! {
318 for {
319 end := string_run_end(s.source, s.pos)
320 s.column += end - s.pos
321 s.pos = end
322 if s.at_end() { break }
323 c := s.source[s.pos]
324 if c == `"` {
325 s.skip_bytes(1)
326 return
327 }
328 if c == `\\` {
329 if s.pos + 1 >= s.source.len {
330 s.skip_bytes(1)
331 break
332 }
333 if s.source[s.pos + 1] in [`"`, `\\`] {
334 s.skip_bytes(2)
335 legacy_end := string_legacy_run_end(s.source, s.pos)
336 s.column += legacy_end - s.pos
337 s.pos = legacy_end
338 continue
339 }
340 s.scan_extended_string_escape()!
341 } else if c == `\r` {
342 s.flags |= token_string_extended
343 s.skip_line_ending(line_ending_width(s.source, s.pos))
344 } else {
345 s.advance_line(c)
346 }
347 }
348 return s.lexical_error(start, line, column, 'unterminated string', true)
349}
350
351@[noinline]
352fn (mut s Scanner) scan_string_unicode(start int, line int, column int) ! {
353 for {
354 end := string_run_end_unicode(s.source, s.pos)
355 s.column += end - s.pos
356 s.pos = end
357 if s.at_end() { break }
358 c := s.source[s.pos]
359 if c == `"` {
360 s.skip_bytes(1)
361 return
362 }
363 if c == `\\` {
364 if s.pos + 1 >= s.source.len {
365 s.skip_bytes(1)
366 break
367 }
368 if s.source[s.pos + 1] in [`"`, `\\`] {
369 s.skip_bytes(2)
370 continue
371 }
372 s.scan_extended_string_escape()!
373 } else if c == `\n` {
374 s.advance_line(c)
375 } else {
376 s.flags |= token_string_extended
377 s.skip_line_ending(line_ending_width(s.source, s.pos))
378 }
379 }
380 return s.lexical_error(start, line, column, 'unterminated string', true)
381}
382
383@[noinline]
384fn (mut s Scanner) scan_extended_string_escape() ! {
385 position, line, column := s.pos, s.line, s.column
386 s.skip_bytes(1)
387 s.flags |= token_string_extended
388 s.extra_escape(position, line, column, false)!
389}
390
391fn (mut s Scanner) scan_character(start int, line int, column int) ! {
392 s.skip_bytes(2)
393 if s.at_end() {
394 return s.lexical_error(start, line, column, 'missing character after #\\', true)
395 }
396 first := s.pos
397 cp, width := utf8.decode_rune_at(s.source, s.pos)
398 if cp in [rune(10), rune(13), rune(0x85), rune(0x2028)] {
399 s.skip_line_ending(width)
400 } else {
401 s.skip_bytes(width)
402 }
403 if cp in [`x`, `X`] && !s.at_end() && hex_digit(s.source[s.pos]) >= 0 {
404 s.pos = first + 1
405 s.column = column + 3
406 s.hex_escape(start, line, column, false)!
407 if !source_boundary(s.source, s.pos) {
408 return s.lexical_error(start, line, column, 'invalid hexadecimal character', false)
409 }
410 return
411 }
412 for !s.at_end() && !source_boundary(s.source, s.pos) { s.skip_bytes(1) }
413 if s.pos - first == width { return }
414 if character_name_value(s.source, first, s.pos, !s.no_fold) == rune(-1) {
415 return s.lexical_error(start, line, column, 'invalid character literal', false)
416 }
417}
418
419fn (mut s Scanner) scan_atom(start int, line int, column int) !TokenSpan {
420 // Atoms contain no line endings: every newline is a delimiter. Advance
421 // the byte cursor locally, then update the column once for the whole atom.
422 mut end := start
423 first := s.source[start]
424 if is_initial(first) {
425 // Identifier bytes cannot be delimiters. Validate while finding the
426 // end, testing the delimiter only when this run stops. Invalid bytes
427 // fall through to the full atom scan so errors retain their spelling.
428 end = identifier_end(s.source, start + 1)
429 if end == s.source.len || is_delimiter(s.source[end]) || extended_source_boundary(s.source, end) {
430 s.column += end - start
431 s.pos = end
432 return TokenSpan{.identifier, start, end, line, column}
433 }
434 } else {
435 digits := if first in [`+`, `-`] { start + 1 } else { start }
436 if digits < s.source.len && s.source[digits] >= `0` && s.source[digits] <= `9` {
437 end = digits + 1
438 for end < s.source.len && s.source[end] >= `0` && s.source[end] <= `9` {
439 end++
440 }
441 // A decimal digit run with an optional sign is already a valid
442 // number. Every suffix still goes through the full R5RS grammar.
443 if end == s.source.len || is_delimiter(s.source[end]) || extended_source_boundary(s.source, end) {
444 s.column += end - start
445 s.pos = end
446 return TokenSpan{.number, start, end, line, column}
447 }
448 }
449 }
450 for end < s.source.len && !source_boundary(s.source, end) { end++ }
451 s.column += end - start
452 s.pos = end
453 // Classify directly in the source. Materializing text is optional and
454 // happens outside the scanner, so the parser can work entirely with spans.
455 mut kind := TokenKind.identifier
456 if end - start == 1 && first == `.` {
457 kind = .dot
458 } else if (end - start == 1 && first in [`+`, `-`])
459 || (end - start == 3 && first == `.` && s.source[start + 1] == `.`
460 && s.source[start + 2] == `.`) {
461 kind = .identifier
462 } else if is_number(s.source, start, end) {
463 kind = .number
464 } else {
465 mut extended := first >= 128 || first in [`\\`, `+`, `-`, `.`]
466 for i in start .. end {
467 if s.source[i] >= 128 || s.source[i] == `\\` {
468 extended = true
469 break
470 }
471 }
472 numeric_initial := (first >= `0` && first <= `9`) || (first in [`+`, `-`, `.`] && start + 1 < end && s.source[start + 1] >= `0` && s.source[start + 1] <= `9`)
473 if extended && !numeric_initial && (is_initial(first) || first >= 128 || first in [
474 `\\`,
475 `+`,
476 `-`,
477 `.`,
478 ]) {
479 return s.extended_identifier(start, line, column)
480 }
481 return s.lexical_error(start, line, column, 'invalid token `${spelling_view(s.source, start, end)}`', false)
482 }
483 return TokenSpan{
484 kind: kind
485 start: start
486 end: s.pos
487 line: line
488 column: column
489 }
490}
491
492fn ascii_lower(c u8) u8 {
493 return if c >= `A` && c <= `Z` { c + 32 } else { c }
494}
495
496fn matches_ascii_name(source string, start int, end int, expected string) bool {
497 if end - start != expected.len {
498 return false
499 }
500 for i := 0; i < expected.len; i++ {
501 if ascii_lower(source[start + i]) != expected[i] {
502 return false
503 }
504 }
505 return true
506}
507
508fn is_whitespace(c u8) bool {
509 return c == ` ` || (c >= 0x09 && c <= 0x0d)
510}
511
512fn is_delimiter(c u8) bool {
513 return is_whitespace(c) || c in [`(`, `)`, `"`, `;`, `|`]
514}
515
516fn is_initial(c u8) bool {
517 return (c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`)
518 || c in [`@`, `!`, `$`, `%`, `&`, `*`, `/`, `:`, `<`, `=`, `>`, `?`, `^`, `_`, `~`]
519}
520
521fn is_subsequent(c u8) bool {
522 // R5RS subsequent: A-Z, a-z, 0-9, !$%&*/:<=>?^_~+-.@.
523 // Each bit represents its ASCII byte (the upper mask starts at 64).
524 // One membership test replaces repeated initial/digit/punctuation checks.
525 if c < 64 {
526 return (u64(0xf7ffec7200000000) & (u64(1) << c)) != 0
527 }
528 return c < 128 && (u64(0x47fffffec7ffffff) & (u64(1) << (c - 64))) != 0
529}
530
531// Metadata belongs to the most recently returned span and survives until next().
532pub fn (s &Scanner) token_flags() u8 { return s.flags }
533
534pub fn (s &Scanner) fold_case() bool { return !s.no_fold }
535