func.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. local M = {}
  2. -- TODO(lewis6991): Private for now until:
  3. -- - There are other places in the codebase that could benefit from this
  4. -- (e.g. LSP), but might require other changes to accommodate.
  5. -- - Invalidation of the cache needs to be controllable. Using weak tables
  6. -- is an acceptable invalidation policy, but it shouldn't be the only
  7. -- one.
  8. -- - I don't think the story around `hash` is completely thought out. We
  9. -- may be able to have a good default hash by hashing each argument,
  10. -- so basically a better 'concat'.
  11. -- - Need to support multi level caches. Can be done by allow `hash` to
  12. -- return multiple values.
  13. --
  14. --- Memoizes a function {fn} using {hash} to hash the arguments.
  15. ---
  16. --- Internally uses a |lua-weaktable| to cache the results of {fn} meaning the
  17. --- cache will be invalidated whenever Lua does garbage collection.
  18. ---
  19. --- The memoized function returns shared references so be wary about
  20. --- mutating return values.
  21. ---
  22. --- @generic F: function
  23. --- @param hash integer|string|function Hash function to create a hash to use as a key to
  24. --- store results. Possible values:
  25. --- - When integer, refers to the index of an argument of {fn} to hash.
  26. --- This argument can have any type.
  27. --- - When function, is evaluated using the same arguments passed to {fn}.
  28. --- - When `concat`, the hash is determined by string concatenating all the
  29. --- arguments passed to {fn}.
  30. --- - When `concat-n`, the hash is determined by string concatenating the
  31. --- first n arguments passed to {fn}.
  32. ---
  33. --- @param fn F Function to memoize.
  34. --- @param strong? boolean Do not use a weak table
  35. --- @return F # Memoized version of {fn}
  36. --- @nodoc
  37. function M._memoize(hash, fn, strong)
  38. return require('vim.func._memoize')(hash, fn, strong)
  39. end
  40. return M