Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions addons/cppcheck.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

import cppcheckdata, sys, os
import cppcheckdata
import sys
import os

__checkers__ = []

Expand Down Expand Up @@ -33,7 +34,7 @@ def runcheckers():

for cfg in data.iterconfigurations():
if not args.quiet:
print('Checking %s, config %s...' % (dumpfile, cfg.name))
print('Checking {}, config {}...'.format(dumpfile, cfg.name))
for c in __checkers__:
__errorid__ = c.__name__
c(cfg, data)
38 changes: 19 additions & 19 deletions addons/cppcheckdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
'extra': ''}
sys.stdout.write(json.dumps(msg) + '\n')
else:
sys.stderr.write('%s [%s]\n' % (message, error_id))
sys.stderr.write('{} [{}]\n'.format(message, error_id))
sys.exit(1)

from xml.etree import ElementTree
Expand Down Expand Up @@ -91,7 +91,7 @@ def __repr__(self):
attrs = ["str", "file", "linenr"]
return "{}({})".format(
"Directive",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

class MacroUsage:
Expand Down Expand Up @@ -127,7 +127,7 @@ def __repr__(self):
attrs = ["name", "file", "linenr", "column", "usefile", "useline", "usecolumn", "isKnownValue"]
return "{}({})".format(
"MacroUsage",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -156,7 +156,7 @@ def __repr__(self):
attrs = ["file", "linenr", "column", "E", "result"]
return "{}({})".format(
"PreprocessorIfCondition",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

class ValueType:
Expand Down Expand Up @@ -202,7 +202,7 @@ def __repr__(self):
"constness", "pointer"]
return "{}({})".format(
"ValueType",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -445,7 +445,7 @@ def __repr__(self):
"linenr", "column"]
return "{}({})".format(
"Token",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def setId(self, IdMap):
Expand Down Expand Up @@ -602,7 +602,7 @@ def __repr__(self):
"nestedInId", "nestedIn", "type", "definedType", "isExecutable", "functions"]
return "{}({})".format(
"Scope",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def setId(self, IdMap):
Expand Down Expand Up @@ -682,7 +682,7 @@ def __repr__(self):
"isAttributeNoreturn", "overriddenFunction", "nestedIn", "argumentId"]
return "{}({})".format(
"Function",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def setId(self, IdMap):
Expand Down Expand Up @@ -777,7 +777,7 @@ def __repr__(self):
"isReference", "isStatic", "isVolatile", "constness"]
return "{}({})".format(
"Variable",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def setId(self, IdMap):
Expand Down Expand Up @@ -905,7 +905,7 @@ def __repr__(self):
"bufferSize", "containerSize", "condition", "valueKind"]
return "{}({})".format(
"Value",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand All @@ -932,7 +932,7 @@ def __repr__(self):
attrs = ["Id", "values"]
return "{}({})".format(
"ValueFlow",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -972,7 +972,7 @@ def __repr__(self):
attrs = ["errorId", "fileName", "lineNumber", "symbolName", "lineBegin", "lineEnd","suppressionType"]
return "{}({})".format(
"Suppression",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def isMatch(self, file, line, message, errorId):
Expand Down Expand Up @@ -1138,7 +1138,7 @@ def __repr__(self):
"long_bit", "long_long_bit", "pointer_bit"]
return "{}({})".format(
"Platform",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -1170,7 +1170,7 @@ def __repr__(self):
attrs = ["c", "cpp", "posix"]
return "{}({})".format(
"Standards",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -1405,7 +1405,7 @@ def __repr__(self):
attrs = ["configurations", "platform"]
return "{}({})".format(
"CppcheckData",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -1506,7 +1506,7 @@ def get_files(args):
"""Return dump_files, ctu_info_files"""
all_files = args.dumpfile
if args.file_list:
with open(args.file_list, 'rt') as f:
with open(args.file_list) as f:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not like this at all. This should be explicitly specified for various reasons.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was considering adding pyupgrade to the CI but the open() thing still irked me.

And then I came across asottile/pyupgrade#714.

Given the attitude of the author I will refrain from integrating that tool and would also be reluctant to accept changes which are based on it. Such behavior should be not supported...

for line in f.readlines():
all_files.append(line.rstrip())
dump_files = []
Expand Down Expand Up @@ -1671,19 +1671,19 @@ def reportError(location, severity, message, addon, errorId, extra='', columnOve
'extra': extra}
sys.stdout.write(json.dumps(msg) + '\n')
else:
if is_suppressed(location, message, '%s-%s' % (addon, errorId)):
if is_suppressed(location, message, '{}-{}'.format(addon, errorId)):
return
loc = '[%s:%i]' % (location.file, location.linenr)
if len(extra) > 0:
message += ' (' + extra + ')'
sys.stderr.write('%s (%s) %s [%s-%s]\n' % (loc, severity, message, addon, errorId))
sys.stderr.write('{} ({}) {} [{}-{}]\n'.format(loc, severity, message, addon, errorId))
global EXIT_CODE
EXIT_CODE = 1

def reportSummary(dumpfile, summary_type, summary_data):
# dumpfile ends with ".dump"
ctu_info_file = dumpfile[:-4] + "ctu-info"
with open(ctu_info_file, 'at') as f:
with open(ctu_info_file, 'a') as f:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above. "text" vs "binary" might be important in some cases so that should be explicitly stated.

msg = {'summary': summary_type, 'data': summary_data}
f.write(json.dumps(msg) + '\n')

Expand Down
39 changes: 19 additions & 20 deletions addons/misra.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
#
# Total number of rules: 143

from __future__ import print_function

import cppcheckdata
import itertools
Expand Down Expand Up @@ -536,9 +535,9 @@ def get_essential_type_from_value(value, is_signed):
range_max = (1 << bits) - 1
sign = 'signed' if is_signed else 'unsigned'
if is_signed and value < 0 and value >= range_min:
return '%s %s' % (sign, t)
return '{} {}'.format(sign, t)
if value >= 0 and value <= range_max:
return '%s %s' % (sign, t)
return '{} {}'.format(sign, t)
return None

def getEssentialType(expr):
Expand All @@ -549,7 +548,7 @@ def getEssentialType(expr):
if expr.str[0] == "'" and expr.str[-1] == "'":
if len(expr.str) == 3 or (len(expr.str) == 4 and expr.str[1] == '\\'):
return 'char'
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
return '{} {}'.format(expr.valueType.sign, expr.valueType.type)

if expr.variable or isCast(expr):
typeToken = expr.variable.typeStartToken if expr.variable else expr.next
Expand All @@ -565,7 +564,7 @@ def getEssentialType(expr):
if expr.valueType.isIntegral():
if (expr.valueType.sign is None) and expr.valueType.type == 'char':
return 'char'
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
return '{} {}'.format(expr.valueType.sign, expr.valueType.type)

elif expr.isNumber:
# Appendix D, D.6 The essential type of literal constants
Expand All @@ -576,7 +575,7 @@ def getEssentialType(expr):
return expr.valueType.type
if expr.valueType.isIntegral():
if expr.valueType.type != 'int':
return '%s %s' % (expr.valueType.sign, expr.valueType.type)
return '{} {}'.format(expr.valueType.sign, expr.valueType.type)
return get_essential_type_from_value(expr.getKnownIntValue(), expr.valueType.sign == 'signed')

elif expr.str in ('<', '<=', '>=', '>', '==', '!=', '&&', '||', '!'):
Expand Down Expand Up @@ -1169,7 +1168,7 @@ def __repr__(self):
attrs = ["name", "args", "expansionList"]
return "{}({})".format(
"Define",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -1285,7 +1284,7 @@ def remove_file_prefix(file_path, prefix):
return result


class Rule(object):
class Rule:
"""Class to keep rule text and metadata"""

MISRA_SEVERITY_LEVELS = ['Required', 'Mandatory', 'Advisory']
Expand Down Expand Up @@ -1319,7 +1318,7 @@ def __repr__(self):
return "%d.%d (%s)" % (self.num1, self.num2, self.misra_severity)


class MisraSettings(object):
class MisraSettings:
"""Hold settings for misra.py script."""

__slots__ = ["verify", "quiet", "show_summary"]
Expand All @@ -1346,7 +1345,7 @@ def __repr__(self):
attrs = ["verify", "quiet", "show_summary", "verify"]
return "{}({})".format(
"MisraSettings",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)


Expand Down Expand Up @@ -1408,7 +1407,7 @@ def __repr__(self):
"suppressionStats", "stdversion", "severity"]
return "{}({})".format(
"MisraChecker",
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

def get_num_significant_naming_chars(self, cfg):
Expand Down Expand Up @@ -2713,7 +2712,7 @@ def misra_12_1(self, data):

def misra_12_2(self, data):
for token in data.tokenlist:
if not (token.str in ('<<', '>>')):
if token.str not in ('<<', '>>'):
continue
if (not token.astOperand2) or (not token.astOperand2.values):
continue
Expand Down Expand Up @@ -2857,7 +2856,7 @@ def misra_13_4(self, data):
continue
if token.astOperand1.str == '[' and token.astOperand1.previous.str in ('{', ','):
continue
if not (token.astParent.str in [',', ';', '{']):
if token.astParent.str not in [',', ';', '{']:
self.reportError(token, 13, 4)

def misra_13_5(self, data):
Expand Down Expand Up @@ -2930,7 +2929,7 @@ def misra_14_4(self, data):
for token in data.tokenlist:
if token.str != '(':
continue
if not token.astOperand1 or not (token.astOperand1.str in ['if', 'while']):
if not token.astOperand1 or token.astOperand1.str not in ['if', 'while']:
continue
if isBoolExpression(token.astOperand2):
continue
Expand Down Expand Up @@ -3348,7 +3347,7 @@ def misra_config(self, data):
has_var = True
continue
unknown_constant = True
self.report_config_error(tok, 'Unknown constant {}, please review configuration'.format(t.str))
self.report_config_error(tok, f'Unknown constant {t.str}, please review configuration')
if t.isArithmeticalOp:
tokens += [t.astOperand1, t.astOperand2]
if not unknown_constant and not has_var:
Expand Down Expand Up @@ -4335,7 +4334,7 @@ def reportError(self, location, num1, num2):
if self.severity:
cppcheck_severity = self.severity

this_violation = '{}-{}-{}-{}'.format(location.file, location.linenr, location.column, ruleNum)
this_violation = f'{location.file}-{location.linenr}-{location.column}-{ruleNum}'

# If this is new violation then record it and show it. If not then
# skip it since it has already been displayed.
Expand Down Expand Up @@ -4376,10 +4375,10 @@ def loadRuleTexts(self, filename):
print('If you know the codec please report it to the developers so the list can be enhanced.')
print('Trying with default codec now and ignoring errors if possible ...')
try:
file_stream = open(filename, 'rt', errors='ignore')
file_stream = open(filename, errors='ignore')
except TypeError:
# Python 2 does not support the errors parameter
file_stream = open(filename, 'rt')
file_stream = open(filename)

rule = None
have_severity = False
Expand Down Expand Up @@ -4537,7 +4536,7 @@ def fillVerifyExpected(verify_expected, tok):

for cfgNumber, cfg in enumerate(data.iterconfigurations()):
if not self.settings.quiet:
self.printStatus('Checking %s, config %s...' % (dumpfile, cfg.name))
self.printStatus('Checking {}, config {}...'.format(dumpfile, cfg.name))

self.executeCheck(102, self.misra_1_2, cfg)
if not path_premium_addon:
Expand Down Expand Up @@ -4720,7 +4719,7 @@ def is_different_file(loc1, loc2):

try:
for filename in ctu_info_files:
for line in open(filename, 'rt'):
for line in open(filename):
s = self.read_ctu_info_line(line)
if s is None:
continue
Expand Down
7 changes: 3 additions & 4 deletions addons/misra_9.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import cppcheckdata

# Holds information about an array, struct or union's element definition.
class ElementDef:
Expand Down Expand Up @@ -35,7 +34,7 @@ def __repr__(self):
"ElementDef",
self.getLongName(),
inits,
", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs))
", ".join(f"{a}={repr(getattr(self, a))}" for a in attrs)
)

@property
Expand Down Expand Up @@ -521,13 +520,13 @@ def createRecordChildrenDefs(ed, var):
child = getElementDef(variable.nameToken)
ed1.addChild(child)
child_dict[scopes.bodyStart] = ed1
sorted_keys = sorted(list(child_dict.keys()), key=lambda k: "%s %s %s" % (k.file, k.linenr, k.column))
sorted_keys = sorted(list(child_dict.keys()), key=lambda k: "{} {} {}".format(k.file, k.linenr, k.column))
for _key in sorted_keys:
ed.addChild(child_dict[_key])


def getElementByDesignator(ed, token):
if not token.str in [ '.', '[' ]:
if token.str not in [ '.', '[' ]:
return None

while token.str in [ '.', '[' ]:
Expand Down
Loading