vile / scheme / record_syntax.v
477 lines · 453 sloc · 16.71 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4
5struct RecordSyntax {
6 rtd SyntaxBinding
7 cd SyntaxBinding
8 legacy bool
9}
10
11@[heap]
12struct RecordSyntaxBindings {
13mut:
14 locals map[int]RecordSyntax
15 globals map[string]RecordSyntax
16}
17
18@[heap]
19struct R6RecordDeclaration {
20 parent reader.NodeId = reader.no_node
21 parent_cd reader.NodeId = reader.no_node
22 parent_name string
23 protocol reader.NodeId = reader.no_node
24 parent_rtd_clause bool
25 uid Value
26 sealed bool
27 opaque bool
28 fields Value
29}
30
31const record_auxiliary_names = ['fields', 'mutable', 'immutable', 'parent', 'protocol', 'sealed',
32 'opaque', 'nongenerative', 'parent-rtd']!
33
34fn (mut vm VM) record_auto_uid(value Value) Value {
35 mut token := unsafe { &RecordUID(value.pointer()) }
36 if token.value.tag == .symbol { return token.value }
37 mut state := vm.record_runtime()
38 for {
39 label := 'vile-record-uid-${vm.next_context()}'
40 if label !in state.uids {
41 token.value = text_value(.symbol, label)
42 return token.value
43 }
44 }
45 return unspecified()
46}
47
48fn (mut vm VM) install_record_name(function &Function, name int, constructor int) ! {
49 slot := vm.global_index_in(function.code.namespace, function.names[name])!
50 cd_slot := if constructor < 0 {
51 -1
52 } else {
53 vm.global_index_in(function.code.namespace, function.names[constructor])!
54 }
55 mut state := vm.record_runtime()
56 state.names[slot] = GlobalRecordName{slot, cd_slot}
57}
58
59fn (mut b Builder) record_annotation(binding SyntaxBinding) !RecordSyntax {
60 if binding.kind == .lexical {
61 mut cursor := ScopeRef{b.scope}
62 for !isnil(cursor.value) {
63 scope := cursor.value
64 if syntax_binding_function_matches(binding, scope.function) && !isnil(scope.syntax) && !isnil(scope.syntax.records) {
65 if record := scope.syntax.records.locals[binding.slot] { return record }
66 }
67 cursor = ScopeRef{scope.parent}
68 }
69 } else if binding.kind == .global {
70 if !isnil(b.code.generated) && !isnil(b.code.generated.record_names) && voidptr(binding.namespace) == voidptr(b.code.namespace) {
71 if record := b.code.generated.record_names.globals[binding.name] { return record }
72 }
73 if !isnil(b.code.compiler_vm) && binding.global_slot >= 0 {
74 vm := unsafe { &VM(b.code.compiler_vm) }
75 if !isnil(vm.system) && !isnil(vm.system.records) {
76 if record := vm.system.records.names[binding.global_slot] {
77 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 }
78 }
79 }
80 }
81 }
82 return failure('expected a name bound by define-record-type')
83}
84
85fn (mut b Builder) install_record_annotation(declaration RecordDeclaration) {
86 rtd := b.resolve_binding(declaration.bindings[0])
87 cd := if declaration.hidden_cd == '' {
88 SyntaxBinding{}
89 } else {
90 b.resolve_binding(declaration.hidden_cd)
91 }
92 record := RecordSyntax{ rtd: rtd, cd: cd, legacy: isnil(declaration.r6) }
93 if isnil(b.scope) {
94 mut arena := b.code.syntax_arena()
95 if isnil(arena.record_names) { arena.record_names = &RecordSyntaxBindings{} }
96 arena.record_names.globals[rtd.name] = record
97 } else {
98 if isnil(b.scope.syntax) { b.scope.syntax = &SyntaxBindings{} }
99 if isnil(b.scope.syntax.records) { b.scope.syntax.records = &RecordSyntaxBindings{} }
100 b.scope.syntax.records.locals[rtd.slot] = record
101 }
102}
103
104fn (mut b Builder) record_load_binding(binding SyntaxBinding, origin reader.NodeId) ! {
105 key := b.code.identifier_alias(IdentifierAlias{ binding: binding })!
106 b.load(key, origin)!
107}
108
109fn (mut b Builder) record_descriptor_expression(nodes []reader.NodeId, origin reader.NodeId, constructor bool) ! {
110 check_arity('record descriptor syntax', nodes.len - 1, 1, 1)!
111 key := b.code.name(nodes[1])!
112 record := b.record_annotation(b.resolve_binding(key))!
113 b.record_load_binding(if constructor && !record.legacy { record.cd } else { record.rtd }, origin)!
114 if constructor && record.legacy { b.emit(.record_default_cd, 0, 0, origin) }
115}
116
117fn (mut b Builder) record_auxiliary(id reader.NodeId) !string {
118 if b.code.node(id)!.kind != .symbol { return '' }
119 binding := b.resolve_binding(b.code.name(id)!)
120 if binding.kind == .keyword && binding.name.starts_with('record-aux:') {
121 return text_view(binding.name, 11, binding.name.len)
122 }
123 if binding.kind == .global && binding.unbound {
124 for index in 0 .. record_auxiliary_names.len {
125 if binding.name == record_auxiliary_names[index] { return binding.name }
126 }
127 }
128 return ''
129}
130
131fn (mut b Builder) record_declaration(nodes []reader.NodeId, origin reader.NodeId) !RecordDeclaration {
132 mut arena := b.code.syntax_arena()
133 if !isnil(arena.records) {
134 if existing := arena.records.entries[origin] {
135 b.mark_record_global_aliases(existing)
136 return existing
137 }
138 }
139 legacy := nodes.len >= 4 && b.code.node(nodes[1])!.kind == .symbol && b.code.node(nodes[3])!.kind == .symbol
140 declaration := if legacy {
141 b.r7_record_declaration(nodes)!
142 } else {
143 b.r6_record_declaration(nodes, origin)!
144 }
145 if isnil(arena.records) { arena.records = &RecordDeclarations{} }
146 arena.records.entries[origin] = declaration
147 b.mark_record_global_aliases(declaration)
148 return declaration
149}
150
151fn (mut b Builder) r6_record_declaration(nodes []reader.NodeId, _origin reader.NodeId) !RecordDeclaration {
152 check_arity('define-record-type', nodes.len - 1, 1, -1)!
153 mut type_id := nodes[1]
154 mut bindings := []string{}
155 mut procedure_names := []string{}
156 if b.code.node(type_id)!.kind == .symbol {
157 key := b.code.variable(type_id)!
158 bindings << key
159 raw := b.code.datum_name(type_id)!
160 ctor := b.derive_record_name(type_id, 'make-${raw}')!
161 predicate := b.derive_record_name(type_id, '${raw}?')!
162 bindings << ctor
163 bindings << predicate
164 procedure_names << 'make-${raw}'
165 procedure_names << '${raw}?'
166 } else {
167 parts := b.code.nodes(type_id)!
168 if parts.len != 3 {
169 return failure('record name spec needs type, constructor and predicate identifiers')
170 }
171 type_id = parts[0]
172 for id in parts { bindings << b.code.variable(id)! }
173 procedure_names << b.code.datum_name(parts[1])!
174 procedure_names << b.code.datum_name(parts[2])!
175 }
176 type_raw := b.code.datum_name(type_id)!
177 mut seen := map[string]bool{}
178 mut field_nodes := []reader.NodeId{}
179 mut parent := reader.no_node
180 mut parent_cd := reader.no_node
181 mut parent_name := ''
182 mut protocol := reader.no_node
183 mut parent_rtd_clause := false
184 mut uid := boolean(false)
185 mut sealed := false
186 mut opaque := false
187 for id in nodes[2..] {
188 parts := b.code.nodes(id)!
189 if parts.len == 0 { return failure('record clause must not be empty') }
190 kind := b.record_auxiliary(parts[0])!
191 if kind == '' || kind in ['mutable', 'immutable'] {
192 return failure('unknown or shadowed record clause')
193 }
194 if kind in seen { return failure('duplicate record clause') }
195 seen[kind] = true
196 match kind {
197 'fields' {
198 for field in parts[1..] { field_nodes << field }
199 }
200 'parent' {
201 check_arity(kind, parts.len - 1, 1, 1)!
202 parent_name = b.code.name(parts[1])!
203 }
204 'parent-rtd' {
205 check_arity(kind, parts.len - 1, 2, 2)!
206 parent = parts[1]
207 parent_cd = parts[2]
208 parent_rtd_clause = true
209 }
210 'protocol' {
211 check_arity(kind, parts.len - 1, 1, 1)!
212 protocol = parts[1]
213 }
214 'sealed', 'opaque' {
215 check_arity(kind, parts.len - 1, 1, 1)!
216 if b.code.node(parts[1])!.kind != .boolean {
217 return failure('record sealed/opaque clauses need boolean literals')
218 }
219 flag := b.code.datum(parts[1])!.is_true()
220 if kind == 'sealed' { sealed = flag } else { opaque = flag }
221 }
222 'nongenerative' {
223 check_arity(kind, parts.len - 1, 0, 1)!
224 if parts.len == 2 {
225 b.code.name(parts[1])!
226 uid = text_value(.symbol, b.code.datum_name(parts[1])!)
227 } else {
228 uid = b.record_expansion_uid(_origin)!
229 }
230 }
231 else {}
232 }
233 }
234 if parent_name != '' && parent_rtd_clause {
235 return failure('record cannot have both parent and parent-rtd clauses')
236 }
237 mut fields := []RecordField{cap: field_nodes.len}
238 mut field_specs := []Value{cap: field_nodes.len}
239 for field_id in field_nodes {
240 mut name_id := field_id
241 mut mutable := false
242 mut explicit := []reader.NodeId{}
243 if b.code.node(field_id)!.kind != .symbol {
244 parts := b.code.nodes(field_id)!
245 if parts.len < 2 { return failure('record field spec needs mutability and a name') }
246 kind := b.record_auxiliary(parts[0])!
247 if kind !in ['mutable', 'immutable'] {
248 return failure('unknown or shadowed record mutability')
249 }
250 mutable = kind == 'mutable'
251 if parts.len != 2 && parts.len != if mutable { 4 } else { 3 } {
252 return failure('record field has the wrong number of accessor/mutator names')
253 }
254 name_id = parts[1]
255 for item in parts[2..] { explicit << item }
256 }
257 b.code.name(name_id)!
258 raw := b.code.datum_name(name_id)!
259 fields << RecordField{raw, mutable}
260 field_specs << cons(text_value(.symbol, if mutable { 'mutable' } else { 'immutable' }), cons(text_value(.symbol, raw), Value{ tag: .nil }))
261 for index in 0 .. if mutable { 2 } else { 1 } {
262 label := if index == 0 { '${type_raw}-${raw}' } else { '${type_raw}-${raw}-set!' }
263 key := if explicit.len == 0 {
264 b.derive_record_name(type_id, label)!
265 } else {
266 b.code.variable(explicit[index])!
267 }
268 bindings << key
269 procedure_names << if explicit.len == 0 {
270 label
271 } else {
272 b.code.datum_name(explicit[index])!
273 }
274 }
275 }
276 mut unique := map[string]bool{}
277 for binding in bindings {
278 key := b.record_definition_key(binding)
279 if b.code.binding_key(key) in unique {
280 return failure('duplicate record definition binding')
281 }
282 unique[b.code.binding_key(key)] = true
283 }
284 if fields.len > (max_int - record_field_offset()) / int(sizeof(Value)) {
285 return failure('record allocation exceeds supported range')
286 }
287 mut arena := b.code.syntax_arena()
288 arena.serial++
289 hidden := '\x00record-cd${b.code.syntax_seed}.${arena.serial}'
290 return RecordDeclaration{
291 spec: &RecordSpec{ name: type_raw, fields: fields, procedure_names: procedure_names }
292 bindings: bindings
293 hidden_cd: hidden
294 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 })) }
295 }
296}
297
298fn (mut b Builder) r6_record_definition(declaration RecordDeclaration, origin reader.NodeId) ! {
299 r6 := declaration.r6
300 b.constant(text_value(.symbol, declaration.spec.name), origin)
301 if r6.parent_name != '' {
302 parent := b.record_annotation(b.resolve_binding(r6.parent_name))!
303 b.record_load_binding(parent.rtd, origin)!
304 } else if r6.parent != reader.no_node {
305 b.expression(r6.parent, false)
306 } else {
307 b.constant(boolean(false), origin)
308 }
309 if r6.uid.tag == .record_uid {
310 index := b.function.constants.len
311 b.function.constants << r6.uid
312 b.emit(.record_auto_uid, index, 0, origin)
313 } else {
314 b.constant(r6.uid, origin)
315 }
316 b.constant(boolean(r6.sealed), origin)
317 b.constant(boolean(r6.opaque), origin)
318 b.constant(r6.fields, origin)
319 b.emit(.record_make_type, 0, 0, origin)
320 b.store(declaration.bindings[0], true, origin)!
321 b.emit(.drop, 0, 0, origin)
322 b.load(declaration.bindings[0], origin)!
323 index := b.function.constants.len
324 b.function.constants << payload_value(.record_spec, declaration.spec)
325 b.emit(.record_operations, index, 0, origin)
326 for i := declaration.bindings.len - 1; i >= 2; i-- {
327 b.store(declaration.bindings[i], true, origin)!
328 b.emit(.drop, 0, 0, origin)
329 }
330 b.load(declaration.bindings[0], origin)!
331 if r6.parent_name != '' {
332 parent := b.record_annotation(b.resolve_binding(r6.parent_name))!
333 b.record_load_binding(if parent.legacy { parent.rtd } else { parent.cd }, origin)!
334 if parent.legacy { b.emit(.record_default_cd, 0, 0, origin) }
335 } else if r6.parent_cd != reader.no_node {
336 b.expression(r6.parent_cd, false)
337 } else {
338 b.constant(boolean(false), origin)
339 }
340 if r6.protocol != reader.no_node {
341 b.expression(r6.protocol, false)
342 } else {
343 b.constant(boolean(false), origin)
344 }
345 b.emit(.record_make_cd, int(r6.parent_rtd_clause && r6.protocol == reader.no_node), int(r6.protocol != reader.no_node), origin)
346 b.store(declaration.hidden_cd, true, origin)!
347 b.emit(.drop, 0, 0, origin)
348 b.emit_record_name(declaration, origin)
349 b.load(declaration.hidden_cd, origin)!
350 b.emit(.record_factory, 0, 0, origin)
351 b.store(declaration.bindings[1], true, origin)!
352 b.emit(.drop, 0, 0, origin)
353 b.constant(unspecified(), origin)
354}
355
356fn (mut b Builder) emit_record_name(declaration RecordDeclaration, origin reader.NodeId) {
357 if !isnil(b.scope) { return }
358 rtd := b.resolve_binding(declaration.bindings[0])
359 name := b.name_index(rtd.name)
360 cd := if declaration.hidden_cd == '' {
361 -1
362 } else {
363 b.name_index(b.resolve_binding(declaration.hidden_cd).name)
364 }
365 b.emit(.record_name_define, name, cd, origin)
366}
367
368fn (mut m Machine) record_operations(owner &Owner, spec &RecordSpec) {
369 rtd := m.pop_value()
370 storage := &Environment{ slots: [rtd] }
371 m.push(record_procedure(owner, .record_predicate, spec.procedure_names[1], storage))
372 mut operation := 2
373 for index, field in spec.fields {
374 position := record_own_offset(rtd.record_type_pointer()) + index
375 scope := &Environment{ slots: [rtd, integer(position)] }
376 m.push(record_procedure(owner, .record_accessor, spec.procedure_names[operation], scope))
377 operation++
378 if field.mutable {
379 m.push(record_procedure(owner, .record_mutator, spec.procedure_names[operation], scope))
380 operation++
381 }
382 }
383}
384
385// The source driver recompiles already-expanded forms on continuation replay.
386// Keep only the detached UID token stable, rather than retaining a transformer,
387// compiler scope, or expanded source tree in a runtime registry.
388fn (mut b Builder) record_expansion_uid(origin reader.NodeId) !Value {
389 if token := b.code.existing_record_source_uid(origin) { return token }
390 if origin >= reader.no_node && !isnil(b.code.compiler_vm) {
391 mut vm := unsafe { &VM(b.code.compiler_vm) }
392 seed := if b.code.record_seed != 0 { b.code.record_seed } else { b.code.syntax_seed }
393 key := '${seed}:${int(origin)}'
394 mut state := vm.record_runtime()
395 if token := state.anonymous[key] { return token }
396 token := payload_value(.record_uid, &RecordUID{})
397 state.anonymous[key] = token
398 return token
399 }
400 token := payload_value(.record_uid, &RecordUID{})
401 b.code.keep_record_source_uid(origin, token)
402 return token
403}
404
405fn (code &Code) record_source_keyword(id reader.NodeId, keyword string) !bool {
406 node := code.node(id)!
407 if node.kind != .symbol { return false }
408 if id < reader.no_node {
409 name := code.generated.symbols[code.generated.nodes[-int(id) - 2].car].name
410 if alias := code.generated.aliases[name] {
411 binding := alias.binding.name
412 return binding == keyword || (binding.starts_with('record-aux:') && text_view(binding, 11, binding.len) == keyword)
413 }
414 return name == keyword
415 }
416 // Match decoded spelling and the directive active at this occurrence without
417 // populating name caches while importing ordinary source.
418 doc, local, _ := code.reader_source(id)!
419 return doc.arena.symbol_matches(local, keyword)
420}
421
422// Generated imports already visit these cells. Reserve a token only for an
423// anonymous nongenerative declaration, so sibling/nested staged begins can
424// import the token alongside the exact source occurrence. False positives in
425// malformed or shadowed declarations never execute and do not affect identity.
426fn (mut code Code) record_source_uid(source reader.NodeId) !Value {
427 if token := code.existing_record_source_uid(source) { return token }
428 node := code.node(source)!
429 if node.kind != .pair || !code.record_source_keyword(node.car, 'define-record-type')! {
430 return unspecified()
431 }
432 type_tail := code.node(node.cdr)!
433 if type_tail.kind != .pair { return unspecified() }
434 mut cursor := type_tail.cdr
435 // This scan also visits quoted/imported data. Cyclic data which resembles a
436 // declaration needs no UID; executable syntax receives its own validation.
437 if !isnil(code.graphs) {
438 code.require_finite_spine(cursor) or { return unspecified() }
439 }
440 for {
441 clause := code.node(cursor)!
442 if clause.kind != .pair { return unspecified() }
443 body := code.node(clause.car)!
444 if body.kind == .pair && code.record_source_keyword(body.car, 'nongenerative')! && code.node(body.cdr)!.kind == .empty_list {
445 token := payload_value(.record_uid, &RecordUID{})
446 code.keep_record_source_uid(source, token)
447 return token
448 }
449 cursor = clause.cdr
450 }
451 return unspecified()
452}
453
454@[heap]
455struct RecordSourceTokens {
456mut:
457 tokens map[reader.NodeId]Value
458}
459
460fn (code &Code) existing_record_source_uid(source reader.NodeId) ?Value {
461 if !isnil(code.record_uids) {
462 if token := code.record_uids.tokens[source] { return token }
463 }
464 return none
465}
466
467fn (mut code Code) keep_record_source_uid(source reader.NodeId, token Value) {
468 if isnil(code.record_uids) { code.record_uids = &RecordSourceTokens{} }
469 code.record_uids.tokens[source] = token
470}
471
472@[heap]
473struct RecordDeclarations {
474mut:
475 entries map[reader.NodeId]RecordDeclaration
476 aliases &RecordGlobalAliases = unsafe { nil }
477}
478