module scheme import reader struct RecordField { name string mutable bool } // Immutable declaration metadata is shared by every execution of its bytecode. // It retains names and field indexes, never compiler scopes or source arenas. @[heap] struct RecordSpec { name string fields []RecordField initializers []int procedure_names []string } struct RecordDeclaration { spec &RecordSpec bindings []string r6 &R6RecordDeclaration = unsafe { nil } hidden_cd string } // A distinct wrapper is allocated whenever a definition executes. Identical // declarations, recursive calls, and continuation reentry remain generative. @[heap] struct RecordType { spec &RecordSpec details &RecordDetails = unsafe { nil } } @[heap] struct Record { record_type &RecordType fields &Value = unsafe { nil } } // Round the private header up to a Value-sized boundary. Tail fields share this // scanned allocation; their fixed count lives in the type, not an array header // on every instance. No view of this tail storage escapes to a host. @[inline] fn record_field_offset() int { width := int(sizeof(Value)) return ((int(sizeof(Record)) + width - 1) / width) * width } fn record_spec_pointer(value Value) &RecordSpec { return unsafe { &RecordSpec(value.pointer()) } } fn (value Value) record_type_pointer() &RecordType { return unsafe { &RecordType(value.pointer()) } } fn (value Value) record_pointer() &Record { return unsafe { &Record(value.pointer()) } } pub fn (value Value) record_type() !Value { if value.tag != .record { return failure('expected a record') } return payload_value(.record_type, value.record_pointer().record_type) } pub fn (value Value) record_type_name() !string { if value.tag != .record_type { return failure('expected a record type') } return value.record_type_pointer().spec.name.clone() } // As with vector_items, the container is copied and compound field handles are // shared. Hosts cannot resize a record or bypass immutable fields through it. pub fn (value Value) record_fields() ![]Value { if value.tag != .record { return failure('expected a record') } record := value.record_pointer() count := record_total_fields(record.record_type) mut items := []Value{len: count} if count > 0 { unsafe { vmemcpy(items.data, record.fields, count * int(sizeof(Value))) } } return items } pub fn (value Value) record_field_names() ![]string { if value.tag != .record_type { return failure('expected a record type') } rtype := value.record_type_pointer() mut names := []string{len: record_total_fields(rtype)} mut current := RecordTypeCursor{rtype} for !isnil(current.value) { offset := record_own_offset(current.value) for i, field in current.value.spec.fields { names[offset + i] = field.name.clone() } current = RecordTypeCursor{record_parent(current.value)} } return names } fn (mut b Builder) record_display_name(id reader.NodeId, key string) !string { return if key.len > 0 && key[0] == 0 { b.code.datum_name(id)! } else { key } } fn (mut b Builder) r7_record_declaration(nodes []reader.NodeId) !RecordDeclaration { check_arity('define-record-type', nodes.len - 1, 3, -1)! name := b.code.variable(nodes[1])! constructor := b.code.nodes(nodes[2])! if constructor.len == 0 { return failure('record constructor needs a name') } ctor := b.code.variable(constructor[0])! predicate := b.code.variable(nodes[3])! mut bindings := [name, ctor, predicate] mut procedure_names := [b.record_display_name(constructor[0], ctor)!, b.record_display_name(nodes[3], predicate)!] mut fields := []RecordField{cap: nodes.len - 4} mut field_indices := map[string]int{} for clause in nodes[4..] { parts := b.code.nodes(clause)! if parts.len !in [2, 3] { return failure('record field needs a name, accessor, and optional mutator') } key := b.code.variable(parts[0])! if key in field_indices { return failure('duplicate record field') } field_indices[key] = fields.len fields << RecordField{b.record_display_name(parts[0], key)!, parts.len == 3} for id in parts[1..] { binding := b.code.variable(id)! bindings << binding procedure_names << b.record_display_name(id, binding)! } } mut seen_bindings := map[string]bool{} if fields.len > (max_int - record_field_offset()) / int(sizeof(Value)) { return failure('record allocation exceeds supported range') } for binding in bindings { if b.code.binding_key(binding) in seen_bindings { return failure('duplicate record definition binding') } seen_bindings[b.code.binding_key(binding)] = true } mut initializers := []int{cap: constructor.len - 1} mut seen_fields := map[int]bool{} for id in constructor[1..] { key := b.code.variable(id)! index := field_indices[key] or { return failure('record constructor names an unknown field') } if index in seen_fields { return failure('duplicate record constructor field') } seen_fields[index] = true initializers << index } return RecordDeclaration{ spec: &RecordSpec{ name: b.record_display_name(nodes[1], name)!, fields: fields, initializers: initializers, procedure_names: procedure_names } bindings: bindings } } fn (mut b Builder) record_definition(nodes []reader.NodeId, origin reader.NodeId) ! { declaration := b.record_declaration(nodes, origin)! for name in declaration.bindings { b.declare_global_keyword(name) } if declaration.hidden_cd != '' { b.declare_global_keyword(declaration.hidden_cd) } b.install_record_annotation(declaration) if !isnil(declaration.r6) { return b.r6_record_definition(declaration, origin) } index := b.function.constants.len b.function.constants << payload_value(.record_spec, declaration.spec) b.emit(.record_define, index, 0, origin) // Creation pushes the descriptor and all generated procedures in declaration // order. Ordinary stores preserve lexical/global binding locations and hygiene. for i := declaration.bindings.len - 1; i >= 0; i-- { b.store(declaration.bindings[i], true, origin)! b.emit(.drop, 0, 0, origin) } b.emit_record_name(declaration, origin) b.constant(unspecified(), origin) } fn record_procedure(owner &Owner, mode ProcedureKind, name string, storage &Environment) Value { return procedure_value(&Procedure{ owner: owner, mode: mode, name: name, env: storage }) } @[direct_array_access] fn (mut m Machine) define_record(owner &Owner, spec &RecordSpec) { type_value := payload_value(.record_type, &RecordType{ spec: spec }) type_storage := &Environment{ slots: [type_value] } m.push(type_value) m.push(record_procedure(owner, .record_constructor, spec.procedure_names[0], type_storage)) m.push(record_procedure(owner, .record_predicate, spec.procedure_names[1], type_storage)) mut operation := 2 for i in 0 .. spec.fields.len { storage := &Environment{ slots: [type_value, integer(i)] } m.push(record_procedure(owner, .record_accessor, spec.procedure_names[operation], storage)) operation++ if spec.fields[i].mutable { m.push(record_procedure(owner, .record_mutator, spec.procedure_names[operation], storage)) operation++ } } } // Apply has already validated callable ownership. All metadata and field indexes // are private compiler products; only user record identity and arity need checks. // No name lookup, argument copy, activation, or allocation occurs for field access. @[direct_array_access] fn record_call(procedure &Procedure, args []Value) !Value { record_type := procedure.env.slots[0].record_type_pointer() if procedure.mode == .record_constructor { check_arity(procedure.name, args.len, record_type.spec.initializers.len, record_type.spec.initializers.len)! count := record_type.spec.fields.len offset := record_field_offset() // vcalloc uses scanned GC storage, so both the type pointer and all field // handles remain visible. Zeroing also supplies unspecified omitted fields. // The compiler already checked the size and every initializer index. data := unsafe { vcalloc(offset + count * int(sizeof(Value))) } fields := if count == 0 { unsafe { &Value(nil) } } else { unsafe { &Value(data + offset) } } mut record := unsafe { &Record(data) } unsafe { *record = Record{ record_type: record_type, fields: fields } } for i in 0 .. args.len { if args[i].tag == .multiple { return failure('record field requires one value') } unsafe { fields[record_type.spec.initializers[i]] = args[i] } } return payload_value(.record, record) } arity := if procedure.mode == .record_mutator { 2 } else { 1 } check_arity(procedure.name, args.len, arity, arity)! if procedure.mode == .record_predicate { return boolean(args[0].tag == .record && record_is_a(args[0].record_pointer().record_type, record_type)) } if args[0].tag != .record { return failure('${procedure.name}: expected a ${record_type.spec.name} record') } mut record := args[0].record_pointer() if !record_is_a(record.record_type, record_type) { return failure('${procedure.name}: record belongs to a different record type') } index := int(procedure.env.slots[1].whole()) if procedure.mode == .record_accessor { return unsafe { record.fields[index] } } if args[0].read_only { return failure('cannot modify a literal or constant record') } if args[1].tag == .multiple { return failure('record field requires one value') } unsafe { record.fields[index] = args[1] } return unspecified() }