From eb6b923135f085bd508d9412c0bc6704e6f403a3 Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Sat, 18 Apr 2026 15:40:55 +0800 Subject: [PATCH] fixes #25751; JS backend crashes when returning `Option[T]` with custom `=destroy` (#25752) fixes #25751 This pull request improves the JavaScript backend code generation and expands test coverage, particularly around temporary and loop variables, as well as object destruction behavior. The main changes include updating the code generator to handle more symbol kinds and adding tests to ensure proper destruction and option handling. **JavaScript code generation improvements:** * Updated `genSymAddr` in `compiler/jsgen.nim` to support additional symbol kinds, specifically `skTemp` and `skForVar`, ensuring correct address generation for temporaries and loop variables. **Test suite enhancements:** * Added tests in `tests/js/test2.nim` to verify correct behavior of option types, object destruction (`=destroy`), and to check for backend-specific crashes. This includes printing results of option-returning functions and confirming destruction messages. * Updated expected output in `tests/js/test2.nim` to include results from new tests and destruction messages, ensuring the test suite reflects the latest code behavior. (cherry picked from commit 98131a9fa15d92687c852a4b0373a58e9b91a58c) --- compiler/jsgen.nim | 2 +- tests/js/test2.nim | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index ed2452241e..9bd107995d 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1532,7 +1532,7 @@ proc genSymAddr(p: PProc, n: PNode, typ: PType, r: var TCompRes) = r.res = s.loc.snippet r.address = "" r.typ = etyNone - of skVar, skLet, skResult: + of skVar, skLet, skResult, skTemp, skForVar: r.kind = resExpr let jsType = mapType(p): if typ.isNil: diff --git a/tests/js/test2.nim b/tests/js/test2.nim index fa857ccc5c..c4cb2a25d3 100644 --- a/tests/js/test2.nim +++ b/tests/js/test2.nim @@ -4,7 +4,12 @@ js 3.14 7 1 -21550 --21550''' +-21550 +none(TT) +() +destroyed +destroyed +''' """ # This file tests the JavaScript generator @@ -56,3 +61,15 @@ proc foo09() = const y = 86400 echo (x - (y - 1)) div y # Still gives `-21551` foo09() + +import std/options + +type TT = object + +proc `=destroy`(x: TT) = echo "destroyed" + +func test1: Option[TT] = discard +func test2: TT = discard + +echo test1() # Crash in JS backend, not crash in C backend +echo test2() # Not crash