xref: /btstack/tool/misc/fix-misra-12.1.py (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
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 remove_whitespace(line):
19    return line.replace(' ','')
20
21def add_parantheses(line, expression):
22    stripped_line = ''
23    positions = []
24    for (char,pos) in zip(line, range(len(line))):
25        if char in string.whitespace:
26            continue
27        stripped_line += char
28        positions.append(pos)
29    pos = stripped_line.find(expression)
30    if pos < 0:
31        return line
32    pos_start = positions[pos]
33    pos_end   = positions[pos + len(expression)-1]
34    new_line = line[0:pos_start] + '(' + line[pos_start:pos_end+1] + ")" + line[pos_end+1:]
35    return new_line
36
37def fix(path, lineno, expression):
38    full_path = btstack_root + "/" + path
39    print(full_path, lineno, expression)
40    for line in fileinput.input(full_path, inplace=True):
41        if fileinput.lineno() == lineno:
42            line = add_parantheses(line, expression)
43        sys.stdout.write(line)
44
45with open(cstat_file, 'rt') as fin:
46    fixed = 0
47    total = 0
48    for line in fin:
49        chunks = line.strip().split('\t')
50        if len(chunks) != 4: continue
51        (msg, rule, severity, location) = chunks
52        if not rule.startswith('MISRAC2012-Rule-12.1'): continue
53        parts = re.match(".*Suggest parentheses.*`(.*)'", msg)
54        total += 1
55        expression = parts.groups()[0]
56        expression = remove_whitespace(expression)
57        # skip some expressions
58        if expression.endswith('=='): continue
59        if expression.endswith('!='): continue
60        if expression.endswith('>'): continue
61        if expression.endswith('<'): continue
62        if expression.endswith('>='): continue
63        if expression.endswith('<='): continue
64        # remove windows prefix
65        location = location.replace(project_prefix, '').replace('\\','/')
66        parts = location.split(':')
67        (path, lineno) = parts
68        fix(path, int(lineno), expression)
69        fixed += 1
70    print ("Fixed %u of %u messsages" % (fixed, total))
71