vile / scheme / library.v
367 lines · 343 sloc · 14.65 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4
5enum LibraryStatus as u8 {
6 registered
7 initializing
8 suspended
9 ready
10 failed
11}
12
13@[heap]
14struct Library {
15 name LibraryName
16 identity &LibraryIdentity = unsafe { nil }
17 source_path string
18 space &Namespace
19mut:
20 declaration &LibraryDeclaration = unsafe { nil }
21 exports []LibraryBinding
22 status LibraryStatus
23 initializer Value
24 active int
25}
26
27@[heap]
28struct LibraryRegistry {
29mut:
30 entries map[string]&Library
31 paths []string
32 source_roots map[string]string
33}
34
35@[heap]
36struct LibraryImports {
37 sets []ImportSet
38}
39
40@[heap]
41struct LibraryImportState {
42 request &LibraryImports
43 target &Namespace = unsafe { nil }
44 caller string
45 result Value
46}
47
48struct LibraryCursor {
49 library &Library
50mut:
51 next int
52}
53
54// Persistent exports contain no lexical/compiler-only SyntaxBinding fields.
55// Variable exports store their external name and slot. Builtin catalogs retain
56// encoded report slots until import selection, using the library's report space.
57struct LibraryBinding {
58 name string
59 slot int = -1
60 syntax &LibrarySyntaxBinding = unsafe { nil }
61}
62
63@[heap]
64struct LibrarySyntaxBinding {
65 kind SyntaxBindingKind
66 name string
67 namespace &Namespace = unsafe { nil }
68 transformer &SyntaxTransformer = unsafe { nil }
69}
70
71@[direct_array_access]
72fn compact_library_exports(items []NamespaceImport) []LibraryBinding {
73 mut result := filled_storage(items.len, LibraryBinding{})
74 for i, item in items {
75 container_store_validated(mut result, i, compact_library_export(item.name, item.binding))
76 }
77 return result
78}
79
80@[inline]
81fn compact_library_export(name string, binding SyntaxBinding) LibraryBinding {
82 return if binding.kind == .global {
83 LibraryBinding{ name: name, slot: binding.global_slot }
84 } else {
85 LibraryBinding{ name: name, syntax: &LibrarySyntaxBinding{ kind: binding.kind, name: binding.name, namespace: binding.namespace, transformer: binding.transformer } }
86 }
87}
88
89@[direct_array_access]
90fn append_library_exports(mut result []NamespaceImport, items []LibraryBinding, space &Namespace) {
91 if items.len == 0 { return }
92 start := result.len
93 // The batch is private. Fill the new range before validation/publication;
94 // binding construction cannot call user code or allocate nested payloads.
95 unsafe { result.grow_len(items.len) }
96 for i, item in items {
97 binding := if isnil(item.syntax) {
98 SyntaxBinding{ kind: .global, name: item.name, global_slot: item.slot,
99 namespace: if report_slot(space, item.slot) { space } else { unsafe { nil } } }
100 } else {
101 SyntaxBinding{ kind: item.syntax.kind, name: item.syntax.name, namespace: item.syntax.namespace, transformer: item.syntax.transformer, top_level: item.syntax.kind == .transformer }
102 }
103 container_store_validated(mut result, start + i, NamespaceImport{item.name, binding})
104 }
105}
106
107fn (mut vm VM) library_registry() &LibraryRegistry {
108 if isnil(vm.libraries) { vm.libraries = &LibraryRegistry{} }
109 return vm.libraries
110}
111
112fn (mut vm VM) register_library(declaration &LibraryDeclaration) ! {
113 mut registry := vm.library_registry()
114 if declaration.name.parts[0].text == 'scheme' && !declaration.name.parts[0].number {
115 return failure('the scheme library namespace is reserved')
116 }
117 if vile_base_name(declaration.name) { return failure('the vile base library is reserved') }
118 if prior := registry.entries[declaration.name.key] {
119 if voidptr(prior.identity) == voidptr(declaration.identity) { return }
120 return failure('library ${declaration.name.display} is already defined')
121 }
122 registry.entries[declaration.name.key] = &Library{
123 name: declaration.name
124 identity: declaration.identity
125 source_path: declaration.source_path
126 space: &Namespace{ writable: true, implicit_syntax: false }
127 declaration: declaration
128 }
129}
130
131// Resolve the complete graph before executing any Scheme initializer. DFS uses
132// explicit cursors, so deep dependency chains consume no native recursion.
133fn (mut vm VM) library_plan(request &LibraryImports, caller string) ![]&Library {
134 mut result := []&Library{}
135 mut colors := map[string]u8{}
136 for spec in request.sets {
137 root := vm.resolve_library(spec.library, spec.caller_path(caller), spec.search_root)!
138 if root.status == .ready || colors[root.name.key] == 2 { continue }
139 mut pending := [LibraryCursor{ library: root }]
140 colors[root.name.key] = 1
141 for pending.len > 0 {
142 last := pending.len - 1
143 library := pending[last].library
144 if library.status == .failed {
145 return failure('library ${library.name.display} initialization previously failed')
146 }
147 if library.status == .suspended {
148 return failure('library ${library.name.display} initialization is suspended; resume its continuation')
149 }
150 if library.status == .initializing || library.active > 0 {
151 return failure('library ${library.name.display} initialization is already in progress')
152 }
153 imports := library.declaration.imports
154 if pending[last].next < imports.len {
155 specification := imports[pending[last].next]
156 pending[last].next++
157 dependency := vm.resolve_library(specification.library, specification.caller_path(library.source_path), specification.search_root)!
158 if dependency.status == .ready || colors[dependency.name.key] == 2 { continue }
159 if colors[dependency.name.key] == 1 {
160 return failure('cyclic library dependency: ${library.name.display} -> ${dependency.name.display}')
161 }
162 colors[dependency.name.key] = 1
163 pending << LibraryCursor{ library: dependency }
164 } else {
165 colors[library.name.key] = 2
166 result << library
167 pending.pop()
168 }
169 }
170 }
171 return result
172}
173
174fn library_procedure(owner &Owner, function &Function, name string) Value {
175 return procedure_value(&Procedure{ owner: owner, mode: .closure, function: function, name: name })
176}
177
178@[direct_array_access]
179fn (mut vm VM) import_driver(request &LibraryImports, target &Namespace, caller string, result Value) !Value {
180 if !isnil(target) && !target.writable { return failure('environment does not permit imports') }
181 // Root imports may replace interaction bindings. Save the pristine names and
182 // values first, before an alias replaces a standard name's original location.
183 if isnil(target) { vm.report_environment(5)! }
184 plan := vm.library_plan(request, caller)!
185 // Each library occupies a constant operand; instruction positions themselves
186 // are full-width cursors and need not fit an operand.
187 if plan.len > 2147483647 { return failure('library import exceeds constant operand range') }
188 instruction_count := library_instruction_count(plan.len, 3, 2)!
189 state := &LibraryImportState{ request: request, target: target, caller: caller, result: result }
190 mut function := &Function{ code: unsafe { nil }, constants: value_storage(plan.len + 1), instructions: filled_storage(instruction_count, Instruction{}) }
191 function.constants[0] = payload_value(.library_import_state, state)
192 for i, library in plan {
193 initializer := vm.library_initializer(library)!
194 container_store_validated(mut function.constants, i + 1, initializer)
195 container_store_validated(mut function.instructions, i * 3, bridge_instruction(.constant, i + 1, 0))
196 container_store_validated(mut function.instructions, i * 3 + 1, bridge_instruction(.call, 0, 0))
197 container_store_validated(mut function.instructions, i * 3 + 2, bridge_instruction(.drop, 0, 0))
198 }
199 container_store_validated(mut function.instructions, plan.len * 3, bridge_instruction(.library_commit, 0, 0))
200 container_store_validated(mut function.instructions, plan.len * 3 + 1, bridge_instruction(.ret, 0, 0))
201 return library_procedure(vm.owner, function, 'library import')
202}
203
204@[direct_array_access]
205fn (mut vm VM) library_initializer(library &Library) !Value {
206 mut instance := unsafe { &Library(library) }
207 if instance.initializer.tag == .procedure { return instance.initializer }
208 declaration := instance.declaration
209 instruction_count := library_instruction_count(declaration.forms.len, 2, 4)!
210 instance_value := payload_value(.library_instance, instance)
211 before := library_procedure(vm.owner, &Function{
212 code: unsafe { nil }
213 constants: [instance_value]
214 instructions: [
215 bridge_instruction(.library_mark_enter, 0, 0),
216 bridge_instruction(.ret, 0, 0),
217 ]
218 }, 'library enter')
219 after := library_procedure(vm.owner, &Function{
220 code: unsafe { nil }
221 constants: [instance_value]
222 instructions: [
223 bridge_instruction(.library_mark_leave, 0, 0),
224 bridge_instruction(.ret, 0, 0),
225 ]
226 }, 'library leave')
227 mut code := vm.new_code(declaration.code.doc, vm.next_context(), instance.space, declaration.code.source_path)
228 code.generated = declaration.code.generated
229 code.sources = declaration.code.sources
230 // The driver shares generated syntax and included documents, so it must
231 // also preserve their detached graph identities. Active compiler stacks
232 // stay private to this new Code.
233 if !isnil(declaration.code.graphs) {
234 code.enable_datum_graphs()
235 code.graphs.generated = declaration.code.graphs.generated
236 code.graphs.staged = declaration.code.graphs.staged
237 code.graphs.literals = declaration.code.graph_literal_owner()
238 }
239 state := &LibraryImportState{ request: &LibraryImports{ sets: declaration.imports }, target: instance.space, caller: instance.source_path }
240 mut body := &Function{
241 code: code
242 constants: [
243 payload_value(.library_import_state, state),
244 instance_value,
245 ]
246 instructions: filled_storage(instruction_count, Instruction{})
247 }
248 body.instructions[0] = bridge_instruction(.library_commit, 0, 0)
249 body.instructions[1] = bridge_instruction(.drop, 0, 0)
250 for i, id in declaration.forms {
251 origin := code.source_origin(id)
252 container_store_validated(mut body.instructions, i * 2 + 2, Instruction{ op: .source_form, a: id, origin: origin })
253 container_store_validated(mut body.instructions, i * 2 + 3, Instruction{ op: .drop, origin: origin })
254 }
255 container_store_validated(mut body.instructions, declaration.forms.len * 2 + 2, bridge_instruction(.library_complete, 1, 0))
256 container_store_validated(mut body.instructions, declaration.forms.len * 2 + 3, bridge_instruction(.ret, 0, 0))
257 // The driver retains uncompiled forms, but never a borrow of the VM.
258 code.release_compile_borrows()
259 body_procedure := library_procedure(vm.owner, body, 'library body')
260 wrapper := &Function{
261 code: unsafe { nil }
262 slot_count: 5
263 constants: [before, body_procedure, after, instance_value]
264 instructions: [
265 bridge_instruction(.library_init_guard, 3, 0),
266 bridge_instruction(.constant, 0, 0),
267 bridge_instruction(.define_local, 0, 0),
268 bridge_instruction(.drop, 0, 0),
269 bridge_instruction(.constant, 1, 0),
270 bridge_instruction(.define_local, 0, 1),
271 bridge_instruction(.drop, 0, 0),
272 bridge_instruction(.constant, 2, 0),
273 bridge_instruction(.define_local, 0, 2),
274 bridge_instruction(.drop, 0, 0),
275 bridge_instruction(.wind_init, 0, 0),
276 bridge_instruction(.wind_enter, 0, 0),
277 bridge_instruction(.wind_leave, 0, 0),
278 bridge_instruction(.wind_finish, 0, 0),
279 bridge_instruction(.ret, 0, 0),
280 ]
281 }
282 instance.initializer = library_procedure(vm.owner, wrapper, 'library initializer')
283 return instance.initializer
284}
285
286fn (mut vm VM) commit_library_imports(state &LibraryImportState) !Value {
287 mut items := []NamespaceImport{}
288 // No slice or pointer into this buffer escapes; later import sets may grow it.
289 unsafe { items.flags.set(.noslices) }
290 defer { unsafe { items.free() } }
291 for spec in state.request.sets {
292 library := vm.resolve_library(spec.library, spec.caller_path(state.caller), spec.search_root)!
293 if library.status != .ready {
294 return failure('library ${library.name.display} has not finished initialization')
295 }
296 mut selected := transformed_imports(spec, library.exports)!
297 defer { selected.release() }
298 append_library_exports(mut items, selected.items, library.space)
299 }
300 check_import_collisions(items)!
301 if !isnil(state.target) {
302 for item in items {
303 if vm.namespace_has_binding(state.target, item.name) && !same_syntax_binding(vm.namespace_binding(state.target, item.name), item.binding) {
304 return failure('import conflicts with existing binding ${binding_diagnostic_name(item.name)}')
305 }
306 }
307 }
308 for item in items { vm.install_import(state.target, item) }
309 if state.result.tag == .environment {
310 mut target := unsafe { &Namespace(state.target) }
311 target.writable = false
312 }
313 return state.result
314}
315
316fn (mut vm VM) complete_library(library &Library) ! {
317 mut instance := unsafe { &Library(library) }
318 if instance.status == .ready { return }
319 mut exports := filled_storage(instance.declaration.exports.len, NamespaceImport{})
320 for i, spec in instance.declaration.exports {
321 binding := vm.namespace_binding(instance.space, spec.internal)
322 if binding.kind == .global && binding.global_slot < 0 {
323 return library_file_error(instance.declaration.code, spec.origin, failure('library ${instance.name.display} exports unbound identifier ${binding_diagnostic_name(spec.external)}'))
324 }
325 container_store_validated(mut exports, i, NamespaceImport{spec.external, binding})
326 }
327 check_import_collisions(exports)!
328 instance.exports = compact_library_exports(exports)
329 instance.status = .ready
330 // Escaped closures/continuations retain their own code and winders. The
331 // registry needs neither an initializer nor its uncompiled source anymore.
332 instance.initializer = unspecified()
333 instance.declaration = unsafe { nil }
334}
335
336fn (mut vm VM) install_library_primitive() {
337 vm.environment_constructor = procedure_value(&Procedure{ owner: vm.owner, mode: .library_environment, name: 'environment' })
338 vm.bind_global('environment', vm.environment_constructor)
339}
340
341pub fn (mut vm VM) environment(import_sets []Value) !Value {
342 return vm.call(vm.environment_constructor, import_sets)
343}
344
345fn (mut vm VM) library_environment_driver(import_sets []Value, caller string) !Value {
346 mut code := vm.new_code(reader.Document{}, vm.next_context(), unsafe { nil }, caller)
347 mut converter := DatumCompiler{ code: code }
348 mut b := Builder{ code: code, function: &Function{ code: code } }
349 mut sets := filled_storage(import_sets.len, ImportSet{})
350 for i, value in import_sets {
351 set := b.import_set(converter.convert(value, 0)!)!
352 container_store_validated(mut sets, i, set)
353 }
354 space := &Namespace{ writable: true, implicit_syntax: false }
355 result := payload_value(.environment, &EvalEnvironment{ owner: vm.owner, space: space })
356 return vm.import_driver(&LibraryImports{ sets: sets }, space, caller, result)
357}
358
359// Validate allocation arithmetic before multiplying. The generated drivers use
360// sequential instruction cursors; only their constants carry i32 operands.
361fn library_instruction_count(count int, stride int, extra int) !int {
362 maximum := i64(9223372036854775807) / i64(sizeof(Instruction))
363 if count < 0 || stride <= 0 || extra < 0 || extra > maximum || count > (maximum - extra) / stride {
364 return failure('library instruction storage exceeds supported range')
365 }
366 return count * stride + extra
367}
368