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

Incorrect code emitted for untagged variant switch case #7289

Closed
cknitt opened this issue Feb 10, 2025 · 0 comments · Fixed by #7303
Closed

Incorrect code emitted for untagged variant switch case #7289

cknitt opened this issue Feb 10, 2025 · 0 comments · Fixed by #7303
Assignees
Labels

Comments

@cknitt
Copy link
Member

cknitt commented Feb 10, 2025

This

let printLength = (json: JSON.t) =>
  switch json {
  | Object(o) => Console.log2("Length: ", o->Dict.valuesToArray->Array.length)
  | _ => ()
  }

compiles to

function printLength(json) {
  if (typeof json !== "object" || Array.isArray(json)) {
    return;
  }
  console.log("Length: ", Object.values(json).length);
}

which is incorrect because a check for null is missing.

It will crash at runtime if passed a null value.

@cknitt cknitt added the bug label Feb 10, 2025
cristianoc added a commit that referenced this issue Feb 17, 2025
Fixes #7289

The check emitted for case `Object` was simply `type of ... === "object"`, though that is insufficient when the variant has one case corresponding to `null`.
Now we check if such a variant case exists, and emit `... != null` in addition.
cristianoc added a commit that referenced this issue Feb 17, 2025
Fixes #7289

The check emitted for case `Object` was simply `type of ... === "object"`, though that is insufficient when the variant has one case corresponding to `null`.
Now we check if such a variant case exists, and emit `... != null` in addition.
cristianoc added a commit that referenced this issue Feb 17, 2025
…7303)

* Fix issue with untagged variants and object when null is one case.

Fixes #7289

The check emitted for case `Object` was simply `type of ... === "object"`, though that is insufficient when the variant has one case corresponding to `null`.
Now we check if such a variant case exists, and emit `... != null` in addition.

* Add test example.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants