| 1 | module scheme |
| 2 | |
| 3 | import arena |
| 4 | import reader |
| 5 | import strings |
| 6 | |
| 7 | fn (code &Code) binding_key(name string) string { |
| 8 | if !isnil(code) && !isnil(code.generated) { |
| 9 | if alias := code.generated.aliases[name] { |
| 10 | if alias.capture_key != '' { return alias.capture_key } |
| 11 | // Existing syntax-rules aliases acquire a secondary key only when used |
| 12 | // as binders. Their exact spelling and normal lookup remain unchanged. |
| 13 | raw := if index := code.generated.symbol_ids[name] { |
| 14 | code.generated.symbols[index].raw_name |
| 15 | } else { |
| 16 | external_identifier_spelling(alias.binding.name) |
| 17 | } |
| 18 | mut storage := arena.new(chunk_size: 1024) |
| 19 | defer { storage.free() } |
| 20 | family := syntax_capture_family(alias.wrap, storage) |
| 21 | storage.free() |
| 22 | key := '${family}/${raw}' |
| 23 | mut generated := unsafe { &SyntaxArena(code.generated) } |
| 24 | generated.set_alias(name, IdentifierAlias{ ...alias, capture_key: key }) |
| 25 | return key |
| 26 | } |
| 27 | } |
| 28 | return name |
| 29 | } |
| 30 | |
| 31 | // A canonical, collision-free mark-set spelling serves as a secondary binder |
| 32 | // key. Free references still have distinct aliases and frozen binding locations. |
| 33 | struct SyntaxMarkToken { |
| 34 | domain u64 |
| 35 | mark u64 |
| 36 | } |
| 37 | |
| 38 | fn compare_syntax_mark_tokens(a &SyntaxMarkToken, b &SyntaxMarkToken) int { |
| 39 | if a.domain != b.domain { return if a.domain < b.domain { -1 } else { 1 } } |
| 40 | return if a.mark == b.mark { |
| 41 | 0 |
| 42 | } else if a.mark < b.mark { |
| 43 | -1 |
| 44 | } else { |
| 45 | 1 |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn syntax_capture_family(wrap &SyntaxWrap, storage arena.Arena) string { |
| 50 | return syntax_capture_spelling(wrap, storage, false) |
| 51 | } |
| 52 | |
| 53 | fn syntax_capture_spelling(wrap &SyntaxWrap, storage arena.Arena, scratch bool) string { |
| 54 | if isnil(wrap) { return '\x00~h0:' } |
| 55 | tokens := syntax_capture_tokens(wrap, storage) |
| 56 | if scratch { return syntax_capture_scratch_spelling(wrap, tokens, storage) } |
| 57 | return render_syntax_capture_spelling(wrap, tokens) |
| 58 | } |
| 59 | |
| 60 | fn syntax_capture_tokens(wrap &SyntaxWrap, storage arena.Arena) []SyntaxMarkToken { |
| 61 | storage.push() |
| 62 | defer { storage.pop() } |
| 63 | mut tokens := []SyntaxMarkToken{} |
| 64 | unsafe { tokens.flags.set(.noslices) } |
| 65 | mut cursor := SyntaxWrapRef{wrap} |
| 66 | for !isnil(cursor.value) { |
| 67 | if !cursor.value.antimark { |
| 68 | tokens << SyntaxMarkToken{u64(cursor.value.domain), cursor.value.mark} |
| 69 | } |
| 70 | cursor = SyntaxWrapRef{cursor.value.parent} |
| 71 | } |
| 72 | tokens.sort_with_compare(compare_syntax_mark_tokens) |
| 73 | return tokens |
| 74 | } |
| 75 | |
| 76 | fn syntax_capture_scratch_spelling(wrap &SyntaxWrap, tokens []SyntaxMarkToken, storage arena.Arena) string { |
| 77 | storage.push() |
| 78 | defer { storage.pop() } |
| 79 | return render_syntax_capture_spelling(wrap, tokens) |
| 80 | } |
| 81 | |
| 82 | fn render_syntax_capture_spelling(wrap &SyntaxWrap, tokens []SyntaxMarkToken) string { |
| 83 | mut out := strings.new_buffer(16 + tokens.len * 42) |
| 84 | out.write_string('\x00~h${syntax_antimark_count(wrap)}:') |
| 85 | for i, token in tokens { |
| 86 | if i > 0 && token.domain == tokens[i - 1].domain && token.mark == tokens[i - 1].mark { |
| 87 | continue |
| 88 | } |
| 89 | out.write_string('${token.domain}.${token.mark};') |
| 90 | } |
| 91 | return out.take_string() |
| 92 | } |
| 93 | |
| 94 | fn (mut b Builder) procedural_transformer_spec(spec reader.NodeId, mut transformer SyntaxTransformer) ! { |
| 95 | if isnil(b.code.compiler_vm) { |
| 96 | return failure('procedural transformer initialization requires a VM') |
| 97 | } |
| 98 | mut vm := unsafe { &VM(b.code.compiler_vm) } |
| 99 | mut code := vm.new_code(b.code.doc, vm.next_context(), b.code.namespace, b.code.source_path) |
| 100 | code.sources = b.code.sources |
| 101 | code.has_syntax = b.code.has_syntax |
| 102 | code.has_static = b.code.has_static |
| 103 | code.expansions = b.code.expansions |
| 104 | if !isnil(b.code.generated) { |
| 105 | mut generated := code.syntax_arena() |
| 106 | // This compiler has an independent overlay. The initialized transformer |
| 107 | // bindings themselves are shared, including letrec-syntax placeholders. |
| 108 | generated.globals = b.code.generated.globals.clone() |
| 109 | } |
| 110 | input := if spec >= reader.no_node { |
| 111 | spec |
| 112 | } else { |
| 113 | import_source_form(b.code, code, spec, true)! |
| 114 | } |
| 115 | function := &Function{ code: code } |
| 116 | scope := new_compile_scope(Scope{ parent: b.scope, function: function }) |
| 117 | mut compiler := Builder{ code: code, function: function, scope: scope } |
| 118 | scratch := code.enter_list_scratch() |
| 119 | defer { code.leave_list_scratch(scratch) } |
| 120 | compiler.expression(input, true) |
| 121 | compiler.emit(.ret, 0, 0, input) |
| 122 | compiler.finish_program() |
| 123 | if !isnil(code.procedural) && !isnil(code.procedural.aborted) { |
| 124 | return code.procedural.aborted.error |
| 125 | } |
| 126 | if function.capture_depth > 0 { |
| 127 | return failure('transformer initialization cannot access runtime lexical variables') |
| 128 | } |
| 129 | value := vm.call(procedure_value(&Procedure{ mode: .closure, owner: vm.owner, function: function }), [])! |
| 130 | b.code.expansions = code.expansions |
| 131 | if !value.is_callable() { return failure('transformer expression must return a procedure') } |
| 132 | transformer.procedure = value |
| 133 | } |
| 134 | |
| 135 | // Every identifier in the frozen input receives the same universal antimark |
| 136 | // over its existing history. Wrappers are pooled by prior history, not per node. |
| 137 | @[heap] |
| 138 | struct SyntaxInputOrigins { |
| 139 | storage arena.Arena |
| 140 | mut: |
| 141 | nodes map[i32]reader.NodeId |
| 142 | contexts map[voidptr][]SyntaxOriginOverlay |
| 143 | } |
| 144 | |
| 145 | fn new_syntax_input_origins(storage arena.Arena) &SyntaxInputOrigins { |
| 146 | storage.push() |
| 147 | defer { storage.pop() } |
| 148 | return &SyntaxInputOrigins{ storage: storage } |
| 149 | } |
| 150 | |
| 151 | fn new_syntax_input_wraps(storage arena.Arena) map[voidptr]&SyntaxWrap { |
| 152 | storage.push() |
| 153 | defer { storage.pop() } |
| 154 | return map[voidptr]&SyntaxWrap{} |
| 155 | } |
| 156 | |
| 157 | fn keep_syntax_input_wrap(storage arena.Arena, mut wraps map[voidptr]&SyntaxWrap, key voidptr, wrap &SyntaxWrap) { |
| 158 | storage.push() |
| 159 | defer { storage.pop() } |
| 160 | wraps[key] = wrap |
| 161 | } |
| 162 | |
| 163 | fn (mut origins SyntaxInputOrigins) keep(index i32, source reader.NodeId) { |
| 164 | origins.storage.push() |
| 165 | defer { origins.storage.pop() } |
| 166 | origins.nodes[index] = source |
| 167 | } |
| 168 | |
| 169 | fn (mut b Builder) procedural_input(source reader.NodeId, mut origins SyntaxInputOrigins) !Value { |
| 170 | mut tree, roots := b.freeze_syntax_graph_origins([source], false, &origins)! |
| 171 | mut wraps := new_syntax_input_wraps(origins.storage) |
| 172 | context := b.capture_syntax_lookup_context()! |
| 173 | for i, original in tree.identifiers { |
| 174 | identifier := if !isnil(original.context) { |
| 175 | alias := b.code.generated.aliases[original.name] or { IdentifierAlias{ context: original.context } } |
| 176 | SyntaxIdentifier{ ...original, context: b.overlay_identifier_context(original.context, alias, context, mut origins) } |
| 177 | } else { |
| 178 | original |
| 179 | } |
| 180 | key := voidptr(identifier.wrap) |
| 181 | if wrap := wraps[key] { |
| 182 | tree.identifiers[i] = SyntaxIdentifier{ ...identifier, wrap: wrap } |
| 183 | } else { |
| 184 | wrap := &SyntaxWrap{ domain: unsafe { nil }, antimark: true, parent: identifier.wrap } |
| 185 | keep_syntax_input_wrap(origins.storage, mut wraps, key, wrap) |
| 186 | tree.identifiers[i] = SyntaxIdentifier{ ...identifier, wrap: wrap } |
| 187 | } |
| 188 | } |
| 189 | data := &SyntaxObjectData{ tree: tree, owner: b.syntax_owner(), context: context } |
| 190 | return wrapped_syntax(data, int(roots[0])) |
| 191 | } |
| 192 | |
| 193 | fn (mut b Builder) expand_procedural_transformer(transformer &SyntaxTransformer, source reader.NodeId) !reader.NodeId { |
| 194 | if isnil(b.code.compiler_vm) { |
| 195 | return failure('procedural transformer expansion requires a VM') |
| 196 | } |
| 197 | mut vm := unsafe { &VM(b.code.compiler_vm) } |
| 198 | mut storage := arena.new(chunk_size: 1024) |
| 199 | defer { storage.free() } |
| 200 | mut origins := new_syntax_input_origins(storage) |
| 201 | input := b.procedural_input(source, mut origins)! |
| 202 | output := vm.call(transformer.procedure, [input])! |
| 203 | if output.tag == .multiple { |
| 204 | return failure('transformer must return exactly one syntax object') |
| 205 | } |
| 206 | return b.hydrate_procedural_output(output, (syntax_object_ref(input)!).data, origins, source) |
| 207 | } |
| 208 | |
| 209 | struct SyntaxHydrationJob { |
| 210 | source reader.NodeId |
| 211 | target reader.NodeId |
| 212 | } |
| 213 | |
| 214 | struct SyntaxHydrator { |
| 215 | source &SyntaxValueSource |
| 216 | input &SyntaxObjectData |
| 217 | origins &SyntaxInputOrigins |
| 218 | storage arena.Arena |
| 219 | origin reader.NodeId |
| 220 | mut: |
| 221 | indices map[reader.NodeId]reader.NodeId |
| 222 | identifiers map[voidptr]string |
| 223 | families map[voidptr]string |
| 224 | pending []SyntaxHydrationJob |
| 225 | marks SyntaxExpansion |
| 226 | } |
| 227 | |
| 228 | fn (mut hydrator SyntaxHydrator) push(job SyntaxHydrationJob) { |
| 229 | if hydrator.pending.len == hydrator.pending.cap { |
| 230 | hydrator.reserve_job() |
| 231 | } |
| 232 | hydrator.pending << job |
| 233 | } |
| 234 | |
| 235 | fn (mut hydrator SyntaxHydrator) reserve_job() { |
| 236 | hydrator.storage.push() |
| 237 | defer { hydrator.storage.pop() } |
| 238 | hydrator.pending.ensure_cap(hydrator.pending.len + 1) |
| 239 | } |
| 240 | |
| 241 | fn keep_syntax_hydration_name(storage arena.Arena, mut names map[voidptr]string, key voidptr, name string) { |
| 242 | storage.push() |
| 243 | defer { storage.pop() } |
| 244 | names[key] = name |
| 245 | } |
| 246 | |
| 247 | fn (mut hydrator SyntaxHydrator) keep_index(source reader.NodeId, target reader.NodeId) { |
| 248 | hydrator.storage.push() |
| 249 | defer { hydrator.storage.pop() } |
| 250 | hydrator.indices[source] = target |
| 251 | } |
| 252 | |
| 253 | fn (mut hydrator SyntaxHydrator) identifier(mut b Builder, value Value, origin reader.NodeId) !reader.NodeId { |
| 254 | object := syntax_object_ref(value)! |
| 255 | if !isnil(object.data.owner) && voidptr(object.data.owner) != voidptr(hydrator.input.owner) { |
| 256 | return failure('syntax object belongs to another VM') |
| 257 | } |
| 258 | info := syntax_identifier_info(value)! |
| 259 | if name := hydrator.identifiers[voidptr(info)] { |
| 260 | return b.code.syntax_symbol(name, info.raw_name, origin) |
| 261 | } |
| 262 | wrap := hydrator.marks.transcription_wrap(info.wrap) |
| 263 | family := if cached := hydrator.families[voidptr(wrap)] { |
| 264 | cached |
| 265 | } else { |
| 266 | created := syntax_capture_family(wrap, hydrator.storage) |
| 267 | keep_syntax_hydration_name(hydrator.storage, mut hydrator.families, voidptr(wrap), created) |
| 268 | created |
| 269 | } |
| 270 | capture_key := '${family}/${info.raw_name}' |
| 271 | captured := !isnil(info.wrap) && info.wrap.antimark |
| 272 | origin_context := syntax_identifier_context(value)! |
| 273 | current := captured && voidptr(origin_context) == voidptr(hydrator.input.context) |
| 274 | // Numeric actual labels and ~h capture keys occupy disjoint namespaces, |
| 275 | // including raw identifiers containing slashes or generated-looking suffixes. |
| 276 | name := b.code.identifier_alias(IdentifierAlias{ |
| 277 | context: origin_context |
| 278 | binding: info.binding |
| 279 | wrap: wrap |
| 280 | capture_key: capture_key |
| 281 | capture_scope: b.scope |
| 282 | capture_slots: if isnil(b.scope) { 0 } else { b.scope.function.slot_count } |
| 283 | capture_globals: b.syntax_global_count() |
| 284 | capture_generation: b.code.syntax_global_generation_floor()! |
| 285 | use_site: captured && current |
| 286 | use_scope: if current { b.scope } else { unsafe { nil } } |
| 287 | use_name: external_identifier_key(info.raw_name) |
| 288 | })! |
| 289 | keep_syntax_hydration_name(hydrator.storage, mut hydrator.identifiers, voidptr(info), name) |
| 290 | return b.code.syntax_symbol(name, info.raw_name, origin) |
| 291 | } |
| 292 | |
| 293 | fn (mut hydrator SyntaxHydrator) reference(mut b Builder, source reader.NodeId) !reader.NodeId { |
| 294 | if target := hydrator.indices[source] { |
| 295 | node := b.code.node(target)! |
| 296 | if node.kind in [.pair, .vector] { b.code.enable_datum_graphs() } |
| 297 | return target |
| 298 | } |
| 299 | node := graph_source_node(hydrator.source, source)! |
| 300 | value := hydrator.source.value(source) |
| 301 | original := if value.tag == .syntax && value.pointer() == voidptr(hydrator.input) { |
| 302 | hydrator.origins.nodes[value.syntax_index] or { reader.no_node } |
| 303 | } else { |
| 304 | reader.no_node |
| 305 | } |
| 306 | origin := if original != reader.no_node { |
| 307 | b.code.source_origin(original) |
| 308 | } else { |
| 309 | hydrator.origin |
| 310 | } |
| 311 | if node.kind == .empty_list { return reader.nil_node } |
| 312 | target := if node.kind == .symbol { |
| 313 | if value.tag != .syntax { return failure('transformer returned an unwrapped symbol') } |
| 314 | hydrator.identifier(mut b, value, origin)! |
| 315 | } else if node.kind in [.pair, .vector] { |
| 316 | b.code.syntax_node(SyntaxNode{ kind: node.kind, renamed: true, origin: origin })! |
| 317 | } else { |
| 318 | atom := graph_source_atom(hydrator.source, source)! |
| 319 | b.code.syntax_atom(atom, origin)! |
| 320 | } |
| 321 | hydrator.keep_index(source, target) |
| 322 | if original != reader.no_node && !isnil(b.code.graphs) { |
| 323 | b.code.inherit_graph_identity(b.code, original, target)! |
| 324 | } |
| 325 | if node.kind in [.pair, .vector] { hydrator.push(SyntaxHydrationJob{source, target}) } |
| 326 | return target |
| 327 | } |
| 328 | |
| 329 | fn (mut b Builder) hydrate_procedural_output(output Value, input &SyntaxObjectData, origins &SyntaxInputOrigins, origin reader.NodeId) !reader.NodeId { |
| 330 | domain := b.syntax_mark_domain() |
| 331 | mut storage := arena.new(chunk_size: 1024) |
| 332 | defer { storage.free() } |
| 333 | mut hydrator := new_syntax_hydrator(output, input, origins, storage, b.code.source_origin(origin), domain) |
| 334 | source := hydrator.source |
| 335 | root := hydrator.reference(mut b, 0)! |
| 336 | for hydrator.pending.len > 0 { |
| 337 | job := hydrator.pending.pop() |
| 338 | node := graph_source_node(source, job.source)! |
| 339 | mut result := SyntaxNode{ kind: node.kind, renamed: true, origin: b.code.source_origin(job.target) } |
| 340 | if node.kind == .pair { |
| 341 | car := hydrator.reference(mut b, node.car)! |
| 342 | cdr := hydrator.reference(mut b, node.cdr)! |
| 343 | result = SyntaxNode{ ...result, car: car, cdr: cdr } |
| 344 | } else { |
| 345 | mut generated := b.code.syntax_arena() |
| 346 | start := generated.elements.len |
| 347 | if node.count > 2147483647 - start { |
| 348 | return failure('transformer output vector exceeds supported range') |
| 349 | } |
| 350 | unsafe { generated.elements.grow_len(node.count) } |
| 351 | for i in 0 .. node.count { |
| 352 | child := graph_source_vector_at(source, job.source, i)! |
| 353 | generated.elements[start + i] = hydrator.reference(mut b, child)! |
| 354 | } |
| 355 | result = SyntaxNode{ ...result, car: reader.NodeId(start), cdr: reader.NodeId(node.count) } |
| 356 | } |
| 357 | b.code.generated.nodes[-int(job.target) - 2] = result |
| 358 | } |
| 359 | return root |
| 360 | } |
| 361 | |
| 362 | fn new_syntax_hydrator(output Value, input &SyntaxObjectData, origins &SyntaxInputOrigins, storage arena.Arena, origin reader.NodeId, domain &SyntaxLexicalDomain) SyntaxHydrator { |
| 363 | storage.push() |
| 364 | defer { storage.pop() } |
| 365 | mut source := &SyntaxValueSource{ root: output, storage: storage } |
| 366 | mut hydrator := SyntaxHydrator{ source: source, input: input, origins: origins, storage: storage, origin: origin, marks: SyntaxExpansion{ domain: domain } } |
| 367 | unsafe { |
| 368 | source.nodes.flags.set(.noslices) |
| 369 | hydrator.pending.flags.set(.noslices) |
| 370 | } |
| 371 | return hydrator |
| 372 | } |
| 373 | |
| 374 | // Owner-retained domains prevent allocator address reuse from colliding with |
| 375 | // private global binding spellings after compilation scratch is discarded. |
| 376 | fn (mut b Builder) syntax_mark_domain() &SyntaxLexicalDomain { |
| 377 | mut owner := b.syntax_owner() |
| 378 | if isnil(owner) { return b.code.syntax_identity_domain() } |
| 379 | if isnil(owner.syntax_domain) { owner.syntax_domain = &owner.syntax_domain_storage } |
| 380 | return owner.syntax_domain |
| 381 | } |
| 382 | |
| 383 | fn (b &Builder) syntax_global_count() int { |
| 384 | return if isnil(b.code.compiler_vm) { |
| 385 | -1 |
| 386 | } else { |
| 387 | unsafe { (&VM(b.code.compiler_vm)).globals.len } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | struct SyntaxOriginOverlay { |
| 392 | boundary &Scope = unsafe { nil } |
| 393 | slots int |
| 394 | context &SyntaxLookupContext |
| 395 | } |
| 396 | |
| 397 | fn (mut b Builder) overlay_identifier_context(base &SyntaxLookupContext, alias IdentifierAlias, current &SyntaxLookupContext, mut origins SyntaxInputOrigins) &SyntaxLookupContext { |
| 398 | for entry in origins.contexts[voidptr(base)] or { []SyntaxOriginOverlay{} } { |
| 399 | if voidptr(entry.boundary) == voidptr(alias.capture_scope) && entry.slots == alias.capture_slots { |
| 400 | return entry.context |
| 401 | } |
| 402 | } |
| 403 | mut cursor := ScopeRef{b.scope} |
| 404 | mut frames := 0 |
| 405 | for !isnil(cursor.value) && voidptr(cursor.value) != voidptr(alias.capture_scope) { |
| 406 | if cursor.value.names.len > 0 || (!isnil(cursor.value.syntax) && cursor.value.syntax.entries.len > 0) { |
| 407 | frames++ |
| 408 | } |
| 409 | cursor = ScopeRef{cursor.value.parent} |
| 410 | } |
| 411 | boundary := !isnil(cursor.value) && cursor.value.function.slot_count > alias.capture_slots |
| 412 | && (cursor.value.names.len > 0 || (!isnil(cursor.value.syntax) && cursor.value.syntax.entries.len > 0)) |
| 413 | if (!isnil(alias.capture_scope) && isnil(cursor.value)) || (frames == 0 && !boundary) { |
| 414 | return base |
| 415 | } |
| 416 | context := &SyntaxLookupContext{ |
| 417 | lexical: current.lexical |
| 418 | globals: unsafe { base.globals } |
| 419 | overrides: unsafe { base.overrides } |
| 420 | private_bindings: base.private_bindings |
| 421 | global_floor: base.global_floor |
| 422 | global_generation: base.global_generation |
| 423 | namespace: base.namespace |
| 424 | implicit_syntax: base.implicit_syntax |
| 425 | keyword_variables: unsafe { base.keyword_variables } |
| 426 | origin: base |
| 427 | overlay_frames: frames |
| 428 | overlay_boundary: boundary |
| 429 | overlay_slots: alias.capture_slots |
| 430 | } |
| 431 | origins.keep_context(base, SyntaxOriginOverlay{alias.capture_scope, alias.capture_slots, context}) |
| 432 | return context |
| 433 | } |
| 434 | |
| 435 | fn (mut origins SyntaxInputOrigins) keep_context(base &SyntaxLookupContext, entry SyntaxOriginOverlay) { |
| 436 | origins.storage.push() |
| 437 | defer { origins.storage.pop() } |
| 438 | mut bucket := origins.contexts[voidptr(base)] or { []SyntaxOriginOverlay{} } |
| 439 | bucket << entry |
| 440 | origins.contexts[voidptr(base)] = bucket |
| 441 | } |
| 442 | |