Improve Python code

This commit is contained in:
Ayaz Salikhov 2017-06-05 13:23:00 +02:00 committed by Daniel Marjamäki
parent 2dd6168258
commit 3dc4188292
12 changed files with 31 additions and 33 deletions

View File

@ -26,7 +26,7 @@ def isUnpackedStruct(var):
if structScope: if structScope:
linenr = int(structScope.classStart.linenr) linenr = int(structScope.classStart.linenr)
for line in open(structScope.classStart.file): for line in open(structScope.classStart.file):
linenr = linenr - 1 linenr -= 1
if linenr == 0: if linenr == 0:
return True return True
if re.match(r'#pragma\s+pack\s*\(', line): if re.match(r'#pragma\s+pack\s*\(', line):

View File

@ -642,7 +642,7 @@ def astIsFloat(token):
return False return False
if token.str == '.': if token.str == '.':
return astIsFloat(token.astOperand2) return astIsFloat(token.astOperand2)
if '+-*/%'.find(token.str) == 0: if token.str in '+-*/%':
return astIsFloat(token.astOperand1) or astIsFloat(token.astOperand2) return astIsFloat(token.astOperand1) or astIsFloat(token.astOperand2)
if not token.variable: if not token.variable:
# float literal? # float literal?

View File

@ -223,7 +223,7 @@ def isUnsignedInt(expr):
if not expr: if not expr:
return False return False
if expr.isNumber: if expr.isNumber:
return expr.str.find('u') > 0 or expr.str.find('U') > 0 return 'u' in expr.str or 'U' in expr.str
if expr.str in {'+', '-', '*', '/', '%'}: if expr.str in {'+', '-', '*', '/', '%'}:
return isUnsignedInt(expr.astOperand1) or isUnsignedInt(expr.astOperand2) return isUnsignedInt(expr.astOperand1) or isUnsignedInt(expr.astOperand2)
return False return False
@ -811,7 +811,7 @@ def misra_16_3(rawTokens):
else: else:
state = 0 state = 0
elif token.str.startswith('/*') or token.str.startswith('//'): elif token.str.startswith('/*') or token.str.startswith('//'):
if token.str.lower().find('fallthrough') > 0: if 'fallthrough' in token.str.lower():
state = 2 state = 2
elif token.str == '{': elif token.str == '{':
state = 2 state = 2
@ -956,7 +956,7 @@ def misra_20_2(data):
if not directive.str.startswith('#include '): if not directive.str.startswith('#include '):
continue continue
for pattern in {'\\', '//', '/*', "'"}: for pattern in {'\\', '//', '/*', "'"}:
if directive.str.find(pattern) > 0: if pattern in directive.str:
reportError(directive, 20, 2) reportError(directive, 20, 2)
break break

View File

@ -23,10 +23,8 @@ def parsefile(filename):
functionName = res.group(1) functionName = res.group(1)
if line.startswith('}'): if line.startswith('}'):
functionName = '' functionName = ''
elif line.find('BUG') > 0 or line.find('WARN') > 0 or filename == 'ub.c': elif 'BUG' in line or 'WARN' in line or filename == 'ub.c':
spaces = '' spaces = ' ' * 100
for i in range(100):
spaces = spaces + ' '
s = filename + spaces s = filename + spaces
s = s[:15] + str(linenr) + spaces s = s[:15] + str(linenr) + spaces
s = s[:20] + functionName + spaces s = s[:20] + functionName + spaces

View File

@ -53,7 +53,7 @@ def getpackages(folder):
filename = None filename = None
elif line[:13 + len(folder)] == './pool/main/' + folder + '/': elif line[:13 + len(folder)] == './pool/main/' + folder + '/':
path = line[2:-1] path = line[2:-1]
elif path and line.find('.orig.tar.') > 0: elif path and '.orig.tar.' in line:
filename = line[1 + line.rfind(' '):] filename = line[1 + line.rfind(' '):]
for a in archives: for a in archives:
@ -75,7 +75,7 @@ def handleRemoveReadonly(func, path, exc):
def removeAllExceptResults(): def removeAllExceptResults():
count = 5 count = 5
while count > 0: while count > 0:
count = count - 1 count -= 1
filenames = [] filenames = []
for g in glob.glob('[A-Za-z0-9]*'): for g in glob.glob('[A-Za-z0-9]*'):
@ -116,7 +116,7 @@ def removeLargeFiles(path):
removeLargeFiles(g + '/') removeLargeFiles(g + '/')
elif os.path.isfile(g) and g[-4:] != '.txt': elif os.path.isfile(g) and g[-4:] != '.txt':
statinfo = os.stat(g) statinfo = os.stat(g)
if path.find('/clang/INPUTS/') > 0 or statinfo.st_size > 100000: if '/clang/INPUTS/' in path or statinfo.st_size > 100000:
os.remove(g) os.remove(g)
@ -194,7 +194,7 @@ def scanarchive(filepath, jobs):
addons = sorted(glob.glob(os.path.expanduser('~/cppcheck/addons/*.py'))) addons = sorted(glob.glob(os.path.expanduser('~/cppcheck/addons/*.py')))
for dumpfile in sorted(dumpfiles('')): for dumpfile in sorted(dumpfiles('')):
for addon in addons: for addon in addons:
if addon.find('cppcheckdata.py') > 0: if 'cppcheckdata.py' in addon:
continue continue
p2 = subprocess.Popen(['nice', p2 = subprocess.Popen(['nice',

View File

@ -52,7 +52,7 @@ def getpackages():
filename = None filename = None
elif line[:12] == './pool/main/': elif line[:12] == './pool/main/':
path = line[2:-1] path = line[2:-1]
elif path and line.find('.orig.tar.') > 0: elif path and '.orig.tar.' in line:
filename = line[1 + line.rfind(' '):] filename = line[1 + line.rfind(' '):]
for a in archives: for a in archives:
@ -74,7 +74,7 @@ def handleRemoveReadonly(func, path, exc):
def removeAll(): def removeAll():
count = 5 count = 5
while count > 0: while count > 0:
count = count - 1 count -= 1
filenames = [] filenames = []
for g in glob.glob('[#_A-Za-z0-9]*'): for g in glob.glob('[#_A-Za-z0-9]*'):

View File

@ -10,26 +10,26 @@ def readdate(data):
else: else:
datepos = data.find('\nDATE ') datepos = data.find('\nDATE ')
if datepos >= 0: if datepos >= 0:
datepos = datepos + 1 datepos += 1
if datepos < 0: if datepos < 0:
return None return None
datestr = '' datestr = ''
datepos = datepos + 5 datepos += 5
while True: while True:
if datepos >= len(data): if datepos >= len(data):
return None return None
d = data[datepos] d = data[datepos]
if d >= '0' and d <= '9': if d >= '0' and d <= '9':
datestr = datestr + d datestr += d
elif d == '\n' or d == '\r': elif d == '\n' or d == '\r':
if len(datestr) == 8: if len(datestr) == 8:
return datestr[:4] + '-' + datestr[4:6] + '-' + datestr[6:] return datestr[:4] + '-' + datestr[4:6] + '-' + datestr[6:]
return None return None
elif d != ' ' and d != '-': elif d != ' ' and d != '-':
return None return None
datepos = datepos + 1 datepos += 1
daca2folder = os.path.expanduser('~/daca2/') daca2folder = os.path.expanduser('~/daca2/')
path = '' path = ''
@ -37,11 +37,11 @@ for arg in sys.argv[1:]:
if arg.startswith('--daca2='): if arg.startswith('--daca2='):
daca2folder = arg[8:] daca2folder = arg[8:]
if daca2folder[-1] != '/': if daca2folder[-1] != '/':
daca2folder = daca2folder + '/' daca2folder += '/'
else: else:
path = arg path = arg
if path[-1] != '/': if path[-1] != '/':
path = path + '/' path += '/'
mainpage = open(path + 'daca2.html', 'wt') mainpage = open(path + 'daca2.html', 'wt')
mainpage.write('<!DOCTYPE html>\n') mainpage.write('<!DOCTYPE html>\n')

View File

@ -55,7 +55,7 @@ def getpackages(folder):
filename = None filename = None
elif line[:13 + len(folder)] == './pool/main/' + folder + '/': elif line[:13 + len(folder)] == './pool/main/' + folder + '/':
path = line[2:-1] path = line[2:-1]
elif path and line.find('.orig.tar.') > 0: elif path and '.orig.tar.' in line:
filename = line[1 + line.rfind(' '):] filename = line[1 + line.rfind(' '):]
for a in archives: for a in archives:
@ -82,7 +82,7 @@ def removeAllExceptResults():
for filename in filenames: for filename in filenames:
count = 5 count = 5
while count > 0: while count > 0:
count = count - 1 count -= 1
try: try:
if os.path.isdir(filename): if os.path.isdir(filename):

View File

@ -148,7 +148,7 @@ class MatchCompiler:
gotoNextToken = ' tok = tok->next();\n' gotoNextToken = ' tok = tok->next();\n'
# if varid is provided, check that it's non-zero on first use # if varid is provided, check that it's non-zero on first use
if varid and tok.find('%varid%') != -1 and checked_varid is False: if varid and '%varid%' in tok and not checked_varid:
ret += ' if (varid==0U)\n' ret += ' if (varid==0U)\n'
ret += ' throw InternalError(tok, "Internal error. Token::Match called with varid 0. ' +\ ret += ' throw InternalError(tok, "Internal error. Token::Match called with varid 0. ' +\
'Please report this to Cppcheck developers");\n' 'Please report this to Cppcheck developers");\n'
@ -160,7 +160,7 @@ class MatchCompiler:
ret += ' ' + returnStatement ret += ' ' + returnStatement
# a|b|c # a|b|c
elif tok.find('|') > 0: elif '|' in tok:
tokens2 = tok.split('|') tokens2 = tok.split('|')
logicalOp = ' || ' logicalOp = ' || '
if "" in tokens2: if "" in tokens2:
@ -537,7 +537,7 @@ class MatchCompiler:
# Check for varId # Check for varId
varId = None varId = None
if not is_findsimplematch and g0.find("%varid%") != -1: if not is_findsimplematch and "%varid%" in g0:
if len(res) == 5: if len(res) == 5:
varId = res[4] varId = res[4]
else: else:

View File

@ -19,9 +19,9 @@ def checknonnull(cfg, functionName, nonnull):
continue continue
argpos2 = functionCfg.find('</arg>', argpos1) argpos2 = functionCfg.find('</arg>', argpos1)
notnullpos = functionCfg.find('not-null', argpos1) notnullpos = functionCfg.find('not-null', argpos1)
if notnullpos > 0 and notnullpos < argpos2: if 0 <= notnullpos < argpos2:
if s: if s:
s = s + ', ' + str(argnr) s += ', ' + str(argnr)
else: else:
s = str(argnr) s = str(argnr)
if s != nonnull: if s != nonnull:
@ -102,7 +102,7 @@ def parseheader(cppcheckpath, filename):
nonnull = None nonnull = None
nonnullStart = line.find('__nonnull') nonnullStart = line.find('__nonnull')
if nonnullStart > 0: if nonnullStart >= 0:
nonnullStart += 9 nonnullStart += 9
while nonnullStart < len(line) and line[nonnullStart] == ' ': while nonnullStart < len(line) and line[nonnullStart] == ' ':
nonnullStart += 1 nonnullStart += 1

View File

@ -46,7 +46,7 @@ def runtool():
return True return True
elif p.returncode == 0: elif p.returncode == 0:
out = comm[0] + '\n' + comm[1] out = comm[0] + '\n' + comm[1]
if ('error:' not in out) and (out.find(EXPECTED) > 0): if 'error:' not in out and EXPECTED in out:
return True return True
return False return False
@ -223,7 +223,7 @@ def removeline(filedata):
if stmt and strippedline[-1] == ';' and checkpar(line) and '{' not in line and '}' not in line: if stmt and strippedline[-1] == ';' and checkpar(line) and '{' not in line and '}' not in line:
replaceandrun('remove line', filedata, i, '') replaceandrun('remove line', filedata, i, '')
elif stmt and strippedline.find('{') > 0 and strippedline.find('}') == len(strippedline) - 1: elif stmt and '{' in strippedline and strippedline.find('}') == len(strippedline) - 1:
replaceandrun('remove line', filedata, i, '') replaceandrun('remove line', filedata, i, '')
if strippedline[-1] in ';{}': if strippedline[-1] in ';{}':

View File

@ -71,7 +71,7 @@ for result in results.split('\n'):
f = open(project + '/true-positives.txt', 'rt') f = open(project + '/true-positives.txt', 'rt')
for line in f.readlines(): for line in f.readlines():
line = line.strip() line = line.strip()
if line.find('] -> [') > 0 or '(error)' not in line: if '] -> [' in line or '(error)' not in line:
continue continue
res = re.match('\\[(' + project + '.+):([0-9]+)\\]:\s+[(][a-z]+[)] (.+)', line) res = re.match('\\[(' + project + '.+):([0-9]+)\\]:\s+[(][a-z]+[)] (.+)', line)
@ -101,7 +101,7 @@ for line in f.readlines():
f.close() f.close()
project2 = '' project2 = ''
if project.find('-') > 0: if '-' in project:
project2 = project[:project.find('-')] project2 = project[:project.find('-')]
else: else:
project2 = project project2 = project