Annotate calls to pure functions

Hi :wave:

I noticed, that the generated .bs.js files do not annotate calls to pure functions. They do contain a comment at the end of the file, saying which functions are impure (if any) but I don’t know if this helps for tree shaking.

Common JavaScript Bundlers like Webpack and Rollup say in their docs, that they optimize for annotations like /*#__PURE__*/ or /*@__PURE__*/.

So my questions would be:

  1. Do the already present comments (/* No side effect */) help with tree shaking?
  2. Would it make sense (and be possible) to annotate calls to pure functions with one of the above mentioned tags to further optimize tree shaking?

Thank you and keep up the great work!


This is something that I’ve looked into before, and the only thing I can think of to provide annotations is to run a static analyzer on the JS artifacts and do an AST transformation to inject the annotations in the JS file. This could be done as part of the build pipeline.

As far as I know, the ReScript compiler does not provide any tools for injecting comments in the emitted JS code. Of course, it’s possible to do this using %raw to insert the JS code (including comments) directly. But this is hacky, since you have to write the function in JavaScript in order to be sure it gets annotated correctly.

It would be nice to have some kind of compiler intrinsic for injecting JS comments.

Does ReScript even knows which functions are pure? AFAIK Haskell recognizes purity on type level; OCaml doesn’t.

Yeah, as far as I know OCaml cannot statically guarantee the purity of a function, but I could totally be wrong about that. Either way, I don’t know of a way to act on that info if we had it.

The “no side effect” comment doesn’t mean the functions are pure. It means the module is, loading it executes no code it only defines functions. That’s a far easier analysis to make. And if it’s not pure due to importing an impure module, it says which one.

This annotation isn’t used by existing bundlers, maybe the long term goal was to build one, but either way I think it’s a good idea to add a supported pure comment at the top of the file. Can you log a request for this on GitHub please?