Skip to content

Commit fd21729

Browse files
committed
addons/namingng.py: Add checks for include guards.
Include guard naming can be validated against various patterns: - prefixes/suffixes (_FILE_H, PROJECT_FILE_H, FILE_H_) - basename/full path (FILE_H, SUB_DIR_INC_FILE_H) - upper- or lowercase (FILE_H, file_h) or case kept as-is (File_h) - any combination of the above (project_sub_dir_inc_file_h_) A regexp can be specified to match header filenames. The default matches any filename not starting with / and ending with .h, intended to match C header files while exluding system files. The check is not limited to naming only; validity and presence of include guards can also be tested by setting "required":true in the config file. Enabling this feature requires adding the key "include_guard" to the namingng config file. The namingng unit test is extended to test various features of the include guard check.
1 parent 0c8ee78 commit fd21729

3 files changed

Lines changed: 161 additions & 1 deletion

File tree

‎addons/namingng.config.json‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@
22
"RE_VARNAME": ["[a-z]*[a-zA-Z0-9_]*\\Z"],
33
"RE_PRIVATE_MEMBER_VARIABLE": null,
44
"RE_FUNCTIONNAME": ["[a-z0-9A-Z]*\\Z"],
5+
"include_guard": {
6+
"input": "path",
7+
"prefix": "",
8+
"suffix": "",
9+
"case": "upper",
10+
"max_linenr": 5,
11+
"RE_HEADERFILE": "[^/].*\\.h\\Z",
12+
"required": true
13+
},
514
"var_prefixes": {"uint32_t": "ui32",
615
"int*": "intp"},
716
"function_prefixes": {"uint16_t": "ui16",

‎addons/namingng.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# cppcheck addon for naming conventions
44
# An enhanced version. Configuration is taken from a json file
55
# It supports to check for type-based prefixes in function or variable names.
6+
# Aside from include guard naming, include guard presence can also be tested.
67
#
78
# Example usage (variable name must start with lowercase, function name must start with uppercase):
89
# $ cppcheck --dump path-to-src/
@@ -14,6 +15,14 @@
1415
# "RE_VARNAME": "[a-z]*[a-zA-Z0-9_]*\\Z",
1516
# "RE_PRIVATE_MEMBER_VARIABLE": null,
1617
# "RE_FUNCTIONNAME": "[a-z0-9A-Z]*\\Z",
18+
# "include_guard": {
19+
# "input": "path",
20+
# "prefix": "GUARD_",
21+
# "case": "upper",
22+
# "max_linenr": 5,
23+
# "RE_HEADERFILE": "[^/].*\\.h\\Z",
24+
# "required": true
25+
# },
1726
# "var_prefixes": {"uint32_t": "ui32"},
1827
# "function_prefixes": {"uint16_t": "ui16",
1928
# "uint32_t": "ui32"}
@@ -73,10 +82,115 @@ def evalExpr(conf, exp, mockToken, msgType):
7382
msg = msgType + ' ' + mockToken.str + ' violates naming convention'
7483
checkFalseRegex(mockToken, exp, msg)
7584

85+
def check_include_guard_name(conf_ig,cfg,directive):
86+
parts = directive.str.split()
87+
if len(parts) != 2:
88+
msg = 'syntax error'
89+
reportNamingError(directive,msg,'syntax')
90+
return None
91+
guard_name = parts[1]
92+
93+
filename = directive.file
94+
if conf_ig.get('input','path') == 'basename':
95+
filename = os.path.basename(filename)
96+
use_case = conf_ig.get('case','upper')
97+
if use_case == 'upper':
98+
filename = filename.upper()
99+
elif use_case == 'lower':
100+
filename = filename.lower()
101+
elif use_case == 'keep':
102+
pass # keep filename case as-is
103+
else:
104+
print("invalid config value for 'case': '%s'"%use_case,file=sys.stderr)
105+
sys.exit(1)
106+
107+
barename = re.sub('[^A-Za-z0-9]','_',filename).strip('_')
108+
expect_guard_name = conf_ig.get('prefix','') + barename + conf_ig.get('suffix','')
109+
if expect_guard_name != guard_name:
110+
msg = 'include guard naming violation; %s != %s'%(guard_name,expect_guard_name)
111+
reportNamingError(directive,msg,'includeGuardName')
112+
113+
return guard_name
114+
115+
def check_include_guard(conf_ig,cfg,unguarded_include_files):
116+
# Scan for '#ifndef FILE_H' as the first directive, in the first N lines.
117+
# Then test whether the next directive #defines the found name.
118+
# Various tests are done:
119+
# - check include guards for their naming and consistency
120+
# - test whether include guards are in place
121+
max_linenr = conf_ig.get('max_linenr', 5)
122+
123+
def report(directive,msg,errorId):
124+
reportNamingError(directive,msg,errorId)
125+
126+
def report_pending_ifndef(directive):
127+
report(directive,'include guard #ifndef is not followed by #define','includeGuardIncomplete')
128+
129+
last_fn = None
130+
pending_ifndef = None
131+
phase = 0
132+
for directive in cfg.directives:
133+
if last_fn != directive.file:
134+
if pending_ifndef:
135+
report_pending_ifndef(pending_ifndef)
136+
pending_ifndef = None
137+
last_fn = directive.file
138+
phase = 0
139+
if phase == -1:
140+
# ignore (the remainder of) this file
141+
continue
142+
if not re.match(include_guard_header_re,directive.file):
143+
phase = -1
144+
continue
145+
146+
if directive.linenr > max_linenr:
147+
if phase == 0 and conf_ig.get('required',1):
148+
report(directive,'include guard not found before line %d'%max_linenr,'includeGuardMissing')
149+
pass
150+
phase = -1
151+
continue
152+
153+
if phase == 0:
154+
# looking for '#ifndef FILE_H'
155+
if not directive.str.startswith('#ifndef'):
156+
if conf_ig.get('required',1):
157+
report(directive,'first preprocessor directive should be include guard #ifndef','includeGuardMissing')
158+
phase = -1
159+
continue
160+
guard_name = check_include_guard_name(conf_ig,cfg,directive)
161+
if guard_name == None:
162+
phase = -1
163+
continue
164+
pending_ifndef = directive
165+
phase = 1
166+
elif phase == 1:
167+
pending_ifndef = None
168+
# looking for '#define FILE_H'
169+
if not directive.str.startswith('#define'):
170+
report(directive,'second preprocessor directive should be include guard #define','includeGuardIncomplete')
171+
phase = -1
172+
continue
173+
parts = directive.str.split()
174+
if len(parts) == 1:
175+
report(directive,'syntax error','syntax')
176+
phase = -1
177+
continue
178+
if guard_name != parts[1]:
179+
report(directive,'include guard does not guard; %s != %s'%(guard_name,parts[1]),'includeGuardAwayFromDuty',severity='warning')
180+
181+
unguarded_include_files.remove(directive.file)
182+
183+
phase = -1
184+
if pending_ifndef:
185+
report_pending_ifndef(pending_ifndef)
76186

77187
def process(dumpfiles, configfile, debugprint=False):
78188
conf = loadConfig(configfile)
79189

190+
if "include_guard" in conf and conf["include_guard"]:
191+
global include_guard_header_re
192+
include_guard_header_re = conf["include_guard"].get('RE_HEADERFILE',"[^/].*\\.h\\Z")
193+
80194
for afile in dumpfiles:
81195
if not afile[-5:] == '.dump':
82196
continue
@@ -105,6 +219,11 @@ def process(dumpfiles, configfile, debugprint=False):
105219
for exp in conf["RE_NAMESPACE"]:
106220
evalExpr(conf["RE_NAMESPACE"], exp, mockToken, msgType)
107221

222+
unguarded_include_files = []
223+
if "include_guard" in conf and conf["include_guard"]:
224+
if conf["include_guard"].get('required',1):
225+
unguarded_include_files = [fn for fn in data.files if re.match(include_guard_header_re,fn)]
226+
108227
for cfg in data.configurations:
109228
if not args.cli:
110229
print('Checking %s, config %s...' % (afile, cfg.name))
@@ -203,6 +322,14 @@ def process(dumpfiles, configfile, debugprint=False):
203322
for exp in conf["RE_CLASS_NAME"]:
204323
evalExpr(conf["RE_CLASS_NAME"], exp, mockToken, msgType)
205324

325+
# Check include guard naming
326+
if "include_guard" in conf and conf["include_guard"]:
327+
check_include_guard(conf["include_guard"],cfg,unguarded_include_files)
328+
329+
for fn in unguarded_include_files:
330+
mockToken = DataStruct(fn,0,os.path.basename(fn))
331+
reportNamingError(mockToken,'Missing include guard','includeGuardMissing')
332+
206333
if __name__ == "__main__":
207334
parser = cppcheckdata.ArgumentParser()
208335
parser.add_argument("--debugprint", action="store_true", default=False,

‎test/cli/test-other.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,13 +346,28 @@ def test_addon_namingng(tmpdir):
346346
"RE_VARNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
347347
"RE_GLOBAL_VARNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
348348
"RE_FUNCTIONNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
349+
"include_guard": {
350+
"input": "basename",
351+
"prefix": "_",
352+
"suffix": "",
353+
"case": "upper",
354+
"max_linenr": 5,
355+
"RE_HEADERFILE": ".*\\.h\\Z",
356+
"required": true
357+
},
349358
"var_prefixes": {"uint32_t": "ui32"},
350359
"function_prefixes": {"uint16_t": "ui16",
351360
"uint32_t": "ui32"},
352361
"skip_one_char_variables": false
353362
}
354363
""".replace('\\','\\\\'))
355364

365+
test_unguarded_include_file_basename = 'test_unguarded.h'
366+
test_unguarded_include_file = os.path.join(tmpdir, test_unguarded_include_file_basename)
367+
with open(test_unguarded_include_file, 'wt') as f:
368+
f.write("""
369+
void InvalidFunctionUnguarded();
370+
""")
356371

357372
test_include_file_basename = '_test.h'
358373
test_include_file = os.path.join(tmpdir, test_include_file_basename)
@@ -364,8 +379,10 @@ def test_addon_namingng(tmpdir):
364379
void InvalidFunction();
365380
extern int _invalid_extern_global;
366381
382+
#include "{}"
383+
367384
#endif
368-
""")
385+
""".format(test_unguarded_include_file))
369386

370387
test_file_basename = 'test_.c'
371388
test_file = os.path.join(tmpdir, test_file_basename)
@@ -403,11 +420,18 @@ def test_addon_namingng(tmpdir):
403420
lines = [line for line in stderr.splitlines() if line.strip() != '^' and line != '']
404421
expect = [
405422
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_include_file,test_include_file_basename),
423+
'{}:2:0: style: include guard naming violation; TEST_H != _TEST_H [namingng-includeGuardName]'.format(test_include_file),
424+
'#ifndef TEST_H',
406425
'{}:5:0: style: Function InvalidFunction violates naming convention [namingng-namingConvention]'.format(test_include_file),
407426
'void InvalidFunction();',
408427
'{}:6:0: style: Public member variable _invalid_extern_global violates naming convention [namingng-namingConvention]'.format(test_include_file),
409428
'extern int _invalid_extern_global;',
410429

430+
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file,test_unguarded_include_file_basename),
431+
'{}:0:0: style: Missing include guard [namingng-includeGuardMissing]'.format(test_unguarded_include_file),
432+
'{}:2:0: style: Function InvalidFunctionUnguarded violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file),
433+
'void InvalidFunctionUnguarded();',
434+
411435
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_file,test_file_basename),
412436
'{}:7:0: style: Variable _invalid_arg violates naming convention [namingng-namingConvention]'.format(test_file),
413437
'void valid_function2(int _invalid_arg);',

0 commit comments

Comments
 (0)