From 90f9a4d23df0a412b8e430287cd9b9a8e2d5cb9d Mon Sep 17 00:00:00 2001 From: paul Date: Wed, 25 Nov 2026 08:30:15 +0000 Subject: [PATCH 1/5] codegen: run a trailing block on a discarded call `_ = f() { ... }` took the `_` discard path, which emitted `(void)(f())` and never looked at the call's trailing block, so the block vanished without a diagnostic. The same call bound to a name runs the block with the value as its context. The discard now binds the value to a temporary, pushes it as the context, runs the block, and throws the value away, freeing a fresh string. A builder's block already ran ahead of the call and is left as it was. tests/regression/test_trailing_block_discard.ae fails on 0.941.0 and passes here; it covers an int, a fresh string, and a discard nested in another's block, and is clean under macOS leaks. Mac make test-ae 2357/0; ae-x64 CC=gcc make ci green, 2382/0. Co-Authored-By: Claude Opus 5.5 --- compiler/codegen/codegen_stmt.c | 31 +++++++++++ ...25T080330Z-fixed-discard-trailing-block.md | 5 ++ .../regression/test_trailing_block_discard.ae | 52 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 new_changelogs/20261125T080330Z-fixed-discard-trailing-block.md create mode 100644 tests/regression/test_trailing_block_discard.ae diff --git a/compiler/codegen/codegen_stmt.c b/compiler/codegen/codegen_stmt.c index e8d1f479e..6478506f6 100644 --- a/compiler/codegen/codegen_stmt.c +++ b/compiler/codegen/codegen_stmt.c @@ -10520,6 +10520,37 @@ static void generate_statement_body(CodeGenerator* gen, ASTNode* stmt) { drhs->type == AST_STRING_INTERP || is_owned_string_unwrap(gen, drhs)) && is_heap_string_expr(gen, drhs); + /* A call with a trailing block, `_ = f() { ... }`, runs the + * block with the call's value as its context, as a named + * binding of it does, and the value is thrown away after. + * The `(void)` cast below emitted the call alone and the + * block was dropped without a word. A builder's block runs + * ahead of the call, in the call's own emission. */ + ASTNode* dblock = + (drhs->type == AST_FUNCTION_CALL && + !(drhs->value && is_builder_func_reg(gen, drhs->value))) + ? trailing_dsl_block(gen, drhs) : NULL; + TypeKind dk = drhs->node_type ? drhs->node_type->kind : TYPE_UNKNOWN; + if (dblock && (dk == TYPE_INT || dk == TYPE_INT64 || dk == TYPE_BOOL || + dk == TYPE_PTR || dk == TYPE_ACTOR_REF || + (dk == TYPE_STRING && !is_owned_opt_string_call(gen, drhs)))) { + print_indent(gen); + fprintf(gen->output, "{ %s _od = ", get_c_type(drhs->node_type)); + generate_expression(gen, drhs); + fprintf(gen->output, ";\n"); + gen->indent_level++; + print_indent(gen); + fprintf(gen->output, "_aether_ctx_push((void*)(intptr_t)_od);\n"); + emit_trailing_block_body(gen, dblock); + if (fresh_heap) { + print_indent(gen); + fprintf(gen->output, "aether_heap_str_free((void*)_od);\n"); + } + gen->indent_level--; + print_indent(gen); + fprintf(gen->output, "}\n"); + break; + } print_indent(gen); if (is_owned_opt_string_call(gen, drhs)) { /* #2750: a `string?` an Aether function handed over. */ diff --git a/new_changelogs/20261125T080330Z-fixed-discard-trailing-block.md b/new_changelogs/20261125T080330Z-fixed-discard-trailing-block.md new file mode 100644 index 000000000..ffc4ccf12 --- /dev/null +++ b/new_changelogs/20261125T080330Z-fixed-discard-trailing-block.md @@ -0,0 +1,5 @@ +- **A trailing block on a discarded call runs.** `_ = f() { ... }` emitted + the call alone and dropped its block without a word, while the same call + bound to a name ran the block with the value as its context. The discard + now runs the block the same way, then throws the value away, freeing a + fresh string. diff --git a/tests/regression/test_trailing_block_discard.ae b/tests/regression/test_trailing_block_discard.ae new file mode 100644 index 000000000..cc8952721 --- /dev/null +++ b/tests/regression/test_trailing_block_discard.ae @@ -0,0 +1,52 @@ +// A trailing block on a call whose value is thrown away, `_ = f() { ... }`, +// runs, with the call's value as its context. +// +// The `_` discard emitted `(void)(f())` and never looked at the call's +// trailing block, so the block vanished without a diagnostic. The same call +// bound to a name always ran its block. The test checks each block ran +// once, after the call, with the value as a context to inject, for an int +// and for a fresh string, and for a discard nested in another's block. + +extern exit(code: int) + +var calls = 0 +var ran = 0 +var seen = 0 + +seven(_ctx: ptr) -> int { + calls = calls + 1 + return 7 +} +named(_ctx: ptr, s: string) -> string { + calls = calls + 1 + return "name ${s}" +} +note(_ctx: ptr) { if _ctx != null { seen = seen + 1 } } + +main() { + _ = seven() { + ran = ran + calls + note() + } + if ran != 1 { + println("FAIL: the int block ran to ${ran}, want once after the call (1)") + exit(1) + } + _ = named("x") { + ran = ran + 10 * calls + note() + _ = seven() { + ran = ran + 100 * calls + note() + } + } + if ran != 321 { + println("FAIL: the string and nested blocks ran to ${ran}, want 321") + exit(1) + } + if seen != 3 { + println("FAIL: a block's context was null: ${seen} of 3 had one") + exit(1) + } + println("ok") +} From 073cb3b77f3d7b78a8a2b42711d61b343640fb10 Mon Sep 17 00:00:00 2001 From: paul Date: Wed, 25 Nov 2026 18:16:00 +0000 Subject: [PATCH 2/5] merge: one merge path for a direct and a transitive import With `import std.math (math_sin)` and `import a (sq)` in one module, the program importing that module failed in `a`'s own `math.sqrt(x)` with E0301 "Undefined function 'math.sqrt'". A module the program reaches only through other modules' imports is merged by the transitive pass (#243), which kept its own copy of the direct pass's per-declaration merge. The copy had functions, constants and types, but not `@extern("sym") name(...)` declarations (cloned as `_` so a qualified `ns.name(...)` resolves, #234), fault sets, messages, protocols or actors. So in such a module a qualified call of its own `@extern` was E0301, a fault it returned was E0300 "Undefined variable '_'", and an actor it spawned was "Undefined function 'spawn_'". A bare import anywhere on the path had the #870 synthetic import merge the module through the direct pass, which hid the gap; an all-selective path left only the transitive copy. #3852 (0.944.0) made std.math's sqrt, floor, ceil, round, abs, min, max and clamp `@extern`s, which exposed it for std.math; the same program built on 0.941.0, where they were bare externs. The fault and actor cases failed on 0.941.0 as well. The direct pass's loop is now merge_module_decls, and both passes call it. Regression: tests/integration/transitive_selective_import_merge (a user module's `@extern`s, std.math's, a fault set, a message and an actor, all reached through selective imports only), failing before the fix with six errors. Co-Authored-By: Claude Opus 5.5 --- compiler/aether_module.c | 692 ++++++++---------- ...fixed-transitive-selective-import-merge.md | 12 + .../lib/cmath.ae | 4 + .../lib/mid.ae | 19 + .../lib/pinger.ae | 14 + .../lib/probe.ae | 8 + .../lib/roots.ae | 6 + .../transitive_selective_import_merge/main.ae | 10 + .../test_transitive_selective_import_merge.sh | 40 + 9 files changed, 419 insertions(+), 386 deletions(-) create mode 100644 new_changelogs/20261125T181542Z-fixed-transitive-selective-import-merge.md create mode 100644 tests/integration/transitive_selective_import_merge/lib/cmath.ae create mode 100644 tests/integration/transitive_selective_import_merge/lib/mid.ae create mode 100644 tests/integration/transitive_selective_import_merge/lib/pinger.ae create mode 100644 tests/integration/transitive_selective_import_merge/lib/probe.ae create mode 100644 tests/integration/transitive_selective_import_merge/lib/roots.ae create mode 100644 tests/integration/transitive_selective_import_merge/main.ae create mode 100755 tests/integration/transitive_selective_import_merge/test_transitive_selective_import_merge.sh diff --git a/compiler/aether_module.c b/compiler/aether_module.c index ca754cf29..27daf14b4 100644 --- a/compiler/aether_module.c +++ b/compiler/aether_module.c @@ -4766,6 +4766,310 @@ static ASTNode* ss_clone_struct(ASTNode* program, ASTNode* decl, AetherModule* m return clone; } +/* Is `decl` an `@extern("c_symbol") name(...)` of a module? Such a + * declaration is part of the module's public surface (#234), unlike a bare + * `extern` C binding, which stays private, so the merge clones it like a + * function. */ +static int is_c_symbol_extern(const ASTNode* decl) { + return decl && decl->type == AST_EXTERN_FUNCTION && decl->value && decl->annotation && + strncmp(decl->annotation, "c_symbol:", 9) == 0; +} + +/* The clone of module `m`'s `@extern("c_symbol") name(...)`, as + * `_`, or NULL when the program has it already (a module reached + * twice must not declare it twice). The clone keeps the `c_symbol:` + * annotation, so codegen still forwards every call to the chosen C symbol; + * only the Aether-side name is namespace-prefixed, so a qualified + * `ns.name(...)` resolves. This is the path that makes a variadic `@extern` + * (std.strbuilder's `append_format`) reachable cross-module: an ordinary + * wrapper cannot forward a `...` tail. */ +static ASTNode* clone_c_symbol_extern(ASTNode* program, ASTNode* decl, AetherModule* m, + const char* ns) { + char* prefixed = mod_strf("%s_%s", ns, decl->value); + /* #3546: from the program's index. */ + if (ast_decl_kinds(program, prefixed) & DECL_EXTERN) { + free(prefixed); + return NULL; + } + ASTNode* clone = clone_ast_node(decl); + free(clone->value); + clone->value = prefixed; + /* Merged, not the program's own (#2632 reads the mark). */ + stamp_origin(clone, m); + ss_scope_node(clone, m); + return clone; +} + +/* Merge every declaration of module `mod` (namespace `ns`) into the + * program at *insert_idx, advancing it: its functions and `@extern`s under + * their merged C names, its constants, faults and types. The one path for + * a direct import and a module reached only through other modules' + * imports: the transitive pass kept a copy of it, which lacked the + * `@extern`s, fault sets, messages, protocols and actors a direct import + * merges, so a module reached only through selective imports lost them. */ +static void merge_module_decls(ASTNode* program, AetherModule* mod, const char* ns, + int* insert_idx) { + ASTNode* mod_ast = mod->ast; + MergePass pass = {0}; + for (int j = 0; j < mod_ast->child_count; j++) { + ASTNode* decl = unwrap_export(mod_ast->children[j]); + + if ((decl->type == AST_FUNCTION_DEFINITION || decl->type == AST_BUILDER_FUNCTION) && decl->value) { + // Build prefixed name: "double_it" -> "mymath_double_it", + // apart from an extern of the module (#2978). + char* prefixed = merged_function_name(ns, mod_ast, decl->value); + + // Skip if already merged (e.g. from a prior non-selective + // import); every clause of a set is merged (#2643). + if (program_has_function_before(program, prefixed, &pass)) { + free(prefixed); + continue; + } + + ASTNode* clone = clone_ast_node(decl); + free(clone->value); + clone->value = prefixed; + // Mark as imported so codegen emits this function with the + // C `static` storage class. Each translation unit that + // imports the same module gets its own private copy, and + // the linker no longer sees them as duplicate symbols + // when several .o files are linked together (e.g. macOS + // ld64, which does not support --allow-multiple-definition). + clone->is_imported = 1; + stamp_origin(clone, mod); + stamp_written_name(clone, ns, decl->value); /* #2978 */ + + // Rename intra-module function calls and constant refs within the cloned body + rename_intra_module_refs(clone, ns, module_func_names(mod), + module_const_names(mod), NULL); + // Also rewrite bare-name calls to selectively-imported + // names from M's own `import X (a, b)` statements — see + // apply_inherited_selective_imports comment for why. + apply_inherited_selective_imports(clone, mod_ast); + ss_scope_node(clone, mod); + + insert_child_at(program, clone, (*insert_idx)++); + merge_pass_add(&pass, clone); + } else if (is_c_symbol_extern(decl)) { + ASTNode* clone = clone_c_symbol_extern(program, decl, mod, ns); + if (clone) insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_CONST_DECLARATION && decl->value) { + /* Constants and module-level `var`s (#701) merge whatever the + * import selects: the module's functions read them (#1573: + * `import std.spec (fail)` failed with "Undefined variable + * 'spec_current_fw'"), and every one of its functions is now + * merged (#2613). */ + + // Skip if already merged (e.g. from a prior import of the same + // module, or a synthetic revisit — aether#1009). Without this + // the const is cloned twice → duplicate C definition. + char* prefixed = mod_strf("%s_%s", ns, decl->value); + if (program_has_const(program, prefixed)) { + free(prefixed); + continue; + } + + // Clone and rename constants too + ASTNode* clone = clone_ast_node(decl); + free(clone->value); + clone->value = prefixed; + stamp_origin(clone, mod); + + // Rename references to other module constants in the value expression + rename_intra_module_refs(clone, ns, module_func_names(mod), + module_const_names(mod), NULL); + apply_inherited_selective_imports(clone, mod_ast); + ss_scope_node(clone, mod); + + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_FAULT_DEFINITION) { + /* #error-unification P3: a fault set imported from module `ns`. + * Mirror the const branch: clone the definition, prefix each + * member's C symbol to `_` (so the member-access + * rewrite resolves `ns.Name` → that identifier, exactly like a + * const), and rewrite each member's interned string CONTENT to + * the qualified `"."` (so cross-module identity is + * unambiguous — two modules' same-named faults no longer + * compare equal by content). The parser/typecheck-registration/ + * codegen stages already consume AST_FAULT_DEFINITION with this + * exact `_` symbol / `.` content contract; + * this branch is the piece that fulfils it. */ + ASTNode* clone = clone_ast_node(decl); + int kept = 0; + for (int mi = 0; mi < clone->child_count; mi++) { + ASTNode* mem = clone->children[mi]; + if (!mem || !mem->value) { + free_ast_node(mem); + continue; + } + /* Every member, whatever a selective import names: the + * module's own functions may return any of them (#2613). */ + char* sym = mod_strf("%s_%s", ns, mem->value); + if (program_has_fault_member(program, sym)) { + free(sym); + free_ast_node(mem); + continue; + } + char* qualified = mod_strf("%s.%s", ns, mem->value); + /* Rewrite the interned content (children[0], an + * AST_LITERAL) to the qualified name, then the symbol. */ + if (mem->child_count > 0 && mem->children[0] && + mem->children[0]->value) { + free(mem->children[0]->value); + mem->children[0]->value = strdup(qualified); + } + free(qualified); + free(mem->value); + mem->value = sym; + /* Compact surviving members down over filtered/duped ones. */ + clone->children[kept++] = mem; + } + clone->child_count = kept; + if (kept > 0) { + insert_child_at(program, clone, (*insert_idx)++); + } else { + free_ast_node(clone); + } + } else if (decl->type == AST_STRUCT_DEFINITION && decl->value) { + // Struct definitions from imported modules enter the + // consumer's program AST. Closes the cross-`import` struct + // visibility gap that blocked the opaque-handle pattern: a + // module exposing `new_slot() -> ptr` whose body does + // `s = raw as *Slot` failed to typecheck once imported, + // because the consumer's symbol table lacked `Slot`. + // + // Bypasses the selective-import filter on purpose: a + // function body that casts to `*Slot` cannot type-check + // without the struct in scope, so even + // `import handle (new_slot)` must pull in `Slot`. + // + // Module-scoped: merged as `_` (ss_build_table), + // so two modules' same-named structs are two types; the + // same struct reached twice is merged once, as is one + // identical to an earlier definition (#2129). + ASTNode* clone = ss_clone_struct(program, decl, mod); + if (!clone) continue; + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_DISTINCT_TYPE_DEF && decl->value) { + // #908: `type X = distinct Base` from an imported module must + // enter the consumer's program AST (bare name, like structs) + // so resolve_distinct_types learns `X` and rewrites every + // `expr as X` / `x as Base` reference inside the merged + // constructor/unwrap/builder-child functions. Without this the + // imported distinct stays an unresolved TYPE_STRUCT{X} + // placeholder: the `as` cast fails its kind check ("cannot + // cast X to Base") and codegen emits an unknown C type `X`. + // Bypasses the selective-import filter on purpose (same as + // structs): a merged body that casts to/from `X` cannot + // type-check without the def in scope. + if (program_has_distinct(program, decl->value)) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + ss_scope_node(clone, mod); + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_CFN_TYPE_DEF && decl->value) { + // #2200: a `cfn Name(...) -> R` from an imported module enters + // the consumer's program AST (bare name, like distincts) so + // resolve_cfn_types learns `Name` and rewrites the `x: Name` + // annotations and `p as Name` casts inside the merged bodies. + // Bypasses the selective-import filter on purpose, same as + // structs: a merged body cannot type-check without it. + if (program_has_cfn(program, decl->value)) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + ss_scope_node(clone, mod); + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_BITSTRUCT_DEFINITION && decl->value) { + // A `bitstruct Name : { ... }` from an imported module + // must enter the consumer's program AST (bare name, like structs + // and distinct types) so resolve_bitstruct_types registers it and + // codegen emits its `typedef Name;`. Without this the + // imported bitstruct is unknown to both passes: the `word as + // Name` cast in the module's own (merged) function fails its kind + // check, and codegen emits a prototype referencing `Name` with no + // typedef ("unknown type name 'Name'"). Bypasses the selective- + // import filter on purpose (same as structs/distincts): a merged + // body that casts to/reads a field of the bitstruct cannot + // type-check without the def in scope. Dedup by name. + if (program_has_bitstruct(program, decl->value)) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_ENUM_DEFINITION && decl->value) { + // An `enum X { ... }` from an imported module must enter the + // consumer's program AST (bare name, like structs/bitstructs) so + // the typechecker's enum registry learns `X` (resolving `X.Member` + // selectors and `match` arms) and codegen emits its typedef. + // Without this an imported enum used by name fails: `Undefined + // variable 'X'` at type-check, or `unknown type name 'X'` in the + // emitted C. Bypasses the selective-import filter (same as + // structs): a merged body over the enum can't type-check without + // the def in scope. Dedup by name. + if (program_has_enum(program, decl->value)) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_SUM_TYPE_DEF && decl->value) { + // A `type X = A | B | C` sum type from an imported module enters + // the consumer's program AST (bare name) so its variant names and + // typedef resolve on both the type-check and codegen sides. Same + // failure/fix shape as enums/structs. Dedup by name. + if (program_has_sum(program, decl->value)) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + ss_scope_node(clone, mod); + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_MESSAGE_DEFINITION && decl->value) { + // #1006: `message X { ... }` from an imported module enters the + // consumer's program AST under its bare name (like structs), so + // `actor ! X { ... }` sends and `receive { X(..) -> }` patterns + // resolve, and codegen assigns X a runtime message-type id from + // the (per-program) message registry. Bypasses the selective- + // import filter on purpose: an imported actor's handlers cannot + // type-check without their message types in scope. Dedup by + // name; a different definition under the same name is a + // clash, reported (#2129). + if (definition_already_merged(program, decl, "message")) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + ss_scope_node(clone, mod); + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_PROTOCOL_DEFINITION && decl->value) { + // #385: a `protocol` enters under its bare name, as the + // messages it names do, so an imported actor that implements + // it and an `actor_ref[P]` written by the importer resolve. + if (definition_already_merged(program, decl, "protocol")) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + insert_child_at(program, clone, (*insert_idx)++); + } else if (decl->type == AST_ACTOR_DEFINITION && decl->value) { + // #1006: `actor X { ... }` from an imported module enters the + // consumer's program AST under its bare name. `spawn(X())` + // lowers to a `spawn_X` call and message sends reference bare + // message names, so the consumer needs the actor (and its + // messages, handled above) in scope by bare name. Bypasses the + // selective-import filter (same reasoning as structs/messages). + // Dedup by name; a second actor of the same name from another + // module is a clash, reported (#2129). + if (definition_already_merged(program, decl, "actor")) continue; + ASTNode* clone = clone_ast_node(decl); + clone->is_imported = 1; + stamp_origin(clone, mod); + // Unlike structs, an actor has a body: its receive handlers may + // call module-local functions or read module constants, which + // were cloned above under their `_` prefixed names. Rewrite + // those references so they resolve, exactly as function bodies do. + rename_intra_module_refs(clone, ns, module_func_names(mod), + module_const_names(mod), NULL); + apply_inherited_selective_imports(clone, mod_ast); + ss_scope_node(clone, mod); + insert_child_at(program, clone, (*insert_idx)++); + } + // Skip AST_MAIN_FUNCTION, AST_IMPORT_STATEMENT, etc. + } + merge_pass_free(&pass); +} + void module_merge_into_program(ASTNode* program) { if (!program || !global_module_registry) return; decl_index_drop(program); /* #3546: indexed afresh for this merge */ @@ -4870,293 +5174,7 @@ void module_merge_into_program(ASTNode* program) { // selectively. inject_synthetic_bare_imports_from(program, mod_ast, &insert_idx); - MergePass pass = {0}; - for (int j = 0; j < mod_ast->child_count; j++) { - ASTNode* decl = unwrap_export(mod_ast->children[j]); - - if ((decl->type == AST_FUNCTION_DEFINITION || decl->type == AST_BUILDER_FUNCTION) && decl->value) { - // Build prefixed name: "double_it" -> "mymath_double_it", - // apart from an extern of the module (#2978). - char* prefixed = merged_function_name(ns, mod_ast, decl->value); - - // Skip if already merged (e.g. from a prior non-selective - // import); every clause of a set is merged (#2643). - if (program_has_function_before(program, prefixed, &pass)) { - free(prefixed); - continue; - } - - ASTNode* clone = clone_ast_node(decl); - free(clone->value); - clone->value = prefixed; - // Mark as imported so codegen emits this function with the - // C `static` storage class. Each translation unit that - // imports the same module gets its own private copy, and - // the linker no longer sees them as duplicate symbols - // when several .o files are linked together (e.g. macOS - // ld64, which does not support --allow-multiple-definition). - clone->is_imported = 1; - stamp_origin(clone, mod); - stamp_written_name(clone, ns, decl->value); /* #2978 */ - - // Rename intra-module function calls and constant refs within the cloned body - rename_intra_module_refs(clone, ns, module_func_names(mod), - module_const_names(mod), NULL); - // Also rewrite bare-name calls to selectively-imported - // names from M's own `import X (a, b)` statements — see - // apply_inherited_selective_imports comment for why. - apply_inherited_selective_imports(clone, mod_ast); - ss_scope_node(clone, mod); - - insert_child_at(program, clone, insert_idx++); - merge_pass_add(&pass, clone); - } else if (decl->type == AST_EXTERN_FUNCTION && decl->value && - decl->annotation && - strncmp(decl->annotation, "c_symbol:", 9) == 0) { - // `@extern("c_symbol") name(...)` declarations are part - // of the module's public surface (issue #234) — unlike - // bare `extern` C bindings, which stay private. Clone - // them into the consumer just like Aether-native - // wrappers so a qualified `module.name(...)` call - // resolves. The clone keeps the `c_symbol:` annotation, - // so codegen still forwards every call to the chosen C - // symbol; only the Aether-side name is namespace- - // prefixed. This is the path that makes a variadic - // `@extern` (e.g. std.strbuilder's `append_format`) - // reachable cross-module — an ordinary wrapper cannot - // forward a `...` tail. - char* prefixed = mod_strf("%s_%s", ns, decl->value); - - // Dedup — a module imported twice must not clone the - // extern twice (duplicate registry entries / prototypes). - // #3546: from the program's index. - if (ast_decl_kinds(program, prefixed) & DECL_EXTERN) { - free(prefixed); - continue; - } - - ASTNode* clone = clone_ast_node(decl); - free(clone->value); - clone->value = prefixed; - /* Merged, not the program's own (#2632 reads the mark). */ - stamp_origin(clone, mod); - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_CONST_DECLARATION && decl->value) { - /* Constants and module-level `var`s (#701) merge whatever the - * import selects: the module's functions read them (#1573: - * `import std.spec (fail)` failed with "Undefined variable - * 'spec_current_fw'"), and every one of its functions is now - * merged (#2613). */ - - // Skip if already merged (e.g. from a prior import of the same - // module, or a synthetic revisit — aether#1009). Without this - // the const is cloned twice → duplicate C definition. - char* prefixed = mod_strf("%s_%s", ns, decl->value); - if (program_has_const(program, prefixed)) { - free(prefixed); - continue; - } - - // Clone and rename constants too - ASTNode* clone = clone_ast_node(decl); - free(clone->value); - clone->value = prefixed; - stamp_origin(clone, mod); - - // Rename references to other module constants in the value expression - rename_intra_module_refs(clone, ns, module_func_names(mod), - module_const_names(mod), NULL); - apply_inherited_selective_imports(clone, mod_ast); - ss_scope_node(clone, mod); - - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_FAULT_DEFINITION) { - /* #error-unification P3: a fault set imported from module `ns`. - * Mirror the const branch: clone the definition, prefix each - * member's C symbol to `_` (so the member-access - * rewrite resolves `ns.Name` → that identifier, exactly like a - * const), and rewrite each member's interned string CONTENT to - * the qualified `"."` (so cross-module identity is - * unambiguous — two modules' same-named faults no longer - * compare equal by content). The parser/typecheck-registration/ - * codegen stages already consume AST_FAULT_DEFINITION with this - * exact `_` symbol / `.` content contract; - * this branch is the piece that fulfils it. */ - ASTNode* clone = clone_ast_node(decl); - int kept = 0; - for (int mi = 0; mi < clone->child_count; mi++) { - ASTNode* mem = clone->children[mi]; - if (!mem || !mem->value) { - free_ast_node(mem); - continue; - } - /* Every member, whatever a selective import names: the - * module's own functions may return any of them (#2613). */ - char* sym = mod_strf("%s_%s", ns, mem->value); - if (program_has_fault_member(program, sym)) { - free(sym); - free_ast_node(mem); - continue; - } - char* qualified = mod_strf("%s.%s", ns, mem->value); - /* Rewrite the interned content (children[0], an - * AST_LITERAL) to the qualified name, then the symbol. */ - if (mem->child_count > 0 && mem->children[0] && - mem->children[0]->value) { - free(mem->children[0]->value); - mem->children[0]->value = strdup(qualified); - } - free(qualified); - free(mem->value); - mem->value = sym; - /* Compact surviving members down over filtered/duped ones. */ - clone->children[kept++] = mem; - } - clone->child_count = kept; - if (kept > 0) { - insert_child_at(program, clone, insert_idx++); - } else { - free_ast_node(clone); - } - } else if (decl->type == AST_STRUCT_DEFINITION && decl->value) { - // Struct definitions from imported modules enter the - // consumer's program AST. Closes the cross-`import` struct - // visibility gap that blocked the opaque-handle pattern: a - // module exposing `new_slot() -> ptr` whose body does - // `s = raw as *Slot` failed to typecheck once imported, - // because the consumer's symbol table lacked `Slot`. - // - // Bypasses the selective-import filter on purpose: a - // function body that casts to `*Slot` cannot type-check - // without the struct in scope, so even - // `import handle (new_slot)` must pull in `Slot`. - // - // Module-scoped: merged as `_` (ss_build_table), - // so two modules' same-named structs are two types; the - // same struct reached twice is merged once, as is one - // identical to an earlier definition (#2129). - ASTNode* clone = ss_clone_struct(program, decl, mod); - if (!clone) continue; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_DISTINCT_TYPE_DEF && decl->value) { - // #908: `type X = distinct Base` from an imported module must - // enter the consumer's program AST (bare name, like structs) - // so resolve_distinct_types learns `X` and rewrites every - // `expr as X` / `x as Base` reference inside the merged - // constructor/unwrap/builder-child functions. Without this the - // imported distinct stays an unresolved TYPE_STRUCT{X} - // placeholder: the `as` cast fails its kind check ("cannot - // cast X to Base") and codegen emits an unknown C type `X`. - // Bypasses the selective-import filter on purpose (same as - // structs): a merged body that casts to/from `X` cannot - // type-check without the def in scope. - if (program_has_distinct(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_CFN_TYPE_DEF && decl->value) { - // #2200: a `cfn Name(...) -> R` from an imported module enters - // the consumer's program AST (bare name, like distincts) so - // resolve_cfn_types learns `Name` and rewrites the `x: Name` - // annotations and `p as Name` casts inside the merged bodies. - // Bypasses the selective-import filter on purpose, same as - // structs: a merged body cannot type-check without it. - if (program_has_cfn(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_BITSTRUCT_DEFINITION && decl->value) { - // A `bitstruct Name : { ... }` from an imported module - // must enter the consumer's program AST (bare name, like structs - // and distinct types) so resolve_bitstruct_types registers it and - // codegen emits its `typedef Name;`. Without this the - // imported bitstruct is unknown to both passes: the `word as - // Name` cast in the module's own (merged) function fails its kind - // check, and codegen emits a prototype referencing `Name` with no - // typedef ("unknown type name 'Name'"). Bypasses the selective- - // import filter on purpose (same as structs/distincts): a merged - // body that casts to/reads a field of the bitstruct cannot - // type-check without the def in scope. Dedup by name. - if (program_has_bitstruct(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_ENUM_DEFINITION && decl->value) { - // An `enum X { ... }` from an imported module must enter the - // consumer's program AST (bare name, like structs/bitstructs) so - // the typechecker's enum registry learns `X` (resolving `X.Member` - // selectors and `match` arms) and codegen emits its typedef. - // Without this an imported enum used by name fails: `Undefined - // variable 'X'` at type-check, or `unknown type name 'X'` in the - // emitted C. Bypasses the selective-import filter (same as - // structs): a merged body over the enum can't type-check without - // the def in scope. Dedup by name. - if (program_has_enum(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_SUM_TYPE_DEF && decl->value) { - // A `type X = A | B | C` sum type from an imported module enters - // the consumer's program AST (bare name) so its variant names and - // typedef resolve on both the type-check and codegen sides. Same - // failure/fix shape as enums/structs. Dedup by name. - if (program_has_sum(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_MESSAGE_DEFINITION && decl->value) { - // #1006: `message X { ... }` from an imported module enters the - // consumer's program AST under its bare name (like structs), so - // `actor ! X { ... }` sends and `receive { X(..) -> }` patterns - // resolve, and codegen assigns X a runtime message-type id from - // the (per-program) message registry. Bypasses the selective- - // import filter on purpose: an imported actor's handlers cannot - // type-check without their message types in scope. Dedup by - // name; a different definition under the same name is a - // clash, reported (#2129). - if (definition_already_merged(program, decl, "message")) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_PROTOCOL_DEFINITION && decl->value) { - // #385: a `protocol` enters under its bare name, as the - // messages it names do, so an imported actor that implements - // it and an `actor_ref[P]` written by the importer resolve. - if (definition_already_merged(program, decl, "protocol")) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_ACTOR_DEFINITION && decl->value) { - // #1006: `actor X { ... }` from an imported module enters the - // consumer's program AST under its bare name. `spawn(X())` - // lowers to a `spawn_X` call and message sends reference bare - // message names, so the consumer needs the actor (and its - // messages, handled above) in scope by bare name. Bypasses the - // selective-import filter (same reasoning as structs/messages). - // Dedup by name; a second actor of the same name from another - // module is a clash, reported (#2129). - if (definition_already_merged(program, decl, "actor")) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - stamp_origin(clone, mod); - // Unlike structs, an actor has a body: its receive handlers may - // call module-local functions or read module constants, which - // were cloned above under their `_` prefixed names. Rewrite - // those references so they resolve, exactly as function bodies do. - rename_intra_module_refs(clone, ns, module_func_names(mod), - module_const_names(mod), NULL); - apply_inherited_selective_imports(clone, mod_ast); - ss_scope_node(clone, mod); - insert_child_at(program, clone, insert_idx++); - } - // Skip AST_MAIN_FUNCTION, AST_IMPORT_STATEMENT, etc. - } - merge_pass_free(&pass); + merge_module_decls(program, mod, ns, &insert_idx); } // Transitive cross-module merge (#243). When user code does @@ -5232,7 +5250,6 @@ void module_merge_into_program(ASTNode* program) { AetherModule* dep_mod = module_find(dep_path); if (!dep_mod || !dep_mod->ast) continue; - ASTNode* mod_ast = dep_mod->ast; const char* ns = module_get_namespace(dep_path); // Add a synthetic AST_IMPORT_STATEMENT for this transitive @@ -5274,104 +5291,7 @@ void module_merge_into_program(ASTNode* program) { insert_child_at(program, synth_import, insert_idx++); } - MergePass pass = {0}; - for (int j = 0; j < mod_ast->child_count; j++) { - ASTNode* decl = unwrap_export(mod_ast->children[j]); - if (!decl || !decl->value) continue; - - if (decl->type == AST_FUNCTION_DEFINITION || - decl->type == AST_BUILDER_FUNCTION) { - char* prefixed = merged_function_name(ns, mod_ast, decl->value); - /* Every clause of a set (#2643). */ - if (program_has_function_before(program, prefixed, &pass)) { - free(prefixed); - continue; - } - - ASTNode* clone = clone_ast_node(decl); - free(clone->value); - clone->value = prefixed; - clone->is_imported = 1; - stamp_origin(clone, dep_mod); - stamp_written_name(clone, ns, decl->value); /* #2978 */ - - rename_intra_module_refs(clone, ns, module_func_names(dep_mod), - module_const_names(dep_mod), NULL); - apply_inherited_selective_imports(clone, mod_ast); - ss_scope_node(clone, dep_mod); - - insert_child_at(program, clone, insert_idx++); - merge_pass_add(&pass, clone); - } else if (decl->type == AST_CONST_DECLARATION) { - char* prefixed = mod_strf("%s_%s", ns, decl->value); - - // Dedup against existing CONSTS (not functions — the old - // program_has_function guard here never matched a const, so - // a revisited module re-cloned it: aether#1009 exposed this - // as `redefinition of 'sha2_K256'`). - if (program_has_const(program, prefixed)) { - free(prefixed); - continue; - } - - ASTNode* clone = clone_ast_node(decl); - free(clone->value); - clone->value = prefixed; - stamp_origin(clone, dep_mod); - - rename_intra_module_refs(clone, ns, module_func_names(dep_mod), - module_const_names(dep_mod), NULL); - apply_inherited_selective_imports(clone, mod_ast); - ss_scope_node(clone, dep_mod); - - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_STRUCT_DEFINITION) { - // Same shape as the direct-import struct merge above, - // for transitively-reachable modules pulled in via the - // BFS. A merged function body that casts to `*T` needs - // T in scope regardless of which import edge brought - // the function in. - ASTNode* clone = ss_clone_struct(program, decl, dep_mod); - if (!clone) continue; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_DISTINCT_TYPE_DEF && decl->value) { - // #908: transitive sibling of the distinct-def merge above. - if (program_has_distinct(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, dep_mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_CFN_TYPE_DEF && decl->value) { - // #2200: transitive sibling of the cfn-def merge above. - if (program_has_cfn(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, dep_mod); - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_BITSTRUCT_DEFINITION && decl->value) { - // Transitive sibling of the bitstruct merge above: a - // bitstruct reached through a chain of imports must still - // land in program->children so its typedef is emitted. - if (program_has_bitstruct(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_ENUM_DEFINITION && decl->value) { - // Transitive sibling of the enum merge above. - if (program_has_enum(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - insert_child_at(program, clone, insert_idx++); - } else if (decl->type == AST_SUM_TYPE_DEF && decl->value) { - // Transitive sibling of the sum-type merge above. - if (program_has_sum(program, decl->value)) continue; - ASTNode* clone = clone_ast_node(decl); - clone->is_imported = 1; - ss_scope_node(clone, dep_mod); - insert_child_at(program, clone, insert_idx++); - } - } - merge_pass_free(&pass); + merge_module_decls(program, dep_mod, ns, &insert_idx); } names_free(&visited); } diff --git a/new_changelogs/20261125T181542Z-fixed-transitive-selective-import-merge.md b/new_changelogs/20261125T181542Z-fixed-transitive-selective-import-merge.md new file mode 100644 index 000000000..23202ff21 --- /dev/null +++ b/new_changelogs/20261125T181542Z-fixed-transitive-selective-import-merge.md @@ -0,0 +1,12 @@ +- **A module reached only through selective imports keeps its `@extern`s, + fault sets, messages and actors.** With `import std.math (math_sin)` and + `import a (sq)` in one module, `a`'s own `math.sqrt(x)` failed with E0301 + "Undefined function"; a fault the module returned was E0300 "Undefined + variable", and an actor it spawned "Undefined function 'spawn_X'". A + module the program reaches only through other modules' imports is merged + by the transitive pass, which kept its own copy of the merge with only + functions, constants and types in it. A bare import anywhere on the path + merged the module directly and hid the gap. 0.944.0 made std.math's + `sqrt`, `floor`, `ceil`, `round`, `abs`, `min`, `max` and `clamp` + `@extern`s, which is what exposed it. Both passes now merge a module + through one function. diff --git a/tests/integration/transitive_selective_import_merge/lib/cmath.ae b/tests/integration/transitive_selective_import_merge/lib/cmath.ae new file mode 100644 index 000000000..3e3df9bd4 --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/lib/cmath.ae @@ -0,0 +1,4 @@ +// `@extern("sym") name(...)`s: public, merged as `cmath_`. +exports(cmath_root, cmath_sine) +@extern("sqrt") cmath_root(x: float) -> float +@extern("sin") cmath_sine(x: float) -> float diff --git a/tests/integration/transitive_selective_import_merge/lib/mid.ae b/tests/integration/transitive_selective_import_merge/lib/mid.ae new file mode 100644 index 000000000..fa0f00fe5 --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/lib/mid.ae @@ -0,0 +1,19 @@ +// Only selective imports: cmath, std.math, probe and pinger are reached +// through them (and cmath and std.math through roots), never imported by +// the program. +import cmath(cmath_sine) +import std.math(math_sin) +import roots(root, std_root) +import probe(probe) +import pinger(kick) + +ms(x: float) -> float { return cmath_sine(root(x)) } +std_ms(x: float) -> float { return math_sin(std_root(x)) } + +why(k: int) -> string { + v, err = probe(k) + if err != "" { return "${err}" } + return v +} + +ping(n: int) { kick(n) } diff --git a/tests/integration/transitive_selective_import_merge/lib/pinger.ae b/tests/integration/transitive_selective_import_merge/lib/pinger.ae new file mode 100644 index 000000000..9f0d11ce1 --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/lib/pinger.ae @@ -0,0 +1,14 @@ +// A message and an actor, spawned by the module's own function. +message Ping { n: int } + +actor Pinger { + receive { + Ping(n) -> { println("ping ${n}") } + } +} + +kick(n: int) { + p = spawn(Pinger()) + p ! Ping { n: n } + wait_for_idle() +} diff --git a/tests/integration/transitive_selective_import_merge/lib/probe.ae b/tests/integration/transitive_selective_import_merge/lib/probe.ae new file mode 100644 index 000000000..6a24869dc --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/lib/probe.ae @@ -0,0 +1,8 @@ +// A fault set, returned by the module's own function. +fault Missing, Denied + +probe(k: int) -> string! { + if k == 1 { return "", Missing } + if k == 2 { return "", Denied } + return "found" +} diff --git a/tests/integration/transitive_selective_import_merge/lib/roots.ae b/tests/integration/transitive_selective_import_merge/lib/roots.ae new file mode 100644 index 000000000..662676551 --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/lib/roots.ae @@ -0,0 +1,6 @@ +// Bare imports, qualified calls of the externs. +import cmath +import std.math + +root(x: float) -> float { return cmath.root(x) } +std_root(x: float) -> float { return math.sqrt(x) } diff --git a/tests/integration/transitive_selective_import_merge/main.ae b/tests/integration/transitive_selective_import_merge/main.ae new file mode 100644 index 000000000..ec2bf3fd2 --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/main.ae @@ -0,0 +1,10 @@ +import mid + +main() { + println(mid.ms(4.0)) + println(mid.std_ms(4.0)) + println(mid.why(1)) + println(mid.why(2)) + println(mid.why(0)) + mid.ping(7) +} diff --git a/tests/integration/transitive_selective_import_merge/test_transitive_selective_import_merge.sh b/tests/integration/transitive_selective_import_merge/test_transitive_selective_import_merge.sh new file mode 100755 index 000000000..afbdb28da --- /dev/null +++ b/tests/integration/transitive_selective_import_merge/test_transitive_selective_import_merge.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# A module the program reaches only through selective imports is merged as +# a directly imported one is. The program imports only lib/mid.ae, which +# imports cmath, std.math, roots, probe and pinger selectively, so all of +# them were merged by the transitive pass. That pass kept its own copy of +# the merge, which cloned functions, constants and types but not: +# - `@extern("sym") name(...)`s: roots' `cmath.root(x)` and `math.sqrt(x)` +# were "Undefined function" (E0301); +# - fault sets: probe's own `return "", Missing` was "Undefined variable +# 'probe_Missing'" (E0300); +# - messages and actors: pinger's own `spawn(Pinger())` was "Undefined +# function 'spawn_Pinger'" (E0301). +# A bare import anywhere on the path hid it, by merging the module directly. +# +# Acceptance, main.ae prints exactly: +# 0.909297 0.909297 probe.Missing probe.Denied found ping 7 + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +AE="$ROOT/build/ae" +NAME=transitive_selective_import_merge +WANT="0.909297 0.909297 probe.Missing probe.Denied found ping 7" + +out=$( cd "$SCRIPT_DIR" && AETHER_HOME="" "$AE" run main.ae 2>&1 ) +rc=$? +if [ "$rc" -ne 0 ]; then + echo " [FAIL] $NAME: program errored (rc=$rc)" + echo "$out" | head -30 | sed 's/^/ /' + exit 1 +fi + +got=$(printf '%s\n' "$out" | grep -v '^[[:space:]]*$' | tr '\n' ' ' | sed 's/ *$//') +if [ "$got" != "$WANT" ]; then + echo " [FAIL] $NAME: expected '$WANT', got '$got'" + echo "$out" | head -20 | sed 's/^/ /' + exit 1 +fi + +echo " [PASS] $NAME" +exit 0 From 2c39db5276fc456193debb12de859149e503d2db Mon Sep 17 00:00:00 2001 From: paul Date: Wed, 25 Nov 2026 18:59:16 +0000 Subject: [PATCH 3/5] std.tcp: close_reset, a close that resets on every platform tests/integration/http_proxy_reset_is_502 failed on FreeBSD, on main as well: its upstream closes the proxy's retry connection with the request unread to reset it, and the 502 it got read "the connection closed with no response" rather than naming the reset. A close with bytes unread resets on Linux, macOS and Windows; FreeBSD ends the connection with a FIN, which the client rightly reports as a bare close. tcp.close_reset(sock) (tcp_close_reset_raw) sets SO_LINGER on with a zero timeout and closes, so the peer's next read or write fails with ECONNRESET on every platform. The test's upstream resets the retry connection with it. std/tcp/README.md and docs/api regenerated. Verified on FreeBSD 15.1: both cases of the test fail on main and pass with this. Co-Authored-By: Claude Opus 5.5 --- docs/api/index.html | 4 +++- docs/api/tcp.html | 13 +++++++++++++ docs/stdlib-reference.md | 2 +- .../20261125T185904Z-added-tcp-close-reset.md | 8 ++++++++ std/net/aether_net.c | 17 +++++++++++++++++ std/net/aether_net.h | 2 ++ std/tcp/README.md | 8 ++++++-- std/tcp/module.ae | 17 +++++++++++++++-- .../http_proxy_reset_is_502/reset_is_502.ae | 14 ++++++++------ 9 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 new_changelogs/20261125T185904Z-added-tcp-close-reset.md diff --git a/docs/api/index.html b/docs/api/index.html index 8ee07b0ad..2f639e9b0 100644 --- a/docs/api/index.html +++ b/docs/api/index.html @@ -504,7 +504,7 @@

tar

tcp

std.tcp - TCP Socket Operations (alias for std.net) Raw externs end in `_raw` and return NULL/int in C-style.

- 73 exports + 75 exports

time

@@ -2897,6 +2897,7 @@

Search Results

  • receive_rawtcp
  • receive_n_rawtcp
  • closetcp
  • +
  • close_reset_rawtcp
  • listen_rawtcp
  • listen_on_rawtcp
  • accept_rawtcp
  • @@ -2943,6 +2944,7 @@

    Search Results

  • wait_writabletcp
  • write_sometcp
  • close_drainedtcp
  • +
  • close_resettcp
  • connect_until_rawtcp
  • set_deadline_rawtcp
  • deadline_rawtcp
  • diff --git a/docs/api/tcp.html b/docs/api/tcp.html index 91ad507b8..0e97295fc 100644 --- a/docs/api/tcp.html +++ b/docs/api/tcp.html @@ -22,6 +22,7 @@

    Exports

  • receive_raw
  • receive_n_raw
  • close
  • +
  • close_reset_raw
  • listen_raw
  • listen_on_raw
  • accept_raw
  • @@ -68,6 +69,7 @@

    Exports

  • wait_writable
  • write_some
  • close_drained
  • +
  • close_reset
  • connect_until_raw
  • set_deadline_raw
  • deadline_raw
  • @@ -231,6 +233,11 @@

    close extern

    close(sock) -> int

    sock: ptr

    +
    +

    close_reset_raw extern

    +
    close_reset_raw(sock) -> int
    +

    sock: ptr

    +

    listen_raw extern

    listen_raw(port) -> ptr
    @@ -488,6 +495,12 @@

    close_drained fn

    sock: ptr

    Close `sock` once what the peer has already sent is read and dropped. A socket closed with bytes unread ends with a reset, and a peer that gets one may discard what it had not read yet: an alert just sent, which the peer then sees as a bare close. Bounded: at most 256 KiB, and 5 ms for each more to arrive. For the close after an error the peer must still read (the pure TLS stack's, #3368); a plain close is tcp.close.

    +
    +

    close_reset fn

    +
    close_reset(sock)
    +

    sock: ptr

    +

    Close `sock` with a reset instead of an orderly close: the peer's next read or write fails with "connection reset" rather than seeing the end of the stream, and anything still queued to send is dropped. Closing with bytes unread resets on Linux, macOS and Windows but not on FreeBSD; this resets everywhere. For a test peer that must fail a connection the hard way; a plain close is tcp.close.

    +

    connect_until_raw extern

    connect_until_raw(host, port, due_ms, cancel) -> (ptr, string)
    diff --git a/docs/stdlib-reference.md b/docs/stdlib-reference.md index 3a31eaca4..eb1650494 100644 --- a/docs/stdlib-reference.md +++ b/docs/stdlib-reference.md @@ -89,7 +89,7 @@ header comment is the authoritative description. | `std.supervise` | Supervisors that restart dead actors in place, by strategy and within a restart budget. | 9 | [guide](../std/supervise/README.md) · [source](../std/supervise/module.ae) | | `std.sync` | Atomic 64-bit integer cell (load, store, add, sub, compare-and-swap) for refcounts and lock-free reclamation. | 7 | [guide](../std/sync/README.md) · [source](../std/sync/module.ae) | | `std.tar` | Streaming tar archives: a ustar writer, a ustar, pax and GNU reader. | 24 | [full section](#posix-ustar-archives-stdtar) | -| `std.tcp` | TCP sockets, re-exported from `std.net`. | 73 | [guide](../std/tcp/README.md) · [source](../std/tcp/module.ae) | +| `std.tcp` | TCP sockets, re-exported from `std.net`. | 75 | [guide](../std/tcp/README.md) · [source](../std/tcp/module.ae) | | `std.udp` | Datagram sockets for game networking: non-blocking bind, send_to, recv_from, poll, and address values. | 40 | [guide](../std/udp/README.md) · [source](../std/udp/module.ae) | | `std.time` | Civil date and time over Unix epoch seconds (UTC). | 22 | [guide](../std/time/README.md) · [source](../std/time/module.ae) | | `std.tracking` | Leak-detecting allocator wrapper. | 5 | [guide](../std/tracking/README.md) · [source](../std/tracking/module.ae) | diff --git a/new_changelogs/20261125T185904Z-added-tcp-close-reset.md b/new_changelogs/20261125T185904Z-added-tcp-close-reset.md new file mode 100644 index 000000000..51e5f6190 --- /dev/null +++ b/new_changelogs/20261125T185904Z-added-tcp-close-reset.md @@ -0,0 +1,8 @@ +- **`tcp.close_reset(sock)` closes a connection with a reset on every + platform.** Closing a socket with bytes unread resets the connection on + Linux, macOS and Windows, but FreeBSD ends it with an orderly FIN, so a + peer written to fail a connection the hard way could not do it there: + the reverse proxy's reset test saw a bare close on FreeBSD and its 502 did + not name the reset. `close_reset` sets `SO_LINGER` with a zero timeout and + closes, so the peer's next read or write fails with "connection reset" + wherever it runs. diff --git a/std/net/aether_net.c b/std/net/aether_net.c index 551a1c631..788758d02 100644 --- a/std/net/aether_net.c +++ b/std/net/aether_net.c @@ -26,6 +26,7 @@ int tcp_receive_into_raw(TcpSocket* s, void* b, int c) { (void)s; (void)b; (void int tcp_reset_raw(TcpSocket* s) { (void)s; return 0; } int tcp_send_timed_out_raw(TcpSocket* s) { (void)s; return 0; } int tcp_close(TcpSocket* s) { (void)s; return 0; } +int tcp_close_reset_raw(TcpSocket* s) { (void)s; return 0; } TcpOpenResult tcp_connect_unix_raw(const char* p) { (void)p; TcpOpenResult out = { NULL, "networking disabled at build time" }; @@ -1372,6 +1373,22 @@ int tcp_close(TcpSocket* sock) { return 0; } +/* Close with a reset (RST) instead of an orderly FIN: SO_LINGER on with a + * zero timeout drops what is queued to send and resets the connection, so + * the peer's next read fails with ECONNRESET. A socket closed with bytes + * unread resets on Linux, macOS and Windows but closes with a FIN on + * FreeBSD; this resets on every platform. Frees the handle as tcp_close. */ +int tcp_close_reset_raw(TcpSocket* sock) { + if (!sock) return -1; + if (sock->fd >= 0) { + struct linger lg; + lg.l_onoff = 1; + lg.l_linger = 0; + (void)setsockopt(sock->fd, SOL_SOCKET, SO_LINGER, (const char*)&lg, sizeof(lg)); + } + return tcp_close(sock); +} + /* One listener for both entry points (#2136). `address` NULL means every * IPv4 interface (INADDR_ANY, what tcp_listen_raw always did), "::" every * interface of both families; a numeric IPv4 or IPv6 address binds that diff --git a/std/net/aether_net.h b/std/net/aether_net.h index 5968f3e1b..35484943c 100644 --- a/std/net/aether_net.h +++ b/std/net/aether_net.h @@ -79,6 +79,8 @@ int tcp_reset_raw(TcpSocket* sock); // tcp_reset_raw is, for the pure-Aether TLS client's send. int tcp_send_timed_out_raw(TcpSocket* sock); int tcp_close(TcpSocket* sock); +// Close with a reset (RST, SO_LINGER 0) instead of a FIN; frees the handle. +int tcp_close_reset_raw(TcpSocket* sock); // Unix-domain stream sockets, as the same TcpSocket / TcpServer handles, so // every read, write, poll and close above works on them unchanged. diff --git a/std/tcp/README.md b/std/tcp/README.md index d2c2be2df..46817e7c2 100644 --- a/std/tcp/README.md +++ b/std/tcp/README.md @@ -107,7 +107,11 @@ The budget covers every address the host resolves to. dropped (at most 256 KiB, 5 ms for each more to arrive). A socket closed with bytes unread ends with a reset, and a peer that gets one may discard what it had not read yet, such as an alert just sent (#3465). A plain close is -`tcp_close`. +`tcp_close`. `close_reset(sock)` closes with a reset instead (`SO_LINGER` on, +timeout 0): the peer's next read or write fails with "connection reset" and +anything still queued to send is dropped, on every platform (closing with +bytes unread resets on Linux, macOS and Windows but not on FreeBSD). For a +test peer that must fail a connection the hard way. ```aether,fragment srv, err = tcp.listen_on("127.0.0.1", 0) @@ -241,4 +245,4 @@ address is the wholly bounded dial. The TLS client takes the same pair `connect_until`, `set_deadline`, `deadline`, `stopped`, `cancel_new`, `cancel`, `cancelled`, `cancel_retain`, `cancel_free`, `DEADLINE_EXCEEDED`, `CANCELLED`, `connect`, `connect_buffered`, `connect_timeout`, `connect_unix`, `listen`, `listen_on`, `listen_unix`, `accept`, `available`, `read`, `read_n`, `read_into`, `write`, `write_n`, `write_slice`, `write_all`, `write_some`, `poll`, `poll2`, `wait_writable`, `server_poll`, `server_port`, `set_nodelay`, -`set_read_buffer`, `fd`, `server_fd`, `close_drained`, `tcp_close`, `tcp_server_close`. +`set_read_buffer`, `fd`, `server_fd`, `close_drained`, `close_reset`, `tcp_close`, `tcp_server_close`. diff --git a/std/tcp/module.ae b/std/tcp/module.ae index e8881d414..da44b1b3c 100644 --- a/std/tcp/module.ae +++ b/std/tcp/module.ae @@ -6,7 +6,7 @@ exports( tcp_connect_raw, tcp_connect_buffered_raw, tcp_connect_timeout_raw, tcp_send_raw, - tcp_receive_raw, tcp_receive_n_raw, tcp_close, + tcp_receive_raw, tcp_receive_n_raw, tcp_close, tcp_close_reset_raw, tcp_listen_raw, tcp_listen_on_raw, tcp_accept_raw, tcp_server_close, tcp_server_port_raw, tcp_server_poll_raw, tcp_set_nodelay_raw, tcp_set_read_buffer_raw, tcp_available_raw, tcp_connect_unix_raw, tcp_listen_unix_raw, @@ -16,7 +16,7 @@ exports( listen, listen_on, accept, fd, server_fd, server_port, server_poll, set_nodelay, set_read_buffer, available, poll, poll2, wait_writable, write_some, - close_drained, + close_drained, close_reset, // Deadlines and cancellation (docs/design/tcp-tls-deadlines-and-cancellation.md) tcp_connect_until_raw, tcp_set_deadline_raw, tcp_deadline_raw, tcp_stop_raw, tcp_cancel_new_raw, tcp_cancel_raw, tcp_cancel_tripped_raw, tcp_cancel_retain_raw, tcp_cancel_free_raw, @@ -46,6 +46,7 @@ extern tcp_send_bytes_raw(sock: ptr, data: ptr, length: int) -> int extern tcp_send_all_raw(sock: ptr, data: ptr, length: int) -> int extern tcp_receive_into_raw(sock: ptr, buf: ptr, cap: int) -> int extern tcp_close(sock: ptr) -> int +extern tcp_close_reset_raw(sock: ptr) -> int extern tcp_listen_raw(port: int) -> ptr extern tcp_listen_on_raw(address: string, port: int) -> ptr extern tcp_server_port_raw(server: ptr) -> int @@ -377,6 +378,18 @@ poll2(a: ptr, b: ptr, timeout_ms: int) -> { return a_ready, b_ready, "" } +// Close `sock` with a reset instead of an orderly close: the peer's next +// read or write fails with "connection reset" rather than seeing the end of +// the stream, and anything still queued to send is dropped. Closing with +// bytes unread resets on Linux, macOS and Windows but not on FreeBSD; this +// resets everywhere. For a test peer that must fail a connection the hard +// way; a plain close is tcp.close. +close_reset(sock: ptr) { + if sock != null { + tcp_close_reset_raw(sock) + } +} + // Close `sock` once what the peer has already sent is read and dropped. A // socket closed with bytes unread ends with a reset, and a peer that gets // one may discard what it had not read yet: an alert just sent, which the diff --git a/tests/integration/http_proxy_reset_is_502/reset_is_502.ae b/tests/integration/http_proxy_reset_is_502/reset_is_502.ae index 73e44f2e3..e5c1b9317 100644 --- a/tests/integration/http_proxy_reset_is_502/reset_is_502.ae +++ b/tests/integration/http_proxy_reset_is_502/reset_is_502.ae @@ -11,10 +11,12 @@ // This program is the upstream. On a kept client connection a GET leaves an // upstream connection in the proxy's pool. The next GET reaches the upstream // on it, which closes it unanswered; the proxy sends the GET again on a -// fresh connection, and the upstream closes that one with the request -// unread, which resets it. The client must get 502 with a body naming the -// reset. Through a bare proxy (the event loop on Linux and macOS) and -// through one behind a program's middleware (the worker path). Every socket +// fresh connection, and the upstream resets that one once the request is in +// it (tcp.close_reset: a close with the request unread resets on Linux and +// macOS but ends with a FIN on FreeBSD, read there as a bare close). The +// client must get 502 with a body naming the reset. Through a bare proxy +// (the event loop on Linux and macOS) and through one behind a program's +// middleware (the worker path). Every socket // is on 127.0.0.1 and a port the kernel picks. import std.http @@ -143,7 +145,7 @@ main() { first = status(read_until(k, "\r\n\r\n", 3000)) // The pooled connection ends unanswered, and the retry's fresh one - // is closed with the request in it unread: a reset. + // is reset with the request in it unread. tcp.write(k, GET) _again = read_until(up, "\r\n\r\n", 3000) tcp.close(up) @@ -155,7 +157,7 @@ main() { if !arrived { how = "retry carried nothing" } - tcp.close(retry) + tcp.close_reset(retry) } wire = read_until(k, "reset", 3000) tcp.close(k) From b592459584a7f5dda48534edf35a953c86bc068c Mon Sep 17 00:00:00 2001 From: paul Date: Wed, 25 Nov 2026 18:59:16 +0000 Subject: [PATCH 4/5] tcp_deadline_cancel: echo 256 KiB a chunk at a time "256 KiB echoed whole under a deadline and a cancel handle" wrote all 256 KiB to the echo peer before reading any of it back. The peer echoes as it reads, so once the echo fills this side's receive buffer the peer stops reading, its receive buffer and this side's send buffer fill, and the write stalls until the 20 s deadline wherever the loopback buffers hold less than the 256 KiB in flight. It failed so in a full FreeBSD sweep ("write [deadline exceeded], 0 bytes back") and passed alone. The case now writes 16 KiB and reads it back before the next, so at most 16 KiB is in flight; what it checks is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../tcp_deadline_cancel/deadline.ae | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/tests/integration/tcp_deadline_cancel/deadline.ae b/tests/integration/tcp_deadline_cancel/deadline.ae index 11f116a0f..8beb8ff4c 100644 --- a/tests/integration/tcp_deadline_cancel/deadline.ae +++ b/tests/integration/tcp_deadline_cancel/deadline.ae @@ -216,22 +216,32 @@ main() { big[i] = (i * 7) & 0xFF i = i + 1 } - _w, we = tcp.write_all(s5, big) + // A chunk at a time, each read back before the next goes: the + // peer echoes as it reads, so with all 256 KiB written first the + // echo fills this side's receive buffer, the peer stops reading, + // and the write stalls until the deadline wherever the loopback + // buffers hold less than that (FreeBSD under load). + we = "" got = 0 + sent = 0 same = true rb = make([]byte, 65536) - while got < 262144 && same { - n, re = tcp.read_into(s5, rb) - if re != "" { - same = false - println(" read: ${re}") - } else { - j = 0 - while j < n { - if rb[j] != big[got + j] { same = false } - j = j + 1 + while sent < 262144 && we == "" && same { + _w, we = tcp.write_all(s5, big[sent..sent + 16384]) + sent = sent + 16384 + while we == "" && got < sent && same { + n, re = tcp.read_into(s5, rb) + if re != "" { + same = false + println(" read: ${re}") + } else { + j = 0 + while j < n { + if rb[j] != big[got + j] { same = false } + j = j + 1 + } + got = got + n } - got = got + n } } check(&t, "256 KiB echoed whole under a deadline and a cancel handle", we == "" && got == 262144 && same && tcp.stopped(s5) == "", "write [${we}], ${got} bytes back, same ${same}") From 0eb0b29f7a3ec7990e1eb6d0f552ee87e8b42e1f Mon Sep 17 00:00:00 2001 From: paul Date: Wed, 25 Nov 2026 20:09:19 +0000 Subject: [PATCH 5/5] checker: a local lasts to the end of its function (#3872) A local first bound in a loop or `if` body hid the function of its name to the end of the function in the generated C (codegen names it `ae_local_` from its first binding on), but the checker's scope of it closed with the body, so a call of the function after the body was accepted and failed in the C compiler on an undeclared `ae_local_`. As decided on the issue, a local lives to the end of its function, as the language reference and E0301's hint already say: the checker now refuses such a call with E0301, as it does one after a binding in the function's own body. A local that holds a closure is called through, and is left alone. A closure's own local is the closure's: codegen renamed a call of the function after the closure too, the same C failure, on 0.941.0 as well. The rename now ends with the closure that bound it. Tests: local_named_after_called_function gains a loop and a branch case (refused, E0301 twice) and a closure case (runs, "6 5"); it fails on the compiler before this change. The language reference says the rule outright. Mac make test-ae 2359/0. Closes #3872 Co-Authored-By: Claude Opus 5.5 --- compiler/analysis/typechecker.c | 84 +++++++++++++++++++ compiler/codegen/codegen.c | 14 +++- docs/language-reference.md | 2 +- ...-fixed-3872-local-lasts-to-function-end.md | 8 ++ .../closure_local.ae | 12 +++ .../hidden_past_body.ae | 17 ++++ .../test_local_named_after_called_function.sh | 14 ++++ 7 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 new_changelogs/20261125T193647Z-fixed-3872-local-lasts-to-function-end.md create mode 100644 tests/integration/local_named_after_called_function/closure_local.ae create mode 100644 tests/integration/local_named_after_called_function/hidden_past_body.ae diff --git a/compiler/analysis/typechecker.c b/compiler/analysis/typechecker.c index fbefa5fd8..59d5230d6 100644 --- a/compiler/analysis/typechecker.c +++ b/compiler/analysis/typechecker.c @@ -6349,6 +6349,73 @@ static Type* g_tc_return_type = NULL; * hoist_scope_body, over which a hoisted local's type is joined. */ static ASTNode* g_tc_fn_body = NULL; +/* #3872: a local lasts from its binding to the end of its function, not of + * its block, as the language reference has it and codegen emits it (the + * local takes the name `ae_local_` from its first binding to the end + * of the body). So a local first bound inside a loop or branch body hides + * the function of its name after that body too, where the checker's scope + * of it has closed. Is a local named `name` bound in `body` before `call`? + * The walk is codegen's: children before the node, so a binding's + * initializer comes before the binding, and `helper = helper(t)` calls the + * function. A closure's own locals are its own; a trailing block's are the + * function's, as codegen runs it in line. `*hit` is set on reaching `call`. */ +static int tc_subtree_has(const ASTNode* node, const ASTNode* target) { + if (!node) return 0; + if (node == target) return 1; + for (int i = 0; i < node->child_count; i++) + if (tc_subtree_has(node->children[i], target)) return 1; + return 0; +} + +static int tc_local_bound_before(ASTNode* node, const char* name, ASTNode* call, int* hit) { + if (!node || *hit) return 0; + if (node == call) { *hit = 1; return 0; } + /* Into a closure only when the call is in it: its locals are its own. */ + if (node->type == AST_CLOSURE && !(node->value && strcmp(node->value, "trailing") == 0) && + !tc_subtree_has(node, call)) + return 0; + for (int i = 0; i < node->child_count; i++) { + if (tc_local_bound_before(node->children[i], name, call, hit)) return 1; + if (*hit) return 0; + } + /* A local holding a closure is called through: the call is the + * local's, not a call of the hidden function. */ + return node->type == AST_VARIABLE_DECLARATION && node->value && + strcmp(node->value, name) == 0 && + !(node->child_count > 0 && node->children[0] && + node->children[0]->type == AST_CLOSURE) && + !(node->node_type && node->node_type->kind == TYPE_FUNCTION); +} + +/* The names of the locals `body` declares anywhere, kept for the body being + * checked, so a call names a function with no walk unless one could hide it. */ +static ASTNode* g_tc_decl_names_body = NULL; +static StrMap g_tc_decl_names = {0}; + +static void tc_collect_decl_names(const ASTNode* node) { + if (!node) return; + if (node->type == AST_VARIABLE_DECLARATION && node->value && + !strmap_has(&g_tc_decl_names, node->value)) + strmap_put(&g_tc_decl_names, node->value, NULL); + for (int i = 0; i < node->child_count; i++) tc_collect_decl_names(node->children[i]); +} + +static int tc_local_hides_function(const char* name, ASTNode* call) { + ASTNode* body = g_tc_fn_body; + if (!body || !name || strchr(name, '.')) return 0; + if (g_tc_decl_names_body != body) { + strmap_free(&g_tc_decl_names); + memset(&g_tc_decl_names, 0, sizeof(g_tc_decl_names)); + tc_collect_decl_names(body); + g_tc_decl_names_body = body; + } + /* Actor handlers and the like are checked under no body of their own: + * a call not in this body is not this function's. */ + if (!strmap_has(&g_tc_decl_names, name) || !tc_subtree_has(body, call)) return 0; + int hit = 0; + return tc_local_bound_before(body, name, call, &hit); +} + /* #2733: what the `return`s being checked return from: the function, main * or closure whose body holds them. */ static ASTNode* g_tc_return_owner = NULL; @@ -8766,6 +8833,7 @@ int typecheck_node(ASTNode* node, SymbolTable* table) { ASTNode* saved_fn_body = g_tc_fn_body; ASTNode* saved_owner = g_tc_return_owner; g_tc_fn_body = node->child_count > 0 ? node->children[0] : NULL; + g_tc_decl_names_body = NULL; g_tc_return_owner = node; SymbolTable* main_table = create_symbol_table(table); main_table->binds_body = 1; @@ -13695,6 +13763,7 @@ int typecheck_function_definition(ASTNode* func, SymbolTable* table) { ASTNode* saved_fn_body = g_tc_fn_body; ASTNode* saved_owner = g_tc_return_owner; g_tc_fn_body = body; + g_tc_decl_names_body = NULL; g_tc_return_owner = func; declare_if_branch_hoists(body, func_table); /* #2186 */ typecheck_statement(body, func_table); @@ -22501,6 +22570,21 @@ static int typecheck_function_call_inner(ASTNode* call, SymbolTable* table) { } } + /* #3872: a local bound earlier in the function, in a loop or branch body + * the checker's scope has left, still hides the function of its name. */ + if (symbol && symbol->is_function && call->value && + tc_local_hides_function(call->value, call)) { + type_error_code_hint( + aether_internf("'%s' is a local here, which hides the function '%s'", + call->value, call->value), + aether_internf("a local's scope starts after its initializer and lasts to the end " + "of the function, past the loop or branch body it was first bound " + "in, so the function cannot be called as '%s' here; give the local " + "another name", call->value), + call->line, call->column, AETHER_ERR_UNDEFINED_FUNC); + return 0; + } + if (!symbol || !symbol->is_function) { const char* error_msg = ""; /* #2683: a local bound earlier in the body hides the function of diff --git a/compiler/codegen/codegen.c b/compiler/codegen/codegen.c index 20c33e8fb..1cd0b58a5 100644 --- a/compiler/codegen/codegen.c +++ b/compiler/codegen/codegen.c @@ -6805,10 +6805,22 @@ static void scan_local_shadows(ASTNode* node, LocalShadowScan* s) { /* Rename `from` to `to` in every value node after the first binding of * `from`, and in calls through it. `*active` turns on at that binding, - * after its initializer. */ + * after its initializer. + * + * A closure's own local is its own (#3872): a binding in a closure body + * turns the rename on to the end of that closure only, so after it the name + * is the function's again, as `ae check` resolves it. A local of the + * function bound before the closure is renamed inside it too, captured. + * A trailing block runs in line, and its locals are the function's. */ static void rename_local_after_binding(ASTNode* node, const char* from, const char* to, int* active) { if (!node) return; + if (node->type == AST_CLOSURE && !(node->value && strcmp(node->value, "trailing") == 0)) { + int inner = *active; + for (int i = 0; i < node->child_count; i++) + rename_local_after_binding(node->children[i], from, to, &inner); + return; + } for (int i = 0; i < node->child_count; i++) rename_local_after_binding(node->children[i], from, to, active); if (!node->value || strcmp(node->value, from) != 0) return; diff --git a/docs/language-reference.md b/docs/language-reference.md index f5b5f48cd..f3e161e0f 100644 --- a/docs/language-reference.md +++ b/docs/language-reference.md @@ -657,7 +657,7 @@ main() { **A local has one type: the one its first binding gave it.** A later bare assignment is an assignment, not a new variable, so `x = 5` then `x = "s"` (or `x = true`, `x = null`) is a compile error, *cannot re-bind 'x' as string: it was bound as int by its first assignment*, rather than a C error about `const char*`. Use a new name for the other value. A name first bound inside a branch or loop body and **used after it** is one variable for the whole function: it takes the join of every binding, the one an if-expression's branches take (`if a { n = 1 } else { n = 4000000000 }` makes `n` a `long`; `f = 1.5` in one branch and `f = 2` in the other keeps `f` a `float`; `x = -1` beside a `uint32` makes `x` a `long`, and a signed value beside a `uint64` is the error below, as it is in an if-expression), unless a binding writes its type: `uint64 x = 7` in one branch makes `x` a `uint64` wherever the others are, and a binding of a value it does not hold (`x = -1` or an `int` beside it, `x = 1.5` beside `int x = 0`, `x = 300` beside `uint8 x = 7`, `x = "s"` beside `int x = 1`), or one that writes another type, is a compile error in either order: *cannot bind 'x' to this int value: it is written as uint64 in another branch or loop body of this function, which does not hold the value*. A binding of another kind anywhere in the function, or of another struct or pointer type, is the same kind of error: *cannot bind 'v' as int: it is bound as string in another branch or loop body of this function*. A `switch` case is a branch here as an `if` arm is, and so is the body of a `match` arm ([Match Statements](#match-statements)). A local of a `while` body is declared before the loop, and a name both arms of an `if`/`else` (or every case of a `switch` with a `default`, or every arm of a `match` that runs an arm for every value) bind is declared before the `if` (or `switch`, or `match`), so each is one variable whether or not it is used after them: `view = p as *Apple` in one `while` and `view = p as *Pear` in the next is that error, where a bare `ptr` or `null` binding would fit either. A read of such a local in the body before its binding, which sees the value the previous pass bound, has the binding's type (`out = "${out}${prev}"` ahead of `prev = "p${i}"` reads a string). A name bound in the bodies of separate `if`s or `for` loops and used only inside them is a separate variable per body, except a `string` local, which is always one variable for the whole function. The conversions the [table below](#casting-between-types) permits still apply at a re-bind, and the local keeps its first type: after `f = 1.5`, `f = 2` stores `2.0` and `f` stays a `float`; after `int x = 0`, `x = 2.5` stores `2`. A `string` accepts `null` (it is a nullable `const char*`), and a value that would not fit an *inferred* `int` (a 64-bit integer, a `uint32`, a float) is the narrowing error described there. Each slot of a tuple destructure that names a bound local re-binds it the same way, whether the local is in the same scope or is an outer one a closure writes (`a, b = two()` in a closure after `a, b = names()`): a slot of another kind is the same error, reported at the slot, a slot C converts is stored as the local's type, and an `int` slot binds an inferred `int`, as `x = 5` does (#2762). -**A local's scope starts after its initializer.** In `count = count() + 1` the call is the function `count`, and from that binding on, to the end of the function, `count` is the local. So is a local declared ahead of its binding because both arms of an `if` bind it: until the checker reaches the first binding in source order, the name is still the function's. A reference that comes before the binding, such as the function passed as a value, is the function too: +**A local's scope starts after its initializer.** In `count = count() + 1` the call is the function `count`, and from that binding on, to the end of the function, `count` is the local. So is a local declared ahead of its binding because both arms of an `if` bind it: until the checker reaches the first binding in source order, the name is still the function's. It lasts to the end of the function, not of the block that bound it: a local first bound in a loop or `if` body hides the function after that body too, so calling the function there is E0301. A closure's own local is the closure's, and after the closure the name is the function's again. A reference that comes before the binding, such as the function passed as a value, is the function too: ```aether,run count() -> int { return 41 } diff --git a/new_changelogs/20261125T193647Z-fixed-3872-local-lasts-to-function-end.md b/new_changelogs/20261125T193647Z-fixed-3872-local-lasts-to-function-end.md new file mode 100644 index 000000000..ca6999748 --- /dev/null +++ b/new_changelogs/20261125T193647Z-fixed-3872-local-lasts-to-function-end.md @@ -0,0 +1,8 @@ +- **A local lasts to the end of its function, and the checker says so + (#3872).** A local first bound in a loop or `if` body hid the function of + its name to the end of the function in the generated C, but the checker + let a call of the function after that body through, and it failed in the + C compiler on an undeclared `ae_local_`. Such a call is now E0301, + as one after a binding in the function's own body was. A closure's own + local no longer hides the function after the closure: codegen renamed the + call there too, the same C failure. diff --git a/tests/integration/local_named_after_called_function/closure_local.ae b/tests/integration/local_named_after_called_function/closure_local.ae new file mode 100644 index 000000000..5dd544291 --- /dev/null +++ b/tests/integration/local_named_after_called_function/closure_local.ae @@ -0,0 +1,12 @@ +// #3872: a closure's local is its own, so after the closure the function +// of its name is called as before. +helper(s: string) -> int { return 5 } + +main() { + f = | t: string | { + helper = helper(t) + return helper + 1 + } + a = f("a") + println("${a} ${helper("c")}") +} diff --git a/tests/integration/local_named_after_called_function/hidden_past_body.ae b/tests/integration/local_named_after_called_function/hidden_past_body.ae new file mode 100644 index 000000000..6af0a510a --- /dev/null +++ b/tests/integration/local_named_after_called_function/hidden_past_body.ae @@ -0,0 +1,17 @@ +// #3872: a local first bound in a loop or branch body lasts to the end of +// the function, so after that body it still hides the function. +helper(s: string) -> int { return 5 } +other(s: string) -> int { return 6 } + +main() { + for t in ["a", "b"] { + helper = helper(t) + println(helper) + } + println(helper("c")) + if 1 > 0 { + other = other("x") + println(other) + } + println(other("y")) +} diff --git a/tests/integration/local_named_after_called_function/test_local_named_after_called_function.sh b/tests/integration/local_named_after_called_function/test_local_named_after_called_function.sh index d29d08fc4..d57db0a1d 100644 --- a/tests/integration/local_named_after_called_function/test_local_named_after_called_function.sh +++ b/tests/integration/local_named_after_called_function/test_local_named_after_called_function.sh @@ -14,6 +14,13 @@ # names that differ from the Aether one (`list.size` is `list_size`, an # `@extern`, a selective import). A call through the local after its binding # is an error that says the local hides the function. +# +# #3872: the local lasts to the end of its function, not of its block, as +# codegen has it: after the loop or branch body that first bound it, the +# call is still refused (it was accepted, and failed in the C compiler on +# an undeclared `ae_local_helper`). A closure's own local is the closure's: +# after the closure the function is called as before (codegen renamed the +# call past the closure, the same C failure). SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" @@ -40,4 +47,11 @@ out="$("$AE" check hidden.ae 2>&1)" && { echo "$out"; fail "a call through the l echo "$out" | grep -q "error\[E0301\]: 'helper' is a local here, which hides the function 'helper'" || { echo "$out"; fail "the call through the local is not reported as hiding the function"; } +out="$("$AE" check hidden_past_body.ae 2>&1)" && { echo "$out"; fail "a call after the loop or branch that bound the local was accepted"; } +[ "$(echo "$out" | grep -c "error\[E0301\]: '\(helper\|other\)' is a local here, which hides the function")" = 2 ] || + { echo "$out"; fail "the calls after the loop and the branch are not both reported as hidden"; } + +out="$("$AE" run closure_local.ae 2>&1)" || { echo "$out"; fail "a call after a closure with a local of the name did not build"; } +[ "$out" = "6 5" ] || { echo "$out"; fail "the closure's local or the function after it gave the wrong value"; } + echo " [PASS] local_named_after_called_function: the call is the function's, wherever it sits"