module scheme import reader import arena as alloc_arena struct SyntaxTemplate { root i32 mut: sharing &SyntaxTemplateSharing = unsafe { nil } // The same graph fragment may occur at different ellipsis depths. repeats map[u64][]SyntaxDriver } struct TemplateJob { id i32 depth int nesting int escaped bool } struct SyntaxDriver { variable i32 offset i32 } fn (tree &SyntaxTree) compile_template(root i32, pattern &SyntaxPattern) !SyntaxTemplate { return tree.compile_template_grammar(root, pattern, false) } fn (tree &SyntaxTree) compile_case_template_shape(root i32, pattern &SyntaxPattern) !SyntaxTemplate { return tree.compile_template_grammar(root, pattern, true) } fn (tree &SyntaxTree) compile_template_grammar(root i32, pattern &SyntaxPattern, consecutive bool) !SyntaxTemplate { mut template := SyntaxTemplate{ root: root } mut pending := [TemplateJob{root, 0, 0, false}] mut visits := map[u64]int{} defer { unsafe { visits.free() } } for pending.len > 0 { job := pending.pop() if job.nesting > 512 || job.depth > 512 { return failure('syntax template nesting limit exceeded') } node := tree.nodes[job.id] if !tree.unique_subtrees && node.kind in [.pair, .vector] && syntax_grammar_seen(mut visits, job.id, job.depth, job.escaped, job.nesting) { continue } match node.kind { .symbol { if !job.escaped && tree.ellipsis(job.id) { return failure('misplaced ellipsis in syntax-rules template') } if variable := pattern.indices[node.car] { if pattern.variables[variable].depth > job.depth { return failure('pattern variable needs more template ellipses') } } } .pair { if !job.escaped && tree.ellipsis(node.car) { escaped_body := tree.escaped_template(job.id)! pending << TemplateJob{escaped_body, job.depth, job.nesting + 1, true} continue } mut cursor := job.id for tree.nodes[cursor].kind == .pair { pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] if !job.escaped && tail.kind == .pair && tree.ellipsis(tail.car) { levels, after := tree.template_list_repeat(tail.cdr, consecutive) template.add_repeat_levels(tree, pattern, pair.car, job.depth, levels, consecutive)! pending << TemplateJob{pair.car, job.depth + levels, job.nesting + 1, job.escaped} cursor = after } else { pending << TemplateJob{pair.car, job.depth, job.nesting + 1, job.escaped} cursor = pair.cdr } } if tree.nodes[cursor].kind != .empty_list { pending << TemplateJob{cursor, job.depth, job.nesting + 1, job.escaped} } } .vector { mut i := 0 for i < int(node.cdr) { body := tree.elements[node.car + i] if !job.escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) { levels, after := tree.template_vector_repeat(node, i + 2, consecutive) template.add_repeat_levels(tree, pattern, body, job.depth, levels, consecutive)! pending << TemplateJob{body, job.depth + levels, job.nesting + 1, job.escaped} i = after } else { pending << TemplateJob{body, job.depth, job.nesting + 1, job.escaped} i++ } } } else {} } } if !consecutive && !tree.unique_subtrees { storage := alloc_arena.new(chunk_size: 1024) defer { release_frozen_syntax_scratch(storage) } traits, _ := tree.template_region_traits(root, pattern, storage)! template.sharing = template_sharing(tree, traits, false) } return template } fn (tree &SyntaxTree) template_list_repeat(tail i32, consecutive bool) (int, i32) { mut levels := 1 mut cursor := tail if consecutive { for tree.nodes[cursor].kind == .pair && tree.ellipsis(tree.nodes[cursor].car) { levels++ cursor = tree.nodes[cursor].cdr } } return levels, cursor } fn (tree &SyntaxTree) template_vector_repeat(node SyntaxTreeNode, start int, consecutive bool) (int, int) { mut levels := 1 mut cursor := start if consecutive { for cursor < int(node.cdr) && tree.ellipsis(tree.elements[node.car + cursor]) { levels++ cursor++ } } return levels, cursor } fn (mut template SyntaxTemplate) add_repeat(tree &SyntaxTree, pattern &SyntaxPattern, body i32, depth int) ! { template.add_repeat_levels(tree, pattern, body, depth, 1, false)! } fn (mut template SyntaxTemplate) add_repeat_levels(tree &SyntaxTree, pattern &SyntaxPattern, body i32, depth int, levels int, consecutive bool) ! { if levels > 512 - depth { return failure('syntax template nesting limit exceeded') } for level in 0 .. levels { template.add_repeat_driver(tree, pattern, body, depth + level, depth + levels, consecutive)! } } fn (mut template SyntaxTemplate) add_repeat_driver(tree &SyntaxTree, pattern &SyntaxPattern, body i32, depth int, body_depth int, consecutive bool) ! { key := template_repeat_key(body, depth, body_depth) if key in template.repeats { return } mut drivers := []SyntaxDriver{} mut seen := map[u64]bool{} mut pending := [TemplateJob{body, body_depth, 0, false}] mut visits := map[u64]int{} defer { unsafe { visits.free() } } for pending.len > 0 { job := pending.pop() if job.depth > 512 { return failure('syntax template nesting limit exceeded') } node := tree.nodes[job.id] if !tree.unique_subtrees && node.kind in [.pair, .vector] && syntax_grammar_seen(mut visits, job.id, job.depth, job.escaped, 0) { continue } match node.kind { .symbol { if variable := pattern.indices[node.car] { rank := pattern.variables[variable].depth offset := job.depth - rank if rank > 0 && offset >= 0 && offset <= depth { coordinate := syntax_capture_key(variable, i32(offset)) if coordinate !in seen { seen[coordinate] = true drivers << SyntaxDriver{i32(variable), i32(offset)} } } } } .pair { if !job.escaped && tree.ellipsis(node.car) { pending << TemplateJob{tree.escaped_template(job.id)!, job.depth, job.nesting + 1, true} continue } mut cursor := job.id for tree.nodes[cursor].kind == .pair { pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] repeat := !job.escaped && tail.kind == .pair && tree.ellipsis(tail.car) if repeat { nested, after := tree.template_list_repeat(tail.cdr, consecutive) pending << TemplateJob{pair.car, job.depth + nested, 0, job.escaped} cursor = after } else { pending << TemplateJob{pair.car, job.depth, 0, job.escaped} cursor = pair.cdr } } if tree.nodes[cursor].kind != .empty_list { pending << TemplateJob{cursor, job.depth, 0, job.escaped} } } .vector { mut i := 0 for i < int(node.cdr) { body_id := tree.elements[node.car + i] repeat := !job.escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) if repeat { nested, after := tree.template_vector_repeat(node, i + 2, consecutive) pending << TemplateJob{body_id, job.depth + nested, 0, job.escaped} i = after } else { pending << TemplateJob{body_id, job.depth, 0, job.escaped} i++ } } } else {} } } if drivers.len == 0 { return failure('template ellipsis needs a repeated pattern variable') } template.repeats[key] = drivers } struct SyntaxExpansion { origin reader.NodeId mut: indices []int symbols map[i32]reader.NodeId atoms map[i32]reader.NodeId family string family_context i32 family_wrap &SyntaxWrap = unsafe { nil } wrapped_families &RecordWrappedFamilies = unsafe { nil } families &RecordExpansionGroups = unsafe { nil } domain &SyntaxLexicalDomain = unsafe { nil } wrap &SyntaxWrap = unsafe { nil } other_wraps &SyntaxWrapApplications = unsafe { nil } memo &SyntaxTemplateMemo[reader.NodeId] = unsafe { nil } } fn (template &SyntaxTemplate) repeat_length(body i32, state &SyntaxExpansion, captures &SyntaxCaptures) !int { return template.repeat_length_at(body, state.indices, captures) } fn (template &SyntaxTemplate) repeat_length_at(body i32, indices []int, captures &SyntaxCaptures) !int { return template.repeat_length_levels(body, indices, captures, 1) } fn template_repeat_key(body i32, depth int, body_depth int) u64 { return (u64(u32(body)) << 32) | (u64(depth) << 16) | u64(body_depth) } fn (template &SyntaxTemplate) repeat_length_levels(body i32, indices []int, captures &SyntaxCaptures, levels int) !int { depth := indices.len drivers := template.repeats[template_repeat_key(body, depth, depth + levels)] or { return failure('invalid compiled template repetition') } mut count := -1 for driver in drivers { path := captures.coordinate(indices, int(driver.offset))! width := captures.items[syntax_capture_key(int(driver.variable), path)] or { return failure('missing syntax repetition dimension') } if count >= 0 && count != int(width) { return failure('template repetition lengths do not match') } count = int(width) } return count } fn (captures &SyntaxCaptures) coordinate(indices []int, offset int) !i32 { mut path := i32(0) for i in offset .. indices.len { key := (u64(u32(path)) << 32) | u64(u32(indices[i])) path = captures.paths[key] or { return failure('missing syntax repetition coordinate') } } return path } fn (mut b Builder) expand_syntax_template(tree &SyntaxTree, pattern &SyntaxPattern, template &SyntaxTemplate, captures &SyntaxCaptures, origin reader.NodeId) !reader.NodeId { mut state := SyntaxExpansion{ origin: b.code.source_origin(origin) } defer { unsafe { state.symbols.free() state.atoms.free() state.indices.free() } } if !isnil(template.sharing) { storage := alloc_arena.new(chunk_size: 1024) defer { release_frozen_syntax_scratch(storage) } state.memo = new_syntax_template_memo[reader.NodeId](storage, template.sharing) return b.expand_template_node(tree, pattern, template, captures, template.root, false, mut state) } return b.expand_template_node(tree, pattern, template, captures, template.root, false, mut state) } fn (mut b Builder) expand_template_node(tree &SyntaxTree, pattern &SyntaxPattern, template &SyntaxTemplate, captures &SyntaxCaptures, id i32, escaped bool, mut state SyntaxExpansion) !reader.NodeId { node := tree.nodes[id] 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 } } match node.kind { .symbol { if variable := pattern.indices[node.car] { depth := pattern.variables[variable].depth path := captures.coordinate(state.indices, state.indices.len - depth)! key := syntax_capture_key(variable, path) return reader.NodeId(captures.items[key] or { return failure('missing syntax pattern capture') }) } if cached := state.symbols[node.car] { return cached } original := tree.identifiers[node.car] info := SyntaxIdentifier{ ...original context: if !isnil(original.context) { original.context } else { tree.context } } name := b.template_record_identifier(info, tree.record_context(node.car), mut state)! result := b.code.syntax_symbol(name, info.raw_name, state.origin)! state.symbols[node.car] = result return result } .pair { if !escaped && tree.ellipsis(node.car) { result := b.expand_template_node(tree, pattern, template, captures, tree.escaped_template(id)!, true, mut state)! if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } return result } // Build the private result forward. No temporary list of cars, no // reverse copy, and no native recursion along a flat template cdr. mut root := reader.nil_node mut last := reader.no_node mut cursor := id mut spine := &SyntaxTemplateSpine[reader.NodeId](unsafe { nil }) defer { if !isnil(spine) { state.memo.depth-- } } mut end := reader.no_node for tree.nodes[cursor].kind == .pair { 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; break } if isnil(spine) { spine = state.memo.acquire_spine() } state.memo.note_spine(mut spine, tail_key, if last == reader.no_node { reader.nil_node } else { last }) } } pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] repeat := !escaped && tail.kind == .pair && tree.ellipsis(tail.car) count := if repeat { template.repeat_length(pair.car, state, captures)! } else { 1 } for i in 0 .. count { if repeat { state.indices << i } previous := if repeat && !isnil(state.memo) { state.memo.enter(i)! } else { u32(0) } car := b.expand_template_node(tree, pattern, template, captures, pair.car, escaped, mut state)! if repeat && !isnil(state.memo) { state.memo.path = previous } if repeat { state.indices.pop() } cell := b.code.syntax_pair(car, reader.nil_node, state.origin)! if last == reader.no_node { root = cell } else { index := -int(last) - 2 b.code.generated.nodes[index] = SyntaxNode{ ...b.code.generated.nodes[index], cdr: cell } } last = cell } cursor = if repeat { tail.cdr } else { pair.cdr } } tail := if end != reader.no_node { end } else { b.expand_template_node(tree, pattern, template, captures, cursor, escaped, mut state)! } if last == reader.no_node { root = tail } else { index := -int(last) - 2 b.code.generated.nodes[index] = SyntaxNode{ ...b.code.generated.nodes[index], cdr: tail } } if !isnil(spine) { for i, tail_key in spine.keys { previous := spine.previous[i] value := if previous == reader.nil_node { root } else { b.code.generated.nodes[-int(previous) - 2].cdr } state.memo.keep(tail_key, value) } } if cache_key != no_template_memo_key { state.memo.keep(cache_key, root) } return root } .vector { mut count := 0 mut i := 0 for i < int(node.cdr) { body := tree.elements[node.car + i] repeat := !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) width := if repeat { template.repeat_length(body, state, captures)! } else { 1 } if width > 2147483647 - count { return failure('expanded syntax vector exceeds supported range') } count += width i += if repeat { 2 } else { 1 } } mut arena := b.code.syntax_arena() if count > 2147483647 - arena.elements.len { return failure('expanded syntax vector exceeds supported range') } start := arena.elements.len // Reserve once and fill directly; recursive vectors may grow the arena, // so retain the integer offset rather than a pointer or borrowed slice. unsafe { arena.elements.grow_len(count) } i = 0 mut output := start for i < int(node.cdr) { body := tree.elements[node.car + i] repeat := !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) width := if repeat { template.repeat_length(body, state, captures)! } else { 1 } for index in 0 .. width { if repeat { state.indices << index } previous := if repeat && !isnil(state.memo) { state.memo.enter(index)! } else { u32(0) } child := b.expand_template_node(tree, pattern, template, captures, body, escaped, mut state)! if repeat && !isnil(state.memo) { state.memo.path = previous } if repeat { state.indices.pop() } arena.elements[output] = child output++ } i += if repeat { 2 } else { 1 } } result := b.code.syntax_node(SyntaxNode{ kind: .vector, renamed: true, car: reader.NodeId(start), cdr: reader.NodeId(count), origin: state.origin })! if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } return result } .empty_list { return reader.nil_node } else { if cached := state.atoms[id] { return cached } result := b.code.syntax_atom(tree.values[node.car], state.origin)! state.atoms[id] = result return result } } } fn (tree &SyntaxTree) escaped_template(id i32) !i32 { wrapper := tree.nodes[tree.nodes[id].cdr] if wrapper.kind != .pair || tree.nodes[wrapper.cdr].kind != .empty_list { return failure('ellipsis escape needs exactly one template') } return wrapper.car }