robin/laufey

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

Justin M. Keyesbuild: lint "strtol" #4044287b42e1209

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