robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
d2ca90d87e
master
1--- @brief Glob-to-LPeg Converter (Peglob) 2--- This module converts glob patterns to LPeg patterns according to the LSP 3.17 specification: 3--- https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern 4--- 5--- Glob grammar overview: 6--- - `*` to match zero or more characters in a path segment 7--- - `?` to match on one character in a path segment 8--- - `**` to match any number of path segments, including none 9--- - `{}` to group conditions (e.g. `*.{ts,js}` matches TypeScript and JavaScript files) 10--- - `[]` to declare a range of characters to match in a path segment 11--- (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) 12--- - `[!...]` to negate a range of characters to match in a path segment 13--- (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) 14--- 15--- Additional constraints: 16--- - A Glob pattern must match an entire path, with partial matches 17--- considered failures. 18--- - The pattern only determines success or failure, without specifying 19--- which parts correspond to which characters. 20--- - A *path segment* is the portion of a path between two adjacent path 21--- separators (`/`), or between the start/end of the path and the nearest 22--- separator. 23--- - The `**` (*globstar*) pattern matches zero or more path segments, 24--- including intervening separators (`/`). Within pattern strings, `**` 25--- must be delimited by path separators (`/`) or pattern boundaries and 26--- cannot be adjacent to any characters other than `/`. If `**` is not 27--- the final element, it must be followed by `/`. 28--- - `{}` (*braced conditions*) contains valid Glob patterns as branches, 29--- separated by commas. Commas are exclusively used for separating 30--- branches and cannot appear within a branch for any other purpose. 31--- Nested `{}` structures are allowed, but `{}` must contain at least two 32--- branches—zero or one branch is not permitted. 33--- - In `[]` or `[!...]`, a *character range* consists of character 34--- intervals (e.g., `a-z`) or individual characters (e.g., `w`). A range 35--- including `/` won’t match that character. 36 37--- @diagnostic disable: missing-fields 38 39local m =vim . lpeg 40local mt =getmetatable ( m . P ( 0 )) 41local re =vim . re 42local bit =require ( 'bit' ) 43 44local M ={} 45 46-- Basic patterns for matching glob components 47local letter =m . P ( 1 ) - m . S ( '*?[]{}/\\' ) -- Any character except special glob characters 48local slash =m . P '/' * m . Cc ( m . P '/' ) -- Path separator with capture 49local notslash =m . P ( 1 ) - m . P '/' -- Any character except path separator 50local notcomma =m . P ( 1 ) - m . S ( ',\\' ) -- Any character except comma and backslash 51 52--- Handle EOF, considering whether we're in a segment or not 53--- @type vim.lpeg.Pattern 54local eof =- 1 55* m . Cb ( 'inseg' ) 56/ function ( flag ) 57if flag then 58return # m . P '/' 59else 60return m . P ( - 1 ) 61end 62end 63 64---@alias pat_table { F: string?, [1]: string, [2]: vim.lpeg.Pattern } 65---@alias seg_part { [string]: any, [integer]: pat_table } 66 67--- @param p pat_table Initial segment pattern data 68--- @return seg_part Segment structure with start pattern 69local function start_seg ( p ) 70return { s =p [ 2 ], e =true , n =0 } 71end 72 73--- @param t seg_part Segment structure 74--- @param p pat_table Pattern to look for 75--- @return table Updated segment structure 76local function lookfor ( t , p ) 77t . n =t . n + 1 78t [ t . n ] =p 79return t 80end 81 82--- @param t seg_part Segment structure 83--- @return table Segment structure with end pattern 84local function to_seg_end ( t ) 85t . e =notslash ^ 0 86return t 87end 88 89--- Constructs a segment matching pattern from collected components 90--- 91--- @param t seg_part Segment structure with patterns 92--- @return vim.lpeg.Pattern Complete segment match pattern 93local function end_seg ( t ) 94--- @type table<any,any> 95local seg_grammar ={ 's' } 96if t . n > 0 then 97seg_grammar . s =t . s 98for i =1 , t . n do 99local rname ='_' .. t [ i ][ 1 ] 100if not seg_grammar [ rname ] then 101-- Optimize search when deterministic first character is available 102if t [ i ]. F then 103seg_grammar [ rname ] =t [ i ][ 2 ] + notslash * ( notslash - m . P ( t [ i ]. F )) ^ 0 * m . V ( rname ) 104else 105seg_grammar [ rname ] =t [ i ][ 2 ] + notslash * m . V ( rname ) 106end 107end 108seg_grammar . s =seg_grammar . s * m . V ( rname ) 109end 110if t . e then 111seg_grammar . s =seg_grammar . s * t . e 112end 113return m . P ( seg_grammar ) 114else 115seg_grammar . s =t . s 116if t . e then 117seg_grammar . s =seg_grammar . s * t . e 118end 119return seg_grammar . s 120end 121end 122 123--- @param p vim.lpeg.Pattern Pattern directly after `**/` 124--- @return vim.lpeg.Pattern LPeg pattern for `**/p` 125local function dseg ( p ) 126return m . P { p + notslash ^ 0 * m . P '/' * m . V ( 1 ) } 127end 128 129--- @type (vim.lpeg.Pattern|table) 130local g =nil 131 132--- Multiplies conditions for braced expansion (Cartesian product) 133--- 134--- @param a string|string[] First part 135--- @param b string|string[] Second part 136--- @return string|string[] Cartesian product of values 137local function mul_cond ( a , b ) 138if type ( a ) == 'string' then 139if type ( b ) == 'string' then 140return a .. b 141elseif type ( b ) == 'table' then 142for i =1 , # b do 143b [ i ] =a .. b [ i ] 144end 145return b 146else 147return a 148end 149elseif type ( a ) == 'table' then 150if type ( b ) == 'string' then 151for i =1 , # a do 152a [ i ] =a [ i ] .. b 153end 154return a 155elseif type ( b ) == 'table' then 156--- @type string[] 157local res ={} 158local idx =0 159for i =1 , # a do 160for j =1 , # b do 161idx =idx + 1 162res [ idx ] =a [ i ] .. b [ j ] 163end 164end 165return res 166else 167return a 168end 169else 170return b 171end 172end 173 174--- Combines alternatives in braced patterns 175--- 176--- @param a string|table First part 177--- @param b string|table Second part 178--- @return table #Combined alternatives 179local function add_cond ( a , b ) 180if type ( a ) == 'string' then 181if type ( b ) == 'string' then 182return { a , b } 183elseif type ( b ) == 'table' then 184table . insert ( b , 1 , a ) 185return b 186end 187elseif type ( a ) == 'table' then 188if type ( b ) == 'string' then 189table . insert ( a , b ) 190return a 191elseif type ( b ) == 'table' then 192for i =1 , # b do 193table . insert ( a , b [ i ]) 194end 195return a 196end 197--- @diagnostic disable-next-line: missing-return 198end 199end 200 201--- Expands patterns handling segment boundaries 202--- `#` prefix is added for sub-grammar to detect in-segment flag 203--- 204---@param a (any[]|vim.lpeg.Pattern[]) Array of patterns 205---@param b string Tail string 206---@param inseg boolean Whether inside a path segment 207---@return vim.lpeg.Pattern #Expanded pattern 208local function expand ( a , b , inseg ) 209for i =1 , # a do 210if inseg then 211a [ i ] ='#' .. a [ i ] 212end 213a [ i ] =g : match ( a [ i ] .. b ) 214end 215local res =a [ 1 ] 216for i =2 , # a do 217res =res + a [ i ] 218end 219return res 220end 221 222--- Converts a UTF-8 character to its Unicode codepoint 223--- 224--- @param utf8_str string UTF-8 character 225--- @return number #Codepoint value 226local function to_codepoint ( utf8_str ) 227local codepoint =0 228local byte_count =0 229 230for i =1 , # utf8_str do 231local byte =utf8_str : byte ( i ) 232 233if byte_count ~= 0 then 234codepoint =bit . bor ( bit . lshift ( codepoint , 6 ), bit . band ( byte , 0x3F )) 235byte_count =byte_count - 1 236else 237if byte < 0x80 then 238codepoint =byte 239elseif byte < 0xE0 then 240byte_count =1 241codepoint =bit . band ( byte , 0x1F ) 242elseif byte < 0xF0 then 243byte_count =2 244codepoint =bit . band ( byte , 0x0F ) 245else 246byte_count =3 247codepoint =bit . band ( byte , 0x07 ) 248end 249end 250 251if byte_count == 0 then 252break 253end 254end 255 256return codepoint 257end 258 259--- Pattern for matching UTF-8 characters 260local cont =m . R ( '\128\191' ) 261local any_utf8 =m . R ( '\0\127' ) 262+ m . R ( '\194\223' ) * cont 263+ m . R ( '\224\239' ) * cont * cont 264+ m . R ( '\240\244' ) * cont * cont * cont 265 266--- Creates a character class pattern for glob ranges 267--- @param inv string Inversion flag ('!' or '') 268--- @param ranges (string|string[])[] Character ranges 269--- @return vim.lpeg.Pattern #Character class pattern 270local function class ( inv , ranges ) 271local patt =m . P ( false ) 272if # ranges == 0 then 273if inv == '!' then 274return m . P '[!]' 275else 276return m . P '[]' 277end 278end 279for _ , v in ipairs ( ranges ) do 280patt =patt + ( type ( v ) == 'table' and m . utfR ( to_codepoint ( v [ 1 ]), to_codepoint ( v [ 2 ])) or m . P ( v )) 281end 282if inv == '!' then 283patt =m . P ( 1 ) - patt --[[@as vim.lpeg.Pattern]] 284end 285return patt - m . P '/' 286end 287 288-- Parse constraints for optimizing braced conditions 289local noopt_condlist =re . compile [[ 290s <- '/' / '**' / . [^/*]* s 291]] 292 293local opt_tail =re . compile [[ 294s <- (!'**' [^{/])* &'/' 295]] 296 297-- stylua: ignore start 298--- @nodoc 299--- @diagnostic disable 300--- Main grammar for glob pattern matching 301g ={ 302'Glob' , 303Glob =( m . P '#' * m . Cg ( m . Cc ( true ), 'inseg' ) + m . Cg ( m . Cc ( false ), 'inseg' )) * 304m . Cf ( m . V 'Element' ^- 1 * ( slash * m . V 'Element' ) ^ 0 * ( slash ^- 1 * eof ), mt . __mul ), 305-- Elements handle segments, globstar patterns 306Element =m . V 'DSeg' + m . V 'DSEnd' + m . Cf ( m . V 'Segment' * ( slash * m . V 'Segment' ) ^ 0 * ( slash * eof + eof ^- 1 ), mt . __mul ), 307-- Globstar patterns 308DSeg =m . P '**/' * (( m . V 'Element' + eof ) / dseg ), 309DSEnd =m . P '**' * - 1 * m . Cc ( m . P ( 1 ) ^ 0 ), 310-- Segment handling with word and star patterns 311Segment =( m . V 'Word' / start_seg + m . Cc ( { '' , true } ) / start_seg * ( m . V 'Star' * m . V 'Word' % lookfor )) * 312( m . V 'Star' * m . V 'Word' % lookfor ) ^ 0 * ( m . V 'Star' * m . V 'CheckBnd' % to_seg_end ) ^- 1 / end_seg 313+ m . V 'Star' * m . V 'CheckBnd' * m . Cc ( notslash ^ 0 ), 314CheckBnd =# m . P '/' + - 1 , -- Boundary constraint 315 316-- Word patterns for fixed-length matching 317Word =- m . P '*' * m . Ct ( m . V ( 'FIRST' ) ^- 1 * m . C ( m . V 'WordAux' ) ), 318WordAux =m . V 'Branch' + m . Cf ( m . V 'Simple' ^ 1 * m . V 'Branch' ^- 1 , mt . __mul ), 319Simple =m . Cg ( m . V 'Token' * ( m . V 'Token' % mt . __mul ) ^ 0 * ( m . V 'Boundary' % mt . __mul ) ^- 1 ), 320Boundary =# m . P '/' * m . Cc ( # m . P '/' ) + eof , 321Token =m . V 'Ques' + m . V 'Class' + m . V 'Escape' + m . V 'Literal' , 322Star =m . P '*' , 323Ques =m . P '?' * m . Cc ( notslash ), 324Escape =m . P '\\' * m . C ( 1 ) / m . P , 325Literal =m . C ( letter ^ 1 ) / m . P , 326 327-- Branch handling for braced conditions 328Branch =m . Cmt ( m . C ( m . V 'CondList' ), function ( s , i , p1 , p2 ) 329-- Optimize brace expansion when possible 330-- p1: string form of condition list, p2: transformed lua table 331if noopt_condlist : match ( p1 ) then 332-- Cannot optimize, match till the end 333return # s + 1 , p2 , s : sub ( i ) 334end 335-- Find point to cut for optimization 336local cut =opt_tail : match ( s , i ) 337if cut then 338-- Can optimize: match till cut point 339-- true flag tells expand to transform EOF matches to &'/' predicates 340return cut , p2 , s : sub ( i , cut - 1 ), true 341else 342-- Cannot optimize 343return # s + 1 , p2 , s : sub ( i ) 344end 345end ) / expand , 346-- Brace expansion handling 347CondList =m . Cf ( m . P '{' * m . V 'Cond' * ( m . P ',' * m . V 'Cond' ) ^ 1 * m . P '}' , add_cond ), 348Cond =m . Cf (( m . C (( notcomma + m . P '\\' * 1 - m . S '{}' ) ^ 1 ) + m . V 'CondList' ) ^ 1 , mul_cond ) + m . C ( true ), 349 350-- Character class handling 351Class =m . P '[' * m . C ( m . P '!' ^- 1 ) * m . Ct ( 352( m . Ct ( m . C ( any_utf8 ) * m . P '-' * m . C ( any_utf8 - m . P ']' )) + m . C ( any_utf8 - m . P ']' )) ^ 0 353) * m . P ']' / class , 354 355-- Deterministic first character extraction for optimization 356FIRST =m . Cg ( m . P ( function ( s , i ) 357if letter : match ( s , i ) then return true , s : sub ( i , i ) 358else return false end 359end ), 'F' ) 360} 361-- stylua: ignore end 362--- @diagnostic enable 363 364--- @nodoc 365g =m . P ( g ) 366 367--- Parses a raw glob into an |lua-lpeg| pattern. 368--- 369---@param pattern string The raw glob pattern 370---@return vim.lpeg.Pattern #An |lua-lpeg| representation of the pattern 371function M . to_lpeg ( pattern ) 372local lpeg_pattern =g : match ( pattern ) --[[@as vim.lpeg.Pattern?]] 373assert ( lpeg_pattern , string . format ( 'Invalid glob: %s' , pattern )) 374return lpeg_pattern 375end 376 377return M