robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
87b42e1209
master
1#!/usr/bin/env nvim -l 2---@diagnostic disable: no-unknown 3 4-- Lints C files in the Neovim source tree. 5-- Based on Google "cpplint", modified for Neovim. 6-- 7-- Test coverage: `test/functional/script/clint_spec.lua` 8-- 9-- This can get very confused by /* and // inside strings! We do a small hack, 10-- which is to ignore //'s with "'s after them on the same line, but it is far 11-- from perfect (in either direction). 12 13local vim =vim 14 15-- Error categories used for filtering 16local ERROR_CATEGORIES ={ 17'build/endif_comment' , 18'build/header_guard' , 19'build/include_defs' , 20'build/defs_header' , 21'build/printf_format' , 22'build/storage_class' , 23'build/init_macro' , 24'readability/bool' , 25'readability/multiline_comment' , 26-- Dropped 'readability/multiline_string' detection because it is too buggy, and uncommon. 27-- 'readability/multiline_string', 28'readability/nul' , 29'readability/utf8' , 30'readability/increment' , 31'runtime/arrays' , 32'runtime/int' , 33'runtime/memset' , 34'runtime/printf' , 35'runtime/printf_format' , 36'runtime/threadsafe_fn' , 37'runtime/deprecated' , 38'whitespace/indent' , 39'whitespace/operators' , 40'whitespace/cast' , 41} 42 43-- Default filters (empty by default) 44local DEFAULT_FILTERS ={} 45 46-- Assembly state constants 47local NO_ASM =0 -- Outside of inline assembly block 48local INSIDE_ASM =1 -- Inside inline assembly block 49local END_ASM =2 -- Last line of inline assembly block 50local BLOCK_ASM =3 -- The whole block is an inline assembly block 51 52-- Regex compilation cache 53local regexp_compile_cache ={} 54 55-- Error suppression state 56local error_suppressions ={} 57local error_suppressions_2 ={} 58 59-- Configuration 60local valid_extensions ={ c =true , h =true } 61 62-- Precompiled regex patterns (only the ones still used) 63local RE_SUPPRESSION =vim . regex ( [[\<NOLINT\>]] ) 64local RE_COMMENTLINE =vim . regex ( [[^\s*//]] ) 65local RE_PATTERN_INCLUDE =vim . regex ( [[^\s*#\s*include\s*\([<"]\)\([^>"]*\)[>"].*$]] ) 66 67-- Assembly block matching (using Lua pattern instead of vim.regex for simplicity) 68local function match_asm ( line ) 69return line : find ( '^%s*asm%s*[{(]' ) 70or line : find ( '^%s*_asm%s*[{(]' ) 71or line : find ( '^%s*__asm%s*[{(]' ) 72or line : find ( '^%s*__asm__%s*[{(]' ) 73end 74 75-- Threading function replacements 76local threading_list ={ 77{ 'asctime(' , 'os_asctime_r(' } , 78{ 'ctime(' , 'os_ctime_r(' } , 79{ 'getgrgid(' , 'os_getgrgid_r(' } , 80{ 'getgrnam(' , 'os_getgrnam_r(' } , 81{ 'getlogin(' , 'os_getlogin_r(' } , 82{ 'getpwnam(' , 'os_getpwnam_r(' } , 83{ 'getpwuid(' , 'os_getpwuid_r(' } , 84{ 'gmtime(' , 'os_gmtime_r(' } , 85{ 'localtime(' , 'os_localtime_r(' } , 86{ 'strtok(' , 'os_strtok_r(' } , 87{ 'ttyname(' , 'os_ttyname_r(' } , 88{ 'asctime_r(' , 'os_asctime_r(' } , 89{ 'ctime_r(' , 'os_ctime_r(' } , 90{ 'getgrgid_r(' , 'os_getgrgid_r(' } , 91{ 'getgrnam_r(' , 'os_getgrnam_r(' } , 92{ 'getlogin_r(' , 'os_getlogin_r(' } , 93{ 'getpwnam_r(' , 'os_getpwnam_r(' } , 94{ 'getpwuid_r(' , 'os_getpwuid_r(' } , 95{ 'gmtime_r(' , 'os_gmtime_r(' } , 96{ 'localtime_r(' , 'os_localtime_r(' } , 97{ 'strtok_r(' , 'os_strtok_r(' } , 98{ 'ttyname_r(' , 'os_ttyname_r(' } , 99} 100 101-- Memory function replacements 102local memory_functions ={ 103{ 'malloc(' , 'xmalloc(' } , 104{ 'calloc(' , 'xcalloc(' } , 105{ 'realloc(' , 'xrealloc(' } , 106{ 'strdup(' , 'xstrdup(' } , 107{ 'free(' , 'xfree(' } , 108} 109local memory_ignore_pattern =vim . regex ( [[src/nvim/memory.c$]] ) 110 111-- OS function replacements 112local os_functions ={ 113{ 'setenv(' , 'os_setenv(' } , 114{ 'getenv(' , 'os_getenv(' } , 115{ '_wputenv(' , 'os_setenv(' } , 116{ '_putenv_s(' , 'os_setenv(' } , 117{ 'putenv(' , 'os_setenv(' } , 118{ 'unsetenv(' , 'os_unsetenv(' } , 119} 120 121-- CppLintState class equivalent 122local CppLintState ={} 123CppLintState . __index =CppLintState 124 125function CppLintState . new () 126local self =setmetatable ( {} , CppLintState ) 127self . verbose_level =1 128self . error_count =0 129self . filters =vim . deepcopy ( DEFAULT_FILTERS ) 130self . counting ='total' 131self . errors_by_category ={} 132self . stdin_filename ='' 133self . output_format ='emacs' 134self . record_errors_file =nil 135self . suppressed_errors =vim . defaulttable ( function () 136return vim . defaulttable ( function () 137return {} 138end ) 139end ) 140return self 141end 142 143function CppLintState : set_output_format ( output_format ) 144self . output_format =output_format 145end 146 147function CppLintState : set_verbose_level ( level ) 148local last_verbose_level =self . verbose_level 149self . verbose_level =level 150return last_verbose_level 151end 152 153function CppLintState : set_counting_style ( counting_style ) 154self . counting =counting_style 155end 156 157function CppLintState : set_filters ( filters ) 158self . filters =vim . deepcopy ( DEFAULT_FILTERS ) 159for filt in vim . gsplit ( filters , ',' , { trimempty =true } ) do 160local clean_filt =vim . trim ( filt ) 161if clean_filt ~= '' then 162table . insert ( self . filters , clean_filt ) 163end 164end 165 166for _ , filt in ipairs ( self . filters ) do 167if not ( filt : sub ( 1 , 1 ) == '+' or filt : sub ( 1 , 1 ) == '-' ) then 168error ( 'Every filter in --filters must start with + or - (' .. filt .. ' does not)' ) 169end 170end 171end 172 173function CppLintState : reset_error_counts () 174self . error_count =0 175self . errors_by_category ={} 176end 177 178function CppLintState : increment_error_count ( category ) 179self . error_count =self . error_count + 1 180if self . counting == 'toplevel' or self . counting == 'detailed' then 181local cat =category 182if self . counting ~= 'detailed' then 183cat =category : match ( '([^/]+)' ) or category 184end 185if not self . errors_by_category [ cat ] then 186self . errors_by_category [ cat ] =0 187end 188self . errors_by_category [ cat ] =self . errors_by_category [ cat ] + 1 189end 190end 191 192function CppLintState : print_error_counts () 193for category , count in pairs ( self . errors_by_category ) do 194io . write ( string . format ( "Category '%s' errors found: %d\n" , category , count )) 195end 196if self . error_count > 0 then 197io . write ( string . format ( 'Total errors found: %d\n' , self . error_count )) 198end 199end 200 201function CppLintState : suppress_errors_from ( fname ) 202if not fname then 203return 204end 205 206local ok , content =pcall ( vim . fn . readfile , fname ) 207if not ok then 208return 209end 210 211for _ , line in ipairs ( content ) do 212local ok2 , data =pcall ( vim . json . decode , line ) 213if ok2 then 214local fname2 , lines , category =data [ 1 ], data [ 2 ], data [ 3 ] 215local lines_tuple =vim . islist ( lines ) and lines or { lines } 216self . suppressed_errors [ fname2 ][ vim . inspect ( lines_tuple )][ category ] =true 217end 218end 219end 220 221function CppLintState : record_errors_to ( fname ) 222if not fname then 223return 224end 225self . record_errors_file =io . open ( fname , 'w' ) 226end 227 228-- Global state instance 229local cpplint_state =CppLintState . new () 230 231-- Utility functions 232local function match ( pattern , s ) 233if not regexp_compile_cache [ pattern ] then 234regexp_compile_cache [ pattern ] =vim . regex ( pattern ) 235end 236local s_idx , e_idx =regexp_compile_cache [ pattern ]: match_str ( s ) 237if s_idx then 238local match_obj ={} 239match_obj . start =s_idx 240match_obj . finish =e_idx 241function match_obj . group ( n ) 242if n == 0 then 243return s : sub ( s_idx + 1 , e_idx ) 244else 245-- For subgroups, we need to use a different approach 246-- This is a simplified version - full regex groups would need more complex handling 247return s : sub ( s_idx + 1 , e_idx ) 248end 249end 250return match_obj 251end 252return nil 253end 254 255-- NOLINT suppression functions 256local function parse_nolint_suppressions ( raw_line , linenum ) 257local s_idx , e_idx =RE_SUPPRESSION : match_str ( raw_line ) 258if not s_idx then 259return 260end 261 262-- Extract what comes after NOLINT, looking for optional (category) 263local after_nolint =raw_line : sub ( e_idx + 1 ) 264local category =after_nolint : match ( '^%s*(%([^)]*%))' ) 265 266if not category or category == '(*)' then 267-- Suppress all errors on this line 268if not error_suppressions [ vim . NIL ] then 269error_suppressions [ vim . NIL ] ={} 270end 271table . insert ( error_suppressions [ vim . NIL ], linenum ) 272else 273-- Extract category name from parentheses 274local cat_name =category : match ( '^%((.-)%)$' ) 275if cat_name then 276for _ , cat in ipairs ( ERROR_CATEGORIES ) do 277if cat == cat_name then 278if not error_suppressions [ cat_name ] then 279error_suppressions [ cat_name ] ={} 280end 281table . insert ( error_suppressions [ cat_name ], linenum ) 282break 283end 284end 285end 286end 287end 288 289local function reset_nolint_suppressions () 290error_suppressions ={} 291end 292 293local function reset_known_error_suppressions () 294error_suppressions_2 ={} 295end 296 297local function is_error_suppressed_by_nolint ( category , linenum ) 298local cat_suppressed =error_suppressions [ category ] or {} 299local all_suppressed =error_suppressions [ vim . NIL ] or {} 300 301for _ , line in ipairs ( cat_suppressed ) do 302if line == linenum then 303return true 304end 305end 306for _ , line in ipairs ( all_suppressed ) do 307if line == linenum then 308return true 309end 310end 311return false 312end 313 314local function is_error_in_suppressed_errors_list ( category , linenum ) 315local key =category .. ':' .. linenum 316return error_suppressions_2 [ key ] == true 317end 318 319-- FileInfo class equivalent 320local FileInfo ={} 321FileInfo . __index =FileInfo 322 323function FileInfo . new ( filename ) 324local self =setmetatable ( {} , FileInfo ) 325self . _filename =filename 326return self 327end 328 329function FileInfo : full_name () 330local abspath =vim . fn . fnamemodify ( self . _filename , ':p' ) 331return abspath : gsub ( '\\' , '/' ) 332end 333 334function FileInfo : relative_path () 335local fullname =self : full_name () 336 337if vim . fn . filereadable ( fullname ) == 1 then 338-- Find git repository root using vim.fs.root 339local git_root =vim . fs . root ( fullname , '.git' ) 340if git_root then 341local root_dir =vim . fs . joinpath ( git_root , 'src' , 'nvim' ) 342local relpath =vim . fs . relpath ( root_dir , fullname ) 343if relpath then 344return relpath 345end 346end 347end 348 349return fullname 350end 351 352-- Error reporting 353local function should_print_error ( category , confidence , linenum ) 354if is_error_suppressed_by_nolint ( category , linenum ) then 355return false 356end 357if is_error_in_suppressed_errors_list ( category , linenum ) then 358return false 359end 360if confidence < cpplint_state . verbose_level then 361return false 362end 363 364local is_filtered =false 365for _ , one_filter in ipairs ( cpplint_state . filters ) do 366if one_filter : sub ( 1 , 1 ) == '-' then 367if category : find ( one_filter : sub ( 2 ), 1 , true ) == 1 then 368is_filtered =true 369end 370elseif one_filter : sub ( 1 , 1 ) == '+' then 371if category : find ( one_filter : sub ( 2 ), 1 , true ) == 1 then 372is_filtered =false 373end 374end 375end 376 377return not is_filtered 378end 379 380local function error_func ( filename , linenum , category , confidence , message ) 381if should_print_error ( category , confidence , linenum ) then 382cpplint_state : increment_error_count ( category ) 383 384if cpplint_state . output_format == 'vs7' then 385io . write ( 386string . format ( '%s(%s): %s [%s] [%d]\n' , filename , linenum , message , category , confidence ) 387) 388elseif cpplint_state . output_format == 'eclipse' then 389io . write ( 390string . format ( 391'%s:%s: warning: %s [%s] [%d]\n' , 392filename , 393linenum , 394message , 395category , 396confidence 397) 398) 399elseif cpplint_state . output_format == 'gh_action' then 400io . write ( 401string . format ( 402'::error file=%s,line=%s::%s [%s] [%d]\n' , 403filename , 404linenum , 405message , 406category , 407confidence 408) 409) 410else 411io . write ( 412string . format ( '%s:%s: %s [%s] [%d]\n' , filename , linenum , message , category , confidence ) 413) 414end 415end 416end 417 418-- String processing functions 419local function is_cpp_string ( line ) 420line =line : gsub ( '\\\\' , 'XX' ) 421local quote_count =select ( 2 , line : gsub ( '"' , '' )) 422local escaped_quote_count =select ( 2 , line : gsub ( '\\"' , '' )) 423local combined_quote_count =select ( 2 , line : gsub ( "'\"'" , '' )) 424return (( quote_count - escaped_quote_count - combined_quote_count ) % 2 ) == 1 425end 426 427local function cleanse_comments ( line ) 428local commentpos =line : find ( '//' ) 429if commentpos and not is_cpp_string ( line : sub ( 1 , commentpos - 1 )) then 430line =line : sub ( 1 , commentpos - 1 ): gsub ( '%s+$' , '' ) 431end 432-- Remove /* */ comments 433line =line : gsub ( '/%*.-%*/' , '' ) 434return line 435end 436 437-- CleansedLines class equivalent 438local CleansedLines ={} 439CleansedLines . __index =CleansedLines 440 441function CleansedLines . new ( lines , init_lines ) 442local self =setmetatable ( {} , CleansedLines ) 443self . elided ={} 444self . lines ={} 445self . raw_lines =lines 446self . _num_lines =# lines 447self . init_lines =init_lines 448self . lines_without_raw_strings =lines 449self . elided_with_space_strings ={} 450 451for linenum =1 , # self . lines_without_raw_strings do 452local line =self . lines_without_raw_strings [ linenum ] 453table . insert ( self . lines , cleanse_comments ( line )) 454 455local elided =self : _collapse_strings ( line ) 456table . insert ( self . elided , cleanse_comments ( elided )) 457 458local elided_spaces =self : _collapse_strings ( line , true ) 459table . insert ( self . elided_with_space_strings , cleanse_comments ( elided_spaces )) 460end 461 462return self 463end 464 465function CleansedLines : num_lines () 466return self . _num_lines 467end 468 469function CleansedLines : _collapse_strings ( elided , keep_spaces ) 470if not RE_PATTERN_INCLUDE : match_str ( elided ) then 471-- Remove escaped characters 472elided =elided : gsub ( '\\[abfnrtv?"\\\'\\]' , keep_spaces and ' ' or '' ) 473elided =elided : gsub ( '\\%d+' , keep_spaces and ' ' or '' ) 474elided =elided : gsub ( '\\x[0-9a-fA-F]+' , keep_spaces and ' ' or '' ) 475 476if keep_spaces then 477elided =elided : gsub ( "'([^'])'" , function ( c ) 478return "'" .. string . rep ( ' ' , # c ) .. "'" 479end ) 480elided =elided : gsub ( '"([^"]*)"' , function ( c ) 481return '"' .. string . rep ( ' ' , # c ) .. '"' 482end ) 483else 484elided =elided : gsub ( "'([^'])'" , "''" ) 485elided =elided : gsub ( '"([^"]*)"' , '""' ) 486end 487end 488return elided 489end 490 491-- Helper functions for argument parsing 492local function print_usage ( message ) 493local usage =[[ 494Syntax: clint.lua [--verbose=#] [--output=vs7] [--filter=-x,+y,...] 495[--counting=total|toplevel|detailed] [--root=subdir] 496[--linelength=digits] [--record-errors=file] 497[--suppress-errors=file] [--stdin-filename=filename] 498<file> [file] ... 499 500The style guidelines this tries to follow are those in 501https://neovim.io/doc/user/dev_style.html#dev-style 502 503Note: This is Google's https://github.com/cpplint/cpplint modified for use 504with the Neovim project. 505 506Every problem is given a confidence score from 1-5, with 5 meaning we are 507certain of the problem, and 1 meaning it could be a legitimate construct. 508This will miss some errors, and is not a substitute for a code review. 509 510To suppress false-positive errors of a certain category, add a 511'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) 512suppresses errors of all categories on that line. 513 514The files passed in will be linted; at least one file must be provided. 515Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the 516extensions with the --extensions flag. 517 518Flags: 519 520output=vs7 521By default, the output is formatted to ease emacs parsing. Visual Studio 522compatible output (vs7) may also be used. Other formats are unsupported. 523 524verbose=# 525Specify a number 0-5 to restrict errors to certain verbosity levels. 526 527filter=-x,+y,... 528Specify a comma-separated list of category-filters to apply: only 529error messages whose category names pass the filters will be printed. 530(Category names are printed with the message and look like 531"[whitespace/indent]".) Filters are evaluated left to right. 532"-FOO" and "FOO" means "do not print categories that start with FOO". 533"+FOO" means "do print categories that start with FOO". 534 535Examples: --filter=-whitespace,+whitespace/braces 536--filter=whitespace,runtime/printf,+runtime/printf_format 537--filter=-,+build/include_what_you_use 538 539To see a list of all the categories used in cpplint, pass no arg: 540--filter= 541 542counting=total|toplevel|detailed 543The total number of errors found is always printed. If 544'toplevel' is provided, then the count of errors in each of 545the top-level categories like 'build' and 'whitespace' will 546also be printed. If 'detailed' is provided, then a count 547is provided for each category. 548 549root=subdir 550The root directory used for deriving header guard CPP variable. 551By default, the header guard CPP variable is calculated as the relative 552path to the directory that contains .git, .hg, or .svn. When this flag 553is specified, the relative path is calculated from the specified 554directory. If the specified directory does not exist, this flag is 555ignored. 556 557Examples: 558Assuing that src/.git exists, the header guard CPP variables for 559src/chrome/browser/ui/browser.h are: 560 561No flag => CHROME_BROWSER_UI_BROWSER_H_ 562--root=chrome => BROWSER_UI_BROWSER_H_ 563--root=chrome/browser => UI_BROWSER_H_ 564 565linelength=digits 566This is the allowed line length for the project. The default value is 56780 characters. 568 569Examples: 570--linelength=120 571 572extensions=extension,extension,... 573The allowed file extensions that cpplint will check 574 575Examples: 576--extensions=hpp,cpp 577 578record-errors=file 579Record errors to the given location. This file may later be used for error 580suppression using suppress-errors flag. 581 582suppress-errors=file 583Errors listed in the given file will not be reported. 584 585stdin-filename=filename 586Use specified filename when reading from stdin (file "-"). 587]] 588 589if message then 590io . stderr : write ( usage .. '\nFATAL ERROR: ' .. message .. '\n' ) 591os . exit ( 1 ) 592else 593io . write ( usage ) 594os . exit ( 0 ) 595end 596end 597 598local function print_categories () 599for _ , cat in ipairs ( ERROR_CATEGORIES ) do 600io . write ( ' ' .. cat .. '\n' ) 601end 602os . exit ( 0 ) 603end 604 605-- Argument parsing 606local function parse_arguments ( args ) 607local filenames ={} 608local opts ={ 609output_format ='emacs' , 610verbose_level =1 , 611filters ='' , 612counting_style ='total' , 613extensions ={ 'c' , 'h' } , 614record_errors_file =nil , 615suppress_errors_file =nil , 616stdin_filename ='' , 617} 618 619local i =1 620while i <= # args do 621local arg =args [ i ] 622 623if arg == '--help' then 624print_usage () 625elseif arg : sub ( 1 , 9 ) == '--output=' then 626local format =arg : sub ( 10 ) 627if 628format ~= 'emacs' 629and format ~= 'vs7' 630and format ~= 'eclipse' 631and format ~= 'gh_action' 632then 633print_usage ( 'The only allowed output formats are emacs, vs7 and eclipse.' ) 634end 635opts . output_format =format 636elseif arg : sub ( 1 , 10 ) == '--verbose=' then 637opts . verbose_level =tonumber ( arg : sub ( 11 )) 638elseif arg : sub ( 1 , 9 ) == '--filter=' then 639opts . filters =arg : sub ( 10 ) 640if opts . filters == '' then 641print_categories () 642end 643elseif arg : sub ( 1 , 12 ) == '--counting=' then 644local style =arg : sub ( 13 ) 645if style ~= 'total' and style ~= 'toplevel' and style ~= 'detailed' then 646print_usage ( 'Valid counting options are total, toplevel, and detailed' ) 647end 648opts . counting_style =style 649elseif arg : sub ( 1 , 13 ) == '--extensions=' then 650local exts =arg : sub ( 14 ) 651opts . extensions ={} 652for ext in vim . gsplit ( exts , ',' , { trimempty =true } ) do 653table . insert ( opts . extensions , vim . trim ( ext )) 654end 655elseif arg : sub ( 1 , 16 ) == '--record-errors=' then 656opts . record_errors_file =arg : sub ( 17 ) 657elseif arg : sub ( 1 , 18 ) == '--suppress-errors=' then 658opts . suppress_errors_file =arg : sub ( 19 ) 659elseif arg : sub ( 1 , 17 ) == '--stdin-filename=' then 660opts . stdin_filename =arg : sub ( 18 ) 661elseif arg : sub ( 1 , 2 ) == '--' then 662print_usage ( 'Unknown option: ' .. arg ) 663else 664table . insert ( filenames , arg ) 665end 666 667i =i + 1 668end 669 670if # filenames == 0 then 671print_usage ( 'No files were specified.' ) 672end 673 674return filenames , opts 675end 676 677-- Lint checking functions 678 679local function find_next_multiline_comment_start ( lines , lineix ) 680while lineix <= # lines do 681if lines [ lineix ]: find ( '^%s*/%*' ) then 682if not lines [ lineix ]: find ( '%*/' , 1 , true ) then 683-- Check if this line ends with backslash (line continuation) 684-- If so, don't treat it as a multiline comment start 685local line =lines [ lineix ] 686if not line : find ( '\\%s*$' ) then 687return lineix 688end 689end 690end 691lineix =lineix + 1 692end 693return # lines + 1 694end 695 696local function find_next_multiline_comment_end ( lines , lineix ) 697while lineix <= # lines do 698if lines [ lineix ]: find ( '%*/%s*$' ) then 699return lineix 700end 701lineix =lineix + 1 702end 703return # lines + 1 704end 705 706local function remove_multiline_comments_from_range ( lines , begin , finish ) 707for i =begin , finish do 708lines [ i ] ='// dummy' 709end 710end 711 712local function remove_multiline_comments ( filename , lines , error ) 713local lineix =1 714while lineix <= # lines do 715local lineix_begin =find_next_multiline_comment_start ( lines , lineix ) 716if lineix_begin > # lines then 717return 718end 719local lineix_end =find_next_multiline_comment_end ( lines , lineix_begin ) 720if lineix_end > # lines then 721error ( 722filename , 723lineix_begin , 724'readability/multiline_comment' , 7255 , 726'Could not find end of multi-line comment' 727) 728return 729end 730remove_multiline_comments_from_range ( lines , lineix_begin , lineix_end ) 731lineix =lineix_end + 1 732end 733end 734 735local function check_for_header_guard ( filename , lines , error ) 736if filename : match ( '%.c%.h$' ) or FileInfo . new ( filename ): relative_path () == 'func_attr.h' then 737return 738end 739 740local found_pragma =false 741for _ , line in ipairs ( lines ) do 742if line : find ( '#pragma%s+once' ) then 743found_pragma =true 744break 745end 746end 747 748if not found_pragma then 749error ( filename , 1 , 'build/header_guard' , 5 , 'No "#pragma once" found in header' ) 750end 751end 752 753local function check_includes ( filename , lines , error ) 754if 755filename : match ( '%.c%.h$' ) 756or filename : match ( '%.in%.h$' ) 757or FileInfo . new ( filename ): relative_path () == 'func_attr.h' 758or FileInfo . new ( filename ): relative_path () == 'os/pty_proc.h' 759then 760return 761end 762 763local check_includes_ignore ={ 764'src/nvim/api/private/validate.h' , 765'src/nvim/assert_defs.h' , 766'src/nvim/channel.h' , 767'src/nvim/charset.h' , 768'src/nvim/eval/typval.h' , 769'src/nvim/event/multiqueue.h' , 770'src/nvim/garray.h' , 771'src/nvim/globals.h' , 772'src/nvim/highlight.h' , 773'src/nvim/lua/executor.h' , 774'src/nvim/main.h' , 775'src/nvim/mark.h' , 776'src/nvim/msgpack_rpc/channel_defs.h' , 777'src/nvim/msgpack_rpc/unpacker.h' , 778'src/nvim/option.h' , 779'src/nvim/os/pty_conpty_win.h' , 780'src/nvim/os/pty_proc_win.h' , 781} 782 783local skip_headers ={ 784'auto/config.h' , 785'klib/klist.h' , 786'klib/kvec.h' , 787'mpack/mpack_core.h' , 788'mpack/object.h' , 789'nvim/func_attr.h' , 790'termkey/termkey.h' , 791'vterm/vterm.h' , 792'xdiff/xdiff.h' , 793} 794 795for _ , ignore in ipairs ( check_includes_ignore ) do 796if filename : match ( ignore .. '$' ) then 797return 798end 799end 800 801for i , line in ipairs ( lines ) do 802local matched =match ( '#\\s*include\\s*"([^"]*)"' , line ) 803if matched then 804local name =line : match ( '#\\s*include\\s*"([^"]*)"' ) 805local should_skip =false 806for _ , skip in ipairs ( skip_headers ) do 807if name == skip then 808should_skip =true 809break 810end 811end 812 813if 814not should_skip 815and not name : match ( '%.h%.generated%.h$' ) 816and not name : match ( '/defs%.h$' ) 817and not name : match ( '_defs%.h$' ) 818and not name : match ( '%.h%.inline%.generated%.h$' ) 819and not name : match ( '_defs%.generated%.h$' ) 820and not name : match ( '_enum%.generated%.h$' ) 821then 822error ( 823filename , 824i - 1 , 825'build/include_defs' , 8265 , 827'Headers should not include non-"_defs" headers' 828) 829end 830end 831end 832end 833 834local function check_non_symbols ( filename , lines , error ) 835for i , line in ipairs ( lines ) do 836if line : match ( '^EXTERN ' ) or line : match ( '^extern ' ) then 837error ( 838filename , 839i - 1 , 840'build/defs_header' , 8415 , 842'"_defs" headers should not contain extern variables' 843) 844end 845end 846end 847 848local function check_for_bad_characters ( filename , lines , error ) 849for linenum , line in ipairs ( lines ) do 850if line : find ( '\239\187\191' ) then -- UTF-8 BOM 851error ( 852filename , 853linenum - 1 , 854'readability/utf8' , 8555 , 856'Line contains invalid UTF-8 (or Unicode replacement character).' 857) 858end 859if line : find ( '\0' ) then 860error ( filename , linenum - 1 , 'readability/nul' , 5 , 'Line contains NUL byte.' ) 861end 862end 863end 864 865local function check_for_multiline_comments_and_strings ( filename , clean_lines , linenum , error ) 866-- Use elided line (with strings collapsed) to avoid false positives from /* */ in strings 867local line =clean_lines . elided [ linenum + 1 ] 868if not line then 869return 870end 871 872-- Remove all \\ (escaped backslashes) from the line. They are OK, and the 873-- second (escaped) slash may trigger later \" detection erroneously. 874line =line : gsub ( '\\\\' , '' ) 875 876local comment_count =select ( 2 , line : gsub ( '/%*' , '' )) 877local comment_end_count =select ( 2 , line : gsub ( '%*/' , '' )) 878-- Only warn if there are actually more opening than closing comments 879-- (accounting for the possibility that this is a multi-line comment that continues) 880if comment_count > comment_end_count and comment_count > 0 then 881error ( 882filename , 883linenum , 884'readability/multiline_comment' , 8855 , 886'Complex multi-line /*...*/-style comment found. ' 887.. 'Lint may give bogus warnings. ' 888.. 'Consider replacing these with //-style comments, ' 889.. 'with #if 0...#endif, ' 890.. 'or with more clearly structured multi-line comments.' 891) 892end 893 894-- Dropped 'readability/multiline_string' detection because it produces too many false positives 895-- with escaped quotes in C strings and character literals. 896end 897 898local function check_for_old_style_comments ( filename , line , linenum , error ) 899if line : find ( '/%*' ) and line : sub ( - 1 ) ~= '\\' and not RE_COMMENTLINE : match_str ( line ) then 900error ( 901filename , 902linenum , 903'readability/old_style_comment' , 9045 , 905'/*-style comment found, it should be replaced with //-style. ' 906.. '/*-style comments are only allowed inside macros. ' 907.. 'Note that you should not use /*-style comments to document ' 908.. 'macros itself, use doxygen-style comments for this.' 909) 910end 911end 912 913local function check_posix_threading ( filename , clean_lines , linenum , error ) 914local line =clean_lines . elided [ linenum + 1 ] 915 916for _ , pair in ipairs ( threading_list ) do 917local single_thread_function , multithread_safe_function =pair [ 1 ], pair [ 2 ] 918local start_pos =line : find ( single_thread_function , 1 , true ) 919 920if start_pos then 921local prev_char =start_pos > 1 and line : sub ( start_pos - 1 , start_pos - 1 ) or '' 922if 923start_pos == 1 924or ( 925not prev_char : match ( '%w' ) 926and prev_char ~= '_' 927and prev_char ~= '.' 928and prev_char ~= '>' 929) 930then 931error ( 932filename , 933linenum , 934'runtime/threadsafe_fn' , 9352 , 936'Use ' 937.. multithread_safe_function 938.. '...) instead of ' 939.. single_thread_function 940.. '...). If it is missing, consider implementing it;' 941.. ' see os_localtime_r for an example.' 942) 943end 944end 945end 946end 947 948local function check_memory_functions ( filename , clean_lines , linenum , error ) 949if memory_ignore_pattern : match_str ( filename ) then 950return 951end 952 953local line =clean_lines . elided [ linenum + 1 ] 954 955for _ , pair in ipairs ( memory_functions ) do 956local func , suggested_func =pair [ 1 ], pair [ 2 ] 957local start_pos =line : find ( func , 1 , true ) 958 959if start_pos then 960local prev_char =start_pos > 1 and line : sub ( start_pos - 1 , start_pos - 1 ) or '' 961if 962start_pos == 1 963or ( 964not prev_char : match ( '%w' ) 965and prev_char ~= '_' 966and prev_char ~= '.' 967and prev_char ~= '>' 968) 969then 970error ( 971filename , 972linenum , 973'runtime/memory_fn' , 9742 , 975'Use ' .. suggested_func .. '...) instead of ' .. func .. '...).' 976) 977end 978end 979end 980end 981 982local function check_os_functions ( filename , clean_lines , linenum , error ) 983local line =clean_lines . elided [ linenum + 1 ] 984 985for _ , pair in ipairs ( os_functions ) do 986local func , suggested_func =pair [ 1 ], pair [ 2 ] 987local start_pos =line : find ( func , 1 , true ) 988 989if start_pos then 990local prev_char =start_pos > 1 and line : sub ( start_pos - 1 , start_pos - 1 ) or '' 991if 992start_pos == 1 993or ( 994not prev_char : match ( '%w' ) 995and prev_char ~= '_' 996and prev_char ~= '.' 997and prev_char ~= '>' 998) 999then 1000error ( 1001filename , 1002linenum , 1003'runtime/os_fn' , 10042 , 1005'Use ' .. suggested_func .. '...) instead of ' .. func .. '...).' 1006) 1007end 1008end 1009end 1010end 1011 1012local function check_language ( filename , clean_lines , linenum , error ) 1013local line =clean_lines . elided [ linenum + 1 ] 1014if not line or line == '' then 1015return 1016end 1017 1018-- Check for verboten C basic types 1019local short_regex =vim . regex ( [[\<short\>]] ) 1020local long_long_regex =vim . regex ( [[\<long\> \+\<long\>]] ) 1021 1022if short_regex : match_str ( line ) then 1023error ( 1024filename , 1025linenum , 1026'runtime/int' , 10274 , 1028'Use int16_t/int64_t/etc, rather than the C type short' 1029) 1030elseif long_long_regex : match_str ( line ) then 1031error ( 1032filename , 1033linenum , 1034'runtime/int' , 10354 , 1036'Use int16_t/int64_t/etc, rather than the C type long long' 1037) 1038end 1039 1040-- Check for snprintf with non-zero literal size 1041local snprintf_match =line : match ( 'snprintf%s*%([^,]*,%s*([0-9]+)%s*,' ) 1042if snprintf_match and snprintf_match ~= '0' then 1043error ( 1044filename , 1045linenum , 1046'runtime/printf' , 10473 , 1048'If you can, use sizeof(...) instead of ' .. snprintf_match .. ' as the 2nd arg to snprintf.' 1049) 1050end 1051 1052-- Check for sprintf (use vim.regex for proper word boundaries) 1053local sprintf_regex =vim . regex ( [[\<sprintf\>]] ) 1054if sprintf_regex : match_str ( line ) then 1055error ( filename , linenum , 'runtime/printf' , 5 , 'Use snprintf instead of sprintf.' ) 1056end 1057 1058-- Check for strncpy (use vim.regex for proper word boundaries) 1059local strncpy_regex =vim . regex ( [[\<strncpy\>]] ) 1060local strncpy_upper_regex =vim . regex ( [[\<STRNCPY\>]] ) 1061if strncpy_regex : match_str ( line ) then 1062error ( 1063filename , 1064linenum , 1065'runtime/printf' , 10664 , 1067'Use xstrlcpy, xmemcpyz or snprintf instead of strncpy (unless this is from Vim)' 1068) 1069elseif strncpy_upper_regex : match_str ( line ) then 1070error ( 1071filename , 1072linenum , 1073'runtime/printf' , 10744 , 1075'Use xstrlcpy, xmemcpyz or snprintf instead of STRNCPY (unless this is from Vim)' 1076) 1077end 1078 1079-- Check for strcpy (use vim.regex for proper word boundaries) 1080local strcpy_regex =vim . regex ( [[\<strcpy\>]] ) 1081if strcpy_regex : match_str ( line ) then 1082error ( 1083filename , 1084linenum , 1085'runtime/printf' , 10864 , 1087'Use xstrlcpy, xmemcpyz or snprintf instead of strcpy' 1088) 1089end 1090 1091-- Check for strtol: it silently overflows/truncates and needs error-prone boilerplate. 1092-- TODO: also flag atoi, atol, atoll, strtoul, strtoll, strtoull. 1093local strtol_regex =vim . regex ( [[\<strtol\>]] ) 1094if strtol_regex : match_str ( line ) then 1095error ( 1096filename , 1097linenum , 1098'runtime/deprecated' , 10994 , 1100'Use getdigits()/getdigits_int() (or vim_str2nr() for non-decimal bases) instead of strtol, ' 1101.. 'which overflows silently. See src/nvim/charset.c.' 1102) 1103end 1104 1105-- Check for memset with wrong argument order: memset(buf, sizeof(buf), 0) 1106-- Pattern: memset(arg1, arg2, 0) where arg2 is NOT a valid fill value 1107local memset_start =line : find ( 'memset%s*%([^)]*,%s*[^,]*,%s*0%s*%)' ) 1108if memset_start then 1109-- Extract the full memset call 1110local memset_part =line : sub ( memset_start ) 1111local first_comma =memset_part : find ( ',' ) 1112if first_comma then 1113local after_first =memset_part : sub ( first_comma + 1 ) 1114local second_comma =after_first : find ( ',' ) 1115if second_comma then 1116local second_arg =vim . trim ( after_first : sub ( 1 , second_comma - 1 )) 1117local first_arg =vim . trim ( memset_part : match ( 'memset%s*%(%s*([^,]*)%s*,' )) 1118 1119-- Check if second_arg is NOT a simple literal value 1120if 1121second_arg ~= '' 1122and second_arg ~= "''" 1123and not second_arg : match ( '^%-?%d+$' ) 1124and not second_arg : match ( '^0x[0-9a-fA-F]+$' ) 1125then 1126error ( 1127filename , 1128linenum , 1129'runtime/memset' , 11304 , 1131'Did you mean "memset(' .. first_arg .. ', 0, ' .. second_arg .. ')"?' 1132) 1133end 1134end 1135end 1136end 1137 1138-- Detect variable-length arrays 1139-- Pattern: type varname[size]; where type is an identifier and varname starts with lowercase 1140local var_type =line : match ( '%s*(%w+)%s+' ) 1141if var_type and var_type ~= 'return' and var_type ~= 'delete' then 1142-- Look for array declaration pattern 1143local array_size =line : match ( '%w+%s+[a-z]%w*%s*%[([^%]]+)%]' ) 1144if array_size and not array_size : find ( '%]' ) then -- Ensure no nested brackets (multidimensional arrays) 1145-- Check if size is a compile-time constant 1146local is_const =true 1147 1148-- Split on common operators (space, +, -, *, /, <<, >>) 1149local tokens =vim . split ( array_size , '[%s%+%-%*%/%>%<]+' ) 1150 1151for _ , tok in ipairs ( tokens ) do 1152tok =vim . trim ( tok ) 1153if tok ~= '' then 1154-- Check for sizeof(...) and arraysize(...) or ARRAY_SIZE(...) patterns (before stripping parens) 1155local is_valid =tok : find ( 'sizeof%(.+%)' ) 1156or tok : find ( 'arraysize%(%w+%)' ) 1157or tok : find ( 'ARRAY_SIZE%(.+%)' ) 1158 1159if not is_valid then 1160-- Strip leading and trailing parentheses for other checks 1161tok =tok : gsub ( '^%(*' , '' ): gsub ( '%)*$' , '' ) 1162tok =vim . trim ( tok ) 1163 1164if tok ~= '' then 1165-- Allow: numeric literals, hex, k-prefixed constants, SCREAMING_CASE, sizeof, arraysize 1166is_valid =( 1167tok : match ( '^%d+$' ) -- decimal number 1168or tok : match ( '^0x[0-9a-fA-F]+$' ) -- hex number 1169or tok : match ( '^k[A-Z0-9]' ) -- k-prefixed constant 1170or tok : match ( '^[A-Z][A-Z0-9_]*$' ) -- SCREAMING_CASE 1171or tok : match ( '^sizeof' ) -- sizeof(...) 1172or tok : match ( '^arraysize' ) 1173) -- arraysize(...) 1174end 1175end 1176 1177if not is_valid then 1178is_const =false 1179break 1180end 1181end 1182end 1183 1184if not is_const then 1185error ( 1186filename , 1187linenum , 1188'runtime/arrays' , 11891 , 1190"Do not use variable-length arrays. Use an appropriately named ('k' followed by CamelCase) compile-time constant for the size." 1191) 1192end 1193end 1194end 1195 1196-- Check for TRUE/FALSE (use vim.regex for proper word boundaries) 1197local true_regex =vim . regex ( [[\<TRUE\>]] ) 1198local false_regex =vim . regex ( [[\<FALSE\>]] ) 1199local maybe_regex =vim . regex ( [[\<MAYBE\>]] ) 1200 1201if true_regex : match_str ( line ) then 1202error ( filename , linenum , 'readability/bool' , 4 , 'Use true instead of TRUE.' ) 1203end 1204 1205if false_regex : match_str ( line ) then 1206error ( filename , linenum , 'readability/bool' , 4 , 'Use false instead of FALSE.' ) 1207end 1208 1209-- Check for MAYBE 1210if maybe_regex : match_str ( line ) then 1211error ( filename , linenum , 'readability/bool' , 4 , 'Use kNone from TriState instead of MAYBE.' ) 1212end 1213 1214-- Detect preincrement/predecrement at start of line 1215if line : match ( '^%s*%+%+' ) or line : match ( '^%s*%-%-' ) then 1216error ( 1217filename , 1218linenum , 1219'readability/increment' , 12205 , 1221'Do not use preincrement in statements, use postincrement instead' 1222) 1223end 1224 1225-- Detect preincrement/predecrement in for(;; preincrement) 1226-- Look for pattern like "; ++var" or "; --var" 1227local last_semi_pos =0 1228for i =1 , # line do 1229if line : sub ( i , i ) == ';' then 1230last_semi_pos =i 1231end 1232end 1233 1234if last_semi_pos > 0 then 1235-- Check if there's a preincrement/predecrement after the last semicolon 1236local after_semi =line : sub ( last_semi_pos + 1 ) 1237local op_pos =after_semi : find ( '%+%+' ) 1238if not op_pos then 1239op_pos =after_semi : find ( '%-%-' ) 1240end 1241if op_pos then 1242-- Found preincrement/predecrement after last semicolon 1243local expr_start =after_semi : sub ( 1 , op_pos - 1 ): match ( '^%s*(.*)' ) 1244if not expr_start or expr_start == '' then 1245-- Nothing but whitespace before operator, check the expression 1246local expr_text =after_semi : sub ( op_pos ) 1247if not expr_text : find ( ';' ) and not expr_text : find ( ' = ' ) then 1248error ( 1249filename , 1250linenum , 1251'readability/increment' , 12524 , 1253'Do not use preincrement in statements, including for(;; action)' 1254) 1255end 1256end 1257end 1258end 1259end 1260 1261local function check_for_non_standard_constructs ( filename , clean_lines , linenum , error ) 1262local line =clean_lines . lines [ linenum + 1 ] 1263 1264-- Check for printf format issues with %q and %N$ in quoted strings 1265-- Extract all quoted strings and check their format specifiers 1266for str in line : gmatch ( '"([^"]*)"' ) do 1267-- Check for %q format (deprecated) 1268if str : find ( '%%%-?%+?%s?%d*q' ) then 1269error ( 1270filename , 1271linenum , 1272'runtime/printf_format' , 12733 , 1274'"%q" in format strings is deprecated. Use "%" PRId64 instead.' 1275) 1276end 1277 1278-- Check for %N$ format (unconventional positional specifier) 1279if str : find ( '%%%d+%$' ) then 1280error ( 1281filename , 1282linenum , 1283'runtime/printf_format' , 12842 , 1285'%N$ formats are unconventional. Try rewriting to avoid them.' 1286) 1287end 1288end 1289 1290-- Check for storage class order (type before storage class modifier) 1291-- Match type keywords followed by storage class keywords 1292local type_keywords ={ 1293'const' , 1294'volatile' , 1295'void' , 1296'char' , 1297'short' , 1298'int' , 1299'long' , 1300'float' , 1301'double' , 1302'signed' , 1303'unsigned' , 1304} 1305local storage_keywords ={ 'register' , 'static' , 'extern' , 'typedef' } 1306 1307for _ , type_kw in ipairs ( type_keywords ) do 1308for _ , storage_kw in ipairs ( storage_keywords ) do 1309local pattern ='\\<' .. type_kw .. '\\>\\s\\+\\<' .. storage_kw .. '\\>' 1310if vim . regex ( pattern ): match_str ( line ) then 1311error ( 1312filename , 1313linenum , 1314'build/storage_class' , 13155 , 1316'Storage class (static, extern, typedef, etc) should be first.' 1317) 1318return 1319end 1320end 1321end 1322 1323-- Check for endif comments 1324if line : match ( '^%s*#%s*endif%s*[^/\\s]+' ) then 1325error ( 1326filename , 1327linenum , 1328'build/endif_comment' , 13295 , 1330'Uncommented text after #endif is non-standard. Use a comment.' 1331) 1332end 1333end 1334 1335-- Nesting state classes 1336local BlockInfo ={} 1337BlockInfo . __index =BlockInfo 1338 1339function BlockInfo . new ( seen_open_brace ) 1340local self =setmetatable ( {} , BlockInfo ) 1341self . seen_open_brace =seen_open_brace 1342self . open_parentheses =0 1343self . inline_asm =NO_ASM 1344return self 1345end 1346 1347local PreprocessorInfo ={} 1348PreprocessorInfo . __index =PreprocessorInfo 1349 1350function PreprocessorInfo . new ( stack_before_if ) 1351local self =setmetatable ( {} , PreprocessorInfo ) 1352self . stack_before_if =stack_before_if 1353self . stack_before_else ={} 1354self . seen_else =false 1355return self 1356end 1357 1358local NestingState ={} 1359NestingState . __index =NestingState 1360 1361function NestingState . new () 1362local self =setmetatable ( {} , NestingState ) 1363self . stack ={} 1364self . pp_stack ={} 1365return self 1366end 1367 1368function NestingState : seen_open_brace () 1369return # self . stack == 0 or self . stack [ # self . stack ]. seen_open_brace 1370end 1371 1372function NestingState : update_preprocessor ( line ) 1373if line : match ( '^%s*#%s*(if|ifdef|ifndef)' ) then 1374table . insert ( self . pp_stack , PreprocessorInfo . new ( vim . deepcopy ( self . stack ))) 1375elseif line : match ( '^%s*#%s*(else|elif)' ) then 1376if # self . pp_stack > 0 then 1377if not self . pp_stack [ # self . pp_stack ]. seen_else then 1378self . pp_stack [ # self . pp_stack ]. seen_else =true 1379self . pp_stack [ # self . pp_stack ]. stack_before_else =vim . deepcopy ( self . stack ) 1380end 1381self . stack =vim . deepcopy ( self . pp_stack [ # self . pp_stack ]. stack_before_if ) 1382end 1383elseif line : match ( '^%s*#%s*endif' ) then 1384if # self . pp_stack > 0 then 1385if self . pp_stack [ # self . pp_stack ]. seen_else then 1386self . stack =self . pp_stack [ # self . pp_stack ]. stack_before_else 1387end 1388table . remove ( self . pp_stack ) 1389end 1390end 1391end 1392 1393function NestingState : update ( clean_lines , linenum ) 1394local line =clean_lines . elided [ linenum + 1 ] 1395 1396self : update_preprocessor ( line ) 1397 1398if # self . stack > 0 then 1399local inner_block =self . stack [ # self . stack ] 1400local depth_change =select ( 2 , line : gsub ( '%(' , '' )) - select ( 2 , line : gsub ( '%)' , '' )) 1401inner_block . open_parentheses =inner_block . open_parentheses + depth_change 1402 1403if inner_block . inline_asm == NO_ASM or inner_block . inline_asm == END_ASM then 1404if depth_change ~= 0 and inner_block . open_parentheses == 1 and match_asm ( line ) then 1405inner_block . inline_asm =INSIDE_ASM 1406else 1407inner_block . inline_asm =NO_ASM 1408end 1409elseif inner_block . inline_asm == INSIDE_ASM and inner_block . open_parentheses == 0 then 1410inner_block . inline_asm =END_ASM 1411end 1412end 1413 1414while true do 1415local matched =line : match ( '^[^{;)}]*([{;)}])(.*)$' ) 1416if not matched then 1417break 1418end 1419 1420local token =matched : sub ( 1 , 1 ) 1421if token == '{' then 1422if not self : seen_open_brace () then 1423self . stack [ # self . stack ]. seen_open_brace =true 1424else 1425table . insert ( self . stack , BlockInfo . new ( true )) 1426if match_asm ( line ) then 1427self . stack [ # self . stack ]. inline_asm =BLOCK_ASM 1428end 1429end 1430elseif token == ';' or token == ')' then 1431if not self : seen_open_brace () then 1432table . remove ( self . stack ) 1433end 1434else -- token == '}' 1435if # self . stack > 0 then 1436table . remove ( self . stack ) 1437end 1438end 1439line =matched : sub ( 2 ) 1440end 1441end 1442 1443-- Main processing functions 1444local function process_line ( 1445filename , 1446clean_lines , 1447line , 1448nesting_state , 1449error , 1450extra_check_functions 1451) 1452local raw_lines =clean_lines . raw_lines 1453local init_lines =clean_lines . init_lines 1454 1455parse_nolint_suppressions ( raw_lines [ line + 1 ], line ) 1456nesting_state : update ( clean_lines , line ) 1457 1458if 1459# nesting_state . stack > 0 and nesting_state . stack [ # nesting_state . stack ]. inline_asm ~= NO_ASM 1460then 1461return 1462end 1463 1464check_for_multiline_comments_and_strings ( filename , clean_lines , line , error ) 1465check_for_old_style_comments ( filename , init_lines [ line + 1 ], line , error ) 1466check_language ( filename , clean_lines , line , error ) 1467check_for_non_standard_constructs ( filename , clean_lines , line , error ) 1468check_posix_threading ( filename , clean_lines , line , error ) 1469check_memory_functions ( filename , clean_lines , line , error ) 1470check_os_functions ( filename , clean_lines , line , error ) 1471 1472for _ , check_fn in ipairs ( extra_check_functions or {} ) do 1473check_fn ( filename , clean_lines , line , error ) 1474end 1475end 1476 1477local function process_file_data ( filename , file_extension , lines , error , extra_check_functions ) 1478-- Add marker lines 1479table . insert ( lines , 1 , '// marker so line numbers and indices both start at 1' ) 1480table . insert ( lines , '// marker so line numbers end in a known way' ) 1481 1482local nesting_state =NestingState . new () 1483 1484reset_nolint_suppressions () 1485reset_known_error_suppressions () 1486 1487local init_lines =vim . deepcopy ( lines ) 1488 1489if cpplint_state . record_errors_file then 1490local function recorded_error ( filename_ , linenum , category , confidence , message ) 1491if not is_error_suppressed_by_nolint ( category , linenum ) then 1492local key_start =math . max ( 1 , linenum ) 1493local key_end =math . min ( # lines , linenum + 2 ) 1494local key_lines ={} 1495for i =key_start , key_end do 1496table . insert ( key_lines , lines [ i ]) 1497end 1498local err ={ filename_ , key_lines , category } 1499cpplint_state . record_errors_file : write ( vim . json . encode ( err ) .. '\n' ) 1500end 1501error ( filename_ , linenum , category , confidence , message ) 1502end 1503error =recorded_error 1504end 1505 1506remove_multiline_comments ( filename , lines , error ) 1507local clean_lines =CleansedLines . new ( lines , init_lines ) 1508 1509for line =0 , clean_lines : num_lines () - 1 do 1510process_line ( filename , clean_lines , line , nesting_state , error , extra_check_functions ) 1511end 1512 1513if file_extension == 'h' then 1514check_for_header_guard ( filename , lines , error ) 1515check_includes ( filename , lines , error ) 1516if filename : match ( '/defs%.h$' ) or filename : match ( '_defs%.h$' ) then 1517check_non_symbols ( filename , lines , error ) 1518end 1519end 1520 1521check_for_bad_characters ( filename , lines , error ) 1522end 1523 1524local function process_file ( filename , vlevel , extra_check_functions ) 1525cpplint_state : set_verbose_level ( vlevel ) 1526 1527local lines 1528 1529if filename == '-' then 1530local stdin =io . read ( '*all' ) 1531lines =vim . split ( stdin , '\n' ) 1532if cpplint_state . stdin_filename ~= '' then 1533filename =cpplint_state . stdin_filename 1534end 1535else 1536local ok , content =pcall ( vim . fn . readfile , filename ) 1537if not ok then 1538io . stderr : write ( "Skipping input '" .. filename .. "': Can't open for reading\n" ) 1539return 1540end 1541lines =content 1542end 1543 1544-- Remove trailing '\r' 1545for i , line in ipairs ( lines ) do 1546if line : sub ( - 1 ) == '\r' then 1547lines [ i ] =line : sub ( 1 , - 2 ) 1548end 1549end 1550 1551local file_extension =filename : match ( '^.+%.(.+)$' ) or '' 1552 1553if filename ~= '-' and not valid_extensions [ file_extension ] then 1554local ext_list ={} 1555for ext , _ in pairs ( valid_extensions ) do 1556table . insert ( ext_list , '.' .. ext ) 1557end 1558io . stderr : write ( 1559'Ignoring ' .. filename .. '; only linting ' .. table . concat ( ext_list , ', ' ) .. ' files\n' 1560) 1561else 1562process_file_data ( filename , file_extension , lines , error_func , extra_check_functions ) 1563end 1564end 1565 1566-- Main function 1567local function main ( args ) 1568local filenames , opts =parse_arguments ( args ) 1569 1570cpplint_state : set_output_format ( opts . output_format ) 1571cpplint_state : set_verbose_level ( opts . verbose_level ) 1572cpplint_state : set_filters ( opts . filters ) 1573cpplint_state : set_counting_style ( opts . counting_style ) 1574valid_extensions ={} 1575for _ , ext in ipairs ( opts . extensions ) do 1576valid_extensions [ ext ] =true 1577end 1578 1579cpplint_state : suppress_errors_from ( opts . suppress_errors_file ) 1580cpplint_state : record_errors_to ( opts . record_errors_file ) 1581cpplint_state . stdin_filename =opts . stdin_filename 1582 1583cpplint_state : reset_error_counts () 1584 1585for _ , filename in ipairs ( filenames ) do 1586process_file ( filename , cpplint_state . verbose_level ) 1587end 1588 1589cpplint_state : print_error_counts () 1590 1591if cpplint_state . record_errors_file then 1592cpplint_state . record_errors_file : close () 1593end 1594 1595vim . cmd . cquit ( cpplint_state . error_count > 0 and 1 or 0 ) 1596end 1597 1598-- Export main function 1599main ( _G . arg )