vile / scheme / library_resolve.v
248 lines · 234 sloc · 10.27 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import os
4import reader
5import strings
6
7fn vile_base_name(name LibraryName) bool {
8 return name.parts.len == 2 && !name.parts[0].number && !name.parts[1].number && name.parts[0].text == 'vile' && name.parts[1].text == 'base'
9}
10
11fn library_file_error(code &Code, id reader.NodeId, cause IError) IError {
12 return code.source_failure(id, cause)
13}
14
15pub fn (mut vm VM) add_library_path(path string) ! {
16 vm.ready()!
17 resolved := source_path(path, '')!
18 mut registry := vm.library_registry()
19 if resolved !in registry.paths { registry.paths << resolved }
20}
21
22fn (mut vm VM) resolve_library(name LibraryName, caller string, search_root string) !&Library {
23 mut registry := vm.library_registry()
24 if library := registry.entries[name.key] { return library }
25 if library := vm.standard_library(name) { return library }
26 if path, root := vm.find_library_file(name, caller, search_root) {
27 declarations := vm.library_file_declarations(path, root)!
28 mut found := false
29 for declaration in declarations { if declaration.name.key == name.key { found = true } }
30 if !found { return failure('${path} does not declare library ${name.display}') }
31 for declaration in declarations { vm.register_library(declaration)! }
32 registry.source_roots[path] = root
33 return unsafe { registry.entries[name.key] }
34 }
35 return failure('library not found: ${name.display}')
36}
37
38fn library_path_component(part LibraryNamePart) string {
39 name := part.text
40 if name == '' { return '%00' }
41 mut result := strings.new_buffer(name.len)
42 for i, value in name {
43 if (value >= `a` && value <= `z`) || (value >= `A` && value <= `Z`)
44 || (value >= `0` && value <= `9` && (i > 0 || part.number)) || value in [
45 `-`,
46 `_`,
47 ] {
48 result.write_u8(value)
49 } else {
50 result.write_u8(`%`)
51 result.write_u8('0123456789abcdef'[value >> 4])
52 result.write_u8('0123456789abcdef'[value & 15])
53 }
54 }
55 return result.take_string()
56}
57
58fn (mut vm VM) register_library_file(path string) ! {
59 for declaration in vm.library_file_declarations(path, os.dir(path))! {
60 vm.register_library(declaration)!
61 }
62}
63
64fn (mut vm VM) library_file_declarations(path string, root string) ![]&LibraryDeclaration {
65 doc := read_source_input(vm, path: path) or { return source_error(path, err) }
66 mut code := vm.new_code(doc, vm.next_context(), unsafe { nil }, path)
67 code.sources = source_documents(doc, path, root, code.syntax_seed)
68 mut current := unsafe { &Machine(nil) }
69 if vm.active.len > 0 {
70 current = vm.active.last()
71 code.expansions = current.expansions
72 }
73 defer { if !isnil(current) { current.expansions = code.expansions } }
74 mut b := Builder{ code: code, function: &Function{ code: code } }
75 mut declarations := []&LibraryDeclaration{cap: doc.forms.len}
76 mut names := map[string]bool{}
77 registry := vm.library_registry()
78 for form in doc.forms {
79 nodes := code.nodes(form) or { return library_file_error(code, form, err) }
80 if nodes.len == 0 || code.node(nodes[0])!.kind != .symbol || code.datum_name(nodes[0])! != 'define-library' {
81 return library_file_error(code, form, failure('library source may contain only define-library declarations'))
82 }
83 declaration := b.library_declaration(nodes) or { return library_file_error(code, form, err) }
84 if declaration.name.key in names || declaration.name.key in registry.entries {
85 return library_file_error(code, form, failure('duplicate library ${declaration.name.display}'))
86 }
87 if declaration.name.parts[0].text == 'scheme' && !declaration.name.parts[0].number {
88 return library_file_error(code, form, failure('the scheme library namespace is reserved'))
89 }
90 if vile_base_name(declaration.name) {
91 return library_file_error(code, form, failure('the vile base library is reserved'))
92 }
93 names[declaration.name.key] = true
94 declarations << declaration
95 }
96 return declarations
97}
98
99fn (mut vm VM) standard_library(name LibraryName) ?&Library {
100 if name.parts.len == 3 && !name.parts[0].number && !name.parts[1].number && !name.parts[2].number && name.parts[0].text in [
101 'rnrs',
102 'vile',
103 ] && name.parts[1].text == 'io' && name.parts[2].text == 'ports' {
104 return vm.selected_transcoder_library(name)
105 }
106
107 if name.parts.len == 3 && !name.parts[0].number && !name.parts[1].number && !name.parts[2].number
108 && name.parts[0].text in ['rnrs', 'vile'] && name.parts[1].text == 'arithmetic'
109 && name.parts[2].text in ['fixnums', 'flonums', 'bitwise'] {
110 return vm.selected_arithmetic_library(name)
111 }
112 if name.parts.len == 3 && !name.parts[0].number && !name.parts[1].number && !name.parts[2].number
113 && name.parts[0].text in ['rnrs', 'vile'] && name.parts[1].text == 'records'
114 && name.parts[2].text in ['procedural', 'inspection', 'syntactic'] {
115 return vm.selected_record_library(name)
116 }
117 if name.parts.len != 2 || name.parts[0].number || name.parts[1].number { return none }
118 full := name.parts[0].text == 'vile' && name.parts[1].text == 'base'
119 selected := (name.parts[0].text in ['vile', 'rnrs'] && name.parts[1].text in [
120 'lists',
121 'sorting',
122 'enums',
123 'hashtables',
124 'unicode',
125 'bytevectors',
126 'syntax-case',
127 'eval',
128 ]) || (name.parts[0].text == 'vile' && name.parts[1].text in ['fixnums', 'flonums', 'bitwise',
129 'keywords', 'setters', 'optargs', 'goops'])
130 if !full && !selected && name.parts[0].text != 'scheme' { return none }
131 mut names := []string{}
132 if full {
133 // This list includes the shared dialect's additional forms, not modes.
134 names = 'quote if begin lambda lambda* delay delay-force define define* set! let let* letrec and or cond case do quasiquote unquote unquote-splicing else => when unless letrec* case-lambda let-values let*-values define-values parameterize define-record-type define-class standard-define-class class define-accessor define-extended-generic define-extended-generics define-generic define-method define-method* method method* record-type-descriptor record-constructor-descriptor define-enumeration endianness eol-style error-handling-mode file-options buffer-mode include include-ci cond-expand define-syntax let-syntax letrec-syntax syntax-rules syntax-case syntax with-syntax quasisyntax unsyntax unsyntax-splicing define-library import return break continue vile:statement'.split(' ')
135 } else {
136 catalog := if selected {
137 selected_library_export_names(name.parts[1].text) or { return none }
138 } else {
139 standard_library_export_names(name.parts[1].text) or { return none }
140 }
141 names = catalog.split(' ')
142 }
143 environment := vm.report_environment(5) or { return none }
144 space := vm.environment_space(environment) or { return none }
145 if full {
146 for key, _ in space.bindings { names << key }
147 }
148 mut exports := []LibraryBinding{cap: names.len}
149 for key in names {
150 binding := vm.namespace_binding(space, key)
151 if binding.kind != .global || binding.global_slot >= 0 || report_slot(binding.namespace, binding.global_slot) {
152 exports << compact_library_export(key, binding)
153 }
154 }
155 if exports.len == 0 { return none }
156 library := &Library{ name: name, space: space, status: .ready, exports: exports }
157 mut registry := vm.library_registry()
158 registry.entries[name.key] = library
159 return library
160}
161
162fn (vm &VM) find_library_file(name LibraryName, caller string, search_root string) ?(string, string) {
163 mut roots := []string{}
164 if caller != '' { roots << os.dir(caller) }
165 if search_root != '' { roots << search_root }
166 if !isnil(vm.libraries) {
167 if source_root := vm.libraries.source_roots[caller] { roots << source_root }
168 roots << vm.libraries.paths
169 }
170 roots << os.getwd()
171 mut components := []string{len: name.parts.len}
172 for i, part in name.parts { components[i] = library_path_component(part) }
173 relative := components.join(os.path_separator)
174 mut seen := map[string]bool{}
175 for root in roots {
176 if root in seen { continue }
177 seen[root] = true
178 for suffix in ['.sld', '.scm', '.vile'] {
179 path := os.join_path(root, relative + suffix)
180 if os.is_file(path) { return path, root }
181 }
182 }
183 return none
184}
185
186fn (mut vm VM) library_available(name LibraryName, caller string, search_root string) !bool {
187 if !isnil(vm.libraries) {
188 if library := vm.libraries.entries[name.key] {
189 return library.status in [.registered, .ready]
190 }
191 }
192 if _ := vm.standard_library(name) { return true }
193 if !name.parts[0].number && name.parts[0].text == 'scheme' { return false }
194 path, _ := vm.find_library_file(name, caller, search_root) or { return false }
195 doc := read_source_input(vm, path: path) or {
196 if is_control_transfer(err) { return err }
197 return false
198 }
199 mut code := &Code{ doc: doc, source_path: path }
200 if doc.arena.has_labels() { code.enable_datum_graphs() }
201 mut b := Builder{ code: code, function: &Function{ code: code } }
202 mut found := false
203 for form in doc.forms {
204 nodes := code.nodes(form) or { return false }
205 if nodes.len < 2 || code.node(nodes[0]) or { return false }.kind != .symbol { return false }
206 if code.datum_name(nodes[0]) or { return false } != 'define-library' { return false }
207 candidate := b.library_name(nodes[1]) or { return false }
208 if candidate.key == name.key { found = true }
209 }
210 return found
211}
212
213fn (mut vm VM) selected_arithmetic_library(name LibraryName) ?&Library {
214 catalog := selected_library_export_names(name.parts[2].text) or { return none }
215 environment := vm.report_environment(5) or { return none }
216 space := vm.environment_space(environment) or { return none }
217 keys := catalog.split(' ')
218 mut exports := []LibraryBinding{cap: keys.len}
219 for key in keys {
220 binding := vm.namespace_binding(space, key)
221 exports << compact_library_export(key, binding)
222 }
223 library := &Library{ name: name, space: space, status: .ready, exports: exports }
224 mut registry := vm.library_registry()
225 registry.entries[name.key] = library
226 return library
227}
228
229fn (mut vm VM) selected_record_library(name LibraryName) ?&Library {
230 catalog := record_library_exports(name.parts[2].text)
231 environment := vm.report_environment(5) or { return none }
232 space := vm.environment_space(environment) or { return none }
233 keys := catalog.split(' ')
234 mut exports := []LibraryBinding{cap: keys.len}
235 for key in keys {
236 binding := if key in ['fields', 'mutable', 'immutable', 'parent', 'protocol', 'sealed',
237 'opaque', 'nongenerative', 'parent-rtd'] {
238 SyntaxBinding{ kind: .keyword, name: 'record-aux:${key}' }
239 } else {
240 vm.namespace_binding(space, key)
241 }
242 exports << compact_library_export(key, binding)
243 }
244 library := &Library{ name: name, space: space, status: .ready, exports: exports }
245 mut registry := vm.library_registry()
246 registry.entries[name.key] = library
247 return library
248}
249