xref: /qemu/scripts/qom-cast-macro-clean-cocci-gen.py (revision 70ce076fa6dff60585c229a4b641b13e64bf03cf)
1#!/usr/bin/env python3
2#
3# Generate a Coccinelle semantic patch to remove pointless QOM cast.
4#
5# Usage:
6#
7# $ qom-cast-macro-clean-cocci-gen.py $(git ls-files) > qom_pointless_cast.cocci
8# $ spatch \
9#           --macro-file scripts/cocci-macro-file.h \
10#           --sp-file qom_pointless_cast.cocci \
11#           --keep-comments \
12#           --use-gitgrep \
13#           --in-place \
14#           --dir .
15#
16# Copyright (c) 2023 Linaro Ltd.
17#
18# Authors:
19#   Philippe Mathieu-Daudé
20#
21# SPDX-License-Identifier: GPL-2.0-or-later
22
23import re
24import sys
25
26assert len(sys.argv) > 0
27
28def print_cocci_rule(qom_typedef, qom_cast_macro):
29    print(f'''@@
30typedef {qom_typedef};
31{qom_typedef} *obj;
32@@
33-    {qom_cast_macro}(obj)
34+    obj
35''')
36
37patterns = [
38    r'DECLARE_INSTANCE_CHECKER\((\w+),\W*(\w+),\W*TYPE_\w+\)',
39    r'DECLARE_OBJ_CHECKERS\((\w+),\W*\w+,\W*(\w+),\W*TYPE_\w+\)',
40    r'OBJECT_DECLARE_TYPE\((\w+),\W*\w+,\W*(\w+)\)',
41    r'OBJECT_DECLARE_SIMPLE_TYPE\((\w+),\W*(\w+)\)',
42    r'INTERFACE_CHECK\((\w+),\W*\(\w+\),\W*TYPE_(\w+)\)',
43]
44
45for fn in sys.argv[1:]:
46    try:
47        content = open(fn, 'rt').read()
48    except:
49        continue
50    for pattern in patterns:
51        for match in re.findall(pattern, content):
52            print_cocci_rule(match[0], match[1])
53