xref: /btstack/tool/misc/fix-misra-10.4a.py (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
1#!/usr/bin/env python3
2import os
3import sys
4import re
5import fileinput
6
7# find root
8btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/../../')
9print(btstack_root)
10
11# messages
12cstat_file = 'cstat.txt'
13
14# project prefix
15project_prefixes = [ 'c:\\projects\\iar\\btstack\\btstack\\',
16                     'c:/users/buildbot/buildbot-worker/cstat-develop/btstack/']
17
18def fix(path, lineno, expression):
19    source_path = btstack_root + "/" + path
20    print(source_path, lineno, expression)
21    with open(source_path + '.cocci_res') as cocci_fd:
22        cocci_lines = cocci_fd.readlines()
23        for line_source, line_fix in zip(fileinput.input(source_path, inplace=True), cocci_lines):
24            if fileinput.lineno() == lineno:
25                sys.stdout.write(line_fix)
26            else:
27                sys.stdout.write(line_source)
28
29with open(cstat_file, 'rt') as fin:
30    fixed = 0
31    total = 0
32    for line in fin:
33        chunks = line.strip().split('\t')
34        if len(chunks) != 4: continue
35        (msg, rule, severity, location) = chunks
36        if not rule.startswith('MISRAC2012-Rule-10.4_a'): continue
37        total += 1
38        # remove project prefix
39        for project_prefix in project_prefixes:
40            location = location.replace(project_prefix, '').replace('\\','/')
41        parts = location.split(':')
42        (path, lineno) = parts
43        match = re.match("The operands `(.+)' and `(.+)' have essential type categories (.*) and (.*), which do not match.", msg)
44        # fix if operand is signed literal and cstat complains about signednesss
45        if match:
46            (op1, op2, t1, t2) = match.groups()
47            if re.match("[(0x)0-9]+", op1) and t1.startswith('signed'):
48                fix(path, int(lineno), op1)
49                fixed += 1
50                continue
51            if re.match("[(0x)0-9]+", op2) and t2.startswith('signed'):
52                fix(path, int(lineno), op2)
53                fixed += 1
54                continue
55    print ("Fixed %u of %u messages" % (fixed, total))
56