#! @file lifetimes.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the lifetime warnings: where a function keeps a reference past what #! it refers to, as the checker is sure of it. A reference, a view, or an #! anonymous function refers to the locals it names, which end where their #! scopes do, and to a value a statement makes, which ends with the statement #! unless a name is bound to it. Nothing keeps what they refer to alive, so one #! that outlives it dangles, which is the program's mistake, as in C++. #! #! The checker is sure of what it sees written: a value refers to a local where #! it is `&` of the local's own storage, a `val` bound to such a value, or a #! `var` no assignment changes, an anonymous function naming the local, a #! struct, union, or array literal holding one, or a call keeping one. A call #! keeps an argument where the function says so of its parameter, with #! `@kept`, as `function::new` and `thread::spawn` do, or where the parameter's #! type is a type parameter of the function's own that its result's type #! holds, as an adapter holding the function it is given does. It is sure the #! value outlives the local where it is returned from the function declaring #! the local, or written into a global, into what a parameter refers or points #! to, or into a local of a scope around the local's. A value a statement makes #! outlives it where it is returned, written anywhere, or held in a literal a #! name is bound to. What else a call does with what it is given, the checker #! does not follow, and says nothing of. #! #! What the warnings need is recorded as the checker checks a function's body, #! rather than by walking it again: the scope each local is declared in, and #! each value returned, written, or bound to a name, with the scopes around it. #! Once the body checks, each is looked at in the order it is written. Only what #! checking decides is recorded: not what is within an `if const` or `for const` #! only evaluating or an instance decides, nor a pass of `for const`, whose #! results are its own. #! #! Only functions that are no generic's are recorded, so each warning is said #! once, and `@allow` quiets those of a function. import std::containers; module sakura::analyzer; #! What a value refers to, as far as the checker is sure. enum lifetime_kind : u8 { none, #! Nothing it is sure of. local, #! A local, as `local` says. temporary, #! A value its statement makes. } #! What a value refers to, the local where it is one, and the node of the #! value saying so: the `&`, the slice, the anonymous function, or the `val` #! named, within any literal holding it. struct lifetime_ref { var kind: lifetime_kind; #! What it is. var local: u32; #! The node declaring the local, where it is one. var at: u32; #! The node saying so, which a warning is made at. } #! What the checker records of the bodies it checks for the warnings, and what #! looking at a body's record holds. A body's check may start another's, as #! evaluating a constant checks the function it calls, so each body checked #! has a session of its own on a stack, and what it records follows what the #! sessions around it recorded. struct lifetime_walk { var sessions: vector; #! The bodies being recorded, innermost last. var opened: vector; #! The scopes entered while recording, the first standing for none. var events: vector; #! What was returned, written, or bound while recording. var notes: keyed; #! The scope each local is declared in, by its table and node. var current: u32; #! The innermost scope entered, of the innermost session. var table: u32; #! The table the innermost session's body is checked in, outside which nothing is recorded. # Where looking at an event is: the scopes around it, outermost first, and # the function and anonymous functions among them. var scopes: vector; #! The scopes' nodes. var functions: vector; #! The functions' nodes. } #! A body being recorded: the function, and where its record begins. struct lifetime_session { var decl: u32; #! The function's declaration. var table: u32; #! The table its body is checked in. var scopes: u32; #! Where its scopes begin in `opened`. var events: u32; #! Where its events begin in `events`. var current: u32; #! The innermost scope of the session around it, as it was. var outer: u32; #! The table of the session around it. } #! A scope entered while recording: a function, block, loop, `if`, arm, or #! anonymous function. struct lifetime_scope { var node: u32; #! The node opening it. var parent: u32; #! The scope around it, in `opened`, or 0. var function: bool; #! Whether it is a function's or an anonymous function's. } #! What a value returned, written, or bound is, as an event of a record. enum lifetime_kind_of_event : u8 { returned, #! A `return`, or the value an anonymous function's body is. written, #! An assignment. bound, #! A local declared with a value. } #! A value returned, written, or bound, and the scope it was checked in. struct lifetime_event { var node: u32; #! The `return_stmt`, `lambda`, `assign`, or `variable` node. var kind: lifetime_kind_of_event; #! Which it is. var scope: u32; #! The innermost scope around it, in `opened`. } #! Where a local is declared: its scope, and the function or anonymous #! function that scope is in. struct lifetime_note { var scope: u32; #! The scope's node, or 0 where nothing was recorded of it. var owner: u32; #! The function's node. } #! Makes a walk, which records nothing until a body begins. #! @returns The walk. def lifetime_walk::new(): lifetime_walk { var made := lifetime_walk { sessions = vector::::new(), opened = vector::::new(), events = vector::::new(), notes = keyed::::new(), scopes = vector::::new(), functions = vector::::new() }; made.opened.append(lifetime_scope {}); return made; } #! Where the local was declared, as the session looked at recorded it. #! @param this The walk. #! @param local The node declaring the local. #! @returns The note, or nothing noted where none was recorded. def lifetime_walk::note_of(&this, local: u32): lifetime_note { val at := this.notes.get_or(&table_node { table = this.table, node = local }, 0); return lifetime_note {} if at == 0; var owner := at; while owner != 0 && !this.opened[owner].function { owner = this.opened[owner].parent; } return lifetime_note { scope = this.opened[at].node, owner = this.opened[owner].node }; } #! Whether what is checked now is recorded: within a body a session records, #! in its own table, where checking decides it. #! @param this The checker. #! @returns Whether it is. @inline def checker::recording(&this): bool { return this.lifetimes.sessions.length != 0 && this.undecided == 0 && this.at.table == this.lifetimes.table; } #! Begins recording a function's body, unless it is a generic's, which each #! instance would warn of again, or is `@allow`. #! @param this The checker. #! @param id The function's declaration, whose body is about to be checked. #! @returns Whether it is recorded, which `end_lifetimes` ends. pub def checker::begin_lifetimes(&mut this, id: u32): bool { return false if this.decls.has(id, df::generic) || this.decls.has(id, df::allows) || this.decls.has(id, df::accessor); val node: u32 = this.decls.nodes.p[id]; return false if node == 0 || this.kind_of(node) != nk::function || this.at.instance != 0; val walk := &mut this.lifetimes; if walk.sessions.length == 0 { walk.notes.clear(); } walk.sessions.append(lifetime_session { decl = id, table = this.at.table, scopes = walk.opened.length as u32, events = walk.events.length as u32, current = walk.current, outer = walk.table }); walk.table = this.at.table; walk.current = 0; _ = this.lifetime_open(node); return true; } #! Ends the record of the body last begun, warning of what it keeps past what #! it refers to where it checked. #! @param this The checker. #! @param checks Whether the body checked, without errors. pub def checker::end_lifetimes(&mut this, checks: bool): void { if checks { this.lifetime_warn(); } val walk := &mut this.lifetimes; val held: lifetime_session = walk.sessions.last; walk.opened.resize(held.scopes as u64); walk.events.resize(held.events as u64); walk.current = held.current; walk.table = held.outer; walk.sessions.truncate(); } #! Enters the scope a node opens, where what is checked is recorded. #! @param this The checker. #! @param node The function, block, loop, `if`, arm, or anonymous function. #! @returns The scope it was within, which `lifetime_close` goes back to. def checker::lifetime_open(&mut this, node: u32): u32 { val walk := &mut this.lifetimes; val outer := walk.current; return outer if !this.recording(); val kind := this.kind_of(node); walk.current = walk.opened.length as u32; walk.opened.append(lifetime_scope { node = node, parent = outer, function = kind == nk::function || kind == nk::lambda }); return outer; } #! Leaves the scope last entered. #! @param this The checker. #! @param outer The scope it was within, as `lifetime_open` gave it. def checker::lifetime_close(&mut this, outer: u32): void { this.lifetimes.current = outer; } #! Makes a node a local, noting the scope it is declared in where what is #! checked is recorded. #! @param this The checker. #! @param node The node declaring the local. pub def checker::mark_local(&mut this, node: u32): void { this.set_flag(node, rf::local); if this.recording() { this.lifetimes.notes.set(table_node { table = this.at.table, node = node }, this.lifetimes.current); } } #! Records a value returned, written, or bound, where what is checked is. #! @param this The checker. #! @param node The `return_stmt`, `lambda`, `assign`, or `variable` node. #! @param kind Which it is. def checker::lifetime_event(&mut this, node: u32, kind: lifetime_kind_of_event): void { return if !this.recording(); this.lifetimes.events.append(lifetime_event { node = node, kind = kind, scope = this.lifetimes.current }); } #! An event's place in the order its body is written: after what it holds, and #! before what follows it. struct lifetime_order { var end: u32; #! The last token of its node. var start: u32; #! Its node's token. var index: u32; #! The event, in `events`. } #! Warns of what the body last begun keeps past what it refers to, looking at #! each value it returned, wrote, or bound, in the order they are written, once #! each however many times checking reached it. #! @param this The checker. def checker::lifetime_warn(&mut this): void { val first: u32 = this.lifetimes.sessions.last.events; var order := vector::::new(); for i in first..this.lifetimes.events.length as u32 { val node := this.lifetimes.events[i].node; order.append(lifetime_order { end = this.syn().node_end(node), start = this.token_of(node), index = i }); } order.sort_by(def(a: &lifetime_order, b: &lifetime_order): bool { return a.end < b.end || a.end == b.end && (a.start > b.start || a.start == b.start && a.index < b.index); }); var last: u32 = 0; for i in 0..order.length { val held: lifetime_event = this.lifetimes.events[order[i].index]; continue if i != 0 && held.node == last; last = held.node; # The scopes around it, outermost first. val walk := &mut this.lifetimes; walk.scopes.clear(); walk.functions.clear(); var depth: u64 = 0; var at := held.scope; while at != 0 { depth++; at = walk.opened[at].parent; } walk.scopes.resize(depth); at = held.scope; while at != 0 { depth--; walk.scopes[depth] = walk.opened[at].node; at = walk.opened[at].parent; } for i in 0..walk.scopes.length { val scope := walk.scopes[i]; val kind := this.kind_of(scope); if kind == nk::function || kind == nk::lambda { walk.functions.append(scope); } } match held.kind { lifetime_kind_of_event::returned => { val value := this.kind_of(held.node) == nk::lambda ? this.record(held.node, lambda_slot::body) : this.left_of(held.node); this.lifetime_returned(walk, value); } lifetime_kind_of_event::written => { if this.token_kind(held.node) == tk::assign { this.lifetime_written(walk, this.left_of(held.node), this.right_of(held.node)); } } lifetime_kind_of_event::bound => { # A name bound to a value its statement makes refers to it as long as # the name lives, but a literal holding a reference to one does not. val value := this.record(held.node, variable_slot::value); if value != 0 && this.kind_of(value) != nk::reference { val got := this.lifetime_of(walk, value, 0); if got.kind == lifetime_kind::temporary { this.warn(got.at, ec::lifetime, "The value referred to is made in the statement, and ends with it, so the value holding a reference to it outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name."); } } } } } } #! Warns where a value returned refers to a local of the function returning it, #! or to a value the `return` makes. #! @param this The checker. #! @param walk The walk. #! @param value The value returned, or 0. def checker::lifetime_returned(&mut this, walk: &mut lifetime_walk, value: u32): void { return if value == 0 || walk.functions.length == 0; val held := this.lifetime_of(walk, value, 0); if held.kind == lifetime_kind::temporary { this.warn(held.at, ec::lifetime, "The value returned refers to a value made in the statement, which ends with it."); return; } return if held.kind != lifetime_kind::local || walk.note_of(held.local).owner != walk.functions.last; var text := string::from("The value returned refers to `", nothing {}); text.append(this.names.text(this.local_name(held.local))); text.append("`, which ends as the function returns."); this.warn_text(held.at, ec::lifetime, &text, held.local); } #! Warns where a value written to a place refers to a local the place outlives, #! or to a value the statement makes. #! @param this The checker. #! @param walk The walk. #! @param target The place written. #! @param value The value written. def checker::lifetime_written(&mut this, walk: &mut lifetime_walk, target: u32, value: u32): void { return if this.kind_of(target) == nk::name && this.names.text(this.name_of(target)) == "_"; val held := this.lifetime_of(walk, value, 0); if held.kind == lifetime_kind::temporary { this.warn(held.at, ec::lifetime, "The value referred to is made in the statement, and ends with it, so the reference written here outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name."); return; } return if held.kind != lifetime_kind::local; # The local or global whose storage the place is within, and whether it is # reached through a reference or pointer. var at := target; var through := false; var steps := 0; while steps < 64 { steps++; val kind := this.kind_of(at); if kind == nk::member || kind == nk::index || kind == nk::slice { val object := this.left_of(at); val held_type := this.types.kind_of(this.unalias(this.type_at(object))); if kind == nk::member { through = through || held_type == ty::reference || held_type == ty::pointer; } else { through = through || held_type != ty::fixed; } at = object; continue; } if kind == nk::unary && this.token_kind(at) == tk::star { through = true; at = this.left_of(at); continue; } break; } return if this.kind_of(at) != nk::name; val ref := this.ref_at(at); return if ref == 0 || (ref & ref_type) != 0; var outlives := false; var into := string::new(nothing {}); if (ref & ref_local) == 0 { # A global outlives every local. outlives = this.decls.kinds.p[ref & ref_mask] == dk::variable; into.append("a global"); } else { val root := ref & ref_mask; if through { # What a parameter refers or points to is the caller's, which outlives # every local of the function. val root_type := this.types.kind_of(this.unalias(this.type_at(root))); outlives = this.kind_of(root) == nk::param && (root_type == ty::reference || root_type == ty::pointer); into.append("what `"); into.append(this.names.text(this.local_name(root))); into.append("` refers to"); } else { # A local of a scope around the local's outlives it. val outer := this.lifetime_scope(walk, root); val inner := this.lifetime_scope(walk, held.local); outlives = outer >= 0 && inner >= 0 && outer < inner; into.append("`"); into.append(this.names.text(this.local_name(root))); into.append("`"); } } return if !outlives; var text := string::from("`", nothing {}); text.append(this.names.text(this.local_name(held.local))); text.append("` ends where its scope does, so the reference written to "); text.append(into.span); text.append(" outlives it."); this.warn_text(held.at, ec::lifetime, &text, held.local); } #! Where among the scopes the walk is within a local is declared. #! @param this The checker. #! @param walk The walk. #! @param local The node declaring the local. #! @returns The index of its scope, or -1 where it is in none of them. def checker::lifetime_scope(&this, walk: &lifetime_walk, local: u32): i64 { val scope := walk.note_of(local).scope; return -1 if scope == 0; for i in 0..walk.scopes.length { return i as i64 if walk.scopes[i] == scope; } return -1; } #! What a value refers to, as far as the checker is sure. #! @param this The checker. #! @param walk The walk. #! @param node The value. #! @param depth How many `val`s it was followed through. #! @returns What it refers to. def checker::lifetime_of(&mut this, walk: &lifetime_walk, node: u32, depth: u32): lifetime_ref { val none := lifetime_ref { kind = lifetime_kind::none }; return none if node == 0 || depth > 8; match this.kind_of(node) { nk::reference => { val inner := this.left_of(node); if this.is_place(inner) { val root := this.lifetime_root(inner); return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none; } # `&` of a reference refers to what it does, which is not known. val given := this.types.kind_of(this.unalias(this.type_at(inner))); return given == ty::reference ? none : lifetime_ref { kind = lifetime_kind::temporary, at = node }; } nk::slice => { val object := this.left_of(node); val held := this.types.kind_of(this.unalias(this.type_at(object))); return none if held != ty::fixed || !this.is_place(object); val root := this.lifetime_root(object); return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none; } nk::name => { # A `val` refers to what its value does, as does a `var` no assignment # changes, and one bound to a value its statement makes refers to it as # long as it lives. val ref := this.ref_at(node); return none if (ref & ref_local) == 0; val local := ref & ref_mask; return none if this.kind_of(local) != nk::variable; return none if this.node_has(local, nf::mutable) && !this.lifetime_unwritten(walk, local); val value := this.record(local, variable_slot::value); return none if value == 0; val held := this.lifetime_of(walk, value, depth + 1); if held.kind == lifetime_kind::temporary { return this.kind_of(value) == nk::reference ? lifetime_ref { kind = lifetime_kind::local, local = local, at = node } : none; } return held.kind == lifetime_kind::none ? none : lifetime_ref { kind = held.kind, local = held.local, at = node }; } nk::lambda => { # An anonymous function refers to the locals around it that it names. var held := this.lifetime_captured(walk, node); held.at = node; return held; } nk::call => { # A call refers to what each argument it keeps does. val args := this.right_of(node); for i in 0..this.run_length(args) { continue if !this.call_keeps(node, i as u32); val held := this.lifetime_of(walk, this.run_at(args, i as u32), depth + 1); return held if held.kind != lifetime_kind::none; } return none; } nk::fallback => { # `x else y` refers to what `x` does where `x` holds a value. return this.lifetime_of(walk, this.left_of(node), depth); } nk::construct => { for &each in this.run_view(this.right_of(node)) { val held := this.lifetime_of(walk, this.left_of(each), depth); return held if held.kind != lifetime_kind::none; } return none; } nk::array => { for &each in this.run_view(this.left_of(node)) { val held := this.lifetime_of(walk, each, depth); return held if held.kind != lifetime_kind::none; } return none; } else => return none; } } #! Whether no assignment of the body being looked at writes a local whole. #! @param this The checker. #! @param walk The walk. #! @param local The node declaring the local. #! @returns Whether none does. def checker::lifetime_unwritten(&this, walk: &lifetime_walk, local: u32): bool { val first: u32 = walk.sessions.last.events; for i in first..walk.events.length as u32 { val held: lifetime_event = walk.events[i]; continue if held.kind != lifetime_kind_of_event::written; val target := this.left_of(held.node); continue if this.kind_of(target) != nk::name; val ref := this.ref_at(target); return false if (ref & ref_local) != 0 && (ref & ref_mask) == local; } return true; } #! Whether what a call gives back keeps one of its arguments: the parameter it #! is given for is `@kept`, or its type is a type parameter of the function's #! own that the result's type holds. #! @param this The checker. #! @param call The `call` node. #! @param arg The argument's index among those written. #! @returns Whether it keeps it. def checker::call_keeps(&mut this, call: u32, arg: u32): bool { val callee := this.left_of(call); val ref := this.ref_at(callee); return false if ref == 0 || (ref & (ref_local | ref_type)) != 0; val decl := ref & ref_mask; return false if this.decls.kinds.p[decl] != dk::function || this.decls.nodes.p[decl] == 0; # A method called on a value takes it as `this`, the first parameter. val object := this.kind_of(callee) == nk::member && this.decls.has(decl, df::method); val index := arg + (object ? 1u : 0u); val saved := this.at; this.use_table(this.units[this.decls.files.p[decl]].table); val node: u32 = this.decls.nodes.p[decl]; val params := this.record(node, function_slot::params); var keeps := false; if this.kind_of(node) == nk::function && index < this.run_length(params) { val param := this.run_at(params, index); for &attr in this.run_view(this.record(param, parameter_slot::attributes)) { continue if this.kind_of(attr) != nk::attribute; val named := this.left_of(attr); keeps = keeps || this.segment_name(named, this.segment_count(named) - 1) == word::kept; } # A type parameter of its own the result's type holds. val written := this.left_of(param); if !keeps && written != 0 && this.kind_of(written) == nk::type_name && this.segment_count(written) == 1 { val name := this.segment_name(written, 0); var own := false; for &each in this.run_view(this.record(node, function_slot::type_params)) { own = own || this.name_of(each) == name; } keeps = own && this.type_names(this.record(node, function_slot::result), name); } } this.at = saved; return keeps; } #! Whether a type written names a type, as a type parameter, anywhere within it. #! @param this The checker. #! @param node The type written, or 0. #! @param name The name's ID. #! @returns Whether it does. def checker::type_names(&mut this, node: u32, name: u32): bool { return false if node == 0; var todo := vector::::new(); todo.append(node); var seen := 0; while todo.length != 0 && seen < 4096 { seen++; val at: u32 = todo.last; todo.truncate(); return true if this.kind_of(at) == nk::type_name && this.segment_count(at) == 1 && this.segment_name(at, 0) == name; this.syn().children(at, &mut todo); } return false; } #! The local an anonymous function names that a function around it declares, #! the one declared first where it names several. #! @param this The checker. #! @param walk The walk. #! @param node The `lambda` node. #! @returns The local, or nothing it is sure of. def checker::lifetime_captured(&mut this, walk: &lifetime_walk, node: u32): lifetime_ref { var todo := vector::::new(); this.syn().children(node, &mut todo); var seen := 0; var first: u32 = 0; while todo.length != 0 && seen < 4096 { seen++; val at: u32 = todo.last; todo.truncate(); if this.kind_of(at) == nk::name { val ref := this.ref_at(at); if (ref & ref_local) != 0 { val local := ref & ref_mask; val owner := walk.note_of(local).owner; if owner != 0 && walk.functions.span.contains(&owner) && (first == 0 || this.node_offset_of(local) < this.node_offset_of(first)) { first = local; } } } this.syn().children(at, &mut todo); } return first != 0 ? lifetime_ref { kind = lifetime_kind::local, local = first } : lifetime_ref { kind = lifetime_kind::none }; } #! The local whose own storage a place is within, past fields and the elements #! of fixed arrays it holds as values. A local that is a reference names what #! it refers to, so a place within it is within no local the checker knows. #! @param this The checker. #! @param node The place. #! @returns The node declaring the local, or 0 where the place is not within one. def checker::lifetime_root(&mut this, node: u32): u32 { var at := node; var steps := 0; while steps < 64 { steps++; val kind := this.kind_of(at); if kind == nk::member || kind == nk::index { val object := this.left_of(at); val held := this.types.kind_of(this.unalias(this.type_at(object))); return 0 if kind == nk::member && (held == ty::reference || held == ty::pointer); return 0 if kind == nk::index && held != ty::fixed; if kind == nk::member { val ref := this.ref_at(at); return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.decls.kinds.p[ref] != dk::field; } at = object; continue; } break; } return 0 if this.kind_of(at) != nk::name; val ref := this.ref_at(at); return 0 if (ref & ref_local) == 0; val held := this.types.kind_of(this.unalias(this.type_at(ref & ref_mask))); return held == ty::reference ? 0 : ref & ref_mask; } #! Where in the file a node's token begins. #! @param this The checker. #! @param node The node. #! @returns The token's offset. def checker::node_offset_of(&this, node: u32): u32 { val syntax := &this.syn(); return syntax.token_offsets[syntax.node_tokens[node]]; } #! The name a local is declared with. #! @param this The checker. #! @param local The node declaring it. #! @returns The name's ID. def checker::local_name(&this, local: u32): u32 { return this.name_of(local); }