module scheme import arena // A syntax expression keeps definition-site metadata and captures by identity. // Only maximal constant regions are registered; no per-expansion copy of them // or of captured input graphs is necessary. struct SyntaxCaseTemplate { data &SyntaxObjectData pattern &SyntaxPattern shape SyntaxTemplate constants map[u64]Value splices []bool } fn template_region_key(id i32, escaped bool) u64 { return (u64(u32(id)) << 1) | u64(escaped) } fn template_analysis_push(mut pending []i64, storage arena.Arena, key i64) { if pending.len == pending.cap { reserve_template_analysis(mut pending, storage) } pending << key } fn reserve_template_analysis(mut pending []i64, storage arena.Arena) { storage.push() defer { storage.pop() } pending.ensure_cap(pending.len + 1) } fn new_template_analysis(storage arena.Arena, count int) ([]u8, []i64) { storage.push() defer { storage.pop() } traits := []u8{len: count * 2} mut pending := []i64{cap: 32} unsafe { pending.flags.set(.noslices) } return traits, pending } // Flags: ready=1, contains variable=2, removes escape=4, collected=8. // Iterative postorder also handles long constant spines without C recursion. fn (data &SyntaxObjectData) compile_case_template(root i32, pattern &SyntaxPattern) !SyntaxCaseTemplate { return data.compile_case_template_with_splices(root, pattern, []) } fn (data &SyntaxObjectData) compile_case_template_with_splices(root i32, pattern &SyntaxPattern, splices []bool) !SyntaxCaseTemplate { if root < 0 || root >= data.tree.nodes.len { return failure('invalid syntax template root') } data.tree.require_finite_transformer()! mut shape := data.tree.compile_case_template_shape(root, pattern)! storage := arena.new(chunk_size: 1024) defer { release_frozen_syntax_scratch(storage) } mut traits, mut pending := data.tree.template_region_traits(root, pattern, storage)! if !data.tree.unique_subtrees { shape.sharing = template_sharing(data.tree, traits, true) } mut constants := map[u64]Value{} mut normalizer := &SyntaxConstantNormalizer(unsafe { nil }) template_analysis_push(mut pending, storage, i64(template_region_key(root, false))) for pending.len > 0 { key := u64(pending.pop()) if traits[key] & 8 != 0 { continue } traits[key] |= 8 id := i32(key >> 1) escaped := key & 1 != 0 if traits[key] & 2 == 0 { if traits[key] & 4 == 0 { constants[key] = wrapped_syntax(data, int(id))! } else { if isnil(normalizer) { normalizer = new_syntax_constant_normalizer(data, storage) } constants[key] = normalizer.reference(id, escaped)! } continue } node := data.tree.nodes[id] if node.kind == .pair { if !escaped && data.tree.ellipsis(node.car) { template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.escaped_template(id)!, true))) } else { template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.template_region_tail(node.cdr, escaped), escaped))) template_analysis_push(mut pending, storage, i64(template_region_key(node.car, escaped))) } } else if node.kind == .vector { for i in 0 .. node.cdr { template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.elements[node.car + i], escaped))) } } } if !isnil(normalizer) { normalizer.finish()! } return SyntaxCaseTemplate{data, pattern, shape, constants, splices} } struct SyntaxConstantNormalizer { source &SyntaxObjectData output &SyntaxObjectData storage arena.Arena mut: indices map[u64]i32 pending []i64 } fn new_syntax_constant_normalizer(source &SyntaxObjectData, storage arena.Arena) &SyntaxConstantNormalizer { // Published identifier/value tables are immutable and retain their original // owner. Only structural rows that remove an escape wrapper are rebuilt. output := &SyntaxObjectData{ tree: &SyntaxTree{ identifiers: unsafe { source.tree.identifiers } values: unsafe { source.tree.values } record_contexts: source.tree.record_contexts ellipsis_identifier: source.tree.ellipsis_identifier ellipsis_literal: source.tree.ellipsis_literal } owner: source.owner context: source.context } storage.push() defer { storage.pop() } mut normalizer := &SyntaxConstantNormalizer{ source: source, output: output, storage: storage } unsafe { normalizer.pending.flags.set(.noslices) } return normalizer } fn (mut normalizer SyntaxConstantNormalizer) reference(input i32, escaping bool) !Value { mut id := input mut escaped := escaping if !escaped && normalizer.source.tree.nodes[id].kind == .pair && normalizer.source.tree.ellipsis(normalizer.source.tree.nodes[id].car) { id = normalizer.source.tree.escaped_template(id)! escaped = true } key := template_region_key(id, escaped) if index := normalizer.indices[key] { return wrapped_syntax(normalizer.output, int(index)) } mut tree := normalizer.output.tree if tree.nodes.len >= 2147483647 { return failure('syntax template exceeds supported range') } index := i32(tree.nodes.len) tree.nodes << SyntaxTreeNode{} normalizer.keep_index(key, index) template_analysis_push(mut normalizer.pending, normalizer.storage, i64(key)) return wrapped_syntax(normalizer.output, int(index)) } fn (mut normalizer SyntaxConstantNormalizer) keep_index(key u64, index i32) { normalizer.storage.push() defer { normalizer.storage.pop() } normalizer.indices[key] = index } fn (mut normalizer SyntaxConstantNormalizer) finish() ! { for normalizer.pending.len > 0 { key := u64(normalizer.pending.pop()) index := normalizer.indices[key] escaped := key & 1 != 0 node := normalizer.source.tree.nodes[key >> 1] mut out := node if node.kind == .pair { out = SyntaxTreeNode{ kind: .pair, car: normalizer.reference(node.car, escaped)!.syntax_index, cdr: normalizer.reference(node.cdr, escaped)!.syntax_index } } else if node.kind == .vector { mut tree := normalizer.output.tree start := tree.elements.len // All new slots are initialized below before publication. unsafe { tree.elements.grow_len(int(node.cdr)) } for i in 0 .. node.cdr { tree.elements[start + i] = normalizer.reference(normalizer.source.tree.elements[node.car + i], escaped)!.syntax_index } out = SyntaxTreeNode{ kind: .vector, car: i32(start), cdr: node.cdr } } mut tree := normalizer.output.tree tree.nodes[index] = out } } struct SyntaxCaseRenderState { storage arena.Arena mut: indices []int emissions []&SyntaxCaseEmission depth int memo &SyntaxTemplateMemo[Value] = unsafe { nil } } fn (mut state SyntaxCaseRenderState) push(index int) { if state.indices.len == state.indices.cap { state.reserve_index() } state.indices << index } fn (mut state SyntaxCaseRenderState) reserve_index() { state.storage.push() defer { state.storage.pop() } state.indices.ensure_cap(state.indices.len + 1) } fn (template &SyntaxCaseTemplate) expand[T](captures &T) !Value { if voidptr(template.pattern) != voidptr(captures.pattern) { return failure('syntax template capture pattern mismatch') } root := template.shape.root if constant := template.constants[template_region_key(root, false)] { return constant } if template.data.tree.nodes[root].kind == .symbol { return template.capture(root, []int{}, captures) } storage := arena.new(chunk_size: 1024) defer { release_frozen_syntax_scratch(storage) } mut state := new_syntax_case_render_state(storage) if !isnil(template.shape.sharing) { state.memo = new_syntax_template_memo[Value](storage, template.shape.sharing) } return template.render(root, false, captures, mut state) } fn (template &SyntaxCaseTemplate) capture[T](id i32, indices []int, captures &T) !Value { variable := template.pattern.indices[template.data.tree.nodes[id].car] or { return failure('invalid syntax template variable') } rank := template.pattern.variables[variable].depth return template_capture_value(captures, variable, indices, indices.len - rank) } fn (template &SyntaxCaseTemplate) splice(id i32) bool { if template.splices.len == 0 { return false } node := template.data.tree.nodes[id] return node.kind == .symbol && template.splices[node.car] } fn (template &SyntaxCaseTemplate) element_count[T](id i32, captures &T, mut state SyntaxCaseRenderState) !int { if !template.splice(id) { return 1 } value := template.capture(id, state.indices, captures)! return syntax_spine_length(value) or { return failure('unsyntax-splicing requires a finite proper list') } } // Wrapped syntax and partially wrapped lists share the existing constant-space // spine validation. No datum conversion or temporary element array is needed. fn (template &SyntaxCaseTemplate) emit_element[T](id i32, escaped bool, captures &T, mut state SyntaxCaseRenderState, mut emission SyntaxCaseEmission) ! { if !template.splice(id) { emission.push(template.render(id, escaped, captures, mut state)!) return } mut value := template.capture(id, state.indices, captures)! count := syntax_spine_length(value) or { return failure('unsyntax-splicing requires a finite proper list') } for _ in 0 .. count { if value.tag == .pair { pair := value.pair_pointer() emission.push(pair.car) value = pair.cdr } else { emission.push(syntax_car(value)!) value = syntax_cdr(value)! } } } fn (template &SyntaxCaseTemplate) render[T](id i32, escaped bool, captures &T, mut state SyntaxCaseRenderState) !Value { if constant := template.constants[template_region_key(id, escaped)] { return constant } tree := template.data.tree node := tree.nodes[id] if node.kind == .symbol { return template.capture(id, state.indices, captures) } cache_key := if !isnil(state.memo) && node.kind in [.pair, .vector] { state.memo.key(id, escaped) } else { no_template_memo_key } if cache_key != no_template_memo_key { if cached := state.memo.completed[cache_key] { return cached } } if node.kind == .pair { if !escaped && tree.ellipsis(node.car) { result := template.render(tree.escaped_template(id)!, true, captures, mut state)! if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } return result } mut emission := state.acquire_emission(unsafe { nil }) defer { state.depth-- } mut cursor := id mut spine := &SyntaxTemplateSpine[Value](unsafe { nil }) defer { if !isnil(spine) { state.memo.depth-- } } mut end := unspecified() mut has_end := false for tree.nodes[cursor].kind == .pair { if constant := template.constants[template_region_key(cursor, escaped)] { end = constant has_end = true break } if cursor != id && !isnil(state.memo) { tail_key := state.memo.key(cursor, escaped) if tail_key != no_template_memo_key { if cached := state.memo.completed[tail_key] { end = cached; has_end = true; break } if isnil(spine) { spine = state.memo.acquire_spine() } previous := if isnil(emission.list.tail) { unspecified() } else { payload_value(.pair, emission.list.tail) } state.memo.note_spine(mut spine, tail_key, previous) } } pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] if !escaped && tail.kind == .pair && tree.ellipsis(tail.car) { levels, after := tree.template_list_repeat(tail.cdr, true) template.emit_repeat(pair.car, levels, captures, mut state, mut emission)! cursor = after } else { template.emit_element(pair.car, escaped, captures, mut state, mut emission)! cursor = pair.cdr } } tail := if has_end { end } else { template.render(cursor, escaped, captures, mut state)! } result := emission.list.finish(tail) if !isnil(spine) { for i, tail_key in spine.keys { previous := spine.previous[i] state.memo.keep(tail_key, if previous.tag == .pair { previous.pair_pointer().cdr } else { result }) } } if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } return result } if node.kind == .vector { mut count := 0 mut i := 0 for i < int(node.cdr) { body := tree.elements[node.car + i] if !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) { levels, after := tree.template_vector_repeat(node, i + 2, true) width := template.repeat_count(body, levels, captures, mut state)! if width > max_int - count { return failure('syntax template vector exceeds supported range') } count += width i = after } else { width := template.element_count(body, captures, mut state)! if width > max_int - count { return failure('syntax template vector exceeds supported range') } count += width i++ } } // One exact element array, filled directly. vector() would clone it. mut result := &Vector{ items: []Value{len: count} } mut emission := state.acquire_emission(result) defer { state.depth-- } i = 0 for i < int(node.cdr) { body := tree.elements[node.car + i] if !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) { levels, after := tree.template_vector_repeat(node, i + 2, true) template.emit_repeat(body, levels, captures, mut state, mut emission)! i = after } else { template.emit_element(body, escaped, captures, mut state, mut emission)! i++ } } value := payload_value(.vector, result) if cache_key != no_template_memo_key { state.memo.keep(cache_key, value) } return value } return failure('invalid compiled syntax template') } struct SyntaxCaseEmission { mut: list ListBuilder vector &Vector = unsafe { nil } index int } fn (mut emission SyntaxCaseEmission) push(value Value) { if isnil(emission.vector) { emission.list.push(value) } else { emission.vector.items[emission.index] = value emission.index++ } } fn (template &SyntaxCaseTemplate) emit_repeat[T](body i32, levels int, captures &T, mut state SyntaxCaseRenderState, mut emission SyntaxCaseEmission) ! { width := template_repeat_length(&template.shape, body, state.indices, captures, levels)! for i in 0 .. width { state.push(i) previous := if !isnil(state.memo) { state.memo.enter(i)! } else { u32(0) } if levels > 1 { template.emit_repeat(body, levels - 1, captures, mut state, mut emission)! } else { template.emit_element(body, false, captures, mut state, mut emission)! } if !isnil(state.memo) { state.memo.path = previous } state.indices.pop() } } fn (template &SyntaxCaseTemplate) repeat_count[T](body i32, levels int, captures &T, mut state SyntaxCaseRenderState) !int { width := template_repeat_length(&template.shape, body, state.indices, captures, levels)! if levels == 1 && !template.splice(body) { return width } mut count := 0 for i in 0 .. width { state.push(i) amount := if levels == 1 { template.element_count(body, captures, mut state)! } else { template.repeat_count(body, levels - 1, captures, mut state)! } state.indices.pop() if amount > max_int - count { return failure('syntax template vector exceeds supported range') } count += amount } return count } // A cdr immediately after a repeated body starts with grammar markers, // rather than another template. They never become output fragments. fn (tree &SyntaxTree) template_region_tail(tail i32, escaped bool) i32 { if !escaped && tree.nodes[tail].kind == .pair && tree.ellipsis(tree.nodes[tail].car) { _, after := tree.template_list_repeat(tree.nodes[tail].cdr, true) return after } return tail } // Stable cells live in the one-call scratch arena. Child rendering borrows // a different cell, and siblings reuse it. Registry growth cannot move cells. fn (mut state SyntaxCaseRenderState) acquire_emission(vector &Vector) &SyntaxCaseEmission { if state.depth == state.emissions.len { state.add_emission() } mut emission := state.emissions[state.depth] state.depth++ emission.list.head = nil_value() emission.list.tail = unsafe { nil } emission.vector = vector emission.index = 0 return emission } fn (mut state SyntaxCaseRenderState) add_emission() { state.storage.push() defer { state.storage.pop() } state.emissions << &SyntaxCaseEmission{} } fn new_syntax_case_render_state(storage arena.Arena) SyntaxCaseRenderState { storage.push() defer { storage.pop() } mut state := SyntaxCaseRenderState{ storage: storage } unsafe { state.indices.flags.set(.noslices) state.emissions.flags.set(.noslices) } return state }