// R5RS sections 2 and 7.1.1: source text -> tokens. Reading lists, interpreting // numbers, decoding escapes, and evaluating expressions belong to later stages. module lexer import encoding.utf8 import unicode17 // Scanner consumes source incrementally. Its cursor and each returned TokenSpan // have constant size; successful next calls do not copy source text or collect // tokens. Create one with new_scanner so UTF-8 is checked before scanning. @[params] pub struct ScannerOptions { pub: fold_case bool = true } pub const token_preserve_case = u8(1) pub const token_identifier_escaped = u8(2) pub const token_identifier_barred = u8(4) pub const token_string_extended = u8(8) pub const token_identifier_unicode = u8(16) pub struct Scanner { source string mut: no_fold bool unicode_source bool flags u8 pos int line int = 1 column int = 1 } // new_scanner validates UTF-8 once and creates a cursor over the source. // Identifiers use the report's ASCII alphabet; strings, comments and character // literals accept UTF-8. Letter case is preserved for the reader to normalize. // Space, tab, LF, CR, CRLF, vertical tab and form feed separate tokens. pub fn new_scanner(source string, options ScannerOptions) !Scanner { valid, ascii := source_properties(source) if !valid { return LexError{ line: 1 column: 1 message: 'source is not valid UTF-8' } } return Scanner{ source: source no_fold: !options.fold_case unicode_source: !ascii } } // tokenize collects tokens with owned spellings for callers that need the whole // array. Sequential consumers should use new_scanner and next instead. pub fn tokenize(source string) ![]Token { mut scanner := new_scanner(source)! mut tokens := []Token{} // No slices exist during collection. Growth may release the old metadata // after copying; token spelling allocations have independent ownership. unsafe { tokens.flags.set(.noslices) } for { token := scanner.next()! tokens << Token{ kind: token.kind lexeme: token.text(source) start: token.start end: token.end line: token.line column: token.column } if token.kind == .eof { break } // Use actual progress through the first 32 tokens as a bounded sizing // hint. This adds no lexer pass and never speculates for huge scalar // tokens. The cap limits over-reservation if the rest is mostly trivia. if tokens.len == 32 && token.end > 0 && token.end < source.len { estimate := f64(source.len) * 32 / f64(token.end) + 1 capacity := if estimate > 8192 { 8192 } else { int(estimate) } tokens.ensure_cap(capacity) } } // Callers may freely slice the published array using ordinary semantics. unsafe { tokens.flags.clear(.noslices) } return tokens } // next returns one token span, or a located lexical error. After EOF it keeps // returning the same EOF span. After an error, discard the scanner. pub fn (mut s Scanner) next() !TokenSpan { if s.skip_plain_atmosphere() { s.skip_atmosphere()! } s.flags = if s.no_fold { token_preserve_case } else { u8(0) } start := s.pos line := s.line column := s.column if s.at_end() { return s.token(.eof, start, line, column) } mut kind := TokenKind.identifier match s.source[s.pos] { `(` { s.skip_bytes(1) kind = .lparen } `)` { s.skip_bytes(1) kind = .rparen } `'` { s.skip_bytes(1) kind = .quote } 0x60 { // backquote s.skip_bytes(1) kind = .quasiquote } `,` { s.skip_bytes(1) kind = if !s.at_end() && s.source[s.pos] == `@` { s.skip_bytes(1) TokenKind.unquote_splicing } else { TokenKind.unquote } } `|` { s.barred_identifier(start, line, column)! kind = .identifier } `"` { s.scan_string(start, line, column)! kind = .string_literal } `#` { if s.pos + 1 == s.source.len { return s.scan_atom(start, line, column) } if s.source[s.pos + 1] >= `0` && s.source[s.pos + 1] <= `9` { s.skip_bytes(1) for !s.at_end() && s.source[s.pos] >= `0` && s.source[s.pos] <= `9` { s.skip_bytes(1) } if s.at_end() { return s.lexical_error(start, line, column, 'unfinished datum label', true) } if s.source[s.pos] !in [`=`, `#`] { return s.lexical_error(start, line, column, 'datum label needs = or #', false) } kind = if s.source[s.pos] == `=` { .label_definition } else { .label_reference } s.skip_bytes(1) return s.token(kind, start, line, column) } 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] == `(` { s.skip_bytes(4) return s.token(.bytevector_start, start, line, column) } 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] == `(` { s.skip_bytes(5) return s.token(.bytevector_start, start, line, column) } match s.source[s.pos + 1] { `:` { s.skip_bytes(2) kind = .keyword_prefix } `'` { s.skip_bytes(2) kind = .syntax_quote } 0x60 { s.skip_bytes(2) kind = .syntax_quasiquote } `,` { s.skip_bytes(2) kind = if !s.at_end() && s.source[s.pos] == `@` { s.skip_bytes(1) TokenKind.syntax_unquote_splicing } else { TokenKind.syntax_unquote } } `;` { s.skip_bytes(2) kind = .datum_comment } `(` { s.skip_bytes(2) kind = .vector_start } `\\` { s.scan_character(start, line, column)! kind = .character } `t`, `T`, `f`, `F` { // Long aliases require a delimiter; preserve old short boolean adjacency. length := if ascii_lower(s.source[s.pos + 1]) == `t` { 5 } else { 6 } expected := if length == 5 { '#true' } else { '#false' } if s.pos + length <= s.source.len && matches_ascii_name(s.source, s.pos, s.pos + length, expected) { if !source_boundary(s.source, s.pos + length) { return s.lexical_error(start, line, column, 'long boolean needs a delimiter', false) } s.skip_bytes(length) return s.token(.boolean, start, line, column) } s.skip_bytes(2) kind = .boolean } else { return s.scan_atom(start, line, column) } } } else { return s.scan_atom(start, line, column) } } return s.token(kind, start, line, column) } fn (s &Scanner) at_end() bool { return s.pos >= s.source.len } // Callers have already established an in-bounds span with no CR or LF. @[inline] fn (mut s Scanner) skip_bytes(count int) { s.pos += count s.column += count } // Only an in-bounds CR or LF reaches this helper. Other bytes use skip_bytes, // so ordinary whitespace and punctuation never repeat newline classification. fn (mut s Scanner) advance_line(c u8) { s.pos++ if c == `\r` || s.pos < 2 || s.source[s.pos - 2] != `\r` { s.line++ } s.column = 1 } // Most source needs no fallible atmosphere operation. Stop before extended // comments/directives/Unicode whitespace and keep their error result cold. fn (mut s Scanner) skip_plain_atmosphere() bool { for !s.at_end() { c := s.source[s.pos] if is_whitespace(c) { if c == `\r` { s.skip_line_ending(line_ending_width(s.source, s.pos)) } else if c == `\n` { s.advance_line(c) } else { s.skip_bytes(1) } } else if c == `;` { end := if s.unicode_source { comment_end_unicode(s.source, s.pos) } else { comment_end(s.source, s.pos) } s.column += end - s.pos s.pos = end } else { return c >= 128 || (c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] in [ `|`, `!`, ]) } } return false } @[noinline] fn (mut s Scanner) skip_atmosphere() ! { for !s.at_end() { c := s.source[s.pos] if is_whitespace(c) { width := line_ending_width(s.source, s.pos) if width > 0 { s.skip_line_ending(width) } else { s.skip_bytes(1) } } else if c == `;` { end := if s.unicode_source { comment_end_unicode(s.source, s.pos) } else { comment_end(s.source, s.pos) } s.column += end - s.pos s.pos = end } else if c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] == `|` { s.block_comment(s.pos, s.line, s.column)! } else if c == `#` && s.pos + 1 < s.source.len && s.source[s.pos + 1] == `!` { s.directive(s.pos, s.line, s.column)! } else if c >= 128 { cp, width := utf8.decode_rune_at(s.source, s.pos) if !unicode17.whitespace(cp) { break } line_width := line_ending_width(s.source, s.pos) if line_width > 0 { s.skip_line_ending(line_width) } else { s.skip_bytes(width) } } else { break } } } fn (s &Scanner) token(kind TokenKind, start int, line int, column int) TokenSpan { return TokenSpan{ kind: kind start: start end: s.pos line: line column: column } } fn (mut s Scanner) scan_string(start int, line int, column int) ! { s.skip_bytes(1) if s.unicode_source { return s.scan_string_unicode(start, line, column) } return s.scan_string_ascii(start, line, column) } @[noinline] fn (mut s Scanner) scan_string_ascii(start int, line int, column int) ! { for { end := string_run_end(s.source, s.pos) s.column += end - s.pos s.pos = end if s.at_end() { break } c := s.source[s.pos] if c == `"` { s.skip_bytes(1) return } if c == `\\` { if s.pos + 1 >= s.source.len { s.skip_bytes(1) break } if s.source[s.pos + 1] in [`"`, `\\`] { s.skip_bytes(2) legacy_end := string_legacy_run_end(s.source, s.pos) s.column += legacy_end - s.pos s.pos = legacy_end continue } s.scan_extended_string_escape()! } else if c == `\r` { s.flags |= token_string_extended s.skip_line_ending(line_ending_width(s.source, s.pos)) } else { s.advance_line(c) } } return s.lexical_error(start, line, column, 'unterminated string', true) } @[noinline] fn (mut s Scanner) scan_string_unicode(start int, line int, column int) ! { for { end := string_run_end_unicode(s.source, s.pos) s.column += end - s.pos s.pos = end if s.at_end() { break } c := s.source[s.pos] if c == `"` { s.skip_bytes(1) return } if c == `\\` { if s.pos + 1 >= s.source.len { s.skip_bytes(1) break } if s.source[s.pos + 1] in [`"`, `\\`] { s.skip_bytes(2) continue } s.scan_extended_string_escape()! } else if c == `\n` { s.advance_line(c) } else { s.flags |= token_string_extended s.skip_line_ending(line_ending_width(s.source, s.pos)) } } return s.lexical_error(start, line, column, 'unterminated string', true) } @[noinline] fn (mut s Scanner) scan_extended_string_escape() ! { position, line, column := s.pos, s.line, s.column s.skip_bytes(1) s.flags |= token_string_extended s.extra_escape(position, line, column, false)! } fn (mut s Scanner) scan_character(start int, line int, column int) ! { s.skip_bytes(2) if s.at_end() { return s.lexical_error(start, line, column, 'missing character after #\\', true) } first := s.pos cp, width := utf8.decode_rune_at(s.source, s.pos) if cp in [rune(10), rune(13), rune(0x85), rune(0x2028)] { s.skip_line_ending(width) } else { s.skip_bytes(width) } if cp in [`x`, `X`] && !s.at_end() && hex_digit(s.source[s.pos]) >= 0 { s.pos = first + 1 s.column = column + 3 s.hex_escape(start, line, column, false)! if !source_boundary(s.source, s.pos) { return s.lexical_error(start, line, column, 'invalid hexadecimal character', false) } return } for !s.at_end() && !source_boundary(s.source, s.pos) { s.skip_bytes(1) } if s.pos - first == width { return } if character_name_value(s.source, first, s.pos, !s.no_fold) == rune(-1) { return s.lexical_error(start, line, column, 'invalid character literal', false) } } fn (mut s Scanner) scan_atom(start int, line int, column int) !TokenSpan { // Atoms contain no line endings: every newline is a delimiter. Advance // the byte cursor locally, then update the column once for the whole atom. mut end := start first := s.source[start] if is_initial(first) { // Identifier bytes cannot be delimiters. Validate while finding the // end, testing the delimiter only when this run stops. Invalid bytes // fall through to the full atom scan so errors retain their spelling. end = identifier_end(s.source, start + 1) if end == s.source.len || is_delimiter(s.source[end]) || extended_source_boundary(s.source, end) { s.column += end - start s.pos = end return TokenSpan{.identifier, start, end, line, column} } } else { digits := if first in [`+`, `-`] { start + 1 } else { start } if digits < s.source.len && s.source[digits] >= `0` && s.source[digits] <= `9` { end = digits + 1 for end < s.source.len && s.source[end] >= `0` && s.source[end] <= `9` { end++ } // A decimal digit run with an optional sign is already a valid // number. Every suffix still goes through the full R5RS grammar. if end == s.source.len || is_delimiter(s.source[end]) || extended_source_boundary(s.source, end) { s.column += end - start s.pos = end return TokenSpan{.number, start, end, line, column} } } } for end < s.source.len && !source_boundary(s.source, end) { end++ } s.column += end - start s.pos = end // Classify directly in the source. Materializing text is optional and // happens outside the scanner, so the parser can work entirely with spans. mut kind := TokenKind.identifier if end - start == 1 && first == `.` { kind = .dot } else if (end - start == 1 && first in [`+`, `-`]) || (end - start == 3 && first == `.` && s.source[start + 1] == `.` && s.source[start + 2] == `.`) { kind = .identifier } else if is_number(s.source, start, end) { kind = .number } else { mut extended := first >= 128 || first in [`\\`, `+`, `-`, `.`] for i in start .. end { if s.source[i] >= 128 || s.source[i] == `\\` { extended = true break } } numeric_initial := (first >= `0` && first <= `9`) || (first in [`+`, `-`, `.`] && start + 1 < end && s.source[start + 1] >= `0` && s.source[start + 1] <= `9`) if extended && !numeric_initial && (is_initial(first) || first >= 128 || first in [ `\\`, `+`, `-`, `.`, ]) { return s.extended_identifier(start, line, column) } return s.lexical_error(start, line, column, 'invalid token `${spelling_view(s.source, start, end)}`', false) } return TokenSpan{ kind: kind start: start end: s.pos line: line column: column } } fn ascii_lower(c u8) u8 { return if c >= `A` && c <= `Z` { c + 32 } else { c } } fn matches_ascii_name(source string, start int, end int, expected string) bool { if end - start != expected.len { return false } for i := 0; i < expected.len; i++ { if ascii_lower(source[start + i]) != expected[i] { return false } } return true } fn is_whitespace(c u8) bool { return c == ` ` || (c >= 0x09 && c <= 0x0d) } fn is_delimiter(c u8) bool { return is_whitespace(c) || c in [`(`, `)`, `"`, `;`, `|`] } fn is_initial(c u8) bool { return (c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`) || c in [`@`, `!`, `$`, `%`, `&`, `*`, `/`, `:`, `<`, `=`, `>`, `?`, `^`, `_`, `~`] } fn is_subsequent(c u8) bool { // R5RS subsequent: A-Z, a-z, 0-9, !$%&*/:<=>?^_~+-.@. // Each bit represents its ASCII byte (the upper mask starts at 64). // One membership test replaces repeated initial/digit/punctuation checks. if c < 64 { return (u64(0xf7ffec7200000000) & (u64(1) << c)) != 0 } return c < 128 && (u64(0x47fffffec7ffffff) & (u64(1) << (c - 64))) != 0 } // Metadata belongs to the most recently returned span and survives until next(). pub fn (s &Scanner) token_flags() u8 { return s.flags } pub fn (s &Scanner) fold_case() bool { return !s.no_fold }