Skip to content

Commit 0da2286

Browse files
committed
addons/namingng.py: Add tests 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) - any combination of the above (project_sub_dir_inc_file_h_) A regexp can be specified to match header filenames. The example matches any filename not starting with / and ending with .h, intended to match C header files while exluding system files. The test 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 used. The namingng unit test is extended to test various features of the include guard test.
1 parent 0c8ee78 commit 0da2286

3 files changed

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

77179
def process(dumpfiles, configfile, debugprint=False):
78180
conf = loadConfig(configfile)
79181

182+
if "include_guard" in conf and conf["include_guard"]:
183+
global include_guard_header_re
184+
include_guard_header_re = conf["include_guard"].get('RE_HEADERFILE',"[^/].*\\.h\\Z")
185+
80186
for afile in dumpfiles:
81187
if not afile[-5:] == '.dump':
82188
continue
@@ -105,6 +211,11 @@ def process(dumpfiles, configfile, debugprint=False):
105211
for exp in conf["RE_NAMESPACE"]:
106212
evalExpr(conf["RE_NAMESPACE"], exp, mockToken, msgType)
107213

214+
unguarded_include_files = []
215+
if "include_guard" in conf and conf["include_guard"]:
216+
if conf["include_guard"].get('required',1):
217+
unguarded_include_files = [fn for fn in data.files if re.match(include_guard_header_re,fn)]
218+
108219
for cfg in data.configurations:
109220
if not args.cli:
110221
print('Checking %s, config %s...' % (afile, cfg.name))
@@ -203,6 +314,14 @@ def process(dumpfiles, configfile, debugprint=False):
203314
for exp in conf["RE_CLASS_NAME"]:
204315
evalExpr(conf["RE_CLASS_NAME"], exp, mockToken, msgType)
205316

317+
# Check include guard naming
318+
if "include_guard" in conf and conf["include_guard"]:
319+
check_include_guard(conf["include_guard"],cfg,unguarded_include_files)
320+
321+
for fn in unguarded_include_files:
322+
mockToken = DataStruct(fn,0,os.path.basename(fn))
323+
reportNamingError(mockToken,'Missing include guard','includeGuardMissing')
324+
206325
if __name__ == "__main__":
207326
parser = cppcheckdata.ArgumentParser()
208327
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)