robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 25local message =lint : gsub ( '\n' , ' ' ) 26diagnostics [ # diagnostics + 1 ] ={ 27lnum =range [ 1 ], 28end_lnum =range [ 3 ], 29col =range [ 2 ], 30end_col =range [ 4 ], 31severity =vim . diagnostic . ERROR , 32message =message , 33source =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 ) 41local filename =api . nvim_buf_get_name ( buf ) 42if filename ~= '' then 43-- get <lang> from /path/<lang>/<query_type>.scm 44local resolved =vim . fs . basename ( vim . fs . dirname ( vim . fs . abspath ( filename ))) 45return vim . treesitter . language . get_lang ( resolved ) 46end 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 ) 53opts =opts or {} 54local langs =opts . langs or guess_query_lang ( buf ) 55return { 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 61name: _ @node.named) 62(anonymous_node 63name: _ @node.anonymous) 64(field_definition 65name: (identifier) @field) 66(predicate 67name: (identifier) @predicate.name 68type: (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 ) 76local start_line , start_col =node : range () 77local line_offset , col_offset , msg =err : match ( '.-:%d+: Query error at (%d+):(%d+)%. ([^:]+)' ) 78assert ( line_offset and col_offset and msg ) 79start_line , start_col = 80start_line + vim . _assert_integer ( line_offset ) - 1 , 81start_col + vim . _assert_integer ( col_offset ) - 1 82local end_line , end_col =start_line , start_col 83if msg : match ( '^Invalid syntax' ) or msg : match ( '^Impossible' ) then 84-- Use the length of the underlined node 85local underlined =vim . split ( err , '\n' )[ 2 ] 86end_col =end_col + # underlined 87elseif msg : match ( '^Invalid' ) then 88-- Use the length of the problematic type/capture/field 89end_col =end_col + # ( msg : match ( '"([^"]+)"' ) or '' ) 90end 91 92return { 93msg =msg , 94range ={ 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 ) 102return 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 ) 110local query_text =vim . treesitter . get_node_text ( node , buf ) 111local ok , err =pcall ( vim . treesitter . query . parse , lang , query_text ) ---@type boolean|vim.treesitter.ParseError, string|vim.treesitter.Query 112 113if not ok and type ( err ) == 'string' then 114return get_error_entry ( err , node ) 115end 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 ) 124local lang =lang_context . lang 125local parser_info =lang_context . parser_info 126 127for id , nodes in pairs ( match ) do 128for _ , node in ipairs ( nodes ) do 129local cap_id =query . captures [ id ] 130 131-- perform language-independent checks only for first lang 132if lang_context . is_first_lang and cap_id == 'error' then 133local node_text =vim . treesitter . get_node_text ( node , buf ): gsub ( '\n' , ' ' ) 134---@diagnostic disable-next-line: missing-fields LuaLS varargs bug 135local range ={ node : range () } --- @type Range4 136add_lint_for_node ( diagnostics , range , 'Syntax error: ' .. node_text ) 137end 138 139-- other checks rely on Neovim parser introspection 140if lang and parser_info and cap_id == 'toplevel' then 141local err =parse ( node , buf , lang ) 142if err then 143add_lint_for_node ( diagnostics , err . range , err . msg , lang ) 144end 145end 146end 147end 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 ) 153if buf == 0 then 154buf =api . nvim_get_current_buf () 155end 156 157local diagnostics ={} --- @type vim.Diagnostic.Set[] 158local query =vim . treesitter . query . parse ( 'query' , lint_query ) 159 160opts =normalize_opts ( buf , opts ) 161 162-- perform at least one iteration even with no langs to perform language independent checks 163for i =1 , math . max ( 1 , # opts . langs ) do 164local lang =opts . langs [ i ] 165 166--- @type (table|nil) 167local parser_info =vim . npcall ( vim . treesitter . language . inspect , lang ) 168local lang_context ={ 169lang =lang , 170parser_info =parser_info , 171is_first_lang =i == 1 , 172} 173 174local parser =assert ( vim . treesitter . get_parser ( buf , nil )) 175parser : parse () 176parser : for_each_tree ( function ( tree , ltree ) 177if ltree : lang () == 'query' then 178for _ , match , _ in query : iter_matches ( tree : root (), buf , 0 , - 1 ) do 179lint_match ( buf , match , query , lang_context , diagnostics ) 180end 181end 182end ) 183end 184 185vim . diagnostic . set ( namespace , buf , diagnostics ) 186end 187 188--- @param buf integer 189function M . clear ( buf ) 190vim . diagnostic . reset ( namespace , buf ) 191end 192 193--- @param findstart 0|1 194--- @param base string 195function M . omnifunc ( findstart , base ) 196if findstart == 1 then 197local result = 198api . nvim_get_current_line (): sub ( 1 , api . nvim_win_get_cursor ( 0 )[ 2 ]): find ( '["#%-%w]*$' ) 199assert ( result ) 200return result - 1 201end 202 203local buf =api . nvim_get_current_buf () 204local query_lang =guess_query_lang ( buf ) 205if not query_lang then 206return - 2 207end 208 209local ok , parser_info =pcall ( vim . treesitter . language . inspect , query_lang ) 210if not ok then 211return - 2 212end 213 214local items ={} 215for _ , f in pairs ( parser_info . fields ) do 216if f : find ( base , 1 , true ) then 217table . insert ( items , f .. ':' ) 218end 219end 220for _ , p in pairs ( vim . treesitter . query . list_predicates ()) do 221local text ='#' .. p 222local found =text : find ( base , 1 , true ) 223if found and found <= 2 then -- with or without '#' 224table . insert ( items , text ) 225end 226text ='#not-' .. p 227found =text : find ( base , 1 , true ) 228if found and found <= 2 then -- with or without '#' 229table . insert ( items , text ) 230end 231end 232for _ , p in pairs ( vim . treesitter . query . list_directives ()) do 233local text ='#' .. p 234local found =text : find ( base , 1 , true ) 235if found and found <= 2 then -- with or without '#' 236table . insert ( items , text ) 237end 238end 239for text , named in 240pairs ( parser_info . symbols --[[@as table<string, boolean>]] ) 241do 242if not named then 243text =string . format ( '%q' , text : sub ( 2 , - 2 )): gsub ( '\n' , 'n' ) ---@type string 244end 245if text : find ( base , 1 , true ) then 246table . insert ( items , text ) 247end 248end 249return { words =items , refresh ='always' } 250end 251 252return M