Improve Python code

This commit is contained in:
Ayaz Salikhov 2017-07-22 11:05:50 +02:00 committed by Daniel Marjamäki
parent 12b7843937
commit 2e6a22e882
9 changed files with 33 additions and 56 deletions

View File

@ -499,9 +499,7 @@ class Configuration:
for values in element:
self.valueflow.append(ValueFlow(values))
IdMap = {}
IdMap[None] = None
IdMap['0'] = None
IdMap = {None: None, '0': None}
for token in self.tokenlist:
IdMap[token.Id] = token
for scope in self.scopes:
@ -689,7 +687,7 @@ def ArgumentParser():
return parser
def reportError(template, callstack=[], severity='', message='', id=''):
def reportError(template, callstack=(), severity='', message='', id=''):
"""
Format an error message according to the template.

View File

@ -26,7 +26,6 @@ def reportError(location, num1, num2):
if VERIFY:
VERIFY_ACTUAL.append(str(location.linenr) + ':' + str(num1) + '.' + str(num2))
else:
errmsg = None
num = num1 * 100 + num2
if num in ruleTexts:
errmsg = ruleTexts[num] + ' [misra-c2012-' + str(num1) + '.' + str(num2) + ']'
@ -43,14 +42,6 @@ def simpleMatch(token, pattern):
token = token.next
return True
# Platform
CHAR_BIT = 0
SHORT_BIT = 0
INT_BIT = 0
LONG_BIT = 0
LONG_LONG_BIT = 0
POINTER_BIT = 0
KEYWORDS = {
'auto',
'break',
@ -579,11 +570,11 @@ def misra_12_1(data):
if p < 2 or p > 12:
continue
p1 = getPrecedence(token.astOperand1)
if p1 <= 12 and p1 > p and noParentheses(token.astOperand1, token):
if p < p1 <= 12 and noParentheses(token.astOperand1, token):
reportError(token, 12, 1)
continue
p2 = getPrecedence(token.astOperand2)
if p2 <= 12 and p2 > p and noParentheses(token, token.astOperand2):
if p < p2 <= 12 and noParentheses(token, token.astOperand2):
reportError(token, 12, 1)
continue
@ -617,7 +608,6 @@ def misra_12_3(data):
def misra_12_4(data):
max_uint = 0
if INT_BIT == 16:
max_uint = 0xffff
elif INT_BIT == 32:

View File

@ -262,13 +262,13 @@ for dumpfile in dumpfiles:
elif re_undef_use_time_bits64.match(directive.str):
unsafe = int(srclinenr)
# do we have a safe..unsafe area?
if safe > 0 and unsafe > safe:
if unsafe > safe > 0:
safe_ranges.append((safe, unsafe))
safe = -1
# check end of source beyond last directive
if len(cfg.tokenlist) > 0:
unsafe = int(cfg.tokenlist[-1].linenr)
if safe > 0 and unsafe > safe:
if unsafe > safe > 0:
safe_ranges.append((safe, unsafe))
# go through all tokens
for token in cfg.tokenlist:

View File

@ -68,8 +68,6 @@ def handleRemoveReadonly(func, path, exc):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def removeAllExceptResults():
@ -78,10 +76,8 @@ def removeAllExceptResults():
count -= 1
filenames = []
for g in glob.glob('[A-Za-z0-9]*'):
filenames.append(g)
for g in glob.glob('.[a-z]*'):
filenames.append(g)
filenames.extend(glob.glob('[A-Za-z0-9]*'))
filenames.extend(glob.glob('.[a-z]*'))
try:
for filename in filenames:
@ -187,7 +183,7 @@ def scanarchive(filepath, jobs):
'.'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
comm = p.communicate()
p.communicate()
results = open('results.txt', 'at')

View File

@ -67,8 +67,6 @@ def handleRemoveReadonly(func, path, exc):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def removeAll():
@ -77,10 +75,8 @@ def removeAll():
count -= 1
filenames = []
for g in glob.glob('[#_A-Za-z0-9]*'):
filenames.append(g)
for g in glob.glob('.[A-Za-z]*'):
filenames.append(g)
filenames.extend(glob.glob('[#_A-Za-z0-9]*'))
filenames.extend(glob.glob('.[A-Za-z]*'))
try:
for filename in filenames:

View File

@ -4,7 +4,6 @@ import sys
def readdate(data):
datepos = -1
if data[:5] == 'DATE ':
datepos = 0
else:
@ -21,7 +20,7 @@ def readdate(data):
if datepos >= len(data):
return None
d = data[datepos]
if d >= '0' and d <= '9':
if '0' <= d <= '9':
datestr += d
elif d == '\n' or d == '\r':
if len(datestr) == 8:

View File

@ -70,8 +70,6 @@ def handleRemoveReadonly(func, path, exc):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def removeAllExceptResults():

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python
from __future__ import print_function
import argparse
import xml.etree.ElementTree as ET
@ -12,9 +13,8 @@ def main():
tree = ET.parse(vars(parsed)["F"])
root = tree.getroot()
for child in root.iter("error"):
if "cwe" not in child.attrib:
print child.attrib["id"], ",", child.attrib["severity"], ",", child.attrib["verbose"]
print(child.attrib["id"], child.attrib["severity"], child.attrib["verbose"], sep=", ")
if __name__ == "__main__":
main()

View File

@ -36,8 +36,9 @@ class MatchCompiler:
self._rawMatchFunctions = []
self._matchFunctionCache = {}
@staticmethod
def _generateCacheSignature(
self, pattern, endToken=None, varId=None, isFindMatch=False):
pattern, endToken=None, varId=None, isFindMatch=False):
sig = pattern
if endToken:
@ -82,7 +83,8 @@ class MatchCompiler:
self._matchFunctionCache[signature] = id
def _compileCmd(self, tok):
@staticmethod
def _compileCmd(tok):
if tok == '%any%':
return 'true'
elif tok == '%assign%':
@ -122,9 +124,6 @@ class MatchCompiler:
def _compilePattern(self, pattern, nr, varid,
isFindMatch=False, tokenType="const Token"):
ret = ''
returnStatement = ''
if isFindMatch:
ret = '\n ' + tokenType + ' * tok = start_tok;\n'
returnStatement = 'continue;\n'
@ -193,9 +192,9 @@ class MatchCompiler:
negatedTok = "!" + self._compileCmd(tok)
# fold !true => false ; !false => true
# this avoids cppcheck warnings about condition always being true/false
if (negatedTok == "!false"):
if negatedTok == "!false":
negatedTok = "true"
elif (negatedTok == "!true"):
elif negatedTok == "!true":
negatedTok = "false"
ret += ' if (!tok || ' + negatedTok + ')\n'
ret += ' ' + returnStatement
@ -229,7 +228,8 @@ class MatchCompiler:
return ret
def parseMatch(self, line, pos1):
@staticmethod
def parseMatch(line, pos1):
parlevel = 0
args = []
argstart = 0
@ -250,10 +250,8 @@ class MatchCompiler:
elif line[pos] == ')':
parlevel -= 1
if parlevel == 0:
ret = []
ret.append(line[pos1:pos + 1])
for arg in args:
ret.append(arg)
ret = [line[pos1:pos + 1]]
ret.extend(args)
ret.append(line[argstart:pos])
return ret
elif line[pos] == ',' and parlevel == 1:
@ -263,7 +261,8 @@ class MatchCompiler:
return None
def _isInString(self, line, pos1):
@staticmethod
def _isInString(line, pos1):
pos = 0
inString = False
while pos != pos1:
@ -274,9 +273,9 @@ class MatchCompiler:
pos += 1
return inString
def _parseStringComparison(self, line, pos1):
@staticmethod
def _parseStringComparison(line, pos1):
startPos = 0
endPos = 0
pos = pos1
inString = False
while pos < len(line):
@ -286,7 +285,7 @@ class MatchCompiler:
elif line[pos] == '"':
inString = False
endPos = pos + 1
return (startPos, endPos)
return startPos, endPos
elif line[pos] == '"':
startPos = pos
inString = True
@ -294,8 +293,9 @@ class MatchCompiler:
return None
@staticmethod
def _compileVerifyTokenMatch(
self, is_simplematch, verifyNumber, pattern, patternNumber, varId):
is_simplematch, verifyNumber, pattern, patternNumber, varId):
more_args = ''
if varId:
more_args = ', const unsigned int varid'
@ -421,8 +421,9 @@ class MatchCompiler:
return line
@staticmethod
def _compileVerifyTokenFindMatch(
self, is_findsimplematch, verifyNumber, pattern, patternNumber, endToken, varId):
is_findsimplematch, verifyNumber, pattern, patternNumber, endToken, varId):
more_args = ''
if endToken:
more_args += ', const Token * endToken'
@ -514,7 +515,6 @@ class MatchCompiler:
)
def _replaceTokenFindMatch(self, line, linenr, filename):
pos1 = 0
while True:
is_findsimplematch = True
pos1 = line.find('Token::findsimplematch(')