rescript-lang / rescript-compiler

The compiler for ReScript.
https://rescript-lang.org
Other
6.66k stars 442 forks source link

Optimize literal checks in untagged variants #6393

Open zth opened 1 year ago

github-actions[bot] commented 3 weeks ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

zth commented 3 weeks ago

This is still a thing I'd like us to have a look at eventually. It's about untagged variants sometimes producing excessive code. Example:

let v = JSON.Array([String("hello")])

let x = x =>
  switch x {
  | JSON.Array(arr) =>
    arr
    ->Array.filterMap(a =>
      switch a {
      | String(s) => Some(s)
      | _ => None
      }
    )
    ->Array.join(",")
  | _ => "-"
  }

Produces this JS:

import * as Core__Array from "./stdlib/core__Array.js";

var v = ["hello"];

function x(x$1) {
  if (!Array.isArray(x$1) && (x$1 === null || typeof x$1 !== "object") && typeof x$1 !== "number" && typeof x$1 !== "string" && typeof x$1 !== "boolean" || !Array.isArray(x$1)) {
    return "-";
  } else {
    return Core__Array.filterMap(x$1, (function (a) {
                    if (!Array.isArray(a) && (a === null || typeof a !== "object") && typeof a !== "number" && typeof a !== "string" && typeof a !== "boolean" || typeof a !== "string") {
                      return ;
                    } else {
                      return a;
                    }
                  })).join(",");
  }
}

2 main things:

  1. The if that checks the array: if (!Array.isArray(x$1) && (x$1 === null || typeof x$1 !== "object") && typeof x$1 !== "number" && typeof x$1 !== "string" && typeof x$1 !== "boolean" || !Array.isArray(x$1)). This checks all the ways it can't be an array, but it could just do Array.isArray(x$1).
  2. Checking each element f (!Array.isArray(a) && (a === null || typeof a !== "object") && typeof a !== "number" && typeof a !== "string" && typeof a !== "boolean" || typeof a !== "string") it's looking for a string, so it could just check that it's a string via typeof a === "string". But instead it checks all of the negative cases.

This might not be trivial to fix and is probably a property of how the pattern matching engine is written, but I figured I'd log it anyway so we have it in the tracker.

Playground link: https://rescript-lang.org/try?version=v11.1.3&code=DYUwLgBAbhC8ECkDKB5AcgOgIICccEMBPACgG0kwcBLAOwHNiAiACxGGAHtGBKAXW4BQA0JAAecCONgA+ARAgBnAO5UwAY2aSIAbzkQAPolSZcBEvjzc4s+fIs498gLTTTRDADMqwMCBwBZfAAHYnxrR1tlVQ0IMN1bW0MKanpiBSsZCCQOAFsQNMEE+UMAfWsINA4aEAj5AF8IwtsXN0IMACsOWiYAGh49UvLGJ0Y9BqA