vile / scheme / record.v
235 lines · 215 sloc · 9.15 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4
5struct RecordField {
6 name string
7 mutable bool
8}
9
10// Immutable declaration metadata is shared by every execution of its bytecode.
11// It retains names and field indexes, never compiler scopes or source arenas.
12@[heap]
13struct RecordSpec {
14 name string
15 fields []RecordField
16 initializers []int
17 procedure_names []string
18}
19
20struct RecordDeclaration {
21 spec &RecordSpec
22 bindings []string
23 r6 &R6RecordDeclaration = unsafe { nil }
24 hidden_cd string
25}
26
27// A distinct wrapper is allocated whenever a definition executes. Identical
28// declarations, recursive calls, and continuation reentry remain generative.
29@[heap]
30struct RecordType {
31 spec &RecordSpec
32 details &RecordDetails = unsafe { nil }
33}
34
35@[heap]
36struct Record {
37 record_type &RecordType
38 fields &Value = unsafe { nil }
39}
40
41// Round the private header up to a Value-sized boundary. Tail fields share this
42// scanned allocation; their fixed count lives in the type, not an array header
43// on every instance. No view of this tail storage escapes to a host.
44@[inline]
45fn record_field_offset() int {
46 width := int(sizeof(Value))
47 return ((int(sizeof(Record)) + width - 1) / width) * width
48}
49
50fn record_spec_pointer(value Value) &RecordSpec {
51 return unsafe { &RecordSpec(value.pointer()) }
52}
53
54fn (value Value) record_type_pointer() &RecordType {
55 return unsafe { &RecordType(value.pointer()) }
56}
57
58fn (value Value) record_pointer() &Record {
59 return unsafe { &Record(value.pointer()) }
60}
61
62pub fn (value Value) record_type() !Value {
63 if value.tag != .record { return failure('expected a record') }
64 return payload_value(.record_type, value.record_pointer().record_type)
65}
66
67pub fn (value Value) record_type_name() !string {
68 if value.tag != .record_type { return failure('expected a record type') }
69 return value.record_type_pointer().spec.name.clone()
70}
71
72// As with vector_items, the container is copied and compound field handles are
73// shared. Hosts cannot resize a record or bypass immutable fields through it.
74pub fn (value Value) record_fields() ![]Value {
75 if value.tag != .record { return failure('expected a record') }
76 record := value.record_pointer()
77 count := record_total_fields(record.record_type)
78 mut items := []Value{len: count}
79 if count > 0 { unsafe { vmemcpy(items.data, record.fields, count * int(sizeof(Value))) } }
80 return items
81}
82
83pub fn (value Value) record_field_names() ![]string {
84 if value.tag != .record_type { return failure('expected a record type') }
85 rtype := value.record_type_pointer()
86 mut names := []string{len: record_total_fields(rtype)}
87 mut current := RecordTypeCursor{rtype}
88 for !isnil(current.value) {
89 offset := record_own_offset(current.value)
90 for i, field in current.value.spec.fields { names[offset + i] = field.name.clone() }
91 current = RecordTypeCursor{record_parent(current.value)}
92 }
93 return names
94}
95
96fn (mut b Builder) record_display_name(id reader.NodeId, key string) !string {
97 return if key.len > 0 && key[0] == 0 { b.code.datum_name(id)! } else { key }
98}
99
100fn (mut b Builder) r7_record_declaration(nodes []reader.NodeId) !RecordDeclaration {
101 check_arity('define-record-type', nodes.len - 1, 3, -1)!
102 name := b.code.variable(nodes[1])!
103 constructor := b.code.nodes(nodes[2])!
104 if constructor.len == 0 { return failure('record constructor needs a name') }
105 ctor := b.code.variable(constructor[0])!
106 predicate := b.code.variable(nodes[3])!
107 mut bindings := [name, ctor, predicate]
108 mut procedure_names := [b.record_display_name(constructor[0], ctor)!,
109 b.record_display_name(nodes[3], predicate)!]
110 mut fields := []RecordField{cap: nodes.len - 4}
111 mut field_indices := map[string]int{}
112 for clause in nodes[4..] {
113 parts := b.code.nodes(clause)!
114 if parts.len !in [2, 3] {
115 return failure('record field needs a name, accessor, and optional mutator')
116 }
117 key := b.code.variable(parts[0])!
118 if key in field_indices { return failure('duplicate record field') }
119 field_indices[key] = fields.len
120 fields << RecordField{b.record_display_name(parts[0], key)!, parts.len == 3}
121 for id in parts[1..] {
122 binding := b.code.variable(id)!
123 bindings << binding
124 procedure_names << b.record_display_name(id, binding)!
125 }
126 }
127 mut seen_bindings := map[string]bool{}
128 if fields.len > (max_int - record_field_offset()) / int(sizeof(Value)) {
129 return failure('record allocation exceeds supported range')
130 }
131 for binding in bindings {
132 if b.code.binding_key(binding) in seen_bindings {
133 return failure('duplicate record definition binding')
134 }
135 seen_bindings[b.code.binding_key(binding)] = true
136 }
137 mut initializers := []int{cap: constructor.len - 1}
138 mut seen_fields := map[int]bool{}
139 for id in constructor[1..] {
140 key := b.code.variable(id)!
141 index := field_indices[key] or { return failure('record constructor names an unknown field') }
142 if index in seen_fields { return failure('duplicate record constructor field') }
143 seen_fields[index] = true
144 initializers << index
145 }
146 return RecordDeclaration{
147 spec: &RecordSpec{ name: b.record_display_name(nodes[1], name)!, fields: fields, initializers: initializers, procedure_names: procedure_names }
148 bindings: bindings
149 }
150}
151
152fn (mut b Builder) record_definition(nodes []reader.NodeId, origin reader.NodeId) ! {
153 declaration := b.record_declaration(nodes, origin)!
154 for name in declaration.bindings { b.declare_global_keyword(name) }
155 if declaration.hidden_cd != '' { b.declare_global_keyword(declaration.hidden_cd) }
156 b.install_record_annotation(declaration)
157 if !isnil(declaration.r6) { return b.r6_record_definition(declaration, origin) }
158 index := b.function.constants.len
159 b.function.constants << payload_value(.record_spec, declaration.spec)
160 b.emit(.record_define, index, 0, origin)
161 // Creation pushes the descriptor and all generated procedures in declaration
162 // order. Ordinary stores preserve lexical/global binding locations and hygiene.
163 for i := declaration.bindings.len - 1; i >= 0; i-- {
164 b.store(declaration.bindings[i], true, origin)!
165 b.emit(.drop, 0, 0, origin)
166 }
167 b.emit_record_name(declaration, origin)
168 b.constant(unspecified(), origin)
169}
170
171fn record_procedure(owner &Owner, mode ProcedureKind, name string, storage &Environment) Value {
172 return procedure_value(&Procedure{ owner: owner, mode: mode, name: name, env: storage })
173}
174
175@[direct_array_access]
176fn (mut m Machine) define_record(owner &Owner, spec &RecordSpec) {
177 type_value := payload_value(.record_type, &RecordType{ spec: spec })
178 type_storage := &Environment{ slots: [type_value] }
179 m.push(type_value)
180 m.push(record_procedure(owner, .record_constructor, spec.procedure_names[0], type_storage))
181 m.push(record_procedure(owner, .record_predicate, spec.procedure_names[1], type_storage))
182 mut operation := 2
183 for i in 0 .. spec.fields.len {
184 storage := &Environment{ slots: [type_value, integer(i)] }
185 m.push(record_procedure(owner, .record_accessor, spec.procedure_names[operation], storage))
186 operation++
187 if spec.fields[i].mutable {
188 m.push(record_procedure(owner, .record_mutator, spec.procedure_names[operation], storage))
189 operation++
190 }
191 }
192}
193
194// Apply has already validated callable ownership. All metadata and field indexes
195// are private compiler products; only user record identity and arity need checks.
196// No name lookup, argument copy, activation, or allocation occurs for field access.
197@[direct_array_access]
198fn record_call(procedure &Procedure, args []Value) !Value {
199 record_type := procedure.env.slots[0].record_type_pointer()
200 if procedure.mode == .record_constructor {
201 check_arity(procedure.name, args.len, record_type.spec.initializers.len, record_type.spec.initializers.len)!
202 count := record_type.spec.fields.len
203 offset := record_field_offset()
204 // vcalloc uses scanned GC storage, so both the type pointer and all field
205 // handles remain visible. Zeroing also supplies unspecified omitted fields.
206 // The compiler already checked the size and every initializer index.
207 data := unsafe { vcalloc(offset + count * int(sizeof(Value))) }
208 fields := if count == 0 { unsafe { &Value(nil) } } else { unsafe { &Value(data + offset) } }
209 mut record := unsafe { &Record(data) }
210 unsafe { *record = Record{ record_type: record_type, fields: fields } }
211 for i in 0 .. args.len {
212 if args[i].tag == .multiple { return failure('record field requires one value') }
213 unsafe { fields[record_type.spec.initializers[i]] = args[i] }
214 }
215 return payload_value(.record, record)
216 }
217 arity := if procedure.mode == .record_mutator { 2 } else { 1 }
218 check_arity(procedure.name, args.len, arity, arity)!
219 if procedure.mode == .record_predicate {
220 return boolean(args[0].tag == .record && record_is_a(args[0].record_pointer().record_type, record_type))
221 }
222 if args[0].tag != .record {
223 return failure('${procedure.name}: expected a ${record_type.spec.name} record')
224 }
225 mut record := args[0].record_pointer()
226 if !record_is_a(record.record_type, record_type) {
227 return failure('${procedure.name}: record belongs to a different record type')
228 }
229 index := int(procedure.env.slots[1].whole())
230 if procedure.mode == .record_accessor { return unsafe { record.fields[index] } }
231 if args[0].read_only { return failure('cannot modify a literal or constant record') }
232 if args[1].tag == .multiple { return failure('record field requires one value') }
233 unsafe { record.fields[index] = args[1] }
234 return unspecified()
235}
236