robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
7.8 KiB252 linesraw
1local api = vim.api
2
3local namespace = api.nvim_create_namespace('nvim.treesitter.query_linter')
4
5local M = {}
6
7--- @class QueryLinterNormalizedOpts
8--- @field langs string[]
9--- @field clear? boolean
10
11--- @alias vim.treesitter.ParseError {msg: string, range: Range4}
12
13--- Contains language dependent context for the query linter
14--- @class QueryLinterLanguageContext
15--- @field lang string? Current `lang` of the targeted parser
16--- @field parser_info table? Parser info returned by vim.treesitter.language.inspect
17--- @field is_first_lang boolean Whether this is the first language of a linter run checking queries for multiple `langs`
18
19--- Adds a diagnostic for node in the query buffer
20--- @param diagnostics vim.Diagnostic.Set[]
21--- @param range Range4
22--- @param lint string
23--- @param lang string?
24local function add_lint_for_node(diagnostics, range, lint, lang)
25  local message = lint:gsub('\n', ' ')
26  diagnostics[#diagnostics + 1] = {
27    lnum = range[1],
28    end_lnum = range[3],
29    col = range[2],
30    end_col = range[4],
31    severity = vim.diagnostic.ERROR,
32    message = message,
33    source = lang,
34  }
35end
36
37--- Determines the target language of a query file by its path: <lang>/<query_type>.scm
38--- @param buf integer
39--- @return string?
40local function guess_query_lang(buf)
41  local filename = api.nvim_buf_get_name(buf)
42  if filename ~= '' then
43    -- get <lang> from /path/<lang>/<query_type>.scm
44    local resolved = vim.fs.basename(vim.fs.dirname(vim.fs.abspath(filename)))
45    return vim.treesitter.language.get_lang(resolved)
46  end
47end
48
49--- @param buf integer
50--- @param opts vim.treesitter.query.lint.Opts|QueryLinterNormalizedOpts|nil
51--- @return QueryLinterNormalizedOpts
52local function normalize_opts(buf, opts)
53  opts = opts or {}
54  local langs = opts.langs or guess_query_lang(buf)
55  return { langs = type(langs) == 'table' and langs or { langs }, clear = opts.clear }
56end
57
58local lint_query = [[;; query
59  (program [(named_node) (anonymous_node) (list) (grouping)] @toplevel)
60  (named_node
61    name: _ @node.named)
62  (anonymous_node
63    name: _ @node.anonymous)
64  (field_definition
65    name: (identifier) @field)
66  (predicate
67    name: (identifier) @predicate.name
68    type: (predicate_type) @predicate.type)
69  (ERROR) @error
70]]
71
72--- @param err string
73--- @param node TSNode
74--- @return vim.treesitter.ParseError
75local function get_error_entry(err, node)
76  local start_line, start_col = node:range()
77  local line_offset, col_offset, msg = err:match('.-:%d+: Query error at (%d+):(%d+)%. ([^:]+)')
78  assert(line_offset and col_offset and msg)
79  start_line, start_col =
80    start_line + vim._assert_integer(line_offset) - 1,
81    start_col + vim._assert_integer(col_offset) - 1
82  local end_line, end_col = start_line, start_col
83  if msg:match('^Invalid syntax') or msg:match('^Impossible') then
84    -- Use the length of the underlined node
85    local underlined = vim.split(err, '\n')[2]
86    end_col = end_col + #underlined
87  elseif msg:match('^Invalid') then
88    -- Use the length of the problematic type/capture/field
89    end_col = end_col + #(msg:match('"([^"]+)"') or '')
90  end
91
92  return {
93    msg = msg,
94    range = { start_line, start_col, end_line, end_col },
95  }
96end
97
98--- @param node TSNode
99--- @param buf integer
100--- @param lang string
101local function hash_parse(node, buf, lang)
102  return tostring(node:id()) .. tostring(buf) .. tostring(vim.b[buf].changedtick) .. lang
103end
104
105--- @param node TSNode
106--- @param buf integer
107--- @param lang string
108--- @return vim.treesitter.ParseError?
109local parse = vim.func._memoize(hash_parse, function(node, buf, lang)
110  local query_text = vim.treesitter.get_node_text(node, buf)
111  local ok, err = pcall(vim.treesitter.query.parse, lang, query_text) ---@type boolean|vim.treesitter.ParseError, string|vim.treesitter.Query
112
113  if not ok and type(err) == 'string' then
114    return get_error_entry(err, node)
115  end
116end)
117
118--- @param buf integer
119--- @param match table<integer,TSNode[]>
120--- @param query vim.treesitter.Query
121--- @param lang_context QueryLinterLanguageContext
122--- @param diagnostics vim.Diagnostic.Set[]
123local function lint_match(buf, match, query, lang_context, diagnostics)
124  local lang = lang_context.lang
125  local parser_info = lang_context.parser_info
126
127  for id, nodes in pairs(match) do
128    for _, node in ipairs(nodes) do
129      local cap_id = query.captures[id]
130
131      -- perform language-independent checks only for first lang
132      if lang_context.is_first_lang and cap_id == 'error' then
133        local node_text = vim.treesitter.get_node_text(node, buf):gsub('\n', ' ')
134        ---@diagnostic disable-next-line: missing-fields LuaLS varargs bug
135        local range = { node:range() } --- @type Range4
136        add_lint_for_node(diagnostics, range, 'Syntax error: ' .. node_text)
137      end
138
139      -- other checks rely on Neovim parser introspection
140      if lang and parser_info and cap_id == 'toplevel' then
141        local err = parse(node, buf, lang)
142        if err then
143          add_lint_for_node(diagnostics, err.range, err.msg, lang)
144        end
145      end
146    end
147  end
148end
149
150--- @param buf integer Buffer to lint
151--- @param opts vim.treesitter.query.lint.Opts|QueryLinterNormalizedOpts|nil Options for linting
152function M.lint(buf, opts)
153  if buf == 0 then
154    buf = api.nvim_get_current_buf()
155  end
156
157  local diagnostics = {} --- @type vim.Diagnostic.Set[]
158  local query = vim.treesitter.query.parse('query', lint_query)
159
160  opts = normalize_opts(buf, opts)
161
162  -- perform at least one iteration even with no langs to perform language independent checks
163  for i = 1, math.max(1, #opts.langs) do
164    local lang = opts.langs[i]
165
166    --- @type (table|nil)
167    local parser_info = vim.npcall(vim.treesitter.language.inspect, lang)
168    local lang_context = {
169      lang = lang,
170      parser_info = parser_info,
171      is_first_lang = i == 1,
172    }
173
174    local parser = assert(vim.treesitter.get_parser(buf, nil))
175    parser:parse()
176    parser:for_each_tree(function(tree, ltree)
177      if ltree:lang() == 'query' then
178        for _, match, _ in query:iter_matches(tree:root(), buf, 0, -1) do
179          lint_match(buf, match, query, lang_context, diagnostics)
180        end
181      end
182    end)
183  end
184
185  vim.diagnostic.set(namespace, buf, diagnostics)
186end
187
188--- @param buf integer
189function M.clear(buf)
190  vim.diagnostic.reset(namespace, buf)
191end
192
193--- @param findstart 0|1
194--- @param base string
195function M.omnifunc(findstart, base)
196  if findstart == 1 then
197    local result =
198      api.nvim_get_current_line():sub(1, api.nvim_win_get_cursor(0)[2]):find('["#%-%w]*$')
199    assert(result)
200    return result - 1
201  end
202
203  local buf = api.nvim_get_current_buf()
204  local query_lang = guess_query_lang(buf)
205  if not query_lang then
206    return -2
207  end
208
209  local ok, parser_info = pcall(vim.treesitter.language.inspect, query_lang)
210  if not ok then
211    return -2
212  end
213
214  local items = {}
215  for _, f in pairs(parser_info.fields) do
216    if f:find(base, 1, true) then
217      table.insert(items, f .. ':')
218    end
219  end
220  for _, p in pairs(vim.treesitter.query.list_predicates()) do
221    local text = '#' .. p
222    local found = text:find(base, 1, true)
223    if found and found <= 2 then -- with or without '#'
224      table.insert(items, text)
225    end
226    text = '#not-' .. p
227    found = text:find(base, 1, true)
228    if found and found <= 2 then -- with or without '#'
229      table.insert(items, text)
230    end
231  end
232  for _, p in pairs(vim.treesitter.query.list_directives()) do
233    local text = '#' .. p
234    local found = text:find(base, 1, true)
235    if found and found <= 2 then -- with or without '#'
236      table.insert(items, text)
237    end
238  end
239  for text, named in
240    pairs(parser_info.symbols --[[@as table<string, boolean>]])
241  do
242    if not named then
243      text = string.format('%q', text:sub(2, -2)):gsub('\n', 'n') ---@type string
244    end
245    if text:find(base, 1, true) then
246      table.insert(items, text)
247    end
248  end
249  return { words = items, refresh = 'always' }
250end
251
252return M