xref: /btstack/tool/misc/fix-misra-12.1.py (revision ea1be6558795a2906234f8e2ffce250814bad68e)
1#!/usr/bin/env python3
2import os
3import sys
4import re
5import fileinput
6import string
7
8# find root
9btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/../../')
10print(btstack_root)
11
12# messages
13cstat_file = 'cstat.txt'
14
15# project prefix
16project_prefix = 'c:\\projects\\iar\\btstack\\btstack\\'
17
18def add_parantheses(line, expression):
19    stripped_line = ''
20    positions = []
21    for (char,pos) in zip(line, range(len(line))):
22        if char in string.whitespace:
23            continue
24        stripped_line += char
25        positions.append(pos)
26    pos = stripped_line.find(expression)
27    if pos < 0:
28        return line
29    pos_start = positions[pos]
30    pos_end   = positions[pos + len(expression)-1]
31    new_line = line[0:pos_start] + '(' + line[pos_start:pos_end+1] + ")" + line[pos_end+1:]
32    return new_line
33
34def fix(path, lineno, expression):
35    full_path = btstack_root + "/" + path
36    print(full_path, lineno, expression)
37    for line in fileinput.input(full_path, inplace=True):
38        if fileinput.lineno() == lineno:
39            line = add_parantheses(line, expression)
40        sys.stdout.write(line)
41
42with open(cstat_file, 'rt') as fin:
43    fixed = 0
44    total = 0
45    for line in fin:
46        chunks = line.strip().split('\t')
47        if len(chunks) != 4: continue
48        (msg, rule, severity, location) = chunks
49        if not rule.startswith('MISRAC2012-Rule-12.1'): continue
50        parts = re.match(".*Suggest parentheses.*`(.*)'", msg)
51        total += 1
52        expression = parts.groups()[0]
53        # skip some expressions
54        if expression.endswith('=='): continue
55        if expression.endswith('!='): continue
56        if expression.endswith('>'): continue
57        if expression.endswith('<'): continue
58        if expression.endswith('>='): continue
59        if expression.endswith('<='): continue
60        # remove windows prefix
61        location = location.replace(project_prefix, '').replace('\\','/')
62        parts = location.split(':')
63        (path, lineno) = parts
64        fix(path, int(lineno), expression)
65        fixed += 1
66    print ("Fixed %u of %u messsages" % (fixed, total))
67