fix(treesitter): don't throw an error for missing injected langs

This commit is contained in:
Steven Sojka
2020-12-04 16:56:29 -06:00
parent 0c8d6ab536
commit e15c5f58df
3 changed files with 40 additions and 17 deletions

View File

@@ -8,7 +8,8 @@ local M = {}
--
-- @param lang The language the parser should parse
-- @param path Optionnal path the parser is located at
function M.require_language(lang, path)
-- @param silent Don't throw an error if language not found
function M.require_language(lang, path, silent)
if vim._ts_has_language(lang) then
return true
end
@@ -16,12 +17,23 @@ function M.require_language(lang, path)
local fname = 'parser/' .. lang .. '.*'
local paths = a.nvim_get_runtime_file(fname, false)
if #paths == 0 then
if silent then
return false
end
-- TODO(bfredl): help tag?
error("no parser for '"..lang.."' language, see :help treesitter-parsers")
end
path = paths[1]
end
if silent then
return pcall(function() vim._ts_add_language(path, lang) end)
else
vim._ts_add_language(path, lang)
end
return true
end
--- Inspects the provided language.

View File

@@ -121,6 +121,12 @@ function LanguageTree:parse()
local seen_langs = {}
for lang, injection_ranges in pairs(injections_by_lang) do
local has_lang = language.require_language(lang, nil, true)
-- Child language trees should just be ignored if not found, since
-- they can depend on the text of a node. Intermediate strings
-- would cause errors for unknown parsers.
if has_lang then
local child = self._children[lang]
if not child then
@@ -139,6 +145,7 @@ function LanguageTree:parse()
seen_langs[lang] = true
end
end
for lang, _ in pairs(self._children) do
if not seen_langs[lang] then

View File

@@ -22,6 +22,10 @@ describe('treesitter API', function()
matches("Error executing lua: Failed to load parser: uv_dlopen: .+",
pcall_err(exec_lua, "parser = vim.treesitter.require_language('borklang', 'borkbork.so')"))
-- Should not throw an error when silent
eq(false, exec_lua("return vim.treesitter.require_language('borklang', nil, true)"))
eq(false, exec_lua("return vim.treesitter.require_language('borklang', 'borkbork.so', true)"))
eq("Error executing lua: .../language.lua:0: no parser for 'borklang' language, see :help treesitter-parsers",
pcall_err(exec_lua, "parser = vim.treesitter.inspect_language('borklang')"))
end)