module scheme import arena // Shared grammar nodes can have different ellipsis contexts. A validation // from a shallower structural nesting cannot establish the 512-level limit // for a deeper occurrence of the same grammar state. fn syntax_grammar_seen(mut deepest map[u64]int, id i32, depth int, escaped bool, nesting int) bool { key := (u64(u32(id)) << 32) | (u64(depth) << 1) | u64(escaped) if previous := deepest[key] { if previous >= nesting { return true } } deepest[key] = nesting return false } fn frozen_syntax_job(mut pending []i32, storage arena.Arena, id i32) { if pending.len == pending.cap { reserve_frozen_syntax_jobs(mut pending, storage) } pending << id } fn reserve_frozen_syntax_jobs(mut pending []i32, storage arena.Arena) { storage.push() defer { storage.pop() } pending.ensure_cap(pending.len + 1) } fn new_frozen_syntax_work(storage arena.Arena, count int) ([]u8, []i32) { storage.push() defer { storage.pop() } marks := []u8{len: count} mut pending := []i32{cap: 32} unsafe { pending.flags.set(.noslices) } return marks, pending } fn release_frozen_syntax_scratch(storage arena.Arena) { mut owner := storage owner.free() } // syntax-rules patterns/templates have finite recursive grammar (R7RS ยง7.1.5). // A macro can capture and quote a cyclic datum, but a transformer definition // cannot itself contain a circular pattern/template. Check once after freezing, // before the existing tree-oriented pattern and ellipsis walks can run. // Dense marks cover just this transformer's compact frozen graph, not its source. fn (tree &SyntaxTree) require_finite_transformer() ! { storage := arena.new(chunk_size: 1024) defer { release_frozen_syntax_scratch(storage) } mut marks, mut pending := new_frozen_syntax_work(storage, tree.nodes.len) for root in 0 .. tree.nodes.len { if marks[root] != 0 { continue } frozen_syntax_job(mut pending, storage, i32(root)) for pending.len > 0 { visit := pending.pop() id := if visit < 0 { ~visit } else { visit } if visit < 0 { marks[id] = 2 continue } if marks[id] == 1 { return failure('circular syntax-rules transformer') } if marks[id] == 2 { continue } node := tree.nodes[id] if node.kind !in [.pair, .vector] { marks[id] = 2 continue } marks[id] = 1 frozen_syntax_job(mut pending, storage, ~id) if node.kind == .pair { frozen_syntax_job(mut pending, storage, node.cdr) frozen_syntax_job(mut pending, storage, node.car) } else { for i in 0 .. node.cdr { frozen_syntax_job(mut pending, storage, tree.elements[node.car + i]) } } } } }