Skip to content

e === null || e === undefined compiles to e == null, which evaluates e once #9355

Closed

Description

@mununki

The JS printer turns e === null || e === undefined into e == null when the two operands are the same expression. That evaluates e once instead of twice, which changes the result when e has side effects.

let values: array<Nullable.t<int>> = [Nullable.make(1), Nullable.undefined]
let i = ref(0)

let next = () => {
  let v = values->Array.getUnsafe(i.contents)
  i := i.contents + 1
  v
}

let id = (b: bool) => b

Console.log2(id(next() === Nullable.null || next() === Nullable.undefined), i.contents)

Output, on master and on 12.3.1:

console.log(next() == null, i.contents);

This prints false 1. It should print true 2: the first next() returns 1 and the second undefined.

The rewrite is the Bin (Or, Bin (EqEqEq, e1, Null), Bin (EqEqEq, e2, Undefined)) case of expression_desc in js_dump.ml. It should apply only when e1 has no side effects.

Activity

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

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions