vile / scheme / code.v
209 lines · 197 sloc · 6.81 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4import arena
5
6// Code retains the private source document for diagnostics. The compiler uses
7// the decoding caches below as scratch and discards them after emitting code.
8// Execution accesses the reader only when reporting a source location.
9@[heap]
10struct Code {
11 doc reader.Document
12 allocation_owner voidptr = v_arena_current()
13 source_path string
14 namespace &Namespace = unsafe { nil }
15 syntax_seed u64
16mut:
17 // Intrusive compiler-only lists avoid another tracking allocation. Borrowed
18 // outer scopes belong to their own Code and are never registered here.
19 compile_scopes &Scope = unsafe { nil }
20 compile_tables &NameTable = unsafe { nil }
21 // Anonymous record UIDs and datum graphs keep detached, lazy sidecars.
22 record_seed u64
23 procedural &ProceduralSyntaxCode = unsafe { nil }
24 record_uids &RecordSourceTokens = unsafe { nil }
25 names map[reader.NodeId]string
26 literals map[reader.NodeId]Value
27 graphs &SyntaxGraphState = unsafe { nil }
28 lists map[reader.NodeId][]reader.NodeId
29 // Enabled only by bounded compilation entry points, which always free it
30 // before returning. Inline optional storage avoids a heap-allocated context;
31 // scalar forms and empty lists never create the arena's control block.
32 list_scratch ?arena.Arena
33 list_budget &CompileListBudget = unsafe { nil }
34 keyword_variables []string
35 syntax_base &SyntaxBindings = unsafe { nil }
36 known_globals &map[string]int = unsafe { nil }
37 // Borrowed only during compilation; cleared with known_globals before escape.
38 compiler_vm voidptr = unsafe { nil }
39 generated &SyntaxArena = unsafe { nil }
40 sources &SourceDocuments = unsafe { nil }
41 syntax_exports []SyntaxInstallation
42 expansions int
43 expansion_limit int = 10000
44 has_syntax bool
45 has_static bool
46 // The built-in protocol source is compiled before any VM exists.
47 // Its ordinary root reads can resolve directly in the installing VM.
48 builtin_root bool
49 // Keep the flag beside the existing booleans, using their alignment padding.
50 list_scratch_enabled bool
51 compile_depth int
52}
53
54fn (mut code Code) release_compile_borrows() {
55 if !isnil(code.procedural) {
56 code.procedural.globals_cache = unsafe { nil }
57 code.procedural.private_cache = unsafe { nil }
58 }
59 code.syntax_base = unsafe { nil }
60 code.known_globals = unsafe { nil }
61 code.compiler_vm = unsafe { nil }
62}
63
64fn (mut code Code) nodes(id reader.NodeId) ![]reader.NodeId {
65 if !isnil(code.graphs) { code.require_finite_spine(id)! }
66 if nodes := code.lists[id] { return nodes }
67 if !isnil(code.list_budget) { return code.budgeted_list_nodes(id) }
68 mut result := []reader.NodeId{}
69 mut current := id
70 for {
71 n := code.node(current)!
72 if n.kind == .empty_list { break }
73 if n.kind != .pair { return failure('expected a proper syntax list') }
74 if result.len == result.cap && code.list_scratch_enabled {
75 code.reserve_list_nodes(mut result)
76 }
77 result << n.car
78 current = n.cdr
79 }
80 code.lists[id] = result
81 return result
82}
83
84fn (mut code Code) reserve_list_nodes(mut nodes []reader.NodeId) {
85 if code.list_scratch == none {
86 code.list_scratch = arena.new(chunk_size: 1024)
87 }
88 // No callbacks, decoding or fallible operations may run in this scope:
89 // every V allocation on this thread would otherwise use the same arena.
90 if storage := code.list_scratch {
91 storage.push()
92 defer { storage.pop() }
93 nodes.ensure_cap(nodes.len + 1)
94 }
95}
96
97fn (mut code Code) release_list_scratch(previous ?arena.Arena, was_enabled bool) {
98 if code.lists.len > 0 {
99 // Cleanup also runs after allocation denial. Reuse the map header and
100 // clear borrowed buffer addresses before releasing their arena.
101 for id, _ in code.lists { code.lists[id] = []reader.NodeId{} }
102 code.lists.clear()
103 }
104 if mut storage := code.list_scratch { storage.free() }
105 code.list_scratch = previous
106 code.list_scratch_enabled = was_enabled
107}
108
109fn (mut code Code) datum(id reader.NodeId) !Value {
110 if !isnil(code.graphs) {
111 return materialize_datum_graph(code, id, mut code.literals, true)
112 }
113 return code.tree_datum(id)
114}
115
116fn (mut code Code) tree_datum(id reader.NodeId) !Value {
117 if value := code.literals[id] { return value }
118 n := code.node(id)!
119 value := match n.kind {
120 .empty_list { nil_value() }
121 .boolean, .number, .character, .string_literal, .bytevector, .keyword {
122 code.atom_datum(id)!
123 }
124 .reference { return failure('unresolved reader reference') }
125 .symbol { text_value(.symbol, code.datum_name(id)!) }
126 .pair { code.pair_datum(id)! }
127 .vector {
128 mut items := []Value{len: n.count}
129 for index in 0 .. n.count { items[index] = code.datum(code.vector_at(id, index)!)! }
130 // This compiler-created array has no external owner or borrowed
131 // operand-stack alias; the public vector constructor's copy is unnecessary.
132 payload_value(.vector, &Vector{ items: items })
133 }
134 }
135 literal := literal_value(value)
136 code.literals[id] = literal
137 return literal
138}
139
140// Reader nesting is bounded, but flat lists can be arbitrarily long. Iterate
141// the cdr chain; recursion only follows nested cars, never flat list length.
142fn (mut code Code) pair_datum(id reader.NodeId) !Value {
143 mut ids := []reader.NodeId{}
144 mut cars := []Value{}
145 mut current := id
146 mut tail := nil_value()
147 for {
148 if cached := code.literals[current] {
149 tail = cached
150 break
151 }
152 n := code.node(current)!
153 if n.kind != .pair {
154 tail = code.datum(current)!
155 break
156 }
157 ids << current
158 cars << code.datum(n.car)!
159 current = n.cdr
160 }
161 for i := ids.len - 1; i >= 0; i-- {
162 tail = literal_value(cons(cars[i], tail))
163 code.literals[ids[i]] = tail
164 }
165 return tail
166}
167
168fn (mut code Code) name(id reader.NodeId) !string {
169 if cached := code.names[id] { return cached }
170 node := code.node(id)!
171 if node.kind != .symbol { return failure('expected an identifier') }
172 name := if id < -1 {
173 code.generated.symbols[code.generated.nodes[-int(id) - 2].car].name
174 } else if node.abbreviation == .alt_statement {
175 implicit_statement_name
176 } else {
177 external_identifier_key(code.datum_name(id)!)
178 }
179 code.names[id] = name
180 return name
181}
182
183fn (mut code Code) variable(id reader.NodeId) !string {
184 return code.name(id)
185}
186
187fn (mut code Code) formals(id reader.NodeId) !([]string, string) {
188 if !isnil(code.graphs) { code.require_finite_spine(id)! }
189 mut params := []string{}
190 mut current := id
191 mut rest := ''
192 mut seen := map[string]bool{}
193 for {
194 n := code.node(current)!
195 if n.kind == .empty_list { break }
196 if n.kind == .symbol {
197 rest = code.variable(current)!
198 if code.binding_key(rest) in seen { return failure('duplicate parameter ${rest}') }
199 break
200 }
201 if n.kind != .pair { return failure('lambda parameters must be identifiers') }
202 name := code.variable(n.car)!
203 if code.binding_key(name) in seen { return failure('duplicate parameter ${name}') }
204 seen[code.binding_key(name)] = true
205 params << name
206 current = n.cdr
207 }
208 return params, rest
209}
210