#! @file lexer.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the lexer, which reads the text of a source into tokens. It notes #! what is wrong with the text as it goes, keeps the comments and documentation #! for the tokens they are written before, and follows the holes of interpolated #! strings, so the parser is given tokens alone. import std::containers; import core::swar; module sakura::analyzer; #! Represents a structure capable of lexically analyzing a source object. #! #! The lexer reports what is wrong with the text it reads itself: numbers and #! quotes that are malformed, escapes that do not exist, character literals of #! more or less than one character, and text spanning lines that is laid out #! wrong. A character that is no part of the language is reported and dropped, #! so the parser never sees it. #! #! A `>` begins the longest operator it can, as `>>`, `>=`, or `>>=`, and a #! token is made at each `>` and `=` after its first as well, holding what is #! left of it: `>>=` is `>>=`, `>=`, then `=`. An operator is the first of those #! tokens, and the parser moves past the rest with it, while type arguments #! closed by `>>` take its tokens one `>` at a time. So no token is ever split, #! and the tokens of a file are always those the lexer made. pub struct lexer { var source: &source; #! The file being lexed. var names: &mut names; #! The names it interns words into. var holes: stack; #! The holes of interpolated strings it is within, innermost on top. var text: *u8; #! The bytes of the source's text, read where they are. var size: u32; #! How many bytes the text holds. var file: u32; #! The index of the file, which its notes give. var index: u32; #! The byte it is at. var within: u32; #! Where the `>` operator the index is within ends, past which none of its tokens reach. var name: u32; #! The ID of the last word scanned. # Where what it finds wrong is noted, which `max_notes` bounds: kept, or # heard as it is made, as where another thread reports it. pub var sink: note_sink; #! Where what it finds wrong is noted. } #! A hole of an interpolated string that the lexer is within. #! #! The braces opened within the hole are counted, so that the `}` closing it is #! told apart from one closing a block or a struct literal inside it. pub struct lexer::hole { var braces: u32; #! How many braces are open within it. var block: bool; #! Whether its string is a text block, `$"""`. var text: u32; #! Where the text of the string begins, past its `$"` or `$"""`. } #! The maximum depth that the lexer allows the nesting of interpolated strings. pub const lexer::max_depth := 16; #! The most notes the lexer makes for one file. pub const lexer::max_notes: u32 = 100; #! Creates a new lexer from the provided source and names references. #! @param source The source that this lexer will be tokenizing. #! @param names A place to store and track already known names. #! @param notes Where the lexer reports what is wrong with the text. #! @param file The index of the file the source is. #! @returns The instantiated lexer. pub def lexer::new( source: &source, names: &mut names, notes: &mut vector, file: u32 ): lexer { return lexer { source = source, names = names, sink = note_sink::new(notes, lexer::max_notes), holes = stack::::new(), text = source.text.span.data, size = source.length as u32, file = file }; } #! Tokenizes the whole source into the syntax, through the `eof` that ends it, #! with the comments and documentation lines written before each token. #! @param this The lexer. #! @param syntax The syntax the tokens and comments are written to. pub def lexer::tokenize_all(&mut this, syntax: &mut syntax): void { syntax.reserve_for_text(this.size); while true { this.skip_fluff(syntax); this.name = 0; val start := this.index; val kind := this.scan(); if kind == tk::unknown { this.report(start, this.index - start, ec::token, "The character is no part of the language."); continue; } # What follows the first `>` of an operator is read again, as the tokens of # what is left of it. val end := this.index; if kind.has(tt::angle) && end - start > 1 { this.within = end; this.index = start + 1; } syntax.add_token(kind, start, end - start, this.name); break if kind == tk::eof; } syntax.fit_tokens(); } val lexer::curr: u8 { get => this.peek(0); } val lexer::next: u8 { get => this.peek(1); } val lexer::ahead: u8 { get => this.peek(2); } val lexer::eof: bool { get => this.index >= this.size; } val lexer::eol: bool { get => this.eof || this.curr.is_eol; } #! Whether the current byte is of the class. #! @param this The lexer. #! @param class The class of byte. #! @returns Whether it is. def lexer::curr_is(&this, class: cc): bool { return (char_classes[this.curr as u64] & class as u8) != 0; } val lexer::at_block_quote: bool { get { return this.curr.is_dquote && this.next.is_dquote && this.ahead.is_dquote; } } val lexer::in_line_hole: bool { get { return this.holes.length > 0 && !this.holes.peek().block; } } def lexer::advance(&mut this): void { if this.index < this.size { this.index++; } } def lexer::advance_for(&mut this, count: u64): void { for _ in 0..count { this.advance(); } } def lexer::skip_line(&mut this): void { val text := this.text; val size := this.size; var at := this.index; # Sixteen bytes at a time while none is `\n` where vectors are held in # registers, then eight, as `source::find_lines` finds them. if lanes_held() { val newline := u8x16::splat('\n'); while at + 16 <= size { val chunk: u8x16 = *((text + at) as *u8x16); val marks := chunk.equal(&newline).bits(); if marks != 0 { this.index = at + trailing_zeros(marks); return; } at += 16; } } while at + 8 <= size { val word := *((text + at) as *u64) ^ 0x0A0A0A0A0A0A0A0A; break if ((word - 0x0101010101010101) & ~word & 0x8080808080808080) != 0; at += 8; } while at < size && text[at] != '\n' { at++; } this.index = at; } #! Skips spacing and comments, keeping each comment in the syntax: a `#!` line #! as documentation, and any other as a comment, each for the token after it. #! @param this The lexer. #! @param syntax The syntax the comments are written to. def lexer::skip_fluff(&mut this, syntax: &mut syntax): void { # The index is held here, and written back for a comment and where it ends. val text := this.text; val size := this.size; var at := this.index; while at < size { val byte: u8 = text[at]; if (char_classes[byte as u64] & cc::space as u8) != 0 { at++; continue; } break if !byte.is_cmnt; val start := at; this.index = at; this.skip_line(); at = this.index; val token := syntax.token_count as u32; val length := at - start; if this.byte_at(start + 1) == '!' { syntax.docs.append(doc { offset = start, length = length, token = token }); } else { syntax.comments.append(comment { offset = start, length = length, token = token }); } } this.index = at; } def lexer::peek(&this, offset: u32): u8 { val index := this.index + offset; return index < this.size ? this.text[index] : '\0'; } #! The byte of the source text at the offset, or `\0` past its end. #! @param this The lexer. #! @param offset The byte's offset. #! @returns The byte. def lexer::byte_at(&this, offset: u32): u8 { return offset < this.size ? this.text[offset] : '\0'; } def lexer::scan(&mut this): tk { return tk::eof if this.eof; val byte := this.curr; val class := char_classes[byte as u64]; return this.close_hole() if byte.is_eol && this.in_line_hole; return this.scan_word() if (class & cc::start as u8) != 0; return this.scan_number() if (class & cc::digit as u8) != 0; return this.scan_quoted('\"', this.at_block_quote) if byte.is_dquote; return this.scan_quoted('\'', false) if byte.is_squote; return this.scan_istring() if byte.is_format && this.next.is_dquote; return this.scan_brace() if this.holes.length != 0 && byte.is_brace; return this.scan_foreign() if byte >= 0x80; return this.scan_punct(); } def lexer::scan_word(&mut this): tk { val start := this.index; val text := this.text; val size := this.size; var at := start; while at < size && (char_classes[text[at] as u64] & cc::word as u8) != 0 { at++; } this.index = at; val lex := strview::over(text + start, (at - start) as u64); val id := this.names.intern(&lex); this.name = id; return id <= tk::kw_end as u32 ? id as tk : tk::name; } def lexer::scan_number(&mut this): tk { var base: u8 = 10; var valid: bool = true; var start: u32 = this.index; if this.curr.is_zero { base = match this.next { 'x' => 16, 'o' => 8, 'b' => 2, else => 10 }; } var sym := tk::signed; if base != 10 { this.advance(); this.advance(); while this.curr.is_base_digit(base) { this.advance(); } valid = this.index > start + 2; # `u` makes an integer unsigned, in any base: `0xFFu`. if this.curr == 'u' { sym = tk::unsigned; this.advance(); } } else { while this.curr_is(cc::digit) { this.advance(); } if this.curr.is_dot && this.next.is_digit { sym = tk::float; this.advance(); while this.curr_is(cc::digit) { this.advance(); } } # An exponent makes a float too: `e` or `E`, an optional sign, then digits, as # `6.02e23` and `1e-9`. An `e` without digits after it is left to the check below. val signed := this.next == '+' || this.next == '-'; val digit := signed ? this.ahead.is_digit : this.next.is_digit; if (this.curr == 'e' || this.curr == 'E') && digit { sym = tk::float; this.advance(); if signed { this.advance(); } while this.curr_is(cc::digit) { this.advance(); } } # A fraction cannot be unsigned, so `1.5u` is left to the check below. if this.curr == 'f' { sym = tk::float; this.advance(); } else if this.curr == 'u' && sym != tk::float { sym = tk::unsigned; this.advance(); } } if this.curr_is(cc::word) { valid = false; while this.curr_is(cc::word) { this.advance(); } } return sym if valid; this.report(start, this.index - start, ec::token, "The number is malformed, as a digit outside its base or letters after it."); return tk::bad_number; } def lexer::scan_istring(&mut this): tk { val start := this.index; this.advance(); val block := this.at_block_quote; this.advance_for(block ? 3 : 1); val text := this.index; val stop := this.scan_text(block); return this.open_hole(block, text) if stop == tk::lbrace; if stop != tk::string { return this.unclosed(start); } if block { this.check_block(text, this.index - 3); } return tk::istring; } def lexer::scan_quoted(&mut this, quote: u8, block: bool): tk { val start := this.index; val quotes: u64 = block ? 3 : 1; this.advance_for(quotes); # A character literal holds one character, which is one or more bytes, or one # escape, so what it holds is counted as it is read. var count: u32 = 0; while true { # A string's bytes are passed eight at a time to the next that may end it, # since only a character literal counts what it holds. if quote == '"' { this.index = quoted_run(this.text, this.index, this.size, false); } return this.unclosed(start) if this.eof; return this.unclosed(start) if this.eol && !block; # Happy path break aways. break if block && this.at_block_quote; break if !block && this.curr == quote; if !this.curr.is_continuation { count++; } if this.curr.is_escape { this.check_escape(); } else { this.advance(); } } val end := this.index; this.advance_for(quotes); if quote == '\'' && count != 1 { this.report(start, this.index - start, ec::char, "Character literals must contain exactly one character or escape."); } if block { this.check_block(start + 3, end); } return match quote { '\"' => tk::string, '\'' => tk::char, else => tk::unknown }; } def lexer::scan_brace(&mut this): tk { val hole := &mut this.holes.peek(); if this.curr.is_lbrace { hole.braces++; return this.scan_punct(); } if hole.braces != 0 { hole.braces--; return this.scan_punct(); } val start := this.index; this.advance(); val stop := this.scan_text(hole.block); return tk::istring_mid if stop == tk::lbrace; if stop != tk::string { this.unclosed(start); return this.close_hole(); } if hole.block { this.check_block(hole.text, this.index - 3); } return this.close_hole(tk::istring_end); } #! Reads the text of an interpolated string through the `{` opening a hole, or #! through its closing quotes. #! @param this The lexer. #! @param block Whether the text is a text block, `"""`. #! @returns `lbrace` at a hole, `string` at its end, or `bad_quote` where it is #! never closed. def lexer::scan_text(&mut this, block: bool): tk { while true { this.index = quoted_run(this.text, this.index, this.size, true); return tk::bad_quote if this.eof; return tk::bad_quote if this.eol && !block; if block && this.at_block_quote { this.advance_for(3); return tk::string; } if this.curr.is_escape { this.check_escape(); continue; } val curr := this.curr; this.advance(); return tk::string if !block && curr.is_dquote; return tk::lbrace if curr.is_lbrace; } return tk::bad_quote; } #! Where the bytes of quoted text from a place stop needing a look one at a #! time: at the next `"`, `\`, line break, or, in interpolated text, `{`, found #! eight bytes at a time. Fewer than eight left are looked at one at a time. #! @param text The source's bytes. #! @param from Where to begin. #! @param size How many bytes the source has. #! @param holes Whether `{` opens a hole, as in interpolated text. #! @returns Where the first such byte is, or where fewer than eight are left. def quoted_run(text: *u8, from: u64, size: u64, holes: bool): u32 { var at := from; while at + 8 <= size { val word := swar::load(text + at); var stops: swar::mask8 = word.equal('"') | word.equal('\\') | word.equal('\n'); if holes { stops = stops | word.equal('{'); } return (at + stops.first()) as u32 if stops.any(); at += 8; } return at as u32; } #! Reports text that begins at `start` and is never closed. #! @param this The lexer. #! @param start Where the text begins. #! @returns `bad_quote`. def lexer::unclosed(&mut this, start: u32): tk { this.report(start, 1, ec::token, "The text is not closed before the end of its line, or of the file."); return tk::bad_quote; } #! Moves past the escape at the current `\`, reporting it where it is not one of #! the language's. #! @param this The lexer. def lexer::check_escape(&mut this): void { val start := this.index; this.advance(); if this.eol { this.report(start, 1, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH."); return; } val which := this.curr; this.advance(); match which { 'n', 't', 'r', '0', '\\', '\'', '\"', '{', '}' => return; 'x' => { if this.curr.is_base_digit(16) && this.next.is_base_digit(16) { this.advance_for(2); return; } } } this.report(start, 2, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH."); } #! Checks how text spanning lines is laid out, between `text`, past the quotes #! opening it, and `end`, where the quotes closing it begin. #! #! Nothing but the line break follows the opening quotes, the closing quotes #! stand on a line of their own, and every line of the text is indented at least #! as far as they are, or holds only whitespace, since that much is taken off. #! @param this The lexer. #! @param text Where the text begins, past the quotes opening it. #! @param end Where the quotes closing it begin. def lexer::check_block(&mut this, text: u32, end: u32): void { var first := text; while first < end && this.byte_at(first).is_blank { first++; } if first == end || !this.byte_at(first).is_eol { this.report(text - 3, 3, ec::block, "The text of a block begins on the line below the `\"\"\"` that opens it, so nothing else is written there."); return; } var last := end; while last > first && !this.byte_at(last - 1).is_eol { last--; } for at in last..end { if !this.byte_at(at as u32).is_blank { this.report(last, end - last + 3, ec::block, "The `\"\"\"` that closes a block is written on a line of its own, and how far it is indented is how far its text is."); return; } } val indent := end - last; var line := first + 1; while line < last { var stop := line; while stop < last && !this.byte_at(stop).is_eol { stop++; } var at := line; while at < stop && at - line < indent && this.byte_at(at).is_blank { at++; } if at < stop && at - line < indent { this.report(line, stop - line, ec::block, "This line is indented less than the `\"\"\"` that closes the block, so the block cannot take that much off it."); return; } line = stop + 1; } } #! A punctuator, as long as it can be. One within a `>` operator ends where the #! operator does, as what is left of it. #! @param this The lexer. #! @returns The punctuator's kind, or `unknown` where no punctuator begins #! there. def lexer::scan_punct(&mut this): tk { val limit := this.index < this.within ? this.within : this.size; val text := this.text; var at := this.index; var kind: tk = punct_firsts[text[at] as u64]; at++; while (punct_longer[kind as u64] & 1) != 0 && at < limit { val longer := kind.from(text[at]); break if longer == tk::unknown; kind = longer; at++; } this.index = at; return kind; } #! The punctuator each byte begins, worked out while compiling, or `unknown`. const punct_firsts: tk[256] = make_punct_firsts(); #! Whether each kind of token is a punctuator a byte may make longer, as `1`. const punct_longer: u8[tk::count as u64] = make_punct_longer(); const def make_punct_firsts(): tk[256] { var made: tk[256]; for each in 0..256 { made[each] = tk::unknown.from(each as u8); } return made; } const def make_punct_longer(): u8[tk::count as u64] { var made: u8[tk::count as u64]; for kind in 0..tk::count as u64 { continue if kind == tk::unknown as u64; for each in 0..256 { if (kind as tk).from(each as u8) != tk::unknown { made[kind] = 1; } } } return made; } #! A character beyond ASCII, which the language has no use for outside text and #! comments. All of its bytes are read, so it is reported once. #! @param this The lexer. #! @returns `unknown`. def lexer::scan_foreign(&mut this): tk { this.advance(); while this.curr.is_continuation { this.advance(); } return tk::unknown; } def lexer::open_hole( &mut this, block: bool, text: u32 ): tk { if this.holes.length == lexer::max_depth { this.report(text, 1, ec::token, "Interpolated strings are nested within each other's holes too deeply."); return tk::bad_quote; } this.holes.push(lexer::hole { braces = 0, block = block, text = text }); return tk::istring_beg; } def lexer::close_hole( &mut this, kind: tk = tk::bad_quote ): tk { this.holes.pop(); return kind; } #! Reports what is wrong with the text from `offset`, for `length` bytes. #! @param this The lexer. #! @param offset Where the text begins. #! @param length How many bytes it covers. #! @param code What kind of mistake it is. #! @param detail What the note says. def lexer::report(&mut this, offset: u32, length: u32, code: ec, detail: strview): void { return if !this.sink.admits(); var made := note { file = this.file, offset = offset, length = length, code = code, detail = string::from(detail, nothing {}), lexed = true }; this.sink.give(&mut made); }