Correctly mangle this in the JS backend (#8853)

As shown in pragmagic/karax#67 using `this` as parameter name made the
codegen output wrong code (and the user didn't notice the errors in the
browser console).
This commit is contained in:
LemonBoy 2018-09-03 17:51:30 +02:00 • committed by Andreas Rumpf
commit 1a60ffcf1d
3 changed files with 27 additions and 3 deletions

View file

@ -243,7 +243,8 @@ proc mangleName(m: BModule, s: PSym): Rope =
x.add("HEX" & toHex(ord(c), 2)) x.add("HEX" & toHex(ord(c), 2))
inc i inc i
result = rope(x) result = rope(x)
if s.name.s != "this" and s.kind != skField: # From ES5 on reserved words can be used as object field names
if s.kind != skField:
if optHotCodeReloading in m.config.options: if optHotCodeReloading in m.config.options:
# When hot reloading is enabled, we must ensure that the names # When hot reloading is enabled, we must ensure that the names
# of functions and types will be preserved across rebuilds: # of functions and types will be preserved across rebuilds:

View file

@ -267,8 +267,8 @@ block:
type TestObject = object type TestObject = object
a: int a: int
onWhatever: proc(e: int): int onWhatever: proc(e: int): int
proc handleWhatever(that: TestObject, e: int): int = proc handleWhatever(this: TestObject, e: int): int =
e + that.a e + this.a
proc test(): bool = proc test(): bool =
let obj = TestObject(a: 9, onWhatever: bindMethod(handleWhatever)) let obj = TestObject(a: 9, onWhatever: bindMethod(handleWhatever))
obj.onWhatever(1) == 10 obj.onWhatever(1) == 10

23
tests/js/tthismangle.nim Normal file
View file

@ -0,0 +1,23 @@
proc moo1(this: int) =
doAssert this == 42
proc moo2(x: int) =
var this = x
doAssert this == 42
proc moo3() =
for this in [1,1,1]:
doAssert this == 1
proc moo4() =
type
X = object
this: int
var q = X(this: 42)
doAssert q.this == 42
moo1(42)
moo2(42)
moo3()
moo4()