From b28b321eba3c886846c61e30ef01cbd85f3ca08a Mon Sep 17 00:00:00 2001 From: Zoom Date: Mon, 22 Sep 2025 13:02:50 +0400 Subject: [PATCH] stdlib: `system`: fix incorrect VM detection in `substr` impls (#25182) ...introduced by me in #24792. Sorry. This fix doesn't avoid copying the `restrictedBody` twice in the generated code but has the benefit of working. Proper fix needs a detection that can set a const bool for a module once. `when nimvm` is restricted in use and is difficult to dance around. Some details in: #12517, #12518, #13038 I might have copied the buggy solution from some discussion and it might have worked at some point, but it's small excuse. (cherry picked from commit 6938fce40c0bd0adb553e040c0ff0de3aced70b4) --- lib/system.nim | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index bdcfc0725d..4dc537e9b3 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2829,11 +2829,15 @@ template once*(body: untyped): untyped = {.pop.} # warning[GcMem]: off, warning[Uninit]: off -template NotJSnotVMnotNims(): static bool = # hack, see: #12517 #12518 +template whenNotVmJsNims(normalBody, restrictedBody: untyped) = + ## hack, see: #12517 #12518 when nimvm: - false + restrictedBody else: - notJSnotNims + when notJSnotNims: + normalBody + else: + restrictedBody proc substr*(a: openArray[char]): string = ## Returns a new string, copying contents of `a`. @@ -2855,10 +2859,10 @@ proc substr*(a: openArray[char]): string = assert a.toOpenArray(2, high(a)).substr() == "cdefgh" # From index 2 to `high(a)` doAssertRaises(IndexDefect): discard a.toOpenArray(5, 99).substr() result = newStringUninit(a.len) - when NotJSnotVMnotNims: + whenNotVmJsNims(): if a.len > 0: copyMem(result[0].addr, a[0].unsafeAddr, a.len) - else: + do: for i, ch in a: result[i] = ch @@ -2890,10 +2894,10 @@ proc substr*(s: string; first, last: int): string = # A bug with `magic: Slice` last = min(last, high(s)) L = max(last - first + 1, 0) result = newStringUninit(L) - when NotJSnotVMnotNims: + whenNotVmJsNims(): if L > 0: copyMem(result[0].addr, s[first].unsafeAddr, L) - else: + do: for i in 0..