#! @file helpers.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains what the rest of the parser is made from: moving through the tokens, #! making nodes, records, and runs, starting declarations, making notes, lists, #! and recovering from what is wrong to parse what follows. module sakura::analyzer; # Tokens #! Reads the kind of the current token into `kind`, which is `eof` at the limit. #! @param this The parser. def parser::sync(&mut this): void { this.kind = this.index < this.limit ? this.syntax.token_kinds[this.index] : tk::eof; } #! The kind of the token `ahead` past the current one, or `eof` past the limit. #! @param this The parser. #! @param ahead How many tokens past the current one, where 0 is the current #! one. #! @returns The token's kind. def parser::peek(&this, ahead: u32): tk { val at := this.index + ahead; return at < this.limit ? this.syntax.token_kinds[at] : tk::eof; } #! Moves to the next token, staying on the `eof` that ends them. #! #! A `>>`, `>=`, or `>>=` is followed by a token at each `>` and `=` after its #! first, which `close_angle` takes one at a time, and which an operator is #! moved past with, as one token for each byte it spans. #! @param this The parser. def parser::advance(&mut this): void { return if this.kind == tk::eof; if this.kind.has(tt::angle) { this.index += this.kind.width; } else { this.index++; } this.sync(); } def parser::check(&this, kind: tk): bool { return this.kind == kind; } #! Whether the current token is the name of the ID, as `names::this_id`. #! @param this The parser. #! @param word The ID of the name. #! @returns Whether the current token is that name. def parser::check_word(&this, word: u32): bool { return this.kind == tk::name && this.syntax.token_names[this.index] == word; } #! Whether the current token's kind has the trait. #! @param this The parser. #! @param which The trait to ask of the token's kind. #! @returns Whether its kind has it. def parser::at(&this, which: tt): bool { return this.kind.has(which); } #! Moves past the current token when it is of the kind. #! @param this The parser. #! @param kind The kind of token to move past. #! @returns Whether it was, and so was moved past. def parser::accept(&mut this, kind: tk): bool { return false if this.kind != kind; this.advance(); return true; } #! Moves past the current token when it is of the kind, or else reports the #! detail and panics. #! @param this The parser. #! @param kind The kind of token wanted. #! @param detail What the note says where it is not, as `Expected ";" after #! the statement.`. #! @returns Whether it was of the kind. def parser::expect(&mut this, kind: tk, detail: strview): bool { return true if this.accept(kind); this.fail(ec::token, detail); return false; } #! Moves past the `>` closing type arguments or parameters, which may be the #! first of `>>`, `>=`, or `>>=`. The lexer made a token of what is left of #! those, which becomes the current token: `>`, `=`, or `>=`. #! @param this The parser. #! @param detail What the note says where no `>` is there. #! @returns Whether a `>` was moved past. def parser::close_angle(&mut this, detail: strview): bool { if !this.at(tt::angle) { this.fail(ec::token, detail); return false; } this.index++; this.sync(); return true; } #! Whether the type whose `<` is at the token follows `as` or `is`, where a `<` #! always begins type arguments, so what looks like a comparison is not one. #! @param this The parser. #! @param at The token of the `<`. #! @returns Whether `as` or `is` comes before the type. def parser::follows_cast(&this, at: u32): bool { var back := at; while back > 0 { back--; val kind := this.syntax.token_kinds[back]; return kind == tk::kw_as || kind == tk::kw_is if !kind.has(tt::piece); } return false; } # Nodes #! Appends a node, whose last token is the last the parser moved past, or its #! own where it moved past none since. #! @param this The parser. #! @param kind The node's kind. #! @param token Its token. #! @param left Its first slot, which its kind's shape says the meaning of. #! @param right Its second slot. #! @returns The node. def parser::make_node( &mut this, kind: nk, token: u32, left: u32 = 0, right: u32 = 0 ): u32 { val end := this.index > token ? this.index - 1 : token; return this.syntax.add_node(kind, token, left, right, end); } #! An `error` node at the token, standing where the parser made no sense of the #! source, holding the run of what it did parse there, so that tools still find #! what is within it. #! @param this The parser. #! @param token The token it stands at. #! @param held The run of what was parsed there, or 0. #! @returns The node. def parser::error(&mut this, token: u32, held: u32 = 0): u32 { return this.make_node(nk::error, token, held); } #! An `error` node at the current token, holding nothing. #! @param this The parser. #! @returns The node. def parser::error_here(&mut this): u32 { return this.error(this.index); } #! A `when_block`, `if_stmt`, `if_const`, or `ternary`: a condition, and what is #! taken where it holds and where it does not. #! @param this The parser. #! @param kind The node's kind. #! @param token Its token. #! @param condition The condition. #! @param then What is taken where it holds. #! @param other What is taken where it does not, or 0. #! @returns The node. def parser::branch(&mut this, kind: nk, token: u32, condition: u32, then: u32, other: u32): u32 { return this.make_node(kind, token, condition, this.make_record(then, other)); } #! A `name` node of the current token, which is moved past. #! @param this The parser. #! @param detail What the note says where the current token is no name. #! @returns The node, or an `error` node where the token is no name. def parser::name_node(&mut this, detail: strview): u32 { if !this.check(tk::name) { this.fail(ec::ident, detail); return this.error_here(); } this.advance(); return this.make_node(nk::name, this.index - 1); } #! Writes a record of a node's slots to `extras`, unless every slot is 0, where #! the zeros `extras` begins with stand for it. #! @param this The parser. #! @param slots The node's slots, in the order its shape lists them. #! @returns Where the record begins, for the slot of the node holding it. def parser::make_record(&mut this, slots: u32...): u32 { var empty := true; for slot in slots { empty = empty && slot == 0; } return 0 if empty; val at := this.syntax.extras.length as u32; this.syntax.extras.extend(slots); return at; } #! Where the nodes of a run begin on the scratchpad, for `make_run`. #! @param this The parser. #! @returns The scratchpad's length. val parser::mark: u64 { get => this.scratch.length; } #! Holds a node of a run being parsed on the scratchpad. #! @param this The parser. #! @param node The node. def parser::push(&mut this, node: u32): void { this.scratch.push(node); } #! Moves the nodes held on the scratchpad since the mark to a run in `extras`. #! @param this The parser. #! @param mark Where the nodes begin, as `mark` gave it. #! @returns Where the run begins, or 0 for a run of no nodes. def parser::make_run(&mut this, mark: u64): u32 { val count := this.scratch.length - mark; return 0 if count == 0; val at := this.syntax.extras.length as u32; this.syntax.extras.append(count as u32); this.syntax.extras.extend(span::::over(this.scratch.view().data + mark, count)); this.drop(mark); return at; } #! A run of the nodes given, leaving out those that are absent. #! @param this The parser. #! @param nodes The nodes, of which 0 is left out. #! @returns Where the run begins, or 0 where it holds none. def parser::run_of(&mut this, nodes: u32...): u32 { val mark := this.mark; for node in nodes { if node != 0 { this.push(node); } } return this.make_run(mark); } #! Lets go of the nodes held on the scratchpad since the mark. #! @param this The parser. #! @param mark Where the nodes begin, as `mark` gave it. def parser::drop(&mut this, mark: u64): void { this.scratch.resize(mark); } #! A run of the nodes of `first` followed by those of `second`. #! @param this The parser. #! @param first The run whose nodes come first. #! @param second The run whose nodes come after. #! @returns The joined run, or 0 where both are empty. def parser::join_runs(&mut this, first: u32, second: u32): u32 { return second if first == 0; return first if second == 0; val mark := this.mark; for &node in this.run_view(first) { this.push(node); } for &node in this.run_view(second) { this.push(node); } return this.make_run(mark); } #! How many nodes the run holds. #! @param this The parser. #! @param run Where the run begins. #! @returns How many nodes it holds. def parser::run_length(&this, run: u32): u32 { return this.syntax.run_length(run); } #! The node at the index of the run. #! @param this The parser. #! @param run Where the run begins. #! @param index The position, below its length. #! @returns The node. def parser::run_at(&this, run: u32, index: u32): u32 { return this.syntax.run_at(run, index); } #! The nodes of the run, where they are. #! @param this The parser. #! @param run Where the run begins. #! @returns The nodes, a view only good until another run or record is made. def parser::run_view(&this, run: u32): span { return this.syntax.run_view(run); } #! The ID of the name the node's token is. #! @param this The parser. #! @param node The node. #! @returns The name's ID. def parser::name_of(&this, node: u32): u32 { return this.syntax.token_names[this.syntax.node_tokens[node]]; } #! The bit of a flag when it is on, to be or'd with others into a mask, as a #! `flags` slot. #! @tparam T The enum of flags. #! @param on Whether the flag is on. #! @param flag The flag. #! @returns The flag's bit, or 0 where it is off. def parser::bit(on: bool, flag: T): u32 where T: ordinal { return on ? flag as u32 : 0; } # Declarations #! What comes before a declaration: its attributes, `pub`, and the token it #! begins at, which its documentation is written before. struct parser::lead { var attrs: u32; #! The run of its attributes. var exported: bool; #! `pub`. var start: u32; #! The token it begins at. } #! Where a declaration is written, which says what it may be. enum parser::place { top, #! At the top level of a file, or within a `when` there. local, #! Within a function. field, #! Within a struct or union. member, #! Within a trait. } #! The lead of a declaration beginning at the current token, with nothing before #! it. #! @param this The parser. #! @returns The lead. def parser::bare_lead(&this): parser::lead { return parser::lead { start = this.index }; } #! Records where a declaration began, which says what documents it. #! @param this The parser. #! @param made The declaration's node. #! @param lead What came before it: where it began, and its documentation. #! @returns The declaration. def parser::declared_at(&mut this, made: u32, lead: &parser::lead): u32 { if made != 0 && this.syntax.node_kinds[made] != nk::error { this.syntax.starts.set(made as u64, lead.start); } return made; } # Notes #! Reports an error at the current token, then panics, which silences notes #! until the parser resynchronizes so that one mistake is one note. #! @param this The parser. #! @param code What kind of error it is. #! @param detail What the note says. def parser::fail(&mut this, code: ec, detail: strview): void { this.fail_at(this.index, code, detail); } def parser::fail_at(&mut this, token: u32, code: ec, detail: strview): void { # Failing at a limit short of the end of the tokens says a reparse cut what it # parsed short, which a whole parse would have read on past. if this.kind == tk::eof && this.limit + 1 < this.syntax.token_count as u32 { this.cut = true; } return if this.panic; this.report_at(token, code, detail); this.panic = true; } #! Reports an error at the current token without panicking, for mistakes the #! parser reads past knowing what was meant. #! @param this The parser. #! @param code What kind of error it is. #! @param detail What the note says. def parser::report(&mut this, code: ec, detail: strview): void { this.report_at(this.index, code, detail); } #! Reports an error at the token. A note saying what was expected says what was #! found instead, the token it is at, which `note::message` spells. #! @param this The parser. #! @param token The token the error is at. #! @param code What kind of error it is. #! @param detail What the note says. def parser::report_at(&mut this, token: u32, code: ec, detail: strview): void { return if this.panic || this.halted || !this.sink.admits(); var made := note { file = this.file, offset = this.syntax.token_offsets[token], length = this.syntax.token_length(token, this.names), code = code, detail = string::from(detail, nothing {}), found = detail.starts_with("Expected") }; this.sink.give(&mut made); } # Nesting #! Goes one level deeper, unless that is past `max_depth`, where the rest of the #! declaration is given up on: the tokens seem to end where it does, so that #! everything parsing it returns, and the top level resumes after it. #! @param this The parser. #! @returns Whether the parser went deeper, and must `leave` again. def parser::enter(&mut this): bool { if this.depth < parser::max_depth { this.depth++; return true; } if !this.halted { this.panic = false; this.fail(ec::syntax, "Nesting exceeds the maximum depth."); val end := this.declaration_end(); this.index = end; this.limit = end; this.halted = true; this.sync(); } return false; } def parser::leave(&mut this): void { this.depth--; } #! Where the top-level declaration the parser is within ends, from where it #! began: past the `}` closing the braces it opens, or the `;` ending it outside #! any, whichever comes past the current token. #! @param this The parser. #! @returns The token after the declaration. def parser::declaration_end(&this): u32 { val last := this.syntax.token_count as u32 - 1; var braces: u32 = 0; for at in this.begun..last { val kind := this.syntax.token_kinds[at]; if kind == tk::lbrace { braces++; } else if kind == tk::rbrace { return at + 1 if braces <= 1 && at >= this.index; braces = braces > 0 ? braces - 1 : 0; } else if kind == tk::semicolon && braces == 0 && at >= this.index { return at + 1; } } return last; } #! Takes up the tokens after a declaration given up on, through the limit. #! @param this The parser. #! @param limit The last token to take up. def parser::resume(&mut this, limit: u32): void { this.limit = limit; this.halted = false; this.panic = false; this.sync(); } # Recovery #! Where the parser resumes after an error, which decides the tokens it stops #! at. enum parser::scope { document, #! The top level of a file. declarations, #! Within a `when` at the top level. block, #! Statements. fields, #! The members of a struct or union. members, #! The members of a trait. } #! Whether the current token begins the next item of the scope. #! @param this The parser. #! @param scope What the parser is within. #! @returns Whether the token begins an item of it. def parser::resumes(&this, scope: parser::scope): bool { return match scope { parser::scope::document => this.at(tt::declares) || this.at(tt::imports), parser::scope::declarations => this.at(tt::declares), parser::scope::block => this.at(tt::states), parser::scope::fields => this.at(tt::fields), parser::scope::members => this.at(tt::members), else => false }; } #! Skips tokens until one that can begin the next item of the scope, stepping #! over balanced braces, then stops panicking. Every token it stops on is #! consumed by the item parser, or ends the enclosing loop, so parsing always #! makes progress. #! @param this The parser. #! @param scope What the parser is within. def parser::synchronize(&mut this, scope: parser::scope): void { var braces: u32 = 0; while !this.check(tk::eof) { if braces == 0 { break if this.resumes(scope); if this.check(tk::semicolon) { this.advance(); break; } if this.check(tk::rbrace) { if scope == parser::scope::document { this.advance(); } break; } } if this.check(tk::lbrace) { braces++; } else if this.check(tk::rbrace) { braces--; if braces == 0 { this.advance(); break; } } this.advance(); } this.panic = false; } #! Skips to the `}` closing the braces the parser is within, without moving #! past it, then stops panicking. #! @param this The parser. def parser::skip_to_close(&mut this): void { var braces: u32 = 0; while !this.check(tk::eof) { if this.check(tk::lbrace) { braces++; } else if this.check(tk::rbrace) { break if braces == 0; braces--; } this.advance(); } this.panic = false; } # Lists #! What a list holds, which `list_item` parses one of. enum parser::item { argument, #! Of a call. element, #! Of an array. field, #! Of a struct literal or an attribute. param_type, #! Of a function type. rename, #! Of a spread field. enumerator, #! Of an enum. value_arm, #! Of a match used as a value. } def parser::list_item(&mut this, kind: parser::item): u32 { return match kind { parser::item::argument => this.argument(), parser::item::element => this.expression(), parser::item::field => this.field_init(), parser::item::param_type => this.spread_type(), parser::item::rename => this.rename(), parser::item::enumerator => this.enumerator(), parser::item::value_arm => this.arm(true), else => this.error_here() }; } #! The items of a list separated by commas, which may end with one, through the #! token closing it. An item that fails is skipped to the comma or closing token #! after it, so one mistake leaves the rest of the list parsed. #! @param this The parser. #! @param kind What the items are. #! @param close The kind of token closing the list. #! @param detail What the note says where the closing token is missing. #! @returns The run of items. def parser::list(&mut this, kind: parser::item, close: tk, detail: strview): u32 { val angled := this.angled; this.angled = false; val mark := this.mark; while !this.check(close) && !this.check(tk::eof) { this.push(this.list_item(kind)); break if this.panic && !this.skip_item(close); break if !this.accept(tk::comma); } val items := this.make_run(mark); this.expect(close, detail); this.angled = angled; return items; } #! Skips what is left of an item that failed, stepping over what is nested in #! it, to the comma or closing token after it, then stops panicking. It gives up #! at a `;`, or at a closing token of something outside the list, which the #! enclosing parser recovers at instead. #! @param this The parser. #! @param close The kind of token closing the list. #! @returns Whether the list goes on. def parser::skip_item(&mut this, close: tk): bool { var depth: u32 = 0; while !this.check(tk::eof) { if depth == 0 && (this.check(tk::comma) || this.check(close)) { this.panic = false; return true; } val closes := this.at(tt::closes); return false if depth == 0 && (closes || this.check(tk::semicolon) || this.check(tk::istring_mid)); if this.at(tt::opens) { depth++; } if closes { depth--; } this.advance(); } return false; }