module scheme import reader import arena // Code retains the private source document for diagnostics. The compiler uses // the decoding caches below as scratch and discards them after emitting code. // Execution accesses the reader only when reporting a source location. @[heap] struct Code { doc reader.Document allocation_owner voidptr = v_arena_current() source_path string namespace &Namespace = unsafe { nil } syntax_seed u64 mut: // Intrusive compiler-only lists avoid another tracking allocation. Borrowed // outer scopes belong to their own Code and are never registered here. compile_scopes &Scope = unsafe { nil } compile_tables &NameTable = unsafe { nil } // Anonymous record UIDs and datum graphs keep detached, lazy sidecars. record_seed u64 procedural &ProceduralSyntaxCode = unsafe { nil } record_uids &RecordSourceTokens = unsafe { nil } names map[reader.NodeId]string literals map[reader.NodeId]Value graphs &SyntaxGraphState = unsafe { nil } lists map[reader.NodeId][]reader.NodeId // Enabled only by bounded compilation entry points, which always free it // before returning. Inline optional storage avoids a heap-allocated context; // scalar forms and empty lists never create the arena's control block. list_scratch ?arena.Arena list_budget &CompileListBudget = unsafe { nil } keyword_variables []string syntax_base &SyntaxBindings = unsafe { nil } known_globals &map[string]int = unsafe { nil } // Borrowed only during compilation; cleared with known_globals before escape. compiler_vm voidptr = unsafe { nil } generated &SyntaxArena = unsafe { nil } sources &SourceDocuments = unsafe { nil } syntax_exports []SyntaxInstallation expansions int expansion_limit int = 10000 has_syntax bool has_static bool // The built-in protocol source is compiled before any VM exists. // Its ordinary root reads can resolve directly in the installing VM. builtin_root bool // Keep the flag beside the existing booleans, using their alignment padding. list_scratch_enabled bool compile_depth int } fn (mut code Code) release_compile_borrows() { if !isnil(code.procedural) { code.procedural.globals_cache = unsafe { nil } code.procedural.private_cache = unsafe { nil } } code.syntax_base = unsafe { nil } code.known_globals = unsafe { nil } code.compiler_vm = unsafe { nil } } fn (mut code Code) nodes(id reader.NodeId) ![]reader.NodeId { if !isnil(code.graphs) { code.require_finite_spine(id)! } if nodes := code.lists[id] { return nodes } if !isnil(code.list_budget) { return code.budgeted_list_nodes(id) } mut result := []reader.NodeId{} mut current := id for { n := code.node(current)! if n.kind == .empty_list { break } if n.kind != .pair { return failure('expected a proper syntax list') } if result.len == result.cap && code.list_scratch_enabled { code.reserve_list_nodes(mut result) } result << n.car current = n.cdr } code.lists[id] = result return result } fn (mut code Code) reserve_list_nodes(mut nodes []reader.NodeId) { if code.list_scratch == none { code.list_scratch = arena.new(chunk_size: 1024) } // No callbacks, decoding or fallible operations may run in this scope: // every V allocation on this thread would otherwise use the same arena. if storage := code.list_scratch { storage.push() defer { storage.pop() } nodes.ensure_cap(nodes.len + 1) } } fn (mut code Code) release_list_scratch(previous ?arena.Arena, was_enabled bool) { if code.lists.len > 0 { // Cleanup also runs after allocation denial. Reuse the map header and // clear borrowed buffer addresses before releasing their arena. for id, _ in code.lists { code.lists[id] = []reader.NodeId{} } code.lists.clear() } if mut storage := code.list_scratch { storage.free() } code.list_scratch = previous code.list_scratch_enabled = was_enabled } fn (mut code Code) datum(id reader.NodeId) !Value { if !isnil(code.graphs) { return materialize_datum_graph(code, id, mut code.literals, true) } return code.tree_datum(id) } fn (mut code Code) tree_datum(id reader.NodeId) !Value { if value := code.literals[id] { return value } n := code.node(id)! value := match n.kind { .empty_list { nil_value() } .boolean, .number, .character, .string_literal, .bytevector, .keyword { code.atom_datum(id)! } .reference { return failure('unresolved reader reference') } .symbol { text_value(.symbol, code.datum_name(id)!) } .pair { code.pair_datum(id)! } .vector { mut items := []Value{len: n.count} for index in 0 .. n.count { items[index] = code.datum(code.vector_at(id, index)!)! } // This compiler-created array has no external owner or borrowed // operand-stack alias; the public vector constructor's copy is unnecessary. payload_value(.vector, &Vector{ items: items }) } } literal := literal_value(value) code.literals[id] = literal return literal } // Reader nesting is bounded, but flat lists can be arbitrarily long. Iterate // the cdr chain; recursion only follows nested cars, never flat list length. fn (mut code Code) pair_datum(id reader.NodeId) !Value { mut ids := []reader.NodeId{} mut cars := []Value{} mut current := id mut tail := nil_value() for { if cached := code.literals[current] { tail = cached break } n := code.node(current)! if n.kind != .pair { tail = code.datum(current)! break } ids << current cars << code.datum(n.car)! current = n.cdr } for i := ids.len - 1; i >= 0; i-- { tail = literal_value(cons(cars[i], tail)) code.literals[ids[i]] = tail } return tail } fn (mut code Code) name(id reader.NodeId) !string { if cached := code.names[id] { return cached } node := code.node(id)! if node.kind != .symbol { return failure('expected an identifier') } name := if id < -1 { code.generated.symbols[code.generated.nodes[-int(id) - 2].car].name } else if node.abbreviation == .alt_statement { implicit_statement_name } else { external_identifier_key(code.datum_name(id)!) } code.names[id] = name return name } fn (mut code Code) variable(id reader.NodeId) !string { return code.name(id) } fn (mut code Code) formals(id reader.NodeId) !([]string, string) { if !isnil(code.graphs) { code.require_finite_spine(id)! } mut params := []string{} mut current := id mut rest := '' mut seen := map[string]bool{} for { n := code.node(current)! if n.kind == .empty_list { break } if n.kind == .symbol { rest = code.variable(current)! if code.binding_key(rest) in seen { return failure('duplicate parameter ${rest}') } break } if n.kind != .pair { return failure('lambda parameters must be identifiers') } name := code.variable(n.car)! if code.binding_key(name) in seen { return failure('duplicate parameter ${name}') } seen[code.binding_key(name)] = true params << name current = n.cdr } return params, rest }