Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swap silently broken for objects inside functions (js target) #16771

Closed
salvipeter opened this issue Jan 20, 2021 · 1 comment · Fixed by #23473
Closed

swap silently broken for objects inside functions (js target) #16771

salvipeter opened this issue Jan 20, 2021 · 1 comment · Fixed by #23473
Assignees

Comments

@salvipeter
Copy link
Contributor

salvipeter commented Jan 20, 2021

In the example below, foo should do the same as swap (at least that's what the C target does).

Example

type A = object
    n: int

proc foo(a, b: var A) =
  swap a, b

var a, b: A
a.n = 42
b.n = 1
doAssert a.n == 42
doAssert b.n == 1
a.swap b
doAssert a.n == 1
doAssert b.n == 42
a.foo b
doAssert a.n == 42
doAssert b.n == 1

Additional Information

The above function compiles (basically) to this JavaScript code:

function foo(a, b) {
    var tmp = a;
    a = b;
    b = tmp;
}

However this only swaps the local variables of the function, as JavaScript uses "call by sharing".

In contrast, the C target compiles to

void foo(A *a, A *b) {
    A tmp = *a;
    *a = *b;
    *b = tmp;
}

... where the whole struct is swapped.

$ ./nim -v
Nim Compiler Version 1.5.1 [Linux: amd64]
git hash: 61fd19c7e6880d77d20be01d25266e4195e631fa
@salvipeter salvipeter changed the title Assignment of objects inside functions (js target) Swapping objects inside functions (js target) Jan 20, 2021
@timotheecour
Copy link
Member

timotheecour commented Jan 20, 2021

see also workaround mentioned in #16536 (comment) which can potentially serve as basis for fixing swap

@timotheecour timotheecour changed the title Swapping objects inside functions (js target) swap silently broken for objects inside functions (js target) Jan 21, 2021
@timotheecour timotheecour self-assigned this Jan 21, 2021
timotheecour added a commit to timotheecour/Nim that referenced this issue Jan 21, 2021
@ringabout ringabout self-assigned this Apr 3, 2024
ringabout added a commit that referenced this issue Apr 3, 2024
Araq pushed a commit that referenced this issue Apr 3, 2024
fixes #16771

follow up #16536

Ideally it should be handled in the IR part in the future

I have also checked the double evaluation of `swap` in the JS runtime
#16779, that might be solved by a
copy flag or something. Well, it should be best solved in the IR so that
it doesn't bother backends anymore.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants