module scheme import reader // Fixed-width instructions; operands index constants, slots, or jump targets. // Source NodeIds are cold metadata used only when reporting an error. enum Op as u8 { constant local global define_local define_global assign_local closure drop duplicate swap jump jump_false and_jump or_jump case_match qq_cons qq_prefix qq_splice qq_vector call tail_call call_values_tail map_init map_step map_collect promise force_enter force_finish make_promise wind_init wind_enter wind_leave wind_finish wind_step wind_resume ret fail define_syntax file_init file_enter file_leave file_argument file_return eval_enter case_lambda unpack_values source_form load_enter parameter_create parameter_created parameter_set parameter_assigned parameter_init parameter_convert parameter_converted parameter_install parameter_finish indexed_init indexed_step indexed_collect search_init search_step search_collect file_parameterize record_define enumeration_define enumeration_select global_reference assign_global_reference library_define library_import library_commit library_complete library_mark_enter library_mark_leave assign_resolved_global library_init_guard process_exit_finish sort_init sort_step sort_collect list_utility_init list_utility_step list_utility_collect hashtable_init hashtable_step hashtable_collect record_operations record_make_type record_make_cd record_prepare record_prepared record_parent_prepare record_parent_apply record_factory record_default_cd record_name_define record_auto_uid exit_mark early_return return_call loop_continue scope_function scope_call scope_tail implicit_call syntax_match syntax_expand syntax_scope_call syntax_scope_tail syntax_accept syntax_return_call port_io_enter port_io_step port_io_collect port_error_close_step port_error_close_collect assignment_setter assignment_setter_result assignment_finish star_bound_skip star_closure goops_make_class goops_define_generic goops_define_accessor goops_define_method goops_make_method goops_bound_enter goops_bound_finish goops_retry_enter goops_retry_finish goops_missing_enter goops_virtual_read_enter goops_virtual_read_finish goops_missing_read_finish goops_factory_apply goops_applicability_apply goops_effective_apply goops_equal_init goops_equal_step goops_equal_resume goops_migration_start goops_migration_retry goops_class_redefinition goops_top } struct Instruction { op Op a i32 b i32 origin reader.NodeId } @[heap] struct Function { code &Code params int rest bool mut: // Names live in compile-time Scope maps. Execution only needs the size, // so compiled functions retain neither a second name array nor its strings. syntax_identity u32 slot_count int instructions []Instruction constants []Value names []string global_slots []int children []&Function failures []EvalError capture_depth int integer_tail &IntegerTailPlan = unsafe { nil } closed &Procedure = unsafe { nil } star &StarFormals = unsafe { nil } // Only method bodies bind next-method. Its slot stays uninitialized when // the underlying procedure is called directly outside generic dispatch. goops_next_slot int = -1 goops_needs_next bool } @[heap] struct Scope { parent &Scope = unsafe { nil } mut: scratch_next &Scope = unsafe { nil } function &Function names map[string]int syntax &SyntaxBindings = unsafe { nil } return_boundary ReturnBoundary continue_used bool exit_slot i32 = -1 } enum ReturnBoundary as u8 { none function deferred loop } struct ScopeRef { value &Scope } @[heap] struct NameTable { mut: scratch_next &NameTable = unsafe { nil } indices map[string]int } struct Builder { mut: code &Code function &Function scope &Scope = unsafe { nil } table &NameTable = unsafe { nil } definition_context bool // A transparent helper's final result can be the source procedure's result. return_tail bool body_keywords &SyntaxBindings = unsafe { nil } } fn (mut b Builder) emit(op Op, a int, operand int, origin reader.NodeId) int { if op in [.local, .assign_local, .early_return, .loop_continue] && a > b.function.capture_depth { b.function.capture_depth = a } index := b.function.instructions.len // Flatten provenance while the expansion arena is alive. Execution needs // only source IDs (including virtual document ranges), so no generated-node // location table survives. b.function.instructions << Instruction{op, i32(a), i32(operand), b.code.source_origin(origin)} return index } fn (mut b Builder) patch(index int, target int) { container_store(mut b.function.instructions, index, Instruction{ ...b.function.instructions[index] a: i32(target) }) } fn (mut b Builder) constant(value Value, origin reader.NodeId) { index := b.function.constants.len b.function.constants << value b.emit(.constant, index, 0, origin) } fn (mut b Builder) name_table() &NameTable { if isnil(b.table) { mut code := b.code b.table = &NameTable{ scratch_next: code.compile_tables } code.compile_tables = b.table } return b.table } fn (mut b Builder) name_index(name string) int { // Compilation only. Runtime instructions never reconstruct identifiers. mut table := b.name_table() if index := table.indices[name] { return index } index := b.function.names.len b.function.names << name b.function.global_slots << -1 table.indices[name] = index return index } fn (mut scope Scope) declare(name string) int { if slot := scope.names[name] { return slot } key := scope.function.code.binding_key(name) if key != name { if slot := scope.names[key] { scope.names[name] = slot return slot } } slot := scope.function.slot_count scope.names[name] = slot if key != name { scope.names[key] = slot } scope.function.slot_count++ return slot } fn (scope &Scope) resolve(name string) ?(int, int) { mut cursor := ScopeRef{ value: scope } mut depth := 0 for !isnil(cursor.value) { if slot := cursor.value.names[name] { return depth, slot } parent := cursor.value.parent // Compile-time binding regions can share one runtime activation (for // example a body's definitions versus its formal parameters). if !isnil(parent) && voidptr(parent.function) != voidptr(cursor.value.function) { depth++ } cursor = ScopeRef{ value: cursor.value.parent } } return none } @[inline] fn (mut b Builder) load(name string, origin reader.NodeId) ! { binding := b.resolve_binding(name) b.load_resolved(name, binding, origin)! } @[inline] fn (mut b Builder) load_resolved(name string, binding SyntaxBinding, origin reader.NodeId) ! { if !isnil(binding.pattern_variable) { return failure('pattern variable ${name} may only be referenced within syntax') } match binding.kind { .lexical { if !isnil(binding.function) && binding.function.goops_next_slot >= 0 && binding.slot == binding.function.goops_next_slot { mut function := binding.function function.goops_needs_next = true } b.emit(.local, b.syntax_binding_depth(binding)!, binding.slot, origin) } .global { if binding.introduced == '' && report_slot(binding.namespace, binding.global_slot) { if isnil(b.code.compiler_vm) { return failure('report binding requires its compilation VM') } b.constant(unsafe { (&VM(b.code.compiler_vm)).pristine_standard(-binding.global_slot - 2) }, origin) return } if binding.introduced != '' { b.global_reference(binding, origin) } else if voidptr(binding.namespace) != voidptr(b.code.namespace) { b.global_reference(SyntaxBinding{ ...binding, introduced: name, introduced_namespace: b.code.namespace }, origin) } else { if binding.global_slot >= 0 { index := b.name_index(binding.name) b.function.global_slots[index] = binding.global_slot b.emit(.global, index, 0, origin) } else if b.code.builtin_root { b.emit(.global, b.name_index(binding.name), 0, origin) } else { b.global_reference(SyntaxBinding{ ...binding, introduced: binding.name, introduced_namespace: binding.namespace }, origin) } } } .keyword { return failure('syntax keyword ${binding.name} cannot be used as a value') } .transformer { return failure('macro keyword ${binding.name} cannot be used as a value') } } } fn (mut b Builder) keyword_name(id reader.NodeId) !string { binding := b.resolve_binding(b.code.name(id)!) return if binding.kind == .keyword { binding.name } else { '' } } fn (mut b Builder) declare_global_keyword(name string) { if isnil(b.scope) { b.global_definition_name(name) } } fn (mut b Builder) store(name string, define bool, origin reader.NodeId) ! { if define { if !isnil(b.scope) { b.emit(.define_local, 0, b.declare_definition(name), origin) } else { target := b.global_definition_name(name) alias_operand := if target != name { b.record_global_alias_operand(name)! } else { 0 } b.emit(.define_global, b.name_index(target), alias_operand, origin) } return } binding := b.resolve_binding(name) if !isnil(binding.pattern_variable) { return failure('cannot assign pattern variable ${name}') } match binding.kind { .lexical { b.emit(.assign_local, b.syntax_binding_depth(binding)!, binding.slot, origin) } .global { if !isnil(b.code.compiler_vm) { unsafe { (&VM(b.code.compiler_vm)).check_imported_assignment(b.code.namespace, name)! } } if binding.introduced != '' { b.assign_global_reference(binding, origin) } else if voidptr(binding.namespace) != voidptr(b.code.namespace) { b.assign_global_reference(SyntaxBinding{ ...binding, introduced: name, introduced_namespace: b.code.namespace }, origin) } else { if !isnil(b.code.compiler_vm) { unsafe { (&VM(b.code.compiler_vm)).check_assignment_in(binding.namespace, binding.name)! } } index := b.name_index(binding.name) if binding.global_slot >= 0 { b.function.global_slots[index] = binding.global_slot b.emit(.assign_resolved_global, index, 0, origin) } else { b.assign_global_reference(SyntaxBinding{ ...binding, introduced: binding.name, introduced_namespace: binding.namespace }, origin) } } } .keyword { return failure('cannot assign syntax keyword ${binding.name}') } .transformer { return failure('cannot assign macro keyword ${binding.name}') } } } fn compile_program(code &Code, forms []reader.NodeId) &Function { function := &Function{ code: code } mut b := Builder{ code: code, function: function, definition_context: true } if !b.code.has_syntax { syntax_table := b.current_syntax_table() if !isnil(syntax_table) && syntax_table.entries.len > 0 { b.code.syntax_base = syntax_table b.code.has_syntax = true } } scratch := b.code.enter_list_scratch() defer { b.code.leave_list_scratch(scratch) } b.sequence(forms, true) b.emit(.ret, 0, 0, if forms.len > 0 { forms.last() } else { reader.no_node }) return b.finish_program() } fn (mut b Builder) finish_program() &Function { finalize_captures(b.function) // Syntax-decoding caches are compilation scratch. Constants and instruction // operands retain everything execution needs; source stays for diagnostics. // Replacing a map does not release its old containers in GC-free hosts. // These NodeId-keyed maps own their containers, not the retained payloads. unsafe { b.code.names.free() b.code.literals.free() b.code.lists.free() } b.code.names = map[reader.NodeId]string{} b.code.literals = map[reader.NodeId]Value{} b.code.lists = map[reader.NodeId][]reader.NodeId{} b.code.keyword_variables = []string{} b.code.release_compile_borrows() b.code.freeze_syntax_locations() b.code.release_compile_names() b.scope = unsafe { nil } b.table = unsafe { nil } return b.function } fn (mut b Builder) fault(message string, origin reader.NodeId) { b.fault_error(failure(message), origin) } fn (mut b Builder) fault_error(cause IError, origin reader.NodeId) { if is_control_transfer(cause) { mut state := b.code.procedural_syntax() state.aborted = &CompilerControlTransfer{ error: cause } return } index := b.function.failures.len // Store concrete diagnostics by value. The compiler's interface-array // smartcast append emits a raw pointer instead of a boxed IError. if cause is EvalError { b.function.failures << EvalError{ message: cause.message, source_path: cause.source_path, offset: cause.offset, line: cause.line, column: cause.column } } else { b.function.failures << EvalError{ message: cause.msg() } } b.emit(.fail, index, 0, origin) } // Invalid subexpressions become executable failures: an unselected branch stays // unexecuted, and earlier top-level definitions still take effect before errors. fn (mut b Builder) expression(id reader.NodeId, tail bool) { if !isnil(b.code.procedural) && !isnil(b.code.procedural.aborted) { return } // Source nesting is reader-bounded. Macro output needs its own bound, even // when a transformation grows beneath a conditional instead of at its head. tracked := b.code.has_syntax || b.code.has_static if tracked { if b.code.compile_depth >= 512 { b.fault('expanded expression nesting limit exceeded', id) return } b.code.compile_depth++ } defer { if tracked { b.code.compile_depth-- } } start := b.function.instructions.len b.expression_inner(id, tail) or { b.function.instructions.trim(start) b.fault_error(err, id) } } fn (mut b Builder) sequence(nodes []reader.NodeId, tail bool) { if nodes.len == 0 { b.constant(unspecified(), reader.no_node) return } for i, id in nodes { b.expression(id, tail && i == nodes.len - 1) if i != nodes.len - 1 { b.emit(.drop, 0, 0, id) } } } fn (mut b Builder) child(params []string, rest string, body []reader.NodeId, tail bool) &Function { return b.build_child(params, rest, body, false, b.return_tail && tail, false) } fn (mut b Builder) source_child(params []string, rest string, body []reader.NodeId) &Function { return b.build_child(params, rest, body, true, true, false) } fn (mut b Builder) goops_method_child(params []string, rest string, body []reader.NodeId) &Function { return b.build_child(params, rest, body, true, true, true) } fn (mut b Builder) build_child(params []string, rest string, body []reader.NodeId, source bool, return_tail bool, method bool) &Function { mut function := &Function{ code: b.code, params: params.len, rest: rest != '' } mut scope := new_compile_scope(Scope{ parent: b.scope function: function return_boundary: if source { .function } else { .none } }) for name in params { scope.declare(name) } if rest != '' { scope.declare(rest) } if method && 'next-method' !in scope.names { function.goops_next_slot = scope.declare('next-method') } mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: return_tail } inner.body(body) inner.emit(.ret, 0, 0, if body.len > 0 { body.last() } else { reader.no_node }) inner.prepend_exit_mark(scope) return function } fn (mut b Builder) body(nodes []reader.NodeId) { b.body_sequence(nodes, true) } // A delayed expression has no implicit definition region. Actual procedure // and binding bodies use child(), which discovers their internal definitions. fn (mut b Builder) expression_child(expression reader.NodeId) &Function { function := &Function{ code: b.code } scope := new_compile_scope(Scope{ parent: b.scope, function: function, return_boundary: .deferred }) mut inner := Builder{ code: b.code, function: function, scope: scope } inner.expression(expression, true) inner.emit(.ret, 0, 0, expression) return function } fn (mut b Builder) body_sequence(nodes []reader.NodeId, tail bool) { previous := b.scope previous_context := b.definition_context b.scope = new_compile_scope(Scope{ parent: previous, function: b.function }) defer { b.scope = previous b.definition_context = previous_context } prepared := b.prepare_body(nodes) or { b.fault_error(err, if nodes.len > 0 { nodes[0] } else { reader.no_node }) return } // Preparation returns a private flat ID list, not a Code-owned list cache. defer { unsafe { prepared.free() } } b.definition_context = true b.sequence(prepared, tail) } fn (mut b Builder) make_closure(function &Function, origin reader.NodeId) { index := b.function.children.len b.function.children << function b.emit(if isnil(function.star) { Op.closure } else { Op.star_closure }, index, 0, origin) } fn (mut b Builder) scope_application(function &Function, initializers []reader.NodeId, tail bool, origin reader.NodeId) { index := b.function.children.len b.function.children << function b.emit(.scope_function, index, 0, origin) for initializer in initializers { b.expression(initializer, false) } b.emit(if tail { Op.scope_tail } else { Op.scope_call }, initializers.len, 0, origin) } fn (mut b Builder) application(count int, tail bool, origin reader.NodeId) { b.emit(if tail { Op.tail_call } else { Op.call }, count, 0, origin) } fn (mut b Builder) expression_inner(source reader.NodeId, tail bool) ! { graph_expression := if !isnil(b.code.graphs) { b.code.canonical_syntax_id(source)! } else { reader.no_node } if !isnil(b.code.graphs) { b.code.enter_graph_expression(graph_expression)! } defer { if graph_expression != reader.no_node { b.code.leave_graph_expression(graph_expression) } } definitions_allowed := b.definition_context b.definition_context = false defer { b.definition_context = definitions_allowed } id := b.expand_syntax_head(source)! n := b.code.node(id)! match n.kind { .symbol { name := b.code.name(id)! binding := b.resolve_binding(name) if binding.kind == .keyword && binding.name in ['return', 'break', 'continue'] { if binding.name == 'return' { b.return_form([], tail, id)! } else if binding.name == 'break' { b.break_form([], id)! } else { b.continue_form([], id)! } return } b.load_resolved(name, binding, id)! return } .number, .boolean, .string_literal, .character, .bytevector, .keyword { b.constant(b.code.datum(id)!, id) return } .empty_list { return failure('empty list is not an expression') } .reference { return failure('unresolved reader reference in executable syntax') } .vector { b.constant(b.code.datum(id)!, id) return } .pair {} } nodes := b.code.nodes(id)! head := b.code.node(nodes[0])! if head.kind == .symbol { binding := b.resolve_binding(b.code.name(nodes[0])!) if binding.kind == .transformer && !isnil(binding.transformer.enumeration) { b.enumeration_expression(binding, nodes, id)! return } } name := if head.kind == .symbol { b.keyword_name(nodes[0])! } else { '' } match name { implicit_statement_name, 'vile:statement' { b.implicit_statement(nodes, tail, id)! } 'return' { b.return_form(nodes[1..], tail, id)! } 'break' { b.break_form(nodes[1..], id)! } 'continue' { b.continue_form(nodes[1..], id)! } 'record-type-descriptor', 'record-constructor-descriptor' { b.record_descriptor_expression(nodes, id, name == 'record-constructor-descriptor')! } 'eol-style', 'error-handling-mode', 'buffer-mode' { b.transcoder_choice_syntax(name, nodes, id)! } 'file-options' { b.file_options_syntax(nodes, id)! } 'endianness' { b.bytevector_endianness(nodes, id)! } 'quote' { check_arity(name, nodes.len - 1, 1, 1)! b.constant(b.code.datum(nodes[1])!, id) } 'if' { check_arity(name, nodes.len - 1, 2, 3)! b.expression(nodes[1], false) branch := b.emit(.jump_false, 0, 0, id) b.expression(nodes[2], tail) finish := b.emit(.jump, 0, 0, id) b.patch(branch, b.function.instructions.len) if nodes.len == 4 { b.expression(nodes[3], tail) } else { b.constant(unspecified(), id) } b.patch(finish, b.function.instructions.len) } 'include', 'include-ci', 'cond-expand' { forms := b.static_forms(name, nodes, id)! b.definition_context = definitions_allowed b.sequence(forms, tail) } 'begin' { b.definition_context = definitions_allowed b.sequence(nodes[1..], tail) } 'lambda' { check_arity(name, nodes.len - 1, 2, -1)! params, rest := b.code.formals(nodes[1])! b.make_closure(b.source_child(params, rest, nodes[2..]), id) } 'lambda*' { check_arity(name, nodes.len - 1, 2, -1)! formals := b.code.star_formals(nodes[1], false)! b.make_closure(b.star_child(formals, nodes[2..], false), id) } 'case-lambda' { b.case_lambda_form(nodes, id)! } 'syntax-case' { b.syntax_case_form(nodes, tail, id)! } 'with-syntax' { b.with_syntax_form(nodes, tail, id)! } 'syntax' { b.syntax_form(nodes, id)! } 'quasisyntax' { b.quasisyntax_form(nodes, tail, id)! } 'unsyntax', 'unsyntax-splicing' { return failure('${name} is only valid in quasisyntax') } 'let-values', 'let*-values' { b.values_binding_form(name, nodes, tail, id)! } 'parameterize' { b.parameterize_form(nodes, tail, id)! } 'define-library', 'import' { b.library_form(name, nodes, id, definitions_allowed)! } 'define-enumeration' { if !definitions_allowed { return failure('define-enumeration is not valid in an expression position') } b.enumeration_definition(nodes, id)! } 'define-record-type' { if !definitions_allowed { return failure('define-record-type is not valid in an expression position') } b.record_definition(nodes, id)! } 'define-class', 'standard-define-class' { if !definitions_allowed { return failure('${name} is not valid in an expression position') } b.goops_class_definition(nodes, id)! } 'class' { check_arity('class', nodes.len - 1, 1, -1)! b.goops_class_expression(nodes[1], nodes[2..], reader.no_node, id)! } 'define-accessor' { if !definitions_allowed { return failure('define-accessor is not valid in an expression position') } b.goops_accessor_definition(nodes, id)! } 'define-extended-generic', 'define-extended-generics' { if !definitions_allowed { return failure('${name} is not valid in an expression position') } if name == 'define-extended-generic' { b.goops_extended_definition(nodes, id)! } else { b.goops_extended_definitions(nodes, id)! } } 'define-generic' { if !definitions_allowed { return failure('define-generic is not valid in an expression position') } b.goops_generic_definition(nodes, id)! } 'define-method' { if !definitions_allowed { return failure('define-method is not valid in an expression position') } b.goops_method_definition(nodes, id)! } 'define-method*' { if !definitions_allowed { return failure('define-method* is not valid in an expression position') } b.goops_method_star_definition(nodes, id)! } 'method' { b.goops_method_expression(nodes, id)! } 'method*' { b.goops_method_star_expression(nodes, id)! } 'define-values' { if !definitions_allowed { return failure('define-values is not valid in an expression position') } b.values_definition(nodes, id)! } 'delay', 'delay-force' { check_arity(name, nodes.len - 1, 1, 1)! function := b.expression_child(nodes[1]) index := b.function.children.len b.function.children << function b.emit(.promise, index, int(name == 'delay-force'), id) } 'define', 'define*' { b.define_form(name, nodes, id, definitions_allowed)! } 'set!' { b.assignment_form(nodes, id)! } 'and', 'or' { if nodes.len == 1 { b.constant(boolean(name == 'and'), id) return } mut jumps := []int{} for i in 1 .. nodes.len { b.expression(nodes[i], tail && i == nodes.len - 1) if i != nodes.len - 1 { jumps << b.emit(if name == 'and' { Op.and_jump } else { Op.or_jump }, 0, 0, id) } } for jump in jumps { b.patch(jump, b.function.instructions.len) } } 'let', 'let*', 'letrec', 'letrec*' { b.binding_form(name, nodes, tail, id)! } 'when', 'unless' { b.guarded_sequence(name, nodes, tail, id)! } 'define-syntax' { if !definitions_allowed { return failure('define-syntax is not valid in an expression position') } b.syntax_definition(nodes, id)! } 'let-syntax', 'letrec-syntax' { b.local_syntax(name, nodes, tail)! } 'cond' { b.cond_clauses(nodes, 1, tail, id) } 'case' { b.case_form(nodes, tail, id)! } 'do' { b.do_form(nodes, tail, id)! } 'quasiquote' { check_arity(name, nodes.len - 1, 1, 1)! b.quasiquote(nodes[1], 1)! } 'unquote', 'unquote-splicing' { return failure('${name} outside quasiquote') } else { for node in nodes { b.expression(node, false) } b.application(nodes.len - 1, tail, id) } } } // TinyCC reserves stack space for every temporary in a function. Keep these // form-specific temporaries out of unrelated recursive expression frames. fn (mut b Builder) library_form(name string, nodes []reader.NodeId, id reader.NodeId, definitions_allowed bool) ! { if !definitions_allowed || !isnil(b.scope) { return failure('${name} is only valid at top level') } if name == 'define-library' { if !isnil(b.code.namespace) && !b.code.namespace.writable { return failure('environment does not permit library definitions') } index := b.function.constants.len b.function.constants << payload_value(.library_declaration, b.library_declaration(nodes)!) b.emit(.library_define, index, 0, id) } else { mut sets := []ImportSet{len: nodes.len - 1} for i in 1 .. nodes.len { sets[i - 1] = b.import_set(nodes[i])! } index := b.function.constants.len b.function.constants << payload_value(.library_imports, &LibraryImports{ sets: sets }) b.emit(.library_import, index, 0, id) } } fn (mut b Builder) define_form(name string, nodes []reader.NodeId, id reader.NodeId, definitions_allowed bool) ! { if !definitions_allowed { return failure('${name} is not valid in an expression position') } check_arity(name, nodes.len - 1, 2, -1)! target := b.code.node(nodes[1])! if target.kind == .symbol { check_arity(name, nodes.len - 1, 2, 2)! key := b.code.variable(nodes[1])! b.declare_global_keyword(key) b.expression(nodes[2], false) b.store(key, true, id)! } else if target.kind == .pair { key := b.code.variable(target.car)! b.declare_global_keyword(key) if name == 'define*' { formals := b.code.star_formals(target.cdr, false)! b.make_closure(b.star_child(formals, nodes[2..], false), id) } else { params, rest := b.code.formals(target.cdr)! b.make_closure(b.source_child(params, rest, nodes[2..]), id) } b.store(key, true, id)! } else { return failure('define needs an identifier or procedure signature') } } fn (mut b Builder) assignment_form(nodes []reader.NodeId, id reader.NodeId) ! { check_arity('set!', nodes.len - 1, 2, 2)! target := b.code.node(nodes[1])! if target.kind == .pair { call := b.code.nodes(nodes[1])! for part in call { b.expression(part, false) } b.expression(nodes[2], false) // The stack is [getter, arg..., value]. Replace its first entry // with the getter's setter, then invoke it on the same packet. b.emit(.assignment_setter, call.len, 0, id) b.emit(.assignment_setter_result, call.len, 0, id) b.emit(.call, call.len, 0, id) b.emit(.assignment_finish, 0, 0, id) } else { key := b.code.variable(nodes[1])! b.expression(nodes[2], false) b.store(key, false, id)! } } fn (mut b Builder) binding_form(name string, nodes []reader.NodeId, tail bool, origin reader.NodeId) ! { check_arity(name, nodes.len - 1, 2, -1)! mut binding_index := 1 mut loop_name := '' if name == 'let' && b.code.node(nodes[1])!.kind == .symbol { check_arity(name, nodes.len - 1, 3, -1)! loop_name = b.code.variable(nodes[1])! binding_index = 2 } bindings := b.code.nodes(nodes[binding_index])! mut names := []string{} mut initializers := []reader.NodeId{} mut seen := map[string]bool{} for binding in bindings { parts := b.code.nodes(binding)! if parts.len != 2 { return failure('each ${name} binding needs a name and initializer') } key := b.code.variable(parts[0])! if name != 'let*' && b.code.binding_key(key) in seen { return failure('duplicate binding ${key}') } seen[b.code.binding_key(key)] = true names << key initializers << parts[1] } body := nodes[binding_index + 1..] if loop_name != '' { // Initializers run in the enclosing scope. Hidden wrapper parameters carry // their values into the recursive scope without exposing the loop name early. mut function := &Function{ code: b.code, params: names.len } mut scope := new_compile_scope(Scope{ parent: b.scope, function: function }) function.slot_count = names.len loop_slot := scope.declare(loop_name) mut wrapper := Builder{ code: b.code, function: function, scope: scope } wrapper.make_closure(wrapper.source_child(names, '', body), origin) wrapper.emit(.define_local, 0, loop_slot, origin) wrapper.emit(.drop, 0, 0, origin) wrapper.emit(.local, 0, loop_slot, origin) for i in 0 .. names.len { wrapper.emit(.local, 0, i, origin) } // The recursive procedure captures this wrapper. Hidden initializer // parameters have moved to the operand stack and must not pin their // original payloads for the entire lifetime of the loop closure. for i in 0 .. names.len { wrapper.constant(unspecified(), origin) wrapper.emit(.define_local, 0, i, origin) wrapper.emit(.drop, 0, 0, origin) } wrapper.application(names.len, true, origin) wrapper.emit(.ret, 0, 0, origin) b.make_closure(function, origin) for initializer in initializers { b.expression(initializer, false) } b.application(names.len, tail, origin) } else if name == 'let*' { b.sequential_bindings(names, initializers, body, 0, tail, origin) } else if name in ['letrec', 'letrec*'] { function := &Function{ code: b.code } mut scope := new_compile_scope(Scope{ parent: b.scope, function: function }) for key in names { scope.declare(key) } mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail && tail } if name == 'letrec*' { // Every location exists before evaluation, while earlier initializers // become visible immediately to the later ones. for i, initializer in initializers { inner.expression(initializer, false) inner.emit(.define_local, 0, i, origin) inner.emit(.drop, 0, 0, origin) } } else { for initializer in initializers { inner.expression(initializer, false) } // letrec initializes its locations only after every initializer finishes. for i := names.len - 1; i >= 0; i-- { inner.emit(.define_local, 0, i, origin) inner.emit(.drop, 0, 0, origin) } } inner.body(body) inner.emit(.ret, 0, 0, origin) b.make_closure(function, origin) b.application(0, tail, origin) } else { function := b.child(names, '', body, tail) // Initializers run in the enclosing scope. The private function stays // on the operand stack until all arguments are ready, without publishing // a procedure or marking the enclosing locations escaped. b.scope_application(function, initializers, tail, origin) } } fn (mut b Builder) sequential_bindings(names []string, initializers []reader.NodeId, body []reader.NodeId, _index int, tail bool, origin reader.NodeId) { if names.len == 0 { b.make_closure(b.child([], '', body, tail), origin) b.application(0, tail, origin) return } // Build a chain of functions iteratively: flat let* forms can contain many // bindings even though source nesting is bounded by the reader. // This first builder emits into the parent's function and must share its // name cache even when neither builder has emitted a name yet. mut current := Builder{ code: b.code, function: b.function, scope: b.scope, table: b.name_table(), return_tail: b.return_tail } for i, name in names { function := &Function{ code: b.code, params: 1 } mut scope := new_compile_scope(Scope{ parent: current.scope, function: function }) scope.declare(name) current.make_closure(function, origin) current.expression(initializers[i], false) current.application(1, if i == 0 { tail } else { true }, origin) if i > 0 { current.emit(.ret, 0, 0, origin) } current = Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail && tail } } current.body(body) current.emit(.ret, 0, 0, origin) } fn (mut b Builder) cond_clauses(nodes []reader.NodeId, start_index int, tail bool, origin reader.NodeId) { mut ends := []int{} mut completed := false for index in start_index .. nodes.len { start := b.function.instructions.len next := b.cond_clause(nodes, index, tail, origin) or { b.function.instructions.trim(start) b.fault_error(err, nodes[index]) completed = true break } if next < 0 { completed = true break } ends << b.emit(.jump, 0, 0, origin) b.patch(next, b.function.instructions.len) b.emit(.drop, 0, 0, origin) } if !completed { b.constant(unspecified(), origin) } for end in ends { b.patch(end, b.function.instructions.len) } } // Return the false-branch patch point, or -1 for an unconditional else clause. fn (mut b Builder) cond_clause(nodes []reader.NodeId, index int, tail bool, origin reader.NodeId) !int { clause := b.code.nodes(nodes[index])! if clause.len == 0 { return failure('cond clause must not be empty') } test := b.code.node(clause[0])! if test.kind == .symbol && b.keyword_name(clause[0])! == 'else' { if index != nodes.len - 1 || clause.len < 2 { return failure('cond else must be last and have a body') } b.sequence(clause[1..], tail) return -1 } arrow := clause.len >= 2 && b.code.node(clause[1])!.kind == .symbol && b.keyword_name(clause[1])! == '=>' if arrow && clause.len != 3 { return failure('cond => needs one receiver') } b.expression(clause[0], false) b.emit(.duplicate, 0, 0, origin) next := b.emit(.jump_false, 0, 0, origin) if clause.len == 1 { // Keep the successful test value. } else if arrow { b.expression(clause[2], false) b.emit(.swap, 0, 0, origin) b.application(1, tail, nodes[index]) } else { b.emit(.drop, 0, 0, origin) b.sequence(clause[1..], tail) } return next }