Skip to content

Miscompilation of assignment #7170

Closed
Closed

Description

@AndreasLoow

Hi, the following code

{
let j = ref(0)

if Js.String.get("%", j.contents) == "%" {
 j := j.contents + 1
 j := j.contents + 1
} else {
 j := j.contents + 1
}

Console.log(j.contents)
}

is compiled into

var j = 0;

j = j + 1 | 0;

if ("%"[j] === "%") {
  j = j + 1 | 0;
}

console.log(j);

Note how the assignment of j is moved outside the if-expression despite the move changing the evaluation of the condition of the if-expression. The code without the surrounding { and } is compiled correctly.

Activity

  1. cristianoc commented on Nov 24, 2024

    @cristianoc
    Collaborator

    Thanks for reporting.
    This seems to be a long standing issue, that can be reproduced already on old versions of the compiler.
    Seems to be triggered by not exporting variable j, by either putting the code into { ... } block or shadowing the variable.

  2. cristianoc commented on Nov 24, 2024

    @cristianoc
    Collaborator

    This appears to be due to an optimisation for records with only one field, such as contents.
    The optimisation should only affect the generated code, but in this case prematurely turning x.contents into x confuses the checker for side effects, which thinks there are none.

  3. added theissue type on Jul 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions