module scheme import arena import reader import strings fn (code &Code) binding_key(name string) string { if !isnil(code) && !isnil(code.generated) { if alias := code.generated.aliases[name] { if alias.capture_key != '' { return alias.capture_key } // Existing syntax-rules aliases acquire a secondary key only when used // as binders. Their exact spelling and normal lookup remain unchanged. raw := if index := code.generated.symbol_ids[name] { code.generated.symbols[index].raw_name } else { external_identifier_spelling(alias.binding.name) } mut storage := arena.new(chunk_size: 1024) defer { storage.free() } family := syntax_capture_family(alias.wrap, storage) storage.free() key := '${family}/${raw}' mut generated := unsafe { &SyntaxArena(code.generated) } generated.set_alias(name, IdentifierAlias{ ...alias, capture_key: key }) return key } } return name } // A canonical, collision-free mark-set spelling serves as a secondary binder // key. Free references still have distinct aliases and frozen binding locations. struct SyntaxMarkToken { domain u64 mark u64 } fn compare_syntax_mark_tokens(a &SyntaxMarkToken, b &SyntaxMarkToken) int { if a.domain != b.domain { return if a.domain < b.domain { -1 } else { 1 } } return if a.mark == b.mark { 0 } else if a.mark < b.mark { -1 } else { 1 } } fn syntax_capture_family(wrap &SyntaxWrap, storage arena.Arena) string { return syntax_capture_spelling(wrap, storage, false) } fn syntax_capture_spelling(wrap &SyntaxWrap, storage arena.Arena, scratch bool) string { if isnil(wrap) { return '\x00~h0:' } tokens := syntax_capture_tokens(wrap, storage) if scratch { return syntax_capture_scratch_spelling(wrap, tokens, storage) } return render_syntax_capture_spelling(wrap, tokens) } fn syntax_capture_tokens(wrap &SyntaxWrap, storage arena.Arena) []SyntaxMarkToken { storage.push() defer { storage.pop() } mut tokens := []SyntaxMarkToken{} unsafe { tokens.flags.set(.noslices) } mut cursor := SyntaxWrapRef{wrap} for !isnil(cursor.value) { if !cursor.value.antimark { tokens << SyntaxMarkToken{u64(cursor.value.domain), cursor.value.mark} } cursor = SyntaxWrapRef{cursor.value.parent} } tokens.sort_with_compare(compare_syntax_mark_tokens) return tokens } fn syntax_capture_scratch_spelling(wrap &SyntaxWrap, tokens []SyntaxMarkToken, storage arena.Arena) string { storage.push() defer { storage.pop() } return render_syntax_capture_spelling(wrap, tokens) } fn render_syntax_capture_spelling(wrap &SyntaxWrap, tokens []SyntaxMarkToken) string { mut out := strings.new_buffer(16 + tokens.len * 42) out.write_string('\x00~h${syntax_antimark_count(wrap)}:') for i, token in tokens { if i > 0 && token.domain == tokens[i - 1].domain && token.mark == tokens[i - 1].mark { continue } out.write_string('${token.domain}.${token.mark};') } return out.take_string() } fn (mut b Builder) procedural_transformer_spec(spec reader.NodeId, mut transformer SyntaxTransformer) ! { if isnil(b.code.compiler_vm) { return failure('procedural transformer initialization requires a VM') } mut vm := unsafe { &VM(b.code.compiler_vm) } mut code := vm.new_code(b.code.doc, vm.next_context(), b.code.namespace, b.code.source_path) code.sources = b.code.sources code.has_syntax = b.code.has_syntax code.has_static = b.code.has_static code.expansions = b.code.expansions if !isnil(b.code.generated) { mut generated := code.syntax_arena() // This compiler has an independent overlay. The initialized transformer // bindings themselves are shared, including letrec-syntax placeholders. generated.globals = b.code.generated.globals.clone() } input := if spec >= reader.no_node { spec } else { import_source_form(b.code, code, spec, true)! } function := &Function{ code: code } scope := new_compile_scope(Scope{ parent: b.scope, function: function }) mut compiler := Builder{ code: code, function: function, scope: scope } scratch := code.enter_list_scratch() defer { code.leave_list_scratch(scratch) } compiler.expression(input, true) compiler.emit(.ret, 0, 0, input) compiler.finish_program() if !isnil(code.procedural) && !isnil(code.procedural.aborted) { return code.procedural.aborted.error } if function.capture_depth > 0 { return failure('transformer initialization cannot access runtime lexical variables') } value := vm.call(procedure_value(&Procedure{ mode: .closure, owner: vm.owner, function: function }), [])! b.code.expansions = code.expansions if !value.is_callable() { return failure('transformer expression must return a procedure') } transformer.procedure = value } // Every identifier in the frozen input receives the same universal antimark // over its existing history. Wrappers are pooled by prior history, not per node. @[heap] struct SyntaxInputOrigins { storage arena.Arena mut: nodes map[i32]reader.NodeId contexts map[voidptr][]SyntaxOriginOverlay } fn new_syntax_input_origins(storage arena.Arena) &SyntaxInputOrigins { storage.push() defer { storage.pop() } return &SyntaxInputOrigins{ storage: storage } } fn new_syntax_input_wraps(storage arena.Arena) map[voidptr]&SyntaxWrap { storage.push() defer { storage.pop() } return map[voidptr]&SyntaxWrap{} } fn keep_syntax_input_wrap(storage arena.Arena, mut wraps map[voidptr]&SyntaxWrap, key voidptr, wrap &SyntaxWrap) { storage.push() defer { storage.pop() } wraps[key] = wrap } fn (mut origins SyntaxInputOrigins) keep(index i32, source reader.NodeId) { origins.storage.push() defer { origins.storage.pop() } origins.nodes[index] = source } fn (mut b Builder) procedural_input(source reader.NodeId, mut origins SyntaxInputOrigins) !Value { mut tree, roots := b.freeze_syntax_graph_origins([source], false, &origins)! mut wraps := new_syntax_input_wraps(origins.storage) context := b.capture_syntax_lookup_context()! for i, original in tree.identifiers { identifier := if !isnil(original.context) { alias := b.code.generated.aliases[original.name] or { IdentifierAlias{ context: original.context } } SyntaxIdentifier{ ...original, context: b.overlay_identifier_context(original.context, alias, context, mut origins) } } else { original } key := voidptr(identifier.wrap) if wrap := wraps[key] { tree.identifiers[i] = SyntaxIdentifier{ ...identifier, wrap: wrap } } else { wrap := &SyntaxWrap{ domain: unsafe { nil }, antimark: true, parent: identifier.wrap } keep_syntax_input_wrap(origins.storage, mut wraps, key, wrap) tree.identifiers[i] = SyntaxIdentifier{ ...identifier, wrap: wrap } } } data := &SyntaxObjectData{ tree: tree, owner: b.syntax_owner(), context: context } return wrapped_syntax(data, int(roots[0])) } fn (mut b Builder) expand_procedural_transformer(transformer &SyntaxTransformer, source reader.NodeId) !reader.NodeId { if isnil(b.code.compiler_vm) { return failure('procedural transformer expansion requires a VM') } mut vm := unsafe { &VM(b.code.compiler_vm) } mut storage := arena.new(chunk_size: 1024) defer { storage.free() } mut origins := new_syntax_input_origins(storage) input := b.procedural_input(source, mut origins)! output := vm.call(transformer.procedure, [input])! if output.tag == .multiple { return failure('transformer must return exactly one syntax object') } return b.hydrate_procedural_output(output, (syntax_object_ref(input)!).data, origins, source) } struct SyntaxHydrationJob { source reader.NodeId target reader.NodeId } struct SyntaxHydrator { source &SyntaxValueSource input &SyntaxObjectData origins &SyntaxInputOrigins storage arena.Arena origin reader.NodeId mut: indices map[reader.NodeId]reader.NodeId identifiers map[voidptr]string families map[voidptr]string pending []SyntaxHydrationJob marks SyntaxExpansion } fn (mut hydrator SyntaxHydrator) push(job SyntaxHydrationJob) { if hydrator.pending.len == hydrator.pending.cap { hydrator.reserve_job() } hydrator.pending << job } fn (mut hydrator SyntaxHydrator) reserve_job() { hydrator.storage.push() defer { hydrator.storage.pop() } hydrator.pending.ensure_cap(hydrator.pending.len + 1) } fn keep_syntax_hydration_name(storage arena.Arena, mut names map[voidptr]string, key voidptr, name string) { storage.push() defer { storage.pop() } names[key] = name } fn (mut hydrator SyntaxHydrator) keep_index(source reader.NodeId, target reader.NodeId) { hydrator.storage.push() defer { hydrator.storage.pop() } hydrator.indices[source] = target } fn (mut hydrator SyntaxHydrator) identifier(mut b Builder, value Value, origin reader.NodeId) !reader.NodeId { object := syntax_object_ref(value)! if !isnil(object.data.owner) && voidptr(object.data.owner) != voidptr(hydrator.input.owner) { return failure('syntax object belongs to another VM') } info := syntax_identifier_info(value)! if name := hydrator.identifiers[voidptr(info)] { return b.code.syntax_symbol(name, info.raw_name, origin) } wrap := hydrator.marks.transcription_wrap(info.wrap) family := if cached := hydrator.families[voidptr(wrap)] { cached } else { created := syntax_capture_family(wrap, hydrator.storage) keep_syntax_hydration_name(hydrator.storage, mut hydrator.families, voidptr(wrap), created) created } capture_key := '${family}/${info.raw_name}' captured := !isnil(info.wrap) && info.wrap.antimark origin_context := syntax_identifier_context(value)! current := captured && voidptr(origin_context) == voidptr(hydrator.input.context) // Numeric actual labels and ~h capture keys occupy disjoint namespaces, // including raw identifiers containing slashes or generated-looking suffixes. name := b.code.identifier_alias(IdentifierAlias{ context: origin_context binding: info.binding wrap: wrap capture_key: capture_key capture_scope: b.scope capture_slots: if isnil(b.scope) { 0 } else { b.scope.function.slot_count } capture_globals: b.syntax_global_count() capture_generation: b.code.syntax_global_generation_floor()! use_site: captured && current use_scope: if current { b.scope } else { unsafe { nil } } use_name: external_identifier_key(info.raw_name) })! keep_syntax_hydration_name(hydrator.storage, mut hydrator.identifiers, voidptr(info), name) return b.code.syntax_symbol(name, info.raw_name, origin) } fn (mut hydrator SyntaxHydrator) reference(mut b Builder, source reader.NodeId) !reader.NodeId { if target := hydrator.indices[source] { node := b.code.node(target)! if node.kind in [.pair, .vector] { b.code.enable_datum_graphs() } return target } node := graph_source_node(hydrator.source, source)! value := hydrator.source.value(source) original := if value.tag == .syntax && value.pointer() == voidptr(hydrator.input) { hydrator.origins.nodes[value.syntax_index] or { reader.no_node } } else { reader.no_node } origin := if original != reader.no_node { b.code.source_origin(original) } else { hydrator.origin } if node.kind == .empty_list { return reader.nil_node } target := if node.kind == .symbol { if value.tag != .syntax { return failure('transformer returned an unwrapped symbol') } hydrator.identifier(mut b, value, origin)! } else if node.kind in [.pair, .vector] { b.code.syntax_node(SyntaxNode{ kind: node.kind, renamed: true, origin: origin })! } else { atom := graph_source_atom(hydrator.source, source)! b.code.syntax_atom(atom, origin)! } hydrator.keep_index(source, target) if original != reader.no_node && !isnil(b.code.graphs) { b.code.inherit_graph_identity(b.code, original, target)! } if node.kind in [.pair, .vector] { hydrator.push(SyntaxHydrationJob{source, target}) } return target } fn (mut b Builder) hydrate_procedural_output(output Value, input &SyntaxObjectData, origins &SyntaxInputOrigins, origin reader.NodeId) !reader.NodeId { domain := b.syntax_mark_domain() mut storage := arena.new(chunk_size: 1024) defer { storage.free() } mut hydrator := new_syntax_hydrator(output, input, origins, storage, b.code.source_origin(origin), domain) source := hydrator.source root := hydrator.reference(mut b, 0)! for hydrator.pending.len > 0 { job := hydrator.pending.pop() node := graph_source_node(source, job.source)! mut result := SyntaxNode{ kind: node.kind, renamed: true, origin: b.code.source_origin(job.target) } if node.kind == .pair { car := hydrator.reference(mut b, node.car)! cdr := hydrator.reference(mut b, node.cdr)! result = SyntaxNode{ ...result, car: car, cdr: cdr } } else { mut generated := b.code.syntax_arena() start := generated.elements.len if node.count > 2147483647 - start { return failure('transformer output vector exceeds supported range') } unsafe { generated.elements.grow_len(node.count) } for i in 0 .. node.count { child := graph_source_vector_at(source, job.source, i)! generated.elements[start + i] = hydrator.reference(mut b, child)! } result = SyntaxNode{ ...result, car: reader.NodeId(start), cdr: reader.NodeId(node.count) } } b.code.generated.nodes[-int(job.target) - 2] = result } return root } fn new_syntax_hydrator(output Value, input &SyntaxObjectData, origins &SyntaxInputOrigins, storage arena.Arena, origin reader.NodeId, domain &SyntaxLexicalDomain) SyntaxHydrator { storage.push() defer { storage.pop() } mut source := &SyntaxValueSource{ root: output, storage: storage } mut hydrator := SyntaxHydrator{ source: source, input: input, origins: origins, storage: storage, origin: origin, marks: SyntaxExpansion{ domain: domain } } unsafe { source.nodes.flags.set(.noslices) hydrator.pending.flags.set(.noslices) } return hydrator } // Owner-retained domains prevent allocator address reuse from colliding with // private global binding spellings after compilation scratch is discarded. fn (mut b Builder) syntax_mark_domain() &SyntaxLexicalDomain { mut owner := b.syntax_owner() if isnil(owner) { return b.code.syntax_identity_domain() } if isnil(owner.syntax_domain) { owner.syntax_domain = &owner.syntax_domain_storage } return owner.syntax_domain } fn (b &Builder) syntax_global_count() int { return if isnil(b.code.compiler_vm) { -1 } else { unsafe { (&VM(b.code.compiler_vm)).globals.len } } } struct SyntaxOriginOverlay { boundary &Scope = unsafe { nil } slots int context &SyntaxLookupContext } fn (mut b Builder) overlay_identifier_context(base &SyntaxLookupContext, alias IdentifierAlias, current &SyntaxLookupContext, mut origins SyntaxInputOrigins) &SyntaxLookupContext { for entry in origins.contexts[voidptr(base)] or { []SyntaxOriginOverlay{} } { if voidptr(entry.boundary) == voidptr(alias.capture_scope) && entry.slots == alias.capture_slots { return entry.context } } mut cursor := ScopeRef{b.scope} mut frames := 0 for !isnil(cursor.value) && voidptr(cursor.value) != voidptr(alias.capture_scope) { if cursor.value.names.len > 0 || (!isnil(cursor.value.syntax) && cursor.value.syntax.entries.len > 0) { frames++ } cursor = ScopeRef{cursor.value.parent} } boundary := !isnil(cursor.value) && cursor.value.function.slot_count > alias.capture_slots && (cursor.value.names.len > 0 || (!isnil(cursor.value.syntax) && cursor.value.syntax.entries.len > 0)) if (!isnil(alias.capture_scope) && isnil(cursor.value)) || (frames == 0 && !boundary) { return base } context := &SyntaxLookupContext{ lexical: current.lexical globals: unsafe { base.globals } overrides: unsafe { base.overrides } private_bindings: base.private_bindings global_floor: base.global_floor global_generation: base.global_generation namespace: base.namespace implicit_syntax: base.implicit_syntax keyword_variables: unsafe { base.keyword_variables } origin: base overlay_frames: frames overlay_boundary: boundary overlay_slots: alias.capture_slots } origins.keep_context(base, SyntaxOriginOverlay{alias.capture_scope, alias.capture_slots, context}) return context } fn (mut origins SyntaxInputOrigins) keep_context(base &SyntaxLookupContext, entry SyntaxOriginOverlay) { origins.storage.push() defer { origins.storage.pop() } mut bucket := origins.contexts[voidptr(base)] or { []SyntaxOriginOverlay{} } bucket << entry origins.contexts[voidptr(base)] = bucket }