| 1 | module scheme |
| 2 | |
| 3 | import reader |
| 4 | |
| 5 | // Fixed-width instructions; operands index constants, slots, or jump targets. |
| 6 | // Source NodeIds are cold metadata used only when reporting an error. |
| 7 | enum Op as u8 { |
| 8 | constant |
| 9 | local |
| 10 | global |
| 11 | define_local |
| 12 | define_global |
| 13 | assign_local |
| 14 | closure |
| 15 | drop |
| 16 | duplicate |
| 17 | swap |
| 18 | jump |
| 19 | jump_false |
| 20 | and_jump |
| 21 | or_jump |
| 22 | case_match |
| 23 | qq_cons |
| 24 | qq_prefix |
| 25 | qq_splice |
| 26 | qq_vector |
| 27 | call |
| 28 | tail_call |
| 29 | call_values_tail |
| 30 | map_init |
| 31 | map_step |
| 32 | map_collect |
| 33 | promise |
| 34 | force_enter |
| 35 | force_finish |
| 36 | make_promise |
| 37 | wind_init |
| 38 | wind_enter |
| 39 | wind_leave |
| 40 | wind_finish |
| 41 | wind_step |
| 42 | wind_resume |
| 43 | ret |
| 44 | fail |
| 45 | define_syntax |
| 46 | file_init |
| 47 | file_enter |
| 48 | file_leave |
| 49 | file_argument |
| 50 | file_return |
| 51 | eval_enter |
| 52 | case_lambda |
| 53 | unpack_values |
| 54 | source_form |
| 55 | load_enter |
| 56 | parameter_create |
| 57 | parameter_created |
| 58 | parameter_set |
| 59 | parameter_assigned |
| 60 | parameter_init |
| 61 | parameter_convert |
| 62 | parameter_converted |
| 63 | parameter_install |
| 64 | parameter_finish |
| 65 | indexed_init |
| 66 | indexed_step |
| 67 | indexed_collect |
| 68 | search_init |
| 69 | search_step |
| 70 | search_collect |
| 71 | file_parameterize |
| 72 | record_define |
| 73 | enumeration_define |
| 74 | enumeration_select |
| 75 | global_reference |
| 76 | assign_global_reference |
| 77 | library_define |
| 78 | library_import |
| 79 | library_commit |
| 80 | library_complete |
| 81 | library_mark_enter |
| 82 | library_mark_leave |
| 83 | assign_resolved_global |
| 84 | library_init_guard |
| 85 | process_exit_finish |
| 86 | sort_init |
| 87 | sort_step |
| 88 | sort_collect |
| 89 | list_utility_init |
| 90 | list_utility_step |
| 91 | list_utility_collect |
| 92 | hashtable_init |
| 93 | hashtable_step |
| 94 | hashtable_collect |
| 95 | record_operations |
| 96 | record_make_type |
| 97 | record_make_cd |
| 98 | record_prepare |
| 99 | record_prepared |
| 100 | record_parent_prepare |
| 101 | record_parent_apply |
| 102 | record_factory |
| 103 | record_default_cd |
| 104 | record_name_define |
| 105 | record_auto_uid |
| 106 | exit_mark |
| 107 | early_return |
| 108 | return_call |
| 109 | loop_continue |
| 110 | scope_function |
| 111 | scope_call |
| 112 | scope_tail |
| 113 | implicit_call |
| 114 | syntax_match |
| 115 | syntax_expand |
| 116 | syntax_scope_call |
| 117 | syntax_scope_tail |
| 118 | syntax_accept |
| 119 | syntax_return_call |
| 120 | port_io_enter |
| 121 | port_io_step |
| 122 | port_io_collect |
| 123 | port_error_close_step |
| 124 | port_error_close_collect |
| 125 | assignment_setter |
| 126 | assignment_setter_result |
| 127 | assignment_finish |
| 128 | star_bound_skip |
| 129 | star_closure |
| 130 | goops_make_class |
| 131 | goops_define_generic |
| 132 | goops_define_accessor |
| 133 | goops_define_method |
| 134 | goops_make_method |
| 135 | goops_bound_enter |
| 136 | goops_bound_finish |
| 137 | goops_retry_enter |
| 138 | goops_retry_finish |
| 139 | goops_missing_enter |
| 140 | goops_virtual_read_enter |
| 141 | goops_virtual_read_finish |
| 142 | goops_missing_read_finish |
| 143 | goops_factory_apply |
| 144 | goops_applicability_apply |
| 145 | goops_effective_apply |
| 146 | goops_equal_init |
| 147 | goops_equal_step |
| 148 | goops_equal_resume |
| 149 | goops_migration_start |
| 150 | goops_migration_retry |
| 151 | goops_class_redefinition |
| 152 | goops_top |
| 153 | } |
| 154 | |
| 155 | struct Instruction { |
| 156 | op Op |
| 157 | a i32 |
| 158 | b i32 |
| 159 | origin reader.NodeId |
| 160 | } |
| 161 | |
| 162 | @[heap] |
| 163 | struct Function { |
| 164 | code &Code |
| 165 | params int |
| 166 | rest bool |
| 167 | mut: |
| 168 | // Names live in compile-time Scope maps. Execution only needs the size, |
| 169 | // so compiled functions retain neither a second name array nor its strings. |
| 170 | syntax_identity u32 |
| 171 | slot_count int |
| 172 | instructions []Instruction |
| 173 | constants []Value |
| 174 | names []string |
| 175 | global_slots []int |
| 176 | children []&Function |
| 177 | failures []EvalError |
| 178 | capture_depth int |
| 179 | integer_tail &IntegerTailPlan = unsafe { nil } |
| 180 | closed &Procedure = unsafe { nil } |
| 181 | star &StarFormals = unsafe { nil } |
| 182 | // Only method bodies bind next-method. Its slot stays uninitialized when |
| 183 | // the underlying procedure is called directly outside generic dispatch. |
| 184 | goops_next_slot int = -1 |
| 185 | goops_needs_next bool |
| 186 | } |
| 187 | |
| 188 | @[heap] |
| 189 | struct Scope { |
| 190 | parent &Scope = unsafe { nil } |
| 191 | mut: |
| 192 | scratch_next &Scope = unsafe { nil } |
| 193 | function &Function |
| 194 | names map[string]int |
| 195 | syntax &SyntaxBindings = unsafe { nil } |
| 196 | return_boundary ReturnBoundary |
| 197 | continue_used bool |
| 198 | exit_slot i32 = -1 |
| 199 | } |
| 200 | |
| 201 | enum ReturnBoundary as u8 { |
| 202 | none |
| 203 | function |
| 204 | deferred |
| 205 | loop |
| 206 | } |
| 207 | |
| 208 | struct ScopeRef { |
| 209 | value &Scope |
| 210 | } |
| 211 | |
| 212 | @[heap] |
| 213 | struct NameTable { |
| 214 | mut: |
| 215 | scratch_next &NameTable = unsafe { nil } |
| 216 | indices map[string]int |
| 217 | } |
| 218 | |
| 219 | struct Builder { |
| 220 | mut: |
| 221 | code &Code |
| 222 | function &Function |
| 223 | scope &Scope = unsafe { nil } |
| 224 | table &NameTable = unsafe { nil } |
| 225 | definition_context bool |
| 226 | // A transparent helper's final result can be the source procedure's result. |
| 227 | return_tail bool |
| 228 | body_keywords &SyntaxBindings = unsafe { nil } |
| 229 | } |
| 230 | |
| 231 | fn (mut b Builder) emit(op Op, a int, operand int, origin reader.NodeId) int { |
| 232 | if op in [.local, .assign_local, .early_return, .loop_continue] && a > b.function.capture_depth { |
| 233 | b.function.capture_depth = a |
| 234 | } |
| 235 | index := b.function.instructions.len |
| 236 | // Flatten provenance while the expansion arena is alive. Execution needs |
| 237 | // only source IDs (including virtual document ranges), so no generated-node |
| 238 | // location table survives. |
| 239 | b.function.instructions << Instruction{op, i32(a), i32(operand), b.code.source_origin(origin)} |
| 240 | return index |
| 241 | } |
| 242 | |
| 243 | fn (mut b Builder) patch(index int, target int) { |
| 244 | container_store(mut b.function.instructions, index, Instruction{ |
| 245 | ...b.function.instructions[index] |
| 246 | a: i32(target) |
| 247 | }) |
| 248 | } |
| 249 | |
| 250 | fn (mut b Builder) constant(value Value, origin reader.NodeId) { |
| 251 | index := b.function.constants.len |
| 252 | b.function.constants << value |
| 253 | b.emit(.constant, index, 0, origin) |
| 254 | } |
| 255 | |
| 256 | fn (mut b Builder) name_table() &NameTable { |
| 257 | if isnil(b.table) { |
| 258 | mut code := b.code |
| 259 | b.table = &NameTable{ scratch_next: code.compile_tables } |
| 260 | code.compile_tables = b.table |
| 261 | } |
| 262 | return b.table |
| 263 | } |
| 264 | |
| 265 | fn (mut b Builder) name_index(name string) int { |
| 266 | // Compilation only. Runtime instructions never reconstruct identifiers. |
| 267 | mut table := b.name_table() |
| 268 | if index := table.indices[name] { return index } |
| 269 | index := b.function.names.len |
| 270 | b.function.names << name |
| 271 | b.function.global_slots << -1 |
| 272 | table.indices[name] = index |
| 273 | return index |
| 274 | } |
| 275 | |
| 276 | fn (mut scope Scope) declare(name string) int { |
| 277 | if slot := scope.names[name] { return slot } |
| 278 | key := scope.function.code.binding_key(name) |
| 279 | if key != name { |
| 280 | if slot := scope.names[key] { |
| 281 | scope.names[name] = slot |
| 282 | return slot |
| 283 | } |
| 284 | } |
| 285 | slot := scope.function.slot_count |
| 286 | scope.names[name] = slot |
| 287 | if key != name { scope.names[key] = slot } |
| 288 | scope.function.slot_count++ |
| 289 | return slot |
| 290 | } |
| 291 | |
| 292 | fn (scope &Scope) resolve(name string) ?(int, int) { |
| 293 | mut cursor := ScopeRef{ value: scope } |
| 294 | mut depth := 0 |
| 295 | for !isnil(cursor.value) { |
| 296 | if slot := cursor.value.names[name] { return depth, slot } |
| 297 | parent := cursor.value.parent |
| 298 | // Compile-time binding regions can share one runtime activation (for |
| 299 | // example a body's definitions versus its formal parameters). |
| 300 | if !isnil(parent) && voidptr(parent.function) != voidptr(cursor.value.function) { depth++ } |
| 301 | cursor = ScopeRef{ value: cursor.value.parent } |
| 302 | } |
| 303 | return none |
| 304 | } |
| 305 | |
| 306 | @[inline] |
| 307 | fn (mut b Builder) load(name string, origin reader.NodeId) ! { |
| 308 | binding := b.resolve_binding(name) |
| 309 | b.load_resolved(name, binding, origin)! |
| 310 | } |
| 311 | |
| 312 | @[inline] |
| 313 | fn (mut b Builder) load_resolved(name string, binding SyntaxBinding, origin reader.NodeId) ! { |
| 314 | if !isnil(binding.pattern_variable) { |
| 315 | return failure('pattern variable ${name} may only be referenced within syntax') |
| 316 | } |
| 317 | match binding.kind { |
| 318 | .lexical { |
| 319 | if !isnil(binding.function) && binding.function.goops_next_slot >= 0 |
| 320 | && binding.slot == binding.function.goops_next_slot { |
| 321 | mut function := binding.function |
| 322 | function.goops_needs_next = true |
| 323 | } |
| 324 | b.emit(.local, b.syntax_binding_depth(binding)!, binding.slot, origin) |
| 325 | } |
| 326 | .global { |
| 327 | if binding.introduced == '' && report_slot(binding.namespace, binding.global_slot) { |
| 328 | if isnil(b.code.compiler_vm) { |
| 329 | return failure('report binding requires its compilation VM') |
| 330 | } |
| 331 | b.constant(unsafe { (&VM(b.code.compiler_vm)).pristine_standard(-binding.global_slot - 2) }, origin) |
| 332 | return |
| 333 | } |
| 334 | if binding.introduced != '' { |
| 335 | b.global_reference(binding, origin) |
| 336 | } else if voidptr(binding.namespace) != voidptr(b.code.namespace) { |
| 337 | b.global_reference(SyntaxBinding{ ...binding, introduced: name, introduced_namespace: b.code.namespace }, origin) |
| 338 | } else { |
| 339 | if binding.global_slot >= 0 { |
| 340 | index := b.name_index(binding.name) |
| 341 | b.function.global_slots[index] = binding.global_slot |
| 342 | b.emit(.global, index, 0, origin) |
| 343 | } else if b.code.builtin_root { |
| 344 | b.emit(.global, b.name_index(binding.name), 0, origin) |
| 345 | } else { |
| 346 | b.global_reference(SyntaxBinding{ ...binding, introduced: binding.name, introduced_namespace: binding.namespace }, origin) |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | .keyword { return failure('syntax keyword ${binding.name} cannot be used as a value') } |
| 351 | .transformer { return failure('macro keyword ${binding.name} cannot be used as a value') } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn (mut b Builder) keyword_name(id reader.NodeId) !string { |
| 356 | binding := b.resolve_binding(b.code.name(id)!) |
| 357 | return if binding.kind == .keyword { binding.name } else { '' } |
| 358 | } |
| 359 | |
| 360 | fn (mut b Builder) declare_global_keyword(name string) { |
| 361 | if isnil(b.scope) { b.global_definition_name(name) } |
| 362 | } |
| 363 | |
| 364 | fn (mut b Builder) store(name string, define bool, origin reader.NodeId) ! { |
| 365 | if define { |
| 366 | if !isnil(b.scope) { |
| 367 | b.emit(.define_local, 0, b.declare_definition(name), origin) |
| 368 | } else { |
| 369 | target := b.global_definition_name(name) |
| 370 | alias_operand := if target != name { b.record_global_alias_operand(name)! } else { 0 } |
| 371 | b.emit(.define_global, b.name_index(target), alias_operand, origin) |
| 372 | } |
| 373 | return |
| 374 | } |
| 375 | binding := b.resolve_binding(name) |
| 376 | if !isnil(binding.pattern_variable) { return failure('cannot assign pattern variable ${name}') } |
| 377 | match binding.kind { |
| 378 | .lexical { b.emit(.assign_local, b.syntax_binding_depth(binding)!, binding.slot, origin) } |
| 379 | .global { |
| 380 | if !isnil(b.code.compiler_vm) { |
| 381 | unsafe { (&VM(b.code.compiler_vm)).check_imported_assignment(b.code.namespace, name)! } |
| 382 | } |
| 383 | if binding.introduced != '' { |
| 384 | b.assign_global_reference(binding, origin) |
| 385 | } else if voidptr(binding.namespace) != voidptr(b.code.namespace) { |
| 386 | b.assign_global_reference(SyntaxBinding{ ...binding, introduced: name, introduced_namespace: b.code.namespace }, origin) |
| 387 | } else { |
| 388 | if !isnil(b.code.compiler_vm) { |
| 389 | unsafe { (&VM(b.code.compiler_vm)).check_assignment_in(binding.namespace, binding.name)! } |
| 390 | } |
| 391 | index := b.name_index(binding.name) |
| 392 | if binding.global_slot >= 0 { |
| 393 | b.function.global_slots[index] = binding.global_slot |
| 394 | b.emit(.assign_resolved_global, index, 0, origin) |
| 395 | } else { |
| 396 | b.assign_global_reference(SyntaxBinding{ ...binding, introduced: binding.name, introduced_namespace: binding.namespace }, origin) |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | .keyword { return failure('cannot assign syntax keyword ${binding.name}') } |
| 401 | .transformer { return failure('cannot assign macro keyword ${binding.name}') } |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | fn compile_program(code &Code, forms []reader.NodeId) &Function { |
| 406 | function := &Function{ code: code } |
| 407 | mut b := Builder{ code: code, function: function, definition_context: true } |
| 408 | if !b.code.has_syntax { |
| 409 | syntax_table := b.current_syntax_table() |
| 410 | if !isnil(syntax_table) && syntax_table.entries.len > 0 { |
| 411 | b.code.syntax_base = syntax_table |
| 412 | b.code.has_syntax = true |
| 413 | } |
| 414 | } |
| 415 | scratch := b.code.enter_list_scratch() |
| 416 | defer { b.code.leave_list_scratch(scratch) } |
| 417 | b.sequence(forms, true) |
| 418 | b.emit(.ret, 0, 0, if forms.len > 0 { forms.last() } else { reader.no_node }) |
| 419 | return b.finish_program() |
| 420 | } |
| 421 | |
| 422 | fn (mut b Builder) finish_program() &Function { |
| 423 | finalize_captures(b.function) |
| 424 | // Syntax-decoding caches are compilation scratch. Constants and instruction |
| 425 | // operands retain everything execution needs; source stays for diagnostics. |
| 426 | // Replacing a map does not release its old containers in GC-free hosts. |
| 427 | // These NodeId-keyed maps own their containers, not the retained payloads. |
| 428 | unsafe { |
| 429 | b.code.names.free() |
| 430 | b.code.literals.free() |
| 431 | b.code.lists.free() |
| 432 | } |
| 433 | b.code.names = map[reader.NodeId]string{} |
| 434 | b.code.literals = map[reader.NodeId]Value{} |
| 435 | b.code.lists = map[reader.NodeId][]reader.NodeId{} |
| 436 | b.code.keyword_variables = []string{} |
| 437 | b.code.release_compile_borrows() |
| 438 | b.code.freeze_syntax_locations() |
| 439 | b.code.release_compile_names() |
| 440 | b.scope = unsafe { nil } |
| 441 | b.table = unsafe { nil } |
| 442 | return b.function |
| 443 | } |
| 444 | |
| 445 | fn (mut b Builder) fault(message string, origin reader.NodeId) { |
| 446 | b.fault_error(failure(message), origin) |
| 447 | } |
| 448 | |
| 449 | fn (mut b Builder) fault_error(cause IError, origin reader.NodeId) { |
| 450 | if is_control_transfer(cause) { |
| 451 | mut state := b.code.procedural_syntax() |
| 452 | state.aborted = &CompilerControlTransfer{ error: cause } |
| 453 | return |
| 454 | } |
| 455 | index := b.function.failures.len |
| 456 | // Store concrete diagnostics by value. The compiler's interface-array |
| 457 | // smartcast append emits a raw pointer instead of a boxed IError. |
| 458 | if cause is EvalError { |
| 459 | b.function.failures << EvalError{ message: cause.message, source_path: cause.source_path, offset: cause.offset, line: cause.line, column: cause.column } |
| 460 | } else { |
| 461 | b.function.failures << EvalError{ message: cause.msg() } |
| 462 | } |
| 463 | b.emit(.fail, index, 0, origin) |
| 464 | } |
| 465 | |
| 466 | // Invalid subexpressions become executable failures: an unselected branch stays |
| 467 | // unexecuted, and earlier top-level definitions still take effect before errors. |
| 468 | fn (mut b Builder) expression(id reader.NodeId, tail bool) { |
| 469 | if !isnil(b.code.procedural) && !isnil(b.code.procedural.aborted) { return } |
| 470 | // Source nesting is reader-bounded. Macro output needs its own bound, even |
| 471 | // when a transformation grows beneath a conditional instead of at its head. |
| 472 | tracked := b.code.has_syntax || b.code.has_static |
| 473 | if tracked { |
| 474 | if b.code.compile_depth >= 512 { |
| 475 | b.fault('expanded expression nesting limit exceeded', id) |
| 476 | return |
| 477 | } |
| 478 | b.code.compile_depth++ |
| 479 | } |
| 480 | defer { if tracked { b.code.compile_depth-- } } |
| 481 | start := b.function.instructions.len |
| 482 | b.expression_inner(id, tail) or { |
| 483 | b.function.instructions.trim(start) |
| 484 | |
| 485 | b.fault_error(err, id) |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | fn (mut b Builder) sequence(nodes []reader.NodeId, tail bool) { |
| 490 | if nodes.len == 0 { |
| 491 | b.constant(unspecified(), reader.no_node) |
| 492 | return |
| 493 | } |
| 494 | for i, id in nodes { |
| 495 | b.expression(id, tail && i == nodes.len - 1) |
| 496 | if i != nodes.len - 1 { b.emit(.drop, 0, 0, id) } |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | fn (mut b Builder) child(params []string, rest string, body []reader.NodeId, tail bool) &Function { |
| 501 | return b.build_child(params, rest, body, false, b.return_tail && tail, false) |
| 502 | } |
| 503 | |
| 504 | fn (mut b Builder) source_child(params []string, rest string, body []reader.NodeId) &Function { |
| 505 | return b.build_child(params, rest, body, true, true, false) |
| 506 | } |
| 507 | |
| 508 | fn (mut b Builder) goops_method_child(params []string, rest string, body []reader.NodeId) &Function { |
| 509 | return b.build_child(params, rest, body, true, true, true) |
| 510 | } |
| 511 | |
| 512 | fn (mut b Builder) build_child(params []string, rest string, body []reader.NodeId, source bool, return_tail bool, method bool) &Function { |
| 513 | mut function := &Function{ code: b.code, params: params.len, rest: rest != '' } |
| 514 | mut scope := new_compile_scope(Scope{ |
| 515 | parent: b.scope |
| 516 | function: function |
| 517 | return_boundary: if source { |
| 518 | .function |
| 519 | } else { |
| 520 | .none |
| 521 | } |
| 522 | }) |
| 523 | for name in params { scope.declare(name) } |
| 524 | if rest != '' { scope.declare(rest) } |
| 525 | if method && 'next-method' !in scope.names { |
| 526 | function.goops_next_slot = scope.declare('next-method') |
| 527 | } |
| 528 | mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: return_tail } |
| 529 | inner.body(body) |
| 530 | inner.emit(.ret, 0, 0, if body.len > 0 { body.last() } else { reader.no_node }) |
| 531 | inner.prepend_exit_mark(scope) |
| 532 | return function |
| 533 | } |
| 534 | |
| 535 | fn (mut b Builder) body(nodes []reader.NodeId) { |
| 536 | b.body_sequence(nodes, true) |
| 537 | } |
| 538 | |
| 539 | // A delayed expression has no implicit definition region. Actual procedure |
| 540 | // and binding bodies use child(), which discovers their internal definitions. |
| 541 | fn (mut b Builder) expression_child(expression reader.NodeId) &Function { |
| 542 | function := &Function{ code: b.code } |
| 543 | scope := new_compile_scope(Scope{ parent: b.scope, function: function, return_boundary: .deferred }) |
| 544 | mut inner := Builder{ code: b.code, function: function, scope: scope } |
| 545 | inner.expression(expression, true) |
| 546 | inner.emit(.ret, 0, 0, expression) |
| 547 | return function |
| 548 | } |
| 549 | |
| 550 | fn (mut b Builder) body_sequence(nodes []reader.NodeId, tail bool) { |
| 551 | previous := b.scope |
| 552 | previous_context := b.definition_context |
| 553 | b.scope = new_compile_scope(Scope{ parent: previous, function: b.function }) |
| 554 | defer { |
| 555 | b.scope = previous |
| 556 | b.definition_context = previous_context |
| 557 | } |
| 558 | prepared := b.prepare_body(nodes) or { |
| 559 | b.fault_error(err, if nodes.len > 0 { nodes[0] } else { reader.no_node }) |
| 560 | return |
| 561 | } |
| 562 | // Preparation returns a private flat ID list, not a Code-owned list cache. |
| 563 | defer { unsafe { prepared.free() } } |
| 564 | b.definition_context = true |
| 565 | b.sequence(prepared, tail) |
| 566 | } |
| 567 | |
| 568 | fn (mut b Builder) make_closure(function &Function, origin reader.NodeId) { |
| 569 | index := b.function.children.len |
| 570 | b.function.children << function |
| 571 | b.emit(if isnil(function.star) { Op.closure } else { Op.star_closure }, index, 0, origin) |
| 572 | } |
| 573 | |
| 574 | fn (mut b Builder) scope_application(function &Function, initializers []reader.NodeId, tail bool, origin reader.NodeId) { |
| 575 | index := b.function.children.len |
| 576 | b.function.children << function |
| 577 | b.emit(.scope_function, index, 0, origin) |
| 578 | for initializer in initializers { b.expression(initializer, false) } |
| 579 | b.emit(if tail { Op.scope_tail } else { Op.scope_call }, initializers.len, 0, origin) |
| 580 | } |
| 581 | |
| 582 | fn (mut b Builder) application(count int, tail bool, origin reader.NodeId) { |
| 583 | b.emit(if tail { Op.tail_call } else { Op.call }, count, 0, origin) |
| 584 | } |
| 585 | |
| 586 | fn (mut b Builder) expression_inner(source reader.NodeId, tail bool) ! { |
| 587 | graph_expression := if !isnil(b.code.graphs) { |
| 588 | b.code.canonical_syntax_id(source)! |
| 589 | } else { |
| 590 | reader.no_node |
| 591 | } |
| 592 | if !isnil(b.code.graphs) { |
| 593 | b.code.enter_graph_expression(graph_expression)! |
| 594 | } |
| 595 | defer { |
| 596 | if graph_expression != reader.no_node { b.code.leave_graph_expression(graph_expression) } |
| 597 | } |
| 598 | definitions_allowed := b.definition_context |
| 599 | b.definition_context = false |
| 600 | defer { b.definition_context = definitions_allowed } |
| 601 | id := b.expand_syntax_head(source)! |
| 602 | n := b.code.node(id)! |
| 603 | match n.kind { |
| 604 | .symbol { |
| 605 | name := b.code.name(id)! |
| 606 | binding := b.resolve_binding(name) |
| 607 | if binding.kind == .keyword && binding.name in ['return', 'break', 'continue'] { |
| 608 | if binding.name == 'return' { |
| 609 | b.return_form([], tail, id)! |
| 610 | } else if binding.name == 'break' { |
| 611 | b.break_form([], id)! |
| 612 | } else { |
| 613 | b.continue_form([], id)! |
| 614 | } |
| 615 | return |
| 616 | } |
| 617 | b.load_resolved(name, binding, id)! |
| 618 | return |
| 619 | } |
| 620 | .number, .boolean, .string_literal, .character, .bytevector, .keyword { |
| 621 | b.constant(b.code.datum(id)!, id) |
| 622 | return |
| 623 | } |
| 624 | .empty_list { return failure('empty list is not an expression') } |
| 625 | .reference { return failure('unresolved reader reference in executable syntax') } |
| 626 | .vector { |
| 627 | b.constant(b.code.datum(id)!, id) |
| 628 | return |
| 629 | } |
| 630 | .pair {} |
| 631 | } |
| 632 | nodes := b.code.nodes(id)! |
| 633 | head := b.code.node(nodes[0])! |
| 634 | if head.kind == .symbol { |
| 635 | binding := b.resolve_binding(b.code.name(nodes[0])!) |
| 636 | if binding.kind == .transformer && !isnil(binding.transformer.enumeration) { |
| 637 | b.enumeration_expression(binding, nodes, id)! |
| 638 | return |
| 639 | } |
| 640 | } |
| 641 | name := if head.kind == .symbol { b.keyword_name(nodes[0])! } else { '' } |
| 642 | match name { |
| 643 | implicit_statement_name, 'vile:statement' { b.implicit_statement(nodes, tail, id)! } |
| 644 | 'return' { b.return_form(nodes[1..], tail, id)! } |
| 645 | 'break' { b.break_form(nodes[1..], id)! } |
| 646 | 'continue' { b.continue_form(nodes[1..], id)! } |
| 647 | 'record-type-descriptor', 'record-constructor-descriptor' { |
| 648 | b.record_descriptor_expression(nodes, id, name == 'record-constructor-descriptor')! |
| 649 | } |
| 650 | 'eol-style', 'error-handling-mode', 'buffer-mode' { |
| 651 | b.transcoder_choice_syntax(name, nodes, id)! |
| 652 | } |
| 653 | 'file-options' { b.file_options_syntax(nodes, id)! } |
| 654 | 'endianness' { b.bytevector_endianness(nodes, id)! } |
| 655 | 'quote' { |
| 656 | check_arity(name, nodes.len - 1, 1, 1)! |
| 657 | b.constant(b.code.datum(nodes[1])!, id) |
| 658 | } |
| 659 | 'if' { |
| 660 | check_arity(name, nodes.len - 1, 2, 3)! |
| 661 | b.expression(nodes[1], false) |
| 662 | branch := b.emit(.jump_false, 0, 0, id) |
| 663 | b.expression(nodes[2], tail) |
| 664 | finish := b.emit(.jump, 0, 0, id) |
| 665 | b.patch(branch, b.function.instructions.len) |
| 666 | if nodes.len == 4 { |
| 667 | b.expression(nodes[3], tail) |
| 668 | } else { |
| 669 | b.constant(unspecified(), id) |
| 670 | } |
| 671 | b.patch(finish, b.function.instructions.len) |
| 672 | } |
| 673 | 'include', 'include-ci', 'cond-expand' { |
| 674 | forms := b.static_forms(name, nodes, id)! |
| 675 | b.definition_context = definitions_allowed |
| 676 | b.sequence(forms, tail) |
| 677 | } |
| 678 | 'begin' { |
| 679 | b.definition_context = definitions_allowed |
| 680 | b.sequence(nodes[1..], tail) |
| 681 | } |
| 682 | 'lambda' { |
| 683 | check_arity(name, nodes.len - 1, 2, -1)! |
| 684 | params, rest := b.code.formals(nodes[1])! |
| 685 | b.make_closure(b.source_child(params, rest, nodes[2..]), id) |
| 686 | } |
| 687 | 'lambda*' { |
| 688 | check_arity(name, nodes.len - 1, 2, -1)! |
| 689 | formals := b.code.star_formals(nodes[1], false)! |
| 690 | b.make_closure(b.star_child(formals, nodes[2..], false), id) |
| 691 | } |
| 692 | 'case-lambda' { b.case_lambda_form(nodes, id)! } |
| 693 | 'syntax-case' { b.syntax_case_form(nodes, tail, id)! } |
| 694 | 'with-syntax' { b.with_syntax_form(nodes, tail, id)! } |
| 695 | 'syntax' { b.syntax_form(nodes, id)! } |
| 696 | 'quasisyntax' { b.quasisyntax_form(nodes, tail, id)! } |
| 697 | 'unsyntax', 'unsyntax-splicing' { return failure('${name} is only valid in quasisyntax') } |
| 698 | 'let-values', 'let*-values' { b.values_binding_form(name, nodes, tail, id)! } |
| 699 | 'parameterize' { b.parameterize_form(nodes, tail, id)! } |
| 700 | 'define-library', 'import' { b.library_form(name, nodes, id, definitions_allowed)! } |
| 701 | 'define-enumeration' { |
| 702 | if !definitions_allowed { |
| 703 | return failure('define-enumeration is not valid in an expression position') |
| 704 | } |
| 705 | b.enumeration_definition(nodes, id)! |
| 706 | } |
| 707 | 'define-record-type' { |
| 708 | if !definitions_allowed { |
| 709 | return failure('define-record-type is not valid in an expression position') |
| 710 | } |
| 711 | b.record_definition(nodes, id)! |
| 712 | } |
| 713 | 'define-class', 'standard-define-class' { |
| 714 | if !definitions_allowed { |
| 715 | return failure('${name} is not valid in an expression position') |
| 716 | } |
| 717 | b.goops_class_definition(nodes, id)! |
| 718 | } |
| 719 | 'class' { |
| 720 | check_arity('class', nodes.len - 1, 1, -1)! |
| 721 | b.goops_class_expression(nodes[1], nodes[2..], reader.no_node, id)! |
| 722 | } |
| 723 | 'define-accessor' { |
| 724 | if !definitions_allowed { |
| 725 | return failure('define-accessor is not valid in an expression position') |
| 726 | } |
| 727 | b.goops_accessor_definition(nodes, id)! |
| 728 | } |
| 729 | 'define-extended-generic', 'define-extended-generics' { |
| 730 | if !definitions_allowed { |
| 731 | return failure('${name} is not valid in an expression position') |
| 732 | } |
| 733 | if name == 'define-extended-generic' { |
| 734 | b.goops_extended_definition(nodes, id)! |
| 735 | } else { |
| 736 | b.goops_extended_definitions(nodes, id)! |
| 737 | } |
| 738 | } |
| 739 | 'define-generic' { |
| 740 | if !definitions_allowed { |
| 741 | return failure('define-generic is not valid in an expression position') |
| 742 | } |
| 743 | b.goops_generic_definition(nodes, id)! |
| 744 | } |
| 745 | 'define-method' { |
| 746 | if !definitions_allowed { |
| 747 | return failure('define-method is not valid in an expression position') |
| 748 | } |
| 749 | b.goops_method_definition(nodes, id)! |
| 750 | } |
| 751 | 'define-method*' { |
| 752 | if !definitions_allowed { |
| 753 | return failure('define-method* is not valid in an expression position') |
| 754 | } |
| 755 | b.goops_method_star_definition(nodes, id)! |
| 756 | } |
| 757 | 'method' { b.goops_method_expression(nodes, id)! } |
| 758 | 'method*' { b.goops_method_star_expression(nodes, id)! } |
| 759 | 'define-values' { |
| 760 | if !definitions_allowed { |
| 761 | return failure('define-values is not valid in an expression position') |
| 762 | } |
| 763 | b.values_definition(nodes, id)! |
| 764 | } |
| 765 | 'delay', 'delay-force' { |
| 766 | check_arity(name, nodes.len - 1, 1, 1)! |
| 767 | function := b.expression_child(nodes[1]) |
| 768 | index := b.function.children.len |
| 769 | b.function.children << function |
| 770 | b.emit(.promise, index, int(name == 'delay-force'), id) |
| 771 | } |
| 772 | 'define', 'define*' { b.define_form(name, nodes, id, definitions_allowed)! } |
| 773 | 'set!' { b.assignment_form(nodes, id)! } |
| 774 | 'and', 'or' { |
| 775 | if nodes.len == 1 { |
| 776 | b.constant(boolean(name == 'and'), id) |
| 777 | return |
| 778 | } |
| 779 | mut jumps := []int{} |
| 780 | for i in 1 .. nodes.len { |
| 781 | b.expression(nodes[i], tail && i == nodes.len - 1) |
| 782 | if i != nodes.len - 1 { |
| 783 | jumps << b.emit(if name == 'and' { Op.and_jump } else { Op.or_jump }, 0, 0, id) |
| 784 | } |
| 785 | } |
| 786 | for jump in jumps { b.patch(jump, b.function.instructions.len) } |
| 787 | } |
| 788 | 'let', 'let*', 'letrec', 'letrec*' { b.binding_form(name, nodes, tail, id)! } |
| 789 | 'when', 'unless' { b.guarded_sequence(name, nodes, tail, id)! } |
| 790 | 'define-syntax' { |
| 791 | if !definitions_allowed { |
| 792 | return failure('define-syntax is not valid in an expression position') |
| 793 | } |
| 794 | b.syntax_definition(nodes, id)! |
| 795 | } |
| 796 | 'let-syntax', 'letrec-syntax' { b.local_syntax(name, nodes, tail)! } |
| 797 | 'cond' { b.cond_clauses(nodes, 1, tail, id) } |
| 798 | 'case' { b.case_form(nodes, tail, id)! } |
| 799 | 'do' { b.do_form(nodes, tail, id)! } |
| 800 | 'quasiquote' { |
| 801 | check_arity(name, nodes.len - 1, 1, 1)! |
| 802 | b.quasiquote(nodes[1], 1)! |
| 803 | } |
| 804 | 'unquote', 'unquote-splicing' { |
| 805 | return failure('${name} outside quasiquote') |
| 806 | } |
| 807 | else { |
| 808 | for node in nodes { b.expression(node, false) } |
| 809 | b.application(nodes.len - 1, tail, id) |
| 810 | } |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | // TinyCC reserves stack space for every temporary in a function. Keep these |
| 815 | // form-specific temporaries out of unrelated recursive expression frames. |
| 816 | fn (mut b Builder) library_form(name string, nodes []reader.NodeId, id reader.NodeId, definitions_allowed bool) ! { |
| 817 | if !definitions_allowed || !isnil(b.scope) { |
| 818 | return failure('${name} is only valid at top level') |
| 819 | } |
| 820 | if name == 'define-library' { |
| 821 | if !isnil(b.code.namespace) && !b.code.namespace.writable { |
| 822 | return failure('environment does not permit library definitions') |
| 823 | } |
| 824 | index := b.function.constants.len |
| 825 | b.function.constants << payload_value(.library_declaration, b.library_declaration(nodes)!) |
| 826 | b.emit(.library_define, index, 0, id) |
| 827 | } else { |
| 828 | mut sets := []ImportSet{len: nodes.len - 1} |
| 829 | for i in 1 .. nodes.len { sets[i - 1] = b.import_set(nodes[i])! } |
| 830 | index := b.function.constants.len |
| 831 | b.function.constants << payload_value(.library_imports, &LibraryImports{ sets: sets }) |
| 832 | b.emit(.library_import, index, 0, id) |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | fn (mut b Builder) define_form(name string, nodes []reader.NodeId, id reader.NodeId, definitions_allowed bool) ! { |
| 837 | if !definitions_allowed { |
| 838 | return failure('${name} is not valid in an expression position') |
| 839 | } |
| 840 | check_arity(name, nodes.len - 1, 2, -1)! |
| 841 | target := b.code.node(nodes[1])! |
| 842 | if target.kind == .symbol { |
| 843 | check_arity(name, nodes.len - 1, 2, 2)! |
| 844 | key := b.code.variable(nodes[1])! |
| 845 | b.declare_global_keyword(key) |
| 846 | b.expression(nodes[2], false) |
| 847 | b.store(key, true, id)! |
| 848 | } else if target.kind == .pair { |
| 849 | key := b.code.variable(target.car)! |
| 850 | b.declare_global_keyword(key) |
| 851 | if name == 'define*' { |
| 852 | formals := b.code.star_formals(target.cdr, false)! |
| 853 | b.make_closure(b.star_child(formals, nodes[2..], false), id) |
| 854 | } else { |
| 855 | params, rest := b.code.formals(target.cdr)! |
| 856 | b.make_closure(b.source_child(params, rest, nodes[2..]), id) |
| 857 | } |
| 858 | b.store(key, true, id)! |
| 859 | } else { |
| 860 | return failure('define needs an identifier or procedure signature') |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | fn (mut b Builder) assignment_form(nodes []reader.NodeId, id reader.NodeId) ! { |
| 865 | check_arity('set!', nodes.len - 1, 2, 2)! |
| 866 | target := b.code.node(nodes[1])! |
| 867 | if target.kind == .pair { |
| 868 | call := b.code.nodes(nodes[1])! |
| 869 | for part in call { b.expression(part, false) } |
| 870 | b.expression(nodes[2], false) |
| 871 | // The stack is [getter, arg..., value]. Replace its first entry |
| 872 | // with the getter's setter, then invoke it on the same packet. |
| 873 | b.emit(.assignment_setter, call.len, 0, id) |
| 874 | b.emit(.assignment_setter_result, call.len, 0, id) |
| 875 | b.emit(.call, call.len, 0, id) |
| 876 | b.emit(.assignment_finish, 0, 0, id) |
| 877 | } else { |
| 878 | key := b.code.variable(nodes[1])! |
| 879 | b.expression(nodes[2], false) |
| 880 | b.store(key, false, id)! |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | fn (mut b Builder) binding_form(name string, nodes []reader.NodeId, tail bool, origin reader.NodeId) ! { |
| 885 | check_arity(name, nodes.len - 1, 2, -1)! |
| 886 | mut binding_index := 1 |
| 887 | mut loop_name := '' |
| 888 | if name == 'let' && b.code.node(nodes[1])!.kind == .symbol { |
| 889 | check_arity(name, nodes.len - 1, 3, -1)! |
| 890 | loop_name = b.code.variable(nodes[1])! |
| 891 | binding_index = 2 |
| 892 | } |
| 893 | bindings := b.code.nodes(nodes[binding_index])! |
| 894 | mut names := []string{} |
| 895 | mut initializers := []reader.NodeId{} |
| 896 | mut seen := map[string]bool{} |
| 897 | for binding in bindings { |
| 898 | parts := b.code.nodes(binding)! |
| 899 | if parts.len != 2 { return failure('each ${name} binding needs a name and initializer') } |
| 900 | key := b.code.variable(parts[0])! |
| 901 | if name != 'let*' && b.code.binding_key(key) in seen { |
| 902 | return failure('duplicate binding ${key}') |
| 903 | } |
| 904 | seen[b.code.binding_key(key)] = true |
| 905 | names << key |
| 906 | initializers << parts[1] |
| 907 | } |
| 908 | body := nodes[binding_index + 1..] |
| 909 | if loop_name != '' { |
| 910 | // Initializers run in the enclosing scope. Hidden wrapper parameters carry |
| 911 | // their values into the recursive scope without exposing the loop name early. |
| 912 | mut function := &Function{ code: b.code, params: names.len } |
| 913 | mut scope := new_compile_scope(Scope{ parent: b.scope, function: function }) |
| 914 | function.slot_count = names.len |
| 915 | loop_slot := scope.declare(loop_name) |
| 916 | mut wrapper := Builder{ code: b.code, function: function, scope: scope } |
| 917 | wrapper.make_closure(wrapper.source_child(names, '', body), origin) |
| 918 | wrapper.emit(.define_local, 0, loop_slot, origin) |
| 919 | wrapper.emit(.drop, 0, 0, origin) |
| 920 | wrapper.emit(.local, 0, loop_slot, origin) |
| 921 | for i in 0 .. names.len { wrapper.emit(.local, 0, i, origin) } |
| 922 | // The recursive procedure captures this wrapper. Hidden initializer |
| 923 | // parameters have moved to the operand stack and must not pin their |
| 924 | // original payloads for the entire lifetime of the loop closure. |
| 925 | for i in 0 .. names.len { |
| 926 | wrapper.constant(unspecified(), origin) |
| 927 | wrapper.emit(.define_local, 0, i, origin) |
| 928 | wrapper.emit(.drop, 0, 0, origin) |
| 929 | } |
| 930 | wrapper.application(names.len, true, origin) |
| 931 | wrapper.emit(.ret, 0, 0, origin) |
| 932 | b.make_closure(function, origin) |
| 933 | for initializer in initializers { b.expression(initializer, false) } |
| 934 | b.application(names.len, tail, origin) |
| 935 | } else if name == 'let*' { |
| 936 | b.sequential_bindings(names, initializers, body, 0, tail, origin) |
| 937 | } else if name in ['letrec', 'letrec*'] { |
| 938 | function := &Function{ code: b.code } |
| 939 | mut scope := new_compile_scope(Scope{ parent: b.scope, function: function }) |
| 940 | for key in names { scope.declare(key) } |
| 941 | mut inner := Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail && tail } |
| 942 | if name == 'letrec*' { |
| 943 | // Every location exists before evaluation, while earlier initializers |
| 944 | // become visible immediately to the later ones. |
| 945 | for i, initializer in initializers { |
| 946 | inner.expression(initializer, false) |
| 947 | inner.emit(.define_local, 0, i, origin) |
| 948 | inner.emit(.drop, 0, 0, origin) |
| 949 | } |
| 950 | } else { |
| 951 | for initializer in initializers { inner.expression(initializer, false) } |
| 952 | // letrec initializes its locations only after every initializer finishes. |
| 953 | for i := names.len - 1; i >= 0; i-- { |
| 954 | inner.emit(.define_local, 0, i, origin) |
| 955 | inner.emit(.drop, 0, 0, origin) |
| 956 | } |
| 957 | } |
| 958 | inner.body(body) |
| 959 | inner.emit(.ret, 0, 0, origin) |
| 960 | b.make_closure(function, origin) |
| 961 | b.application(0, tail, origin) |
| 962 | } else { |
| 963 | function := b.child(names, '', body, tail) |
| 964 | // Initializers run in the enclosing scope. The private function stays |
| 965 | // on the operand stack until all arguments are ready, without publishing |
| 966 | // a procedure or marking the enclosing locations escaped. |
| 967 | b.scope_application(function, initializers, tail, origin) |
| 968 | } |
| 969 | } |
| 970 | |
| 971 | fn (mut b Builder) sequential_bindings(names []string, initializers []reader.NodeId, body []reader.NodeId, _index int, tail bool, origin reader.NodeId) { |
| 972 | if names.len == 0 { |
| 973 | b.make_closure(b.child([], '', body, tail), origin) |
| 974 | b.application(0, tail, origin) |
| 975 | return |
| 976 | } |
| 977 | // Build a chain of functions iteratively: flat let* forms can contain many |
| 978 | // bindings even though source nesting is bounded by the reader. |
| 979 | // This first builder emits into the parent's function and must share its |
| 980 | // name cache even when neither builder has emitted a name yet. |
| 981 | mut current := Builder{ code: b.code, function: b.function, scope: b.scope, table: b.name_table(), return_tail: b.return_tail } |
| 982 | for i, name in names { |
| 983 | function := &Function{ code: b.code, params: 1 } |
| 984 | mut scope := new_compile_scope(Scope{ parent: current.scope, function: function }) |
| 985 | scope.declare(name) |
| 986 | current.make_closure(function, origin) |
| 987 | current.expression(initializers[i], false) |
| 988 | current.application(1, if i == 0 { tail } else { true }, origin) |
| 989 | if i > 0 { current.emit(.ret, 0, 0, origin) } |
| 990 | current = Builder{ code: b.code, function: function, scope: scope, return_tail: b.return_tail && tail } |
| 991 | } |
| 992 | current.body(body) |
| 993 | current.emit(.ret, 0, 0, origin) |
| 994 | } |
| 995 | |
| 996 | fn (mut b Builder) cond_clauses(nodes []reader.NodeId, start_index int, tail bool, origin reader.NodeId) { |
| 997 | mut ends := []int{} |
| 998 | mut completed := false |
| 999 | for index in start_index .. nodes.len { |
| 1000 | start := b.function.instructions.len |
| 1001 | next := b.cond_clause(nodes, index, tail, origin) or { |
| 1002 | b.function.instructions.trim(start) |
| 1003 | b.fault_error(err, nodes[index]) |
| 1004 | completed = true |
| 1005 | break |
| 1006 | } |
| 1007 | if next < 0 { |
| 1008 | completed = true |
| 1009 | break |
| 1010 | } |
| 1011 | ends << b.emit(.jump, 0, 0, origin) |
| 1012 | b.patch(next, b.function.instructions.len) |
| 1013 | b.emit(.drop, 0, 0, origin) |
| 1014 | } |
| 1015 | if !completed { b.constant(unspecified(), origin) } |
| 1016 | for end in ends { b.patch(end, b.function.instructions.len) } |
| 1017 | } |
| 1018 | |
| 1019 | // Return the false-branch patch point, or -1 for an unconditional else clause. |
| 1020 | fn (mut b Builder) cond_clause(nodes []reader.NodeId, index int, tail bool, origin reader.NodeId) !int { |
| 1021 | clause := b.code.nodes(nodes[index])! |
| 1022 | if clause.len == 0 { return failure('cond clause must not be empty') } |
| 1023 | test := b.code.node(clause[0])! |
| 1024 | if test.kind == .symbol && b.keyword_name(clause[0])! == 'else' { |
| 1025 | if index != nodes.len - 1 || clause.len < 2 { |
| 1026 | return failure('cond else must be last and have a body') |
| 1027 | } |
| 1028 | b.sequence(clause[1..], tail) |
| 1029 | return -1 |
| 1030 | } |
| 1031 | arrow := clause.len >= 2 && b.code.node(clause[1])!.kind == .symbol && b.keyword_name(clause[1])! == '=>' |
| 1032 | if arrow && clause.len != 3 { return failure('cond => needs one receiver') } |
| 1033 | b.expression(clause[0], false) |
| 1034 | b.emit(.duplicate, 0, 0, origin) |
| 1035 | next := b.emit(.jump_false, 0, 0, origin) |
| 1036 | if clause.len == 1 { |
| 1037 | // Keep the successful test value. |
| 1038 | } else if arrow { |
| 1039 | b.expression(clause[2], false) |
| 1040 | b.emit(.swap, 0, 0, origin) |
| 1041 | b.application(1, tail, nodes[index]) |
| 1042 | } else { |
| 1043 | b.emit(.drop, 0, 0, origin) |
| 1044 | b.sequence(clause[1..], tail) |
| 1045 | } |
| 1046 | return next |
| 1047 | } |
| 1048 | |