| 1 | module scheme |
| 2 | |
| 3 | import reader |
| 4 | |
| 5 | // Compile-time pattern-variable bindings share a runtime capture-frame slot. |
| 6 | // The detached descriptor carries no Function, Scope, Code or VM reference. |
| 7 | struct SyntaxCaseVariable { |
| 8 | pattern &SyntaxPattern |
| 9 | variable int |
| 10 | splice bool |
| 11 | } |
| 12 | |
| 13 | struct SyntaxTemplateReference { |
| 14 | depth int |
| 15 | slot int |
| 16 | variable int |
| 17 | pattern &SyntaxPattern |
| 18 | } |
| 19 | |
| 20 | struct CompiledSyntaxTemplate { |
| 21 | template SyntaxCaseTemplate |
| 22 | references []SyntaxTemplateReference |
| 23 | } |
| 24 | |
| 25 | @[heap] |
| 26 | struct ProceduralSyntaxCode { |
| 27 | mut: |
| 28 | globals_cache &SyntaxGlobalCache = unsafe { nil } |
| 29 | private_cache &SyntaxPrivateCache = unsafe { nil } |
| 30 | aborted &CompilerControlTransfer = unsafe { nil } |
| 31 | matchers []SyntaxCaseMatcher |
| 32 | templates []CompiledSyntaxTemplate |
| 33 | } |
| 34 | |
| 35 | fn (mut code Code) procedural_syntax() &ProceduralSyntaxCode { |
| 36 | if isnil(code.procedural) { code.procedural = &ProceduralSyntaxCode{} } |
| 37 | return code.procedural |
| 38 | } |
| 39 | |
| 40 | fn (b &Builder) syntax_owner() &Owner { |
| 41 | return if isnil(b.code.compiler_vm) { |
| 42 | unsafe { nil } |
| 43 | } else { |
| 44 | unsafe { (&VM(b.code.compiler_vm)).owner } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // One ordinary helper evaluates the input once. Each matched clause receives |
| 49 | // its own activation, so captured syntax and continuations keep fresh lexical |
| 50 | // locations. Rejected fenders return to the selector; only the |
| 51 | // fender needs a return frame, discarded before accepted output runs. |
| 52 | enum SyntaxClauseKind { |
| 53 | expression |
| 54 | body |
| 55 | template |
| 56 | } |
| 57 | |
| 58 | fn (mut b Builder) syntax_case_form(nodes []reader.NodeId, tail bool, origin reader.NodeId) ! { |
| 59 | check_arity('syntax-case', nodes.len - 1, 2, -1)! |
| 60 | literals := b.code.nodes(nodes[2])! |
| 61 | b.syntax_case_dispatch(literals, nodes[3..], nodes[1], [], .expression, [], tail, origin)! |
| 62 | } |
| 63 | |
| 64 | // The derived with-syntax form shares matching, captures and control transfer. |
| 65 | // Its parallel RHS values are collected without consulting a variable named list. |
| 66 | fn (mut b Builder) with_syntax_form(nodes []reader.NodeId, tail bool, origin reader.NodeId) ! { |
| 67 | check_arity('with-syntax', nodes.len - 1, 2, -1)! |
| 68 | bindings := b.code.nodes(nodes[1])! |
| 69 | mut patterns := []reader.NodeId{cap: bindings.len} |
| 70 | mut inputs := []reader.NodeId{cap: bindings.len} |
| 71 | for binding in bindings { |
| 72 | parts := b.code.nodes(binding)! |
| 73 | if parts.len != 2 { return failure('with-syntax binding needs a pattern and expression') } |
| 74 | patterns << parts[0] |
| 75 | inputs << parts[1] |
| 76 | } |
| 77 | pattern := b.code.syntax_list(patterns, origin)! |
| 78 | mut clause := []reader.NodeId{cap: nodes.len - 1} |
| 79 | clause << pattern |
| 80 | clause << nodes[2..] |
| 81 | combined := b.code.syntax_list(clause, origin)! |
| 82 | b.syntax_case_dispatch([], [combined], reader.no_node, inputs, .body, [], tail, origin)! |
| 83 | } |
| 84 | |
| 85 | fn (mut b Builder) syntax_case_dispatch(literals []reader.NodeId, clauses []reader.NodeId, input reader.NodeId, inputs []reader.NodeId, kind SyntaxClauseKind, splices []string, tail bool, origin reader.NodeId) ! { |
| 86 | parallel_inputs := kind != .expression |
| 87 | mut names := map[string]bool{} |
| 88 | for literal in literals { |
| 89 | name := b.code.name(literal)! |
| 90 | if b.code.datum_name(literal)! in ['_', '...'] { |
| 91 | return failure('syntax-case literal cannot be underscore or ellipsis') |
| 92 | } |
| 93 | if b.code.binding_key(name) in names { return failure('duplicate syntax-case literal') } |
| 94 | names[b.code.binding_key(name)] = true |
| 95 | } |
| 96 | function := &Function{ code: b.code, params: 1, slot_count: 1 } |
| 97 | scope := new_compile_scope(Scope{ parent: b.scope, function: function }) |
| 98 | mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail && tail } |
| 99 | for clause in clauses { |
| 100 | parts := b.code.nodes(clause)! |
| 101 | if (parallel_inputs && parts.len < 2) || (!parallel_inputs && parts.len !in [ |
| 102 | 2, |
| 103 | 3, |
| 104 | ]) { |
| 105 | return failure('syntax-case clause needs a pattern, optional fender and output expression') |
| 106 | } |
| 107 | mut roots := []reader.NodeId{cap: literals.len + 1} |
| 108 | roots << literals |
| 109 | roots << parts[0] |
| 110 | tree, frozen := inner.freeze_syntax(roots)! |
| 111 | mut bindings := map[i32]SyntaxBinding{} |
| 112 | for id in frozen[..literals.len] { |
| 113 | literal := tree.identifiers[tree.nodes[id].car].binding |
| 114 | for i, info in tree.identifiers { |
| 115 | if same_syntax_binding(literal, info.binding) { bindings[i32(i)] = literal } |
| 116 | } |
| 117 | } |
| 118 | pattern := tree.compile_case_pattern(frozen.last(), bindings)! |
| 119 | mut seen := map[string]bool{} |
| 120 | for variable in pattern.variables { |
| 121 | key := b.code.binding_key(tree.identifiers[variable.identifier].name) |
| 122 | if key in seen { return failure('duplicate syntax-case pattern variable') } |
| 123 | seen[key] = true |
| 124 | } |
| 125 | mut metadata := b.code.procedural_syntax() |
| 126 | index := metadata.matchers.len |
| 127 | metadata.matchers << SyntaxCaseMatcher{ tree: tree, pattern: &pattern, literals: bindings, owner: b.syntax_owner() } |
| 128 | inner.emit(.local, 0, 0, origin) |
| 129 | inner.emit(.syntax_match, index, 0, origin) |
| 130 | inner.emit(.duplicate, 0, 0, origin) |
| 131 | miss := inner.emit(.jump_false, 0, 0, origin) |
| 132 | body := inner.syntax_clause_body(tree, pattern, parts, kind, splices, origin)! |
| 133 | inner.syntax_scope_function(body, origin) |
| 134 | inner.emit(.swap, 0, 0, origin) |
| 135 | inner.emit(if parallel_inputs || parts.len == 2 { |
| 136 | Op.syntax_scope_tail |
| 137 | } else { |
| 138 | Op.syntax_scope_call |
| 139 | }, 0, 0, origin) |
| 140 | inner.patch(miss, inner.function.instructions.len) |
| 141 | inner.emit(.drop, 0, 0, origin) |
| 142 | } |
| 143 | inner.fault(if parallel_inputs { |
| 144 | 'no matching with-syntax pattern' |
| 145 | } else { |
| 146 | 'no matching syntax-case clause' |
| 147 | }, origin) |
| 148 | inner.emit(.ret, 0, 0, origin) |
| 149 | b.syntax_scope_function(function, origin) |
| 150 | if parallel_inputs { |
| 151 | for expression in inputs { |
| 152 | b.expression(expression, false) |
| 153 | b.emit(.unpack_values, 1, 0, expression) |
| 154 | } |
| 155 | b.constant(nil_value(), origin) |
| 156 | for _ in 0 .. inputs.len { b.emit(.qq_cons, 0, 0, origin) } |
| 157 | } else { |
| 158 | b.expression(input, false) |
| 159 | } |
| 160 | b.emit(if tail { Op.syntax_scope_tail } else { Op.syntax_scope_call }, 0, 0, origin) |
| 161 | } |
| 162 | |
| 163 | fn (mut b Builder) syntax_clause_body(tree &SyntaxTree, pattern &SyntaxPattern, parts []reader.NodeId, kind SyntaxClauseKind, splices []string, origin reader.NodeId) !&Function { |
| 164 | function := &Function{ code: b.code, params: 1, slot_count: 1 } |
| 165 | mut scope := new_compile_scope(Scope{ parent: b.scope, function: function, syntax: &SyntaxBindings{} }) |
| 166 | for variable, spec in pattern.variables { |
| 167 | name := tree.identifiers[spec.identifier].name |
| 168 | binding := SyntaxBinding{ kind: .lexical, name: name, function: function, slot: 0, pattern_variable: &SyntaxCaseVariable{ pattern: pattern, variable: variable, splice: name in splices } } |
| 169 | scope.syntax.entries[name] = binding |
| 170 | key := b.code.binding_key(name) |
| 171 | if key != name { scope.syntax.entries[key] = binding } |
| 172 | } |
| 173 | mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail } |
| 174 | if kind == .template { |
| 175 | inner.syntax_template(parts[1], origin)! |
| 176 | } else if kind == .body { |
| 177 | inner.body_sequence(parts[1..], true) |
| 178 | } else if parts.len == 2 { |
| 179 | inner.expression(parts[1], true) |
| 180 | } else { |
| 181 | // Fender results control selection, so return/break cross this helper. |
| 182 | inner.return_tail = false |
| 183 | inner.expression(parts[1], false) |
| 184 | miss := inner.emit(.jump_false, 0, 0, origin) |
| 185 | inner.emit(.syntax_accept, 0, 0, origin) |
| 186 | inner.return_tail = b.return_tail |
| 187 | inner.expression(parts[2], true) |
| 188 | inner.emit(.ret, 0, 0, origin) |
| 189 | inner.patch(miss, inner.function.instructions.len) |
| 190 | inner.constant(boolean(false), origin) |
| 191 | } |
| 192 | inner.emit(.ret, 0, 0, origin) |
| 193 | return function |
| 194 | } |
| 195 | |
| 196 | fn (mut b Builder) syntax_form(nodes []reader.NodeId, origin reader.NodeId) ! { |
| 197 | check_arity('syntax', nodes.len - 1, 1, 1)! |
| 198 | b.syntax_template(nodes[1], origin)! |
| 199 | } |
| 200 | |
| 201 | fn (mut b Builder) syntax_template(source reader.NodeId, origin reader.NodeId) ! { |
| 202 | tree, roots := b.freeze_syntax([source])! |
| 203 | mut pattern := &SyntaxPattern{ root: roots[0] } |
| 204 | mut references := []SyntaxTemplateReference{} |
| 205 | mut splices := []bool{} |
| 206 | for identifier, info in tree.identifiers { |
| 207 | binding := b.resolve_binding(info.name) |
| 208 | if isnil(binding.pattern_variable) { continue } |
| 209 | variable := binding.pattern_variable |
| 210 | if variable.splice { |
| 211 | if splices.len == 0 { splices = []bool{len: tree.identifiers.len} } |
| 212 | splices[identifier] = true |
| 213 | } |
| 214 | index := pattern.variables.len |
| 215 | pattern.indices[i32(identifier)] = index |
| 216 | pattern.variables << SyntaxVariable{i32(identifier), variable.pattern.variables[variable.variable].depth} |
| 217 | depth := b.syntax_binding_depth(binding)! |
| 218 | if depth > b.function.capture_depth { b.function.capture_depth = depth } |
| 219 | references << SyntaxTemplateReference{ depth: depth, slot: binding.slot, variable: variable.variable, pattern: variable.pattern } |
| 220 | } |
| 221 | data := &SyntaxObjectData{ tree: tree, owner: b.syntax_owner(), context: b.capture_syntax_lookup_context()! } |
| 222 | template := data.compile_case_template_with_splices(roots[0], pattern, splices)! |
| 223 | mut metadata := b.code.procedural_syntax() |
| 224 | index := metadata.templates.len |
| 225 | metadata.templates << CompiledSyntaxTemplate{template, references} |
| 226 | b.emit(.syntax_expand, index, 0, origin) |
| 227 | } |
| 228 | |
| 229 | fn (mut m Machine) match_syntax_case(mut vm VM, index int) ! { |
| 230 | prototype := m.function.code.procedural.matchers[index] |
| 231 | matcher := SyntaxCaseMatcher{ ...prototype, owner: vm.owner } |
| 232 | mut captures := &SyntaxCaseCaptures{ pattern: matcher.pattern } |
| 233 | input := m.pop_value() |
| 234 | if matcher.matches_value(input, mut captures)! { |
| 235 | m.push(payload_value(.syntax_captures, captures)) |
| 236 | } else { |
| 237 | m.push(boolean(false)) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | struct SyntaxTemplateEnvironment { |
| 242 | pattern &SyntaxPattern |
| 243 | compiled &CompiledSyntaxTemplate |
| 244 | environment &Environment = unsafe { nil } |
| 245 | } |
| 246 | |
| 247 | fn (source &SyntaxTemplateEnvironment) frame(variable int) !&SyntaxCaseCaptures { |
| 248 | ref := source.compiled.references[variable] |
| 249 | env := source.environment.ancestor(ref.depth) |
| 250 | value := env.slots[ref.slot] |
| 251 | if value.tag != .syntax_captures { return failure('invalid syntax capture environment') } |
| 252 | captures := unsafe { &SyntaxCaseCaptures(value.pointer()) } |
| 253 | if voidptr(captures.pattern) != voidptr(ref.pattern) { |
| 254 | return failure('syntax capture pattern environment mismatch') |
| 255 | } |
| 256 | return captures |
| 257 | } |
| 258 | |
| 259 | fn template_capture_value[T](source &T, variable int, indices []int, offset int) !Value { |
| 260 | $if T is SyntaxCaseCaptures { |
| 261 | return source.value_at(variable, indices, offset) |
| 262 | } $else { |
| 263 | captures := source.frame(variable)! |
| 264 | return captures.value_at(source.compiled.references[variable].variable, indices, offset) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | fn template_repeat_length[T](shape &SyntaxTemplate, body i32, indices []int, source &T, levels int) !int { |
| 269 | depth := indices.len |
| 270 | drivers := shape.repeats[template_repeat_key(body, depth, depth + levels)] or { return failure('invalid compiled template repetition') } |
| 271 | mut count := -1 |
| 272 | for driver in drivers { |
| 273 | variable, coordinates := template_capture_coordinates(source, int(driver.variable))! |
| 274 | path := coordinates.coordinate(indices, int(driver.offset))! |
| 275 | width := coordinates.items[syntax_capture_key(variable, path)] or { return failure('missing syntax repetition dimension') } |
| 276 | if count >= 0 && count != int(width) { |
| 277 | return failure('template repetition lengths do not match') |
| 278 | } |
| 279 | count = int(width) |
| 280 | } |
| 281 | return count |
| 282 | } |
| 283 | |
| 284 | fn template_capture_coordinates[T](source &T, variable int) !(int, &SyntaxCaptures) { |
| 285 | $if T is SyntaxCaseCaptures { |
| 286 | return variable, &source.coordinates |
| 287 | } $else { |
| 288 | captures := source.frame(variable)! |
| 289 | return source.compiled.references[variable].variable, &captures.coordinates |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | fn (mut m Machine) expand_syntax_value(index int) ! { |
| 294 | compiled := &m.function.code.procedural.templates[index] |
| 295 | source := SyntaxTemplateEnvironment{ pattern: compiled.template.pattern, compiled: compiled, environment: m.env } |
| 296 | m.push(compiled.template.expand(&source)!) |
| 297 | } |
| 298 | |
| 299 | fn (mut b Builder) syntax_scope_function(function &Function, origin reader.NodeId) { |
| 300 | index := b.function.children.len |
| 301 | b.function.children << function |
| 302 | b.emit(.scope_function, index, 0, origin) |
| 303 | } |
| 304 | |
| 305 | // Immediate one-argument helpers share the existing activation cache. |
| 306 | // No Scheme Procedure or permanent escape mark is needed for these calls. |
| 307 | @[direct_array_access] |
| 308 | fn (mut m Machine) call_syntax_scope(mut vm VM, tail bool) ! { |
| 309 | m.charge(vm.options.max_steps)! |
| 310 | if !tail && vm.options.max_frames > 0 && m.frames.len >= vm.options.max_frames { |
| 311 | return failure('continuation frame limit exceeded') |
| 312 | } |
| 313 | base := m.stack.len - 2 |
| 314 | function := unsafe { &Function(m.stack[base].pointer()) } |
| 315 | argument := m.stack[base + 1] |
| 316 | parent := if function.capture_depth > 0 { m.env } else { unsafe { &Environment(nil) } } |
| 317 | if !tail { m.reserve_frame_slot(vm)! } |
| 318 | mut scope := m.checked_activation_for(vm, function, parent, tail && isnil(parent))! |
| 319 | scope.tail_parent = tail && !isnil(parent) |
| 320 | container_store_validated(mut scope.slots, 0, argument) |
| 321 | if !tail { |
| 322 | m.frames << CallFrame{ function: m.function, env: m.env, ip: m.ip, base: m.base } |
| 323 | m.base = base |
| 324 | } |
| 325 | m.truncate(if tail { m.base } else { base }) |
| 326 | m.function = function |
| 327 | m.env = scope |
| 328 | m.ip = 0 |
| 329 | } |
| 330 | |
| 331 | // The fender's selector return is no longer needed once its clause is accepted. |
| 332 | // Keep fresh pattern locations, but let output share the source tail context. |
| 333 | @[direct_array_access] |
| 334 | fn (mut m Machine) accept_syntax_clause() ! { |
| 335 | if m.frames.len == 0 { return failure('invalid syntax-case fender continuation') } |
| 336 | index := m.frames.len - 1 |
| 337 | frame := m.frames[index] |
| 338 | container_store_validated(mut m.frames, index, CallFrame{}) |
| 339 | m.frames.trim(index) |
| 340 | m.release_bridge_sites(m.frames.len) |
| 341 | m.truncate(m.base) |
| 342 | m.base = frame.base |
| 343 | if !isnil(m.env.parent) && voidptr(m.env.parent) == voidptr(frame.env) { |
| 344 | m.env.tail_parent = true |
| 345 | } else if !isnil(frame.env) { |
| 346 | // This body does not need its selector activation. Release its transparent |
| 347 | // tail-parent chain just as an ordinary completed immediate helper does. |
| 348 | saved := m.env |
| 349 | m.env = frame.env |
| 350 | if m.env.tail_parent { m.release_tail_parents(unsafe { nil }) } |
| 351 | m.cache_environment(mut m.env) |
| 352 | m.env = saved |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | // Explicit return operands cross transparent helpers through the existing |
| 357 | // ret-only bridge. Materialize only this rare private callee before it exits |
| 358 | // its physical caller; ordinary syntax-case helpers keep their direct path. |
| 359 | @[direct_array_access] |
| 360 | fn (mut m Machine) call_syntax_return(mut vm VM, exit_index int) ! { |
| 361 | base := m.stack.len - 2 |
| 362 | function := unsafe { &Function(m.stack[base].pointer()) } |
| 363 | parent := if function.capture_depth > 0 { m.env } else { unsafe { &Environment(nil) } } |
| 364 | escape_environment(parent) |
| 365 | value := procedure_value(&Procedure{ mode: .closure, owner: vm.owner, function: function, env: parent }) |
| 366 | container_store_validated(mut m.stack, base, value) |
| 367 | m.call_return(mut vm, 1, exit_index)! |
| 368 | } |
| 369 | |
| 370 | struct CompilerControlTransfer { |
| 371 | error IError |
| 372 | } |
| 373 | |