google / closure-compiler

A JavaScript checker and optimizer.
https://developers.google.com/closure/compiler/
Apache License 2.0
7.4k stars 1.15k forks source link

Document @pureOrBreakMyCode #4190

Open ribrdb opened 2 months ago

ribrdb commented 2 months ago

In PR 4180 @shicks said "goog.reflect.cache is also obsoleted by @pureOrBreakMyCode, which can now be used instead of special-purpose caching primitive." I can't find documentation for this annotation anywhere. How are you supposed to use it to replace calls to goog.reflect.cache? Would it be sufficient to add this into the body of goog.reflect.cache or a similar method, or would the callers need the annotation?

KimlikDAO-bot commented 1 month ago

I second this. A well documented and thought-out @pureOrBreakMyCode would be an awesome addition to GCC.

By looking at the java code, it appears that currently @pureOrBreakMyCode is used for removing function calls whose return value is not used (even though i could not trigger this with js examples).

However it would be great if GCC can also constant propagate through @pureOrBreakMyCode annotated functions. This would give a users a tool maybe as powerful as zigs comptime.

Just a simple example: build time dictionary trimming

/** @const {!Object<string, string>} */
const LibraryDict = { "key": value, ... }
/**
 * @pureOrBreakMyCode
 * @param {!Object<string, string>} dict
 * @param {!Array<string>} keys
 * @return {!Object<string, string>}
 */
const trimDict = (dict, keys) => Object.fromEntries(Object.entries(dict).filter(([dict]) => keys.includes(key));

/** @define {string} */
const UsedKeys = "key1,key2"

/** @const {!Object<string, string>} */
const MyAppDict = trimKeys(LibraryDict, UsedKeys.split(","));

You could get the exact object you want for your app at compile time.