1212# JSON format:
1313#
1414# {
15- # "RE_VARNAME": "[a-z]*[a-zA-Z0-9_]*\\Z",
15+ # "RE_VARNAME": [ "[a-z]*[a-zA-Z0-9_]*\\Z"] ,
1616# "RE_PRIVATE_MEMBER_VARIABLE": null,
17- # "RE_FUNCTIONNAME": "[a-z0-9A-Z]*\\Z",
17+ # "RE_FUNCTIONNAME": ["[a-z0-9A-Z]*\\Z"],
18+ # "_comment": "comments can be added to the config with underscore-prefixed keys",
1819# "include_guard": {
1920# "input": "path",
2021# "prefix": "GUARD_",
@@ -49,10 +50,89 @@ def __init__(self, file, linenr, string):
4950def reportNamingError (location ,message ,errorId = 'namingConvention' ,severity = 'style' ,extra = '' ):
5051 cppcheckdata .reportError (location ,severity ,message ,'namingng' ,errorId ,extra )
5152
53+ def configError (error ,fatal = True ):
54+ print ('config error: %s' % error )
55+ if fatal :
56+ sys .exit (1 )
57+
5258def loadConfig (configfile ):
53- with open (configfile ) as fh :
54- data = json .load (fh )
55- return data
59+ if not os .path .exists (configfile ):
60+ configError ("cannot find config file '%s'" % configfile )
61+
62+ try :
63+ with open (configfile ) as fh :
64+ try :
65+ data = json .load (fh )
66+ except json .JSONDecodeError as e :
67+ configError ("error parsing config file as JSON at line %d: %s" % (e .lineno ,e .msg ))
68+ except Exception as e :
69+ configError ("error opening config file '%s': %s" % (configfile ,e ))
70+
71+ if not isinstance (data , dict ):
72+ configError ('config file must contain a JSON object at the top level' )
73+
74+ # All errors are emitted before bailing out, to make the unit test more
75+ # effective.
76+ have_error = False
77+
78+ # Put config items in a class, so that settings can be accessed using
79+ # config.feature
80+ class Config :
81+ pass
82+ config = Config ()
83+
84+ mapping = {
85+ 'file' : ('RE_FILE' , list ),
86+ 'namespace' : ('RE_NAMESPACE' , list ),
87+ 'include_guard' : ('include_guard' , dict ),
88+ 'variable' : ('RE_VARNAME' , list ),
89+ 'variable_prefixes' : ('var_prefixes' , dict , {}),
90+ 'private_member' : ('RE_PRIVATE_MEMBER_VARIABLE' , list ),
91+ 'public_member' : ('RE_PUBLIC_MEMBER_VARIABLE' , list ),
92+ 'global_variable' : ('RE_GLOBAL_VARNAME' , list ),
93+ 'function_name' : ('RE_FUNCTIONNAME' , list ),
94+ 'function_prefixes' : ('function_prefixes' , dict , {}),
95+ 'class_name' : ('RE_CLASS_NAME' , list ),
96+ 'skip_one_char_variables' : ('skip_one_char_variables' , bool ),
97+ }
98+
99+ # parse defined keys and store as members of config object
100+ for key ,opts in mapping .items ():
101+ json_key = opts [0 ]
102+ req_type = opts [1 ]
103+ default = None if len (opts )< 3 else opts [2 ]
104+
105+ value = data .pop (json_key ,default )
106+ if value is not None and not isinstance (value , req_type ):
107+ req_typename = req_type .__name__
108+ got_typename = type (value ).__name__
109+ configError ('%s must be %s (not %s), or not set' % (json_key ,req_typename ,got_typename ),fatal = False )
110+ have_error = True
111+ continue
112+
113+ if req_type == list and value is not None :
114+ # type 'list' implies a list of regular expressions
115+ for item in value :
116+ try :
117+ re .compile (item )
118+ except re .error as err :
119+ configError ("item '%s' of '%s' is not a valid regular expression: %s" % (item ,json_key ,err ),fatal = False )
120+ have_error = True
121+ if have_error :
122+ continue
123+
124+ setattr (config ,key ,value )
125+
126+ # check remaining keys, only accept underscore-prefixed comments
127+ for key ,value in data .items ():
128+ if key == '' or key [0 ] != '_' :
129+ configError ("unknown config key '%s'" % key ,fatal = False )
130+ have_error = True
131+
132+ if have_error :
133+ sys .exit (1 )
134+
135+ return config
56136
57137
58138def checkTrueRegex (data , expr , msg ):
@@ -82,7 +162,7 @@ def evalExpr(conf, exp, mockToken, msgType):
82162 msg = msgType + ' ' + mockToken .str + ' violates naming convention'
83163 checkFalseRegex (mockToken , exp , msg )
84164
85- def check_include_guard_name (conf_ig ,cfg ,directive ):
165+ def check_include_guard_name (conf_include_guard ,cfg ,directive ):
86166 parts = directive .str .split ()
87167 if len (parts ) != 2 :
88168 msg = 'syntax error'
@@ -91,9 +171,9 @@ def check_include_guard_name(conf_ig,cfg,directive):
91171 guard_name = parts [1 ]
92172
93173 filename = directive .file
94- if conf_ig .get ('input' ,'path' ) == 'basename' :
174+ if conf_include_guard .get ('input' ,'path' ) == 'basename' :
95175 filename = os .path .basename (filename )
96- use_case = conf_ig .get ('case' ,'upper' )
176+ use_case = conf_include_guard .get ('case' ,'upper' )
97177 if use_case == 'upper' :
98178 filename = filename .upper ()
99179 elif use_case == 'lower' :
@@ -105,20 +185,20 @@ def check_include_guard_name(conf_ig,cfg,directive):
105185 sys .exit (1 )
106186
107187 barename = re .sub ('[^A-Za-z0-9]' ,'_' ,filename ).strip ('_' )
108- expect_guard_name = conf_ig .get ('prefix' ,'' ) + barename + conf_ig .get ('suffix' ,'' )
188+ expect_guard_name = conf_include_guard .get ('prefix' ,'' ) + barename + conf_include_guard .get ('suffix' ,'' )
109189 if expect_guard_name != guard_name :
110190 msg = 'include guard naming violation; %s != %s' % (guard_name ,expect_guard_name )
111191 reportNamingError (directive ,msg ,'includeGuardName' )
112192
113193 return guard_name
114194
115- def check_include_guard (conf_ig ,cfg ,unguarded_include_files ):
195+ def check_include_guard (conf_include_guard ,cfg ,unguarded_include_files ):
116196 # Scan for '#ifndef FILE_H' as the first directive, in the first N lines.
117197 # Then test whether the next directive #defines the found name.
118198 # Various tests are done:
119199 # - check include guards for their naming and consistency
120200 # - test whether include guards are in place
121- max_linenr = conf_ig .get ('max_linenr' , 5 )
201+ max_linenr = conf_include_guard .get ('max_linenr' , 5 )
122202
123203 def report (directive ,msg ,errorId ):
124204 reportNamingError (directive ,msg ,errorId )
@@ -144,7 +224,7 @@ def report_pending_ifndef(directive):
144224 continue
145225
146226 if directive .linenr > max_linenr :
147- if phase == 0 and conf_ig .get ('required' ,1 ):
227+ if phase == 0 and conf_include_guard .get ('required' ,1 ):
148228 report (directive ,'include guard not found before line %d' % max_linenr ,'includeGuardMissing' )
149229 pass
150230 phase = - 1
@@ -153,11 +233,11 @@ def report_pending_ifndef(directive):
153233 if phase == 0 :
154234 # looking for '#ifndef FILE_H'
155235 if not directive .str .startswith ('#ifndef' ):
156- if conf_ig .get ('required' ,1 ):
236+ if conf_include_guard .get ('required' ,1 ):
157237 report (directive ,'first preprocessor directive should be include guard #ifndef' ,'includeGuardMissing' )
158238 phase = - 1
159239 continue
160- guard_name = check_include_guard_name (conf_ig ,cfg ,directive )
240+ guard_name = check_include_guard_name (conf_include_guard ,cfg ,directive )
161241 if guard_name == None :
162242 phase = - 1
163243 continue
@@ -187,9 +267,9 @@ def report_pending_ifndef(directive):
187267def process (dumpfiles , configfile , debugprint = False ):
188268 conf = loadConfig (configfile )
189269
190- if "include_guard" in conf and conf [ " include_guard" ] :
270+ if conf . include_guard :
191271 global include_guard_header_re
192- include_guard_header_re = conf [ " include_guard" ] .get ('RE_HEADERFILE' ,"[^/].*\\ .h\\ Z" )
272+ include_guard_header_re = conf . include_guard .get ('RE_HEADERFILE' ,"[^/].*\\ .h\\ Z" )
193273
194274 for afile in dumpfiles :
195275 if not afile [- 5 :] == '.dump' :
@@ -199,35 +279,35 @@ def process(dumpfiles, configfile, debugprint=False):
199279 data = cppcheckdata .CppcheckData (afile )
200280
201281 # Check File naming
202- if "RE_FILE" in conf and conf [ "RE_FILE" ] :
282+ if conf . file :
203283 for source_file in data .files :
204284 basename = os .path .basename (source_file )
205285 good = False
206- for exp in conf [ "RE_FILE" ] :
286+ for exp in conf . file :
207287 good |= bool (re .match (exp , source_file ))
208288 good |= bool (re .match (exp , basename ))
209289 if not good :
210290 mockToken = DataStruct (source_file , 0 , basename )
211291 reportNamingError (mockToken , 'File name ' + basename + ' violates naming convention' )
212292
213293 # Check Namespace naming
214- if "RE_NAMESPACE" in conf and conf [ "RE_NAMESPACE" ] :
294+ if conf . namespace :
215295 for tk in data .rawTokens :
216296 if tk .str == 'namespace' :
217297 mockToken = DataStruct (tk .next .file , tk .next .linenr , tk .next .str )
218298 msgType = 'Namespace'
219- for exp in conf [ "RE_NAMESPACE" ] :
220- evalExpr (conf [ "RE_NAMESPACE" ] , exp , mockToken , msgType )
299+ for exp in conf . namespace :
300+ evalExpr (conf . namespace , exp , mockToken , msgType )
221301
222302 unguarded_include_files = []
223- if "include_guard" in conf and conf [ " include_guard" ] :
224- if conf [ " include_guard" ] .get ('required' ,1 ):
303+ if conf . include_guard :
304+ if conf . include_guard .get ('required' ,1 ):
225305 unguarded_include_files = [fn for fn in data .files if re .match (include_guard_header_re ,fn )]
226306
227307 for cfg in data .configurations :
228308 if not args .cli :
229309 print ('Checking %s, config %s...' % (afile , cfg .name ))
230- if "RE_VARNAME" in conf and conf [ "RE_VARNAME" ] :
310+ if conf . variable :
231311 for var in cfg .variables :
232312 if var .nameToken and var .access != 'Global' and var .access != 'Public' and var .access != 'Private' :
233313 prev = var .nameToken .previous
@@ -245,53 +325,54 @@ def process(dumpfiles, configfile, debugprint=False):
245325 print ("\n " )
246326 print ("\t -- {} {}" .format (varType , str (var .nameToken .str )))
247327
248- if conf [ " skip_one_char_variables" ] and len (var .nameToken .str ) == 1 :
328+ if conf . skip_one_char_variables and len (var .nameToken .str ) == 1 :
249329 continue
250- if varType in conf .get ("var_prefixes" ,{}):
251- if not var .nameToken .str .startswith (conf ["var_prefixes" ][varType ]):
330+ if varType in conf .variable_prefixes :
331+ prefix = conf .variable_prefixes [varType ]
332+ if not var .nameToken .str .startswith (prefix ):
252333 reportNamingError (var .typeStartToken ,
253334 'Variable ' +
254335 var .nameToken .str +
255336 ' violates naming convention' )
256337
257338 mockToken = DataStruct (var .typeStartToken .file , var .typeStartToken .linenr , var .nameToken .str )
258339 msgType = 'Variable'
259- for exp in conf [ "RE_VARNAME" ] :
260- evalExpr (conf [ "RE_VARNAME" ] , exp , mockToken , msgType )
340+ for exp in conf . variable :
341+ evalExpr (conf . variable , exp , mockToken , msgType )
261342
262343 # Check Private Variable naming
263- if "RE_PRIVATE_MEMBER_VARIABLE" in conf and conf [ "RE_PRIVATE_MEMBER_VARIABLE" ] :
344+ if conf . private_member :
264345 # TODO: Not converted yet
265346 for var in cfg .variables :
266347 if (var .access is None ) or var .access != 'Private' :
267348 continue
268349 mockToken = DataStruct (var .typeStartToken .file , var .typeStartToken .linenr , var .nameToken .str )
269350 msgType = 'Private member variable'
270- for exp in conf [ "RE_PRIVATE_MEMBER_VARIABLE" ] :
271- evalExpr (conf [ "RE_PRIVATE_MEMBER_VARIABLE" ] , exp , mockToken , msgType )
351+ for exp in conf . private_member :
352+ evalExpr (conf . private_member , exp , mockToken , msgType )
272353
273354 # Check Public Member Variable naming
274- if "RE_PUBLIC_MEMBER_VARIABLE" in conf and conf [ "RE_PUBLIC_MEMBER_VARIABLE" ] :
355+ if conf . public_member :
275356 for var in cfg .variables :
276357 if (var .access is None ) or var .access != 'Public' :
277358 continue
278359 mockToken = DataStruct (var .typeStartToken .file , var .typeStartToken .linenr , var .nameToken .str )
279360 msgType = 'Public member variable'
280- for exp in conf [ "RE_PUBLIC_MEMBER_VARIABLE" ] :
281- evalExpr (conf [ "RE_PUBLIC_MEMBER_VARIABLE" ] , exp , mockToken , msgType )
361+ for exp in conf . public_member :
362+ evalExpr (conf . public_member , exp , mockToken , msgType )
282363
283364 # Check Global Variable naming
284- if "RE_GLOBAL_VARNAME" in conf and conf [ "RE_GLOBAL_VARNAME" ] :
365+ if conf . global_variable :
285366 for var in cfg .variables :
286367 if (var .access is None ) or var .access != 'Global' :
287368 continue
288369 mockToken = DataStruct (var .typeStartToken .file , var .typeStartToken .linenr , var .nameToken .str )
289370 msgType = 'Public member variable'
290- for exp in conf [ "RE_GLOBAL_VARNAME" ] :
291- evalExpr (conf [ "RE_GLOBAL_VARNAME" ] , exp , mockToken , msgType )
371+ for exp in conf . global_variable :
372+ evalExpr (conf . global_variable , exp , mockToken , msgType )
292373
293374 # Check Functions naming
294- if "RE_FUNCTIONNAME" in conf and conf [ "RE_FUNCTIONNAME" ] :
375+ if conf . function_name :
295376 for token in cfg .tokenlist :
296377 if token .function :
297378 if token .function .type in ('Constructor' , 'Destructor' , 'CopyConstructor' , 'MoveConstructor' ):
@@ -304,27 +385,27 @@ def process(dumpfiles, configfile, debugprint=False):
304385 if debugprint :
305386 print ("\t :: {} {}" .format (retval , token .function .name ))
306387
307- if retval and retval in conf .get ( " function_prefixes" ,{}) :
308- if not token .function .name .startswith (conf [ " function_prefixes" ] [retval ]):
388+ if retval and retval in conf .function_prefixes :
389+ if not token .function .name .startswith (conf . function_prefixes [retval ]):
309390 reportNamingError (token , 'Function ' + token .function .name + ' violates naming convention' )
310391 mockToken = DataStruct (token .file , token .linenr , token .function .name )
311392 msgType = 'Function'
312- for exp in conf [ "RE_FUNCTIONNAME" ] :
313- evalExpr (conf [ "RE_FUNCTIONNAME" ] , exp , mockToken , msgType )
393+ for exp in conf . function_name :
394+ evalExpr (conf . function_name , exp , mockToken , msgType )
314395
315396 # Check Class naming
316- if "RE_CLASS_NAME" in conf and conf [ "RE_CLASS_NAME" ] :
397+ if conf . class_name :
317398 for fnc in cfg .functions :
318399 # Check if it is Constructor/Destructor
319400 if fnc .type == 'Constructor' or fnc .type == 'Destructor' :
320401 mockToken = DataStruct (fnc .tokenDef .file , fnc .tokenDef .linenr , fnc .name )
321402 msgType = 'Class ' + fnc .type
322- for exp in conf [ "RE_CLASS_NAME" ] :
323- evalExpr (conf [ "RE_CLASS_NAME" ] , exp , mockToken , msgType )
403+ for exp in conf . class_name :
404+ evalExpr (conf . class_name , exp , mockToken , msgType )
324405
325406 # 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 )
407+ if conf . include_guard :
408+ check_include_guard (conf . include_guard ,cfg ,unguarded_include_files )
328409
329410 for fn in unguarded_include_files :
330411 mockToken = DataStruct (fn ,0 ,os .path .basename (fn ))
0 commit comments