Debian Codegraph @

gtk-priv/scripts/parse.py

raw
1 '''
2 MIT License
3
4 Copyright 2020 Sophie Winter
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
8 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
10 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11 '''
12
13 import logging
14 import re
15
16 from ast import *
17
18 logger = logging.getLogger(__name__)
19
20 def remove_comments(code):
21 return re.sub(r'(/\*.*?\*/|//.*?\n)', '', code, flags=re.DOTALL)
22
23 def parse_type(code):
24 code = code.strip()
25 if code.endswith('*'):
26 return PtrType(parse_type(code[:-1]))
27 elif code.startswith('const '):
28 return ConstType(parse_type(code[5:]))
29 if code.endswith(' const'):
30 return ConstType(parse_type(code[:5]))
31 elif is_std_type(code):
32 return StdType(code)
33 elif re.search(r'^((struct|enum)\s+)?\w+$', code):
34 return CustomType(code)
35 else:
36 assert False, 'Unknown type `' + code + '`'
37
38 def parse_property(code):
39 code = code.strip()
40 bit_field = None
41 bit_field_split = code.rsplit(':', 1)
42 if len(bit_field_split) > 1:
43 code = bit_field_split[0].strip()
44 bit_field = int(bit_field_split[1].strip())
45 fp = re.search(r'^(.*)\(\s*(\*\s*)+(\w*)\s*\)\s*\((.*)\)$', code)
46 if fp:
47 assert bit_field is None
48 ret = parse_type(fp.group(1))
49 pointer_count = fp.group(2).count('*') - 1
50 assert pointer_count == 0, (
51 'Function pointers with multiple levels of indirection not supported '
52 '(indirection count: ' + str(pointer_count) + ' for ' + code + ')')
53 name = fp.group(3)
54 if name == '':
55 name = None
56 args = []
57 for i in fp.group(4).split(','):
58 args.append(parse_property(i))
59 c_type = FpType(ret, args)
60 return PropertyNode(c_type, name, None)
61 array = re.search(r'^(.*)\[(.*)\]$', code)
62 if array:
63 prop = parse_property(array.group(1))
64 prop.c_type = ArrayType(prop.c_type, array.group(2).strip())
65 return prop
66 normal = re.search(r'^((\w+\s*[^\w\,])+(\*\s*)*)([\w\s\,]*)$', code)
67 if normal:
68 c_type = parse_type(normal.group(1))
69 names = normal.group(4).split(',')
70 names = [name.strip() for name in names if name.strip()]
71 if len(names) > 1:
72 nodes = []
73 for name in names:
74 nodes.append(PropertyNode(c_type, name, None))
75 nodes[-1].statement = True
76 return ListNode(nodes)
77 elif len(names) == 1:
78 return PropertyNode(c_type, names[0], bit_field)
79 else:
80 return PropertyNode(c_type, None, bit_field)
81 assert False, 'Could not parse property `' + code + '`'
82
83 def parse_token_list(tokens, i):
84 nodes = []
85 while i < len(tokens):
86 token = tokens[i].strip()
87 if token == '' or token == ';':
88 pass
89 elif token == 'struct' and tokens[i + 1].strip() == '{':
90 i, node = parse_token_list(tokens, i + 2)
91 i += 1
92 assert i < len(tokens)
93 name = tokens[i].strip()
94 assert re.search(r'^\w+$', name)
95 struct = SubStructNode(name, node)
96 nodes.append(struct)
97 elif token == '}':
98 break
99 else:
100 node = parse_property(token)
101 if isinstance(node, PropertyNode):
102 node.statement = True
103 nodes.append(node)
104 i += 1
105 return i, ListNode(nodes)
106
107 def parse_ast(code):
108 code = remove_comments(code)
109 code = code.replace('\n', ' ')
110 code = code.replace('\t', ' ')
111 tokens = re.split(r'([;\{\}])', code)
112 i, node = parse_token_list(tokens, 0)
113 assert i == len(tokens), code
114 return node