module scheme import reader struct RecordSyntax { rtd SyntaxBinding cd SyntaxBinding legacy bool } @[heap] struct RecordSyntaxBindings { mut: locals map[int]RecordSyntax globals map[string]RecordSyntax } @[heap] struct R6RecordDeclaration { parent reader.NodeId = reader.no_node parent_cd reader.NodeId = reader.no_node parent_name string protocol reader.NodeId = reader.no_node parent_rtd_clause bool uid Value sealed bool opaque bool fields Value } const record_auxiliary_names = ['fields', 'mutable', 'immutable', 'parent', 'protocol', 'sealed', 'opaque', 'nongenerative', 'parent-rtd']! fn (mut vm VM) record_auto_uid(value Value) Value { mut token := unsafe { &RecordUID(value.pointer()) } if token.value.tag == .symbol { return token.value } mut state := vm.record_runtime() for { label := 'vile-record-uid-${vm.next_context()}' if label !in state.uids { token.value = text_value(.symbol, label) return token.value } } return unspecified() } fn (mut vm VM) install_record_name(function &Function, name int, constructor int) ! { slot := vm.global_index_in(function.code.namespace, function.names[name])! cd_slot := if constructor < 0 { -1 } else { vm.global_index_in(function.code.namespace, function.names[constructor])! } mut state := vm.record_runtime() state.names[slot] = GlobalRecordName{slot, cd_slot} } fn (mut b Builder) record_annotation(binding SyntaxBinding) !RecordSyntax { if binding.kind == .lexical { mut cursor := ScopeRef{b.scope} for !isnil(cursor.value) { scope := cursor.value if syntax_binding_function_matches(binding, scope.function) && !isnil(scope.syntax) && !isnil(scope.syntax.records) { if record := scope.syntax.records.locals[binding.slot] { return record } } cursor = ScopeRef{scope.parent} } } else if binding.kind == .global { if !isnil(b.code.generated) && !isnil(b.code.generated.record_names) && voidptr(binding.namespace) == voidptr(b.code.namespace) { if record := b.code.generated.record_names.globals[binding.name] { return record } } if !isnil(b.code.compiler_vm) && binding.global_slot >= 0 { vm := unsafe { &VM(b.code.compiler_vm) } if !isnil(vm.system) && !isnil(vm.system.records) { if record := vm.system.records.names[binding.global_slot] { return RecordSyntax{ rtd: SyntaxBinding{ kind: .global, global_slot: record.rtd_slot }, cd: SyntaxBinding{ kind: .global, global_slot: record.cd_slot }, legacy: record.cd_slot < 0 } } } } } return failure('expected a name bound by define-record-type') } fn (mut b Builder) install_record_annotation(declaration RecordDeclaration) { rtd := b.resolve_binding(declaration.bindings[0]) cd := if declaration.hidden_cd == '' { SyntaxBinding{} } else { b.resolve_binding(declaration.hidden_cd) } record := RecordSyntax{ rtd: rtd, cd: cd, legacy: isnil(declaration.r6) } if isnil(b.scope) { mut arena := b.code.syntax_arena() if isnil(arena.record_names) { arena.record_names = &RecordSyntaxBindings{} } arena.record_names.globals[rtd.name] = record } else { if isnil(b.scope.syntax) { b.scope.syntax = &SyntaxBindings{} } if isnil(b.scope.syntax.records) { b.scope.syntax.records = &RecordSyntaxBindings{} } b.scope.syntax.records.locals[rtd.slot] = record } } fn (mut b Builder) record_load_binding(binding SyntaxBinding, origin reader.NodeId) ! { key := b.code.identifier_alias(IdentifierAlias{ binding: binding })! b.load(key, origin)! } fn (mut b Builder) record_descriptor_expression(nodes []reader.NodeId, origin reader.NodeId, constructor bool) ! { check_arity('record descriptor syntax', nodes.len - 1, 1, 1)! key := b.code.name(nodes[1])! record := b.record_annotation(b.resolve_binding(key))! b.record_load_binding(if constructor && !record.legacy { record.cd } else { record.rtd }, origin)! if constructor && record.legacy { b.emit(.record_default_cd, 0, 0, origin) } } fn (mut b Builder) record_auxiliary(id reader.NodeId) !string { if b.code.node(id)!.kind != .symbol { return '' } binding := b.resolve_binding(b.code.name(id)!) if binding.kind == .keyword && binding.name.starts_with('record-aux:') { return text_view(binding.name, 11, binding.name.len) } if binding.kind == .global && binding.unbound { for index in 0 .. record_auxiliary_names.len { if binding.name == record_auxiliary_names[index] { return binding.name } } } return '' } fn (mut b Builder) record_declaration(nodes []reader.NodeId, origin reader.NodeId) !RecordDeclaration { mut arena := b.code.syntax_arena() if !isnil(arena.records) { if existing := arena.records.entries[origin] { b.mark_record_global_aliases(existing) return existing } } legacy := nodes.len >= 4 && b.code.node(nodes[1])!.kind == .symbol && b.code.node(nodes[3])!.kind == .symbol declaration := if legacy { b.r7_record_declaration(nodes)! } else { b.r6_record_declaration(nodes, origin)! } if isnil(arena.records) { arena.records = &RecordDeclarations{} } arena.records.entries[origin] = declaration b.mark_record_global_aliases(declaration) return declaration } fn (mut b Builder) r6_record_declaration(nodes []reader.NodeId, _origin reader.NodeId) !RecordDeclaration { check_arity('define-record-type', nodes.len - 1, 1, -1)! mut type_id := nodes[1] mut bindings := []string{} mut procedure_names := []string{} if b.code.node(type_id)!.kind == .symbol { key := b.code.variable(type_id)! bindings << key raw := b.code.datum_name(type_id)! ctor := b.derive_record_name(type_id, 'make-${raw}')! predicate := b.derive_record_name(type_id, '${raw}?')! bindings << ctor bindings << predicate procedure_names << 'make-${raw}' procedure_names << '${raw}?' } else { parts := b.code.nodes(type_id)! if parts.len != 3 { return failure('record name spec needs type, constructor and predicate identifiers') } type_id = parts[0] for id in parts { bindings << b.code.variable(id)! } procedure_names << b.code.datum_name(parts[1])! procedure_names << b.code.datum_name(parts[2])! } type_raw := b.code.datum_name(type_id)! mut seen := map[string]bool{} mut field_nodes := []reader.NodeId{} mut parent := reader.no_node mut parent_cd := reader.no_node mut parent_name := '' mut protocol := reader.no_node mut parent_rtd_clause := false mut uid := boolean(false) mut sealed := false mut opaque := false for id in nodes[2..] { parts := b.code.nodes(id)! if parts.len == 0 { return failure('record clause must not be empty') } kind := b.record_auxiliary(parts[0])! if kind == '' || kind in ['mutable', 'immutable'] { return failure('unknown or shadowed record clause') } if kind in seen { return failure('duplicate record clause') } seen[kind] = true match kind { 'fields' { for field in parts[1..] { field_nodes << field } } 'parent' { check_arity(kind, parts.len - 1, 1, 1)! parent_name = b.code.name(parts[1])! } 'parent-rtd' { check_arity(kind, parts.len - 1, 2, 2)! parent = parts[1] parent_cd = parts[2] parent_rtd_clause = true } 'protocol' { check_arity(kind, parts.len - 1, 1, 1)! protocol = parts[1] } 'sealed', 'opaque' { check_arity(kind, parts.len - 1, 1, 1)! if b.code.node(parts[1])!.kind != .boolean { return failure('record sealed/opaque clauses need boolean literals') } flag := b.code.datum(parts[1])!.is_true() if kind == 'sealed' { sealed = flag } else { opaque = flag } } 'nongenerative' { check_arity(kind, parts.len - 1, 0, 1)! if parts.len == 2 { b.code.name(parts[1])! uid = text_value(.symbol, b.code.datum_name(parts[1])!) } else { uid = b.record_expansion_uid(_origin)! } } else {} } } if parent_name != '' && parent_rtd_clause { return failure('record cannot have both parent and parent-rtd clauses') } mut fields := []RecordField{cap: field_nodes.len} mut field_specs := []Value{cap: field_nodes.len} for field_id in field_nodes { mut name_id := field_id mut mutable := false mut explicit := []reader.NodeId{} if b.code.node(field_id)!.kind != .symbol { parts := b.code.nodes(field_id)! if parts.len < 2 { return failure('record field spec needs mutability and a name') } kind := b.record_auxiliary(parts[0])! if kind !in ['mutable', 'immutable'] { return failure('unknown or shadowed record mutability') } mutable = kind == 'mutable' if parts.len != 2 && parts.len != if mutable { 4 } else { 3 } { return failure('record field has the wrong number of accessor/mutator names') } name_id = parts[1] for item in parts[2..] { explicit << item } } b.code.name(name_id)! raw := b.code.datum_name(name_id)! fields << RecordField{raw, mutable} field_specs << cons(text_value(.symbol, if mutable { 'mutable' } else { 'immutable' }), cons(text_value(.symbol, raw), Value{ tag: .nil })) for index in 0 .. if mutable { 2 } else { 1 } { label := if index == 0 { '${type_raw}-${raw}' } else { '${type_raw}-${raw}-set!' } key := if explicit.len == 0 { b.derive_record_name(type_id, label)! } else { b.code.variable(explicit[index])! } bindings << key procedure_names << if explicit.len == 0 { label } else { b.code.datum_name(explicit[index])! } } } mut unique := map[string]bool{} for binding in bindings { key := b.record_definition_key(binding) if b.code.binding_key(key) in unique { return failure('duplicate record definition binding') } unique[b.code.binding_key(key)] = true } if fields.len > (max_int - record_field_offset()) / int(sizeof(Value)) { return failure('record allocation exceeds supported range') } mut arena := b.code.syntax_arena() arena.serial++ hidden := '\x00record-cd${b.code.syntax_seed}.${arena.serial}' return RecordDeclaration{ spec: &RecordSpec{ name: type_raw, fields: fields, procedure_names: procedure_names } bindings: bindings hidden_cd: hidden r6: &R6RecordDeclaration{ parent: parent, parent_cd: parent_cd, parent_name: parent_name, protocol: protocol, parent_rtd_clause: parent_rtd_clause, uid: uid, sealed: sealed, opaque: opaque, fields: literal_value(payload_value(.vector, &Vector{ items: field_specs })) } } } fn (mut b Builder) r6_record_definition(declaration RecordDeclaration, origin reader.NodeId) ! { r6 := declaration.r6 b.constant(text_value(.symbol, declaration.spec.name), origin) if r6.parent_name != '' { parent := b.record_annotation(b.resolve_binding(r6.parent_name))! b.record_load_binding(parent.rtd, origin)! } else if r6.parent != reader.no_node { b.expression(r6.parent, false) } else { b.constant(boolean(false), origin) } if r6.uid.tag == .record_uid { index := b.function.constants.len b.function.constants << r6.uid b.emit(.record_auto_uid, index, 0, origin) } else { b.constant(r6.uid, origin) } b.constant(boolean(r6.sealed), origin) b.constant(boolean(r6.opaque), origin) b.constant(r6.fields, origin) b.emit(.record_make_type, 0, 0, origin) b.store(declaration.bindings[0], true, origin)! b.emit(.drop, 0, 0, origin) b.load(declaration.bindings[0], origin)! index := b.function.constants.len b.function.constants << payload_value(.record_spec, declaration.spec) b.emit(.record_operations, index, 0, origin) for i := declaration.bindings.len - 1; i >= 2; i-- { b.store(declaration.bindings[i], true, origin)! b.emit(.drop, 0, 0, origin) } b.load(declaration.bindings[0], origin)! if r6.parent_name != '' { parent := b.record_annotation(b.resolve_binding(r6.parent_name))! b.record_load_binding(if parent.legacy { parent.rtd } else { parent.cd }, origin)! if parent.legacy { b.emit(.record_default_cd, 0, 0, origin) } } else if r6.parent_cd != reader.no_node { b.expression(r6.parent_cd, false) } else { b.constant(boolean(false), origin) } if r6.protocol != reader.no_node { b.expression(r6.protocol, false) } else { b.constant(boolean(false), origin) } b.emit(.record_make_cd, int(r6.parent_rtd_clause && r6.protocol == reader.no_node), int(r6.protocol != reader.no_node), origin) b.store(declaration.hidden_cd, true, origin)! b.emit(.drop, 0, 0, origin) b.emit_record_name(declaration, origin) b.load(declaration.hidden_cd, origin)! b.emit(.record_factory, 0, 0, origin) b.store(declaration.bindings[1], true, origin)! b.emit(.drop, 0, 0, origin) b.constant(unspecified(), origin) } fn (mut b Builder) emit_record_name(declaration RecordDeclaration, origin reader.NodeId) { if !isnil(b.scope) { return } rtd := b.resolve_binding(declaration.bindings[0]) name := b.name_index(rtd.name) cd := if declaration.hidden_cd == '' { -1 } else { b.name_index(b.resolve_binding(declaration.hidden_cd).name) } b.emit(.record_name_define, name, cd, origin) } fn (mut m Machine) record_operations(owner &Owner, spec &RecordSpec) { rtd := m.pop_value() storage := &Environment{ slots: [rtd] } m.push(record_procedure(owner, .record_predicate, spec.procedure_names[1], storage)) mut operation := 2 for index, field in spec.fields { position := record_own_offset(rtd.record_type_pointer()) + index scope := &Environment{ slots: [rtd, integer(position)] } m.push(record_procedure(owner, .record_accessor, spec.procedure_names[operation], scope)) operation++ if field.mutable { m.push(record_procedure(owner, .record_mutator, spec.procedure_names[operation], scope)) operation++ } } } // The source driver recompiles already-expanded forms on continuation replay. // Keep only the detached UID token stable, rather than retaining a transformer, // compiler scope, or expanded source tree in a runtime registry. fn (mut b Builder) record_expansion_uid(origin reader.NodeId) !Value { if token := b.code.existing_record_source_uid(origin) { return token } if origin >= reader.no_node && !isnil(b.code.compiler_vm) { mut vm := unsafe { &VM(b.code.compiler_vm) } seed := if b.code.record_seed != 0 { b.code.record_seed } else { b.code.syntax_seed } key := '${seed}:${int(origin)}' mut state := vm.record_runtime() if token := state.anonymous[key] { return token } token := payload_value(.record_uid, &RecordUID{}) state.anonymous[key] = token return token } token := payload_value(.record_uid, &RecordUID{}) b.code.keep_record_source_uid(origin, token) return token } fn (code &Code) record_source_keyword(id reader.NodeId, keyword string) !bool { node := code.node(id)! if node.kind != .symbol { return false } if id < reader.no_node { name := code.generated.symbols[code.generated.nodes[-int(id) - 2].car].name if alias := code.generated.aliases[name] { binding := alias.binding.name return binding == keyword || (binding.starts_with('record-aux:') && text_view(binding, 11, binding.len) == keyword) } return name == keyword } // Match decoded spelling and the directive active at this occurrence without // populating name caches while importing ordinary source. doc, local, _ := code.reader_source(id)! return doc.arena.symbol_matches(local, keyword) } // Generated imports already visit these cells. Reserve a token only for an // anonymous nongenerative declaration, so sibling/nested staged begins can // import the token alongside the exact source occurrence. False positives in // malformed or shadowed declarations never execute and do not affect identity. fn (mut code Code) record_source_uid(source reader.NodeId) !Value { if token := code.existing_record_source_uid(source) { return token } node := code.node(source)! if node.kind != .pair || !code.record_source_keyword(node.car, 'define-record-type')! { return unspecified() } type_tail := code.node(node.cdr)! if type_tail.kind != .pair { return unspecified() } mut cursor := type_tail.cdr // This scan also visits quoted/imported data. Cyclic data which resembles a // declaration needs no UID; executable syntax receives its own validation. if !isnil(code.graphs) { code.require_finite_spine(cursor) or { return unspecified() } } for { clause := code.node(cursor)! if clause.kind != .pair { return unspecified() } body := code.node(clause.car)! if body.kind == .pair && code.record_source_keyword(body.car, 'nongenerative')! && code.node(body.cdr)!.kind == .empty_list { token := payload_value(.record_uid, &RecordUID{}) code.keep_record_source_uid(source, token) return token } cursor = clause.cdr } return unspecified() } @[heap] struct RecordSourceTokens { mut: tokens map[reader.NodeId]Value } fn (code &Code) existing_record_source_uid(source reader.NodeId) ?Value { if !isnil(code.record_uids) { if token := code.record_uids.tokens[source] { return token } } return none } fn (mut code Code) keep_record_source_uid(source reader.NodeId, token Value) { if isnil(code.record_uids) { code.record_uids = &RecordSourceTokens{} } code.record_uids.tokens[source] = token } @[heap] struct RecordDeclarations { mut: entries map[reader.NodeId]RecordDeclaration aliases &RecordGlobalAliases = unsafe { nil } }