diff options
author | Jake Leahy <jake@leahy.dev> | 2022-12-13 18:43:37 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-13 08:43:37 +0100 |
commit | 7ae7832f761adc1b601d4d1baa07ce3cc304fb28 (patch) | |
tree | d01e0fea00ed039b12e843bb7f36c0e0e95a9f41 | |
parent | 1fefb8e92a62c647028d0f00ebd9fc04da169789 (diff) | |
download | Nim-7ae7832f761adc1b601d4d1baa07ce3cc304fb28.tar.gz |
JS backend properly extends string with `setLen` (#21087)
* Add test case * Extend string with '0' when setting length to be longer
-rw-r--r-- | compiler/jsgen.nim | 4 | ||||
-rw-r--r-- | tests/js/t20235.nim | 11 |
2 files changed, 14 insertions, 1 deletions
diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 42a3dcf31..d8fb6d57d 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -2209,7 +2209,9 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) = if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 -= $2") else: binaryExpr(p, n, r, "subInt", "$1 = subInt($3, $2)", true) of mSetLengthStr: - binaryExpr(p, n, r, "mnewString", "($1.length = $2)") + binaryExpr(p, n, r, "mnewString", + """if ($1.length < $2) { for (var i = $3.length; i < $4; ++i) $3.push(0); } + else {$3.length = $4; }""") of mSetLengthSeq: var x, y: TCompRes gen(p, n[1], x) diff --git a/tests/js/t20235.nim b/tests/js/t20235.nim new file mode 100644 index 000000000..3a69c2bd6 --- /dev/null +++ b/tests/js/t20235.nim @@ -0,0 +1,11 @@ +discard """ + action: "run" + output: "0 4" +""" + +proc main = + var s = "" + s.setLen(4) + echo s[0].ord, " ", s.len + +main() |