feat(lua): add vim.func._memoize

Memoizes a function, using a custom function to hash the arguments.

Private for now until:

- There are other places in the codebase that could benefit from this
  (e.g. LSP), but might require other changes to accommodate.
- Invalidation of the cache needs to be controllable. Using weak tables
  is an acceptable invalidation policy, but it shouldn't be the only
  one.
- I don't think the story around `hash_fn` is completely thought out. We
  may be able to have a good default hash_fn by hashing each argument,
  so basically a better 'concat'.
This commit is contained in:
Lewis Russell
2023-09-16 23:10:30 +01:00
committed by Lewis Russell
parent 11865dbe39
commit 877d04d0fb
8 changed files with 137 additions and 73 deletions

View File

@ -191,12 +191,6 @@ function M.set(lang, query_name, text)
explicit_queries[lang][query_name] = M.parse(lang, text)
end
--- `false` if query files didn't exist or were empty
---@type table<string, table<string, Query|false>>
local query_get_cache = vim.defaulttable(function()
return setmetatable({}, { __mode = 'v' })
end)
---@deprecated
function M.get_query(...)
vim.deprecate('vim.treesitter.query.get_query()', 'vim.treesitter.query.get()', '0.10')
@ -209,34 +203,19 @@ end
---@param query_name string Name of the query (e.g. "highlights")
---
---@return Query|nil Parsed query
function M.get(lang, query_name)
M.get = vim.func._memoize('concat-2', function(lang, query_name)
if explicit_queries[lang][query_name] then
return explicit_queries[lang][query_name]
end
local cached = query_get_cache[lang][query_name]
if cached then
return cached
elseif cached == false then
return nil
end
local query_files = M.get_files(lang, query_name)
local query_string = read_query_files(query_files)
if #query_string == 0 then
query_get_cache[lang][query_name] = false
return nil
end
local query = M.parse(lang, query_string)
query_get_cache[lang][query_name] = query
return query
end
---@type table<string, table<string, Query>>
local query_parse_cache = vim.defaulttable(function()
return setmetatable({}, { __mode = 'v' })
return M.parse(lang, query_string)
end)
---@deprecated
@ -262,20 +241,15 @@ end
---@param query string Query in s-expr syntax
---
---@return Query Parsed query
function M.parse(lang, query)
M.parse = vim.func._memoize('concat-2', function(lang, query)
language.add(lang)
local cached = query_parse_cache[lang][query]
if cached then
return cached
end
local self = setmetatable({}, Query)
self.query = vim._ts_parse_query(lang, query)
self.info = self.query:inspect()
self.captures = self.info.captures
query_parse_cache[lang][query] = self
return self
end
end)
---@deprecated
function M.get_range(...)