| 1 | module scheme |
| 2 | |
| 3 | import arena |
| 4 | |
| 5 | // A syntax expression keeps definition-site metadata and captures by identity. |
| 6 | // Only maximal constant regions are registered; no per-expansion copy of them |
| 7 | // or of captured input graphs is necessary. |
| 8 | struct SyntaxCaseTemplate { |
| 9 | data &SyntaxObjectData |
| 10 | pattern &SyntaxPattern |
| 11 | shape SyntaxTemplate |
| 12 | constants map[u64]Value |
| 13 | splices []bool |
| 14 | } |
| 15 | |
| 16 | fn template_region_key(id i32, escaped bool) u64 { |
| 17 | return (u64(u32(id)) << 1) | u64(escaped) |
| 18 | } |
| 19 | |
| 20 | fn template_analysis_push(mut pending []i64, storage arena.Arena, key i64) { |
| 21 | if pending.len == pending.cap { |
| 22 | reserve_template_analysis(mut pending, storage) |
| 23 | } |
| 24 | pending << key |
| 25 | } |
| 26 | |
| 27 | fn reserve_template_analysis(mut pending []i64, storage arena.Arena) { |
| 28 | storage.push() |
| 29 | defer { storage.pop() } |
| 30 | pending.ensure_cap(pending.len + 1) |
| 31 | } |
| 32 | |
| 33 | fn new_template_analysis(storage arena.Arena, count int) ([]u8, []i64) { |
| 34 | storage.push() |
| 35 | defer { storage.pop() } |
| 36 | traits := []u8{len: count * 2} |
| 37 | mut pending := []i64{cap: 32} |
| 38 | unsafe { pending.flags.set(.noslices) } |
| 39 | return traits, pending |
| 40 | } |
| 41 | |
| 42 | // Flags: ready=1, contains variable=2, removes escape=4, collected=8. |
| 43 | // Iterative postorder also handles long constant spines without C recursion. |
| 44 | fn (data &SyntaxObjectData) compile_case_template(root i32, pattern &SyntaxPattern) !SyntaxCaseTemplate { |
| 45 | return data.compile_case_template_with_splices(root, pattern, []) |
| 46 | } |
| 47 | |
| 48 | fn (data &SyntaxObjectData) compile_case_template_with_splices(root i32, pattern &SyntaxPattern, splices []bool) !SyntaxCaseTemplate { |
| 49 | if root < 0 || root >= data.tree.nodes.len { return failure('invalid syntax template root') } |
| 50 | data.tree.require_finite_transformer()! |
| 51 | mut shape := data.tree.compile_case_template_shape(root, pattern)! |
| 52 | storage := arena.new(chunk_size: 1024) |
| 53 | defer { release_frozen_syntax_scratch(storage) } |
| 54 | mut traits, mut pending := data.tree.template_region_traits(root, pattern, storage)! |
| 55 | if !data.tree.unique_subtrees { shape.sharing = template_sharing(data.tree, traits, true) } |
| 56 | |
| 57 | mut constants := map[u64]Value{} |
| 58 | mut normalizer := &SyntaxConstantNormalizer(unsafe { nil }) |
| 59 | template_analysis_push(mut pending, storage, i64(template_region_key(root, false))) |
| 60 | for pending.len > 0 { |
| 61 | key := u64(pending.pop()) |
| 62 | if traits[key] & 8 != 0 { continue } |
| 63 | traits[key] |= 8 |
| 64 | id := i32(key >> 1) |
| 65 | escaped := key & 1 != 0 |
| 66 | if traits[key] & 2 == 0 { |
| 67 | if traits[key] & 4 == 0 { |
| 68 | constants[key] = wrapped_syntax(data, int(id))! |
| 69 | } else { |
| 70 | if isnil(normalizer) { normalizer = new_syntax_constant_normalizer(data, storage) } |
| 71 | constants[key] = normalizer.reference(id, escaped)! |
| 72 | } |
| 73 | continue |
| 74 | } |
| 75 | node := data.tree.nodes[id] |
| 76 | if node.kind == .pair { |
| 77 | if !escaped && data.tree.ellipsis(node.car) { |
| 78 | template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.escaped_template(id)!, true))) |
| 79 | } else { |
| 80 | template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.template_region_tail(node.cdr, escaped), escaped))) |
| 81 | template_analysis_push(mut pending, storage, i64(template_region_key(node.car, escaped))) |
| 82 | } |
| 83 | } else if node.kind == .vector { |
| 84 | for i in 0 .. node.cdr { |
| 85 | template_analysis_push(mut pending, storage, i64(template_region_key(data.tree.elements[node.car + i], escaped))) |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | if !isnil(normalizer) { normalizer.finish()! } |
| 90 | return SyntaxCaseTemplate{data, pattern, shape, constants, splices} |
| 91 | } |
| 92 | |
| 93 | struct SyntaxConstantNormalizer { |
| 94 | source &SyntaxObjectData |
| 95 | output &SyntaxObjectData |
| 96 | storage arena.Arena |
| 97 | mut: |
| 98 | indices map[u64]i32 |
| 99 | pending []i64 |
| 100 | } |
| 101 | |
| 102 | fn new_syntax_constant_normalizer(source &SyntaxObjectData, storage arena.Arena) &SyntaxConstantNormalizer { |
| 103 | // Published identifier/value tables are immutable and retain their original |
| 104 | // owner. Only structural rows that remove an escape wrapper are rebuilt. |
| 105 | output := &SyntaxObjectData{ |
| 106 | tree: &SyntaxTree{ |
| 107 | identifiers: unsafe { source.tree.identifiers } |
| 108 | values: unsafe { source.tree.values } |
| 109 | record_contexts: source.tree.record_contexts |
| 110 | ellipsis_identifier: source.tree.ellipsis_identifier |
| 111 | ellipsis_literal: source.tree.ellipsis_literal |
| 112 | } |
| 113 | owner: source.owner |
| 114 | context: source.context |
| 115 | } |
| 116 | storage.push() |
| 117 | defer { storage.pop() } |
| 118 | mut normalizer := &SyntaxConstantNormalizer{ source: source, output: output, storage: storage } |
| 119 | unsafe { normalizer.pending.flags.set(.noslices) } |
| 120 | return normalizer |
| 121 | } |
| 122 | |
| 123 | fn (mut normalizer SyntaxConstantNormalizer) reference(input i32, escaping bool) !Value { |
| 124 | mut id := input |
| 125 | mut escaped := escaping |
| 126 | if !escaped && normalizer.source.tree.nodes[id].kind == .pair && normalizer.source.tree.ellipsis(normalizer.source.tree.nodes[id].car) { |
| 127 | id = normalizer.source.tree.escaped_template(id)! |
| 128 | escaped = true |
| 129 | } |
| 130 | key := template_region_key(id, escaped) |
| 131 | if index := normalizer.indices[key] { return wrapped_syntax(normalizer.output, int(index)) } |
| 132 | mut tree := normalizer.output.tree |
| 133 | if tree.nodes.len >= 2147483647 { return failure('syntax template exceeds supported range') } |
| 134 | index := i32(tree.nodes.len) |
| 135 | tree.nodes << SyntaxTreeNode{} |
| 136 | normalizer.keep_index(key, index) |
| 137 | template_analysis_push(mut normalizer.pending, normalizer.storage, i64(key)) |
| 138 | return wrapped_syntax(normalizer.output, int(index)) |
| 139 | } |
| 140 | |
| 141 | fn (mut normalizer SyntaxConstantNormalizer) keep_index(key u64, index i32) { |
| 142 | normalizer.storage.push() |
| 143 | defer { normalizer.storage.pop() } |
| 144 | normalizer.indices[key] = index |
| 145 | } |
| 146 | |
| 147 | fn (mut normalizer SyntaxConstantNormalizer) finish() ! { |
| 148 | for normalizer.pending.len > 0 { |
| 149 | key := u64(normalizer.pending.pop()) |
| 150 | index := normalizer.indices[key] |
| 151 | escaped := key & 1 != 0 |
| 152 | node := normalizer.source.tree.nodes[key >> 1] |
| 153 | mut out := node |
| 154 | if node.kind == .pair { |
| 155 | out = SyntaxTreeNode{ kind: .pair, car: normalizer.reference(node.car, escaped)!.syntax_index, cdr: normalizer.reference(node.cdr, escaped)!.syntax_index } |
| 156 | } else if node.kind == .vector { |
| 157 | mut tree := normalizer.output.tree |
| 158 | start := tree.elements.len |
| 159 | // All new slots are initialized below before publication. |
| 160 | unsafe { tree.elements.grow_len(int(node.cdr)) } |
| 161 | for i in 0 .. node.cdr { |
| 162 | tree.elements[start + i] = normalizer.reference(normalizer.source.tree.elements[node.car + i], escaped)!.syntax_index |
| 163 | } |
| 164 | out = SyntaxTreeNode{ kind: .vector, car: i32(start), cdr: node.cdr } |
| 165 | } |
| 166 | mut tree := normalizer.output.tree |
| 167 | tree.nodes[index] = out |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | struct SyntaxCaseRenderState { |
| 172 | storage arena.Arena |
| 173 | mut: |
| 174 | indices []int |
| 175 | emissions []&SyntaxCaseEmission |
| 176 | depth int |
| 177 | memo &SyntaxTemplateMemo[Value] = unsafe { nil } |
| 178 | } |
| 179 | |
| 180 | fn (mut state SyntaxCaseRenderState) push(index int) { |
| 181 | if state.indices.len == state.indices.cap { |
| 182 | state.reserve_index() |
| 183 | } |
| 184 | state.indices << index |
| 185 | } |
| 186 | |
| 187 | fn (mut state SyntaxCaseRenderState) reserve_index() { |
| 188 | state.storage.push() |
| 189 | defer { state.storage.pop() } |
| 190 | state.indices.ensure_cap(state.indices.len + 1) |
| 191 | } |
| 192 | |
| 193 | fn (template &SyntaxCaseTemplate) expand[T](captures &T) !Value { |
| 194 | if voidptr(template.pattern) != voidptr(captures.pattern) { |
| 195 | return failure('syntax template capture pattern mismatch') |
| 196 | } |
| 197 | root := template.shape.root |
| 198 | if constant := template.constants[template_region_key(root, false)] { return constant } |
| 199 | if template.data.tree.nodes[root].kind == .symbol { |
| 200 | return template.capture(root, []int{}, captures) |
| 201 | } |
| 202 | storage := arena.new(chunk_size: 1024) |
| 203 | defer { release_frozen_syntax_scratch(storage) } |
| 204 | mut state := new_syntax_case_render_state(storage) |
| 205 | if !isnil(template.shape.sharing) { |
| 206 | state.memo = new_syntax_template_memo[Value](storage, template.shape.sharing) |
| 207 | } |
| 208 | return template.render(root, false, captures, mut state) |
| 209 | } |
| 210 | |
| 211 | fn (template &SyntaxCaseTemplate) capture[T](id i32, indices []int, captures &T) !Value { |
| 212 | variable := template.pattern.indices[template.data.tree.nodes[id].car] or { return failure('invalid syntax template variable') } |
| 213 | rank := template.pattern.variables[variable].depth |
| 214 | return template_capture_value(captures, variable, indices, indices.len - rank) |
| 215 | } |
| 216 | |
| 217 | fn (template &SyntaxCaseTemplate) splice(id i32) bool { |
| 218 | if template.splices.len == 0 { return false } |
| 219 | node := template.data.tree.nodes[id] |
| 220 | return node.kind == .symbol && template.splices[node.car] |
| 221 | } |
| 222 | |
| 223 | fn (template &SyntaxCaseTemplate) element_count[T](id i32, captures &T, mut state SyntaxCaseRenderState) !int { |
| 224 | if !template.splice(id) { return 1 } |
| 225 | value := template.capture(id, state.indices, captures)! |
| 226 | return syntax_spine_length(value) or { return failure('unsyntax-splicing requires a finite proper list') } |
| 227 | } |
| 228 | |
| 229 | // Wrapped syntax and partially wrapped lists share the existing constant-space |
| 230 | // spine validation. No datum conversion or temporary element array is needed. |
| 231 | fn (template &SyntaxCaseTemplate) emit_element[T](id i32, escaped bool, captures &T, mut state SyntaxCaseRenderState, mut emission SyntaxCaseEmission) ! { |
| 232 | if !template.splice(id) { |
| 233 | emission.push(template.render(id, escaped, captures, mut state)!) |
| 234 | return |
| 235 | } |
| 236 | mut value := template.capture(id, state.indices, captures)! |
| 237 | count := syntax_spine_length(value) or { return failure('unsyntax-splicing requires a finite proper list') } |
| 238 | for _ in 0 .. count { |
| 239 | if value.tag == .pair { |
| 240 | pair := value.pair_pointer() |
| 241 | emission.push(pair.car) |
| 242 | value = pair.cdr |
| 243 | } else { |
| 244 | emission.push(syntax_car(value)!) |
| 245 | value = syntax_cdr(value)! |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | fn (template &SyntaxCaseTemplate) render[T](id i32, escaped bool, captures &T, mut state SyntaxCaseRenderState) !Value { |
| 251 | if constant := template.constants[template_region_key(id, escaped)] { return constant } |
| 252 | tree := template.data.tree |
| 253 | node := tree.nodes[id] |
| 254 | if node.kind == .symbol { return template.capture(id, state.indices, captures) } |
| 255 | cache_key := if !isnil(state.memo) && node.kind in [.pair, .vector] { |
| 256 | state.memo.key(id, escaped) |
| 257 | } else { no_template_memo_key } |
| 258 | if cache_key != no_template_memo_key { |
| 259 | if cached := state.memo.completed[cache_key] { return cached } |
| 260 | } |
| 261 | if node.kind == .pair { |
| 262 | if !escaped && tree.ellipsis(node.car) { |
| 263 | result := template.render(tree.escaped_template(id)!, true, captures, mut state)! |
| 264 | if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } |
| 265 | return result |
| 266 | } |
| 267 | mut emission := state.acquire_emission(unsafe { nil }) |
| 268 | defer { state.depth-- } |
| 269 | mut cursor := id |
| 270 | mut spine := &SyntaxTemplateSpine[Value](unsafe { nil }) |
| 271 | defer { if !isnil(spine) { state.memo.depth-- } } |
| 272 | mut end := unspecified() |
| 273 | mut has_end := false |
| 274 | for tree.nodes[cursor].kind == .pair { |
| 275 | if constant := template.constants[template_region_key(cursor, escaped)] { |
| 276 | end = constant |
| 277 | has_end = true |
| 278 | break |
| 279 | } |
| 280 | if cursor != id && !isnil(state.memo) { |
| 281 | tail_key := state.memo.key(cursor, escaped) |
| 282 | if tail_key != no_template_memo_key { |
| 283 | if cached := state.memo.completed[tail_key] { end = cached; has_end = true; break } |
| 284 | if isnil(spine) { spine = state.memo.acquire_spine() } |
| 285 | previous := if isnil(emission.list.tail) { unspecified() } else { payload_value(.pair, emission.list.tail) } |
| 286 | state.memo.note_spine(mut spine, tail_key, previous) |
| 287 | } |
| 288 | } |
| 289 | pair := tree.nodes[cursor] |
| 290 | tail := tree.nodes[pair.cdr] |
| 291 | if !escaped && tail.kind == .pair && tree.ellipsis(tail.car) { |
| 292 | levels, after := tree.template_list_repeat(tail.cdr, true) |
| 293 | template.emit_repeat(pair.car, levels, captures, mut state, mut emission)! |
| 294 | cursor = after |
| 295 | } else { |
| 296 | template.emit_element(pair.car, escaped, captures, mut state, mut emission)! |
| 297 | cursor = pair.cdr |
| 298 | } |
| 299 | } |
| 300 | tail := if has_end { end } else { |
| 301 | template.render(cursor, escaped, captures, mut state)! |
| 302 | } |
| 303 | result := emission.list.finish(tail) |
| 304 | if !isnil(spine) { |
| 305 | for i, tail_key in spine.keys { |
| 306 | previous := spine.previous[i] |
| 307 | state.memo.keep(tail_key, if previous.tag == .pair { previous.pair_pointer().cdr } else { result }) |
| 308 | } |
| 309 | } |
| 310 | if cache_key != no_template_memo_key { state.memo.keep(cache_key, result) } |
| 311 | return result |
| 312 | } |
| 313 | if node.kind == .vector { |
| 314 | mut count := 0 |
| 315 | mut i := 0 |
| 316 | for i < int(node.cdr) { |
| 317 | body := tree.elements[node.car + i] |
| 318 | if !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) { |
| 319 | levels, after := tree.template_vector_repeat(node, i + 2, true) |
| 320 | width := template.repeat_count(body, levels, captures, mut state)! |
| 321 | if width > max_int - count { |
| 322 | return failure('syntax template vector exceeds supported range') |
| 323 | } |
| 324 | count += width |
| 325 | i = after |
| 326 | } else { |
| 327 | width := template.element_count(body, captures, mut state)! |
| 328 | if width > max_int - count { |
| 329 | return failure('syntax template vector exceeds supported range') |
| 330 | } |
| 331 | count += width |
| 332 | i++ |
| 333 | } |
| 334 | } |
| 335 | // One exact element array, filled directly. vector() would clone it. |
| 336 | mut result := &Vector{ items: []Value{len: count} } |
| 337 | mut emission := state.acquire_emission(result) |
| 338 | defer { state.depth-- } |
| 339 | i = 0 |
| 340 | for i < int(node.cdr) { |
| 341 | body := tree.elements[node.car + i] |
| 342 | if !escaped && i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) { |
| 343 | levels, after := tree.template_vector_repeat(node, i + 2, true) |
| 344 | template.emit_repeat(body, levels, captures, mut state, mut emission)! |
| 345 | i = after |
| 346 | } else { |
| 347 | template.emit_element(body, escaped, captures, mut state, mut emission)! |
| 348 | i++ |
| 349 | } |
| 350 | } |
| 351 | value := payload_value(.vector, result) |
| 352 | if cache_key != no_template_memo_key { state.memo.keep(cache_key, value) } |
| 353 | return value |
| 354 | } |
| 355 | return failure('invalid compiled syntax template') |
| 356 | } |
| 357 | |
| 358 | struct SyntaxCaseEmission { |
| 359 | mut: |
| 360 | list ListBuilder |
| 361 | vector &Vector = unsafe { nil } |
| 362 | index int |
| 363 | } |
| 364 | |
| 365 | fn (mut emission SyntaxCaseEmission) push(value Value) { |
| 366 | if isnil(emission.vector) { |
| 367 | emission.list.push(value) |
| 368 | } else { |
| 369 | emission.vector.items[emission.index] = value |
| 370 | emission.index++ |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | fn (template &SyntaxCaseTemplate) emit_repeat[T](body i32, levels int, captures &T, mut state SyntaxCaseRenderState, mut emission SyntaxCaseEmission) ! { |
| 375 | width := template_repeat_length(&template.shape, body, state.indices, captures, levels)! |
| 376 | for i in 0 .. width { |
| 377 | state.push(i) |
| 378 | previous := if !isnil(state.memo) { state.memo.enter(i)! } else { u32(0) } |
| 379 | if levels > 1 { |
| 380 | template.emit_repeat(body, levels - 1, captures, mut state, mut emission)! |
| 381 | } else { |
| 382 | template.emit_element(body, false, captures, mut state, mut emission)! |
| 383 | } |
| 384 | if !isnil(state.memo) { state.memo.path = previous } |
| 385 | state.indices.pop() |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | fn (template &SyntaxCaseTemplate) repeat_count[T](body i32, levels int, captures &T, mut state SyntaxCaseRenderState) !int { |
| 390 | width := template_repeat_length(&template.shape, body, state.indices, captures, levels)! |
| 391 | if levels == 1 && !template.splice(body) { return width } |
| 392 | mut count := 0 |
| 393 | for i in 0 .. width { |
| 394 | state.push(i) |
| 395 | amount := if levels == 1 { |
| 396 | template.element_count(body, captures, mut state)! |
| 397 | } else { |
| 398 | template.repeat_count(body, levels - 1, captures, mut state)! |
| 399 | } |
| 400 | state.indices.pop() |
| 401 | if amount > max_int - count { |
| 402 | return failure('syntax template vector exceeds supported range') |
| 403 | } |
| 404 | count += amount |
| 405 | } |
| 406 | return count |
| 407 | } |
| 408 | |
| 409 | // A cdr immediately after a repeated body starts with grammar markers, |
| 410 | // rather than another template. They never become output fragments. |
| 411 | fn (tree &SyntaxTree) template_region_tail(tail i32, escaped bool) i32 { |
| 412 | if !escaped && tree.nodes[tail].kind == .pair && tree.ellipsis(tree.nodes[tail].car) { |
| 413 | _, after := tree.template_list_repeat(tree.nodes[tail].cdr, true) |
| 414 | return after |
| 415 | } |
| 416 | return tail |
| 417 | } |
| 418 | |
| 419 | // Stable cells live in the one-call scratch arena. Child rendering borrows |
| 420 | // a different cell, and siblings reuse it. Registry growth cannot move cells. |
| 421 | fn (mut state SyntaxCaseRenderState) acquire_emission(vector &Vector) &SyntaxCaseEmission { |
| 422 | if state.depth == state.emissions.len { |
| 423 | state.add_emission() |
| 424 | } |
| 425 | mut emission := state.emissions[state.depth] |
| 426 | state.depth++ |
| 427 | emission.list.head = nil_value() |
| 428 | emission.list.tail = unsafe { nil } |
| 429 | emission.vector = vector |
| 430 | emission.index = 0 |
| 431 | return emission |
| 432 | } |
| 433 | |
| 434 | fn (mut state SyntaxCaseRenderState) add_emission() { |
| 435 | state.storage.push() |
| 436 | defer { state.storage.pop() } |
| 437 | state.emissions << &SyntaxCaseEmission{} |
| 438 | } |
| 439 | |
| 440 | fn new_syntax_case_render_state(storage arena.Arena) SyntaxCaseRenderState { |
| 441 | storage.push() |
| 442 | defer { storage.pop() } |
| 443 | mut state := SyntaxCaseRenderState{ storage: storage } |
| 444 | unsafe { |
| 445 | state.indices.flags.set(.noslices) |
| 446 | state.emissions.flags.set(.noslices) |
| 447 | } |
| 448 | return state |
| 449 | } |
| 450 | |