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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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