-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy path_builtin_types.py
More file actions
365 lines (318 loc) · 9.73 KB
/
_builtin_types.py
File metadata and controls
365 lines (318 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
from collections import namedtuple
import os.path
import re
import textwrap
from c_common import tables
from . import REPO_ROOT
from ._files import iter_header_files, iter_filenames
CAPI_PREFIX = os.path.join('Include', '')
INTERNAL_PREFIX = os.path.join('Include', 'internal', '')
REGEX = re.compile(textwrap.dedent(rf'''
(?:
^
(?:
(?:
(?:
(?:
(?:
( static ) # <static>
\s+
|
( extern ) # <extern>
\s+
)?
PyTypeObject \s+
)
|
(?:
( PyAPI_DATA ) # <capi>
\s* [(] \s* PyTypeObject \s* [)] \s*
)
)
(\w+) # <name>
\s*
(?:
(?:
( = \s* {{ ) # <def>
$
)
|
( ; ) # <decl>
)
)
|
(?:
# These are specific to Objects/exceptions.c:
(?:
SimpleExtendsException
|
MiddlingExtendsException
|
ComplexExtendsException
)
\( \w+ \s* , \s*
( \w+ ) # <excname>
\s* ,
)
)
)
'''), re.VERBOSE)
def _parse_line(line):
m = re.match(REGEX, line)
if not m:
return None
(static, extern, capi,
name,
def_, decl,
excname,
) = m.groups()
if def_:
isdecl = False
if extern or capi:
raise NotImplementedError(line)
kind = 'static' if static else None
elif excname:
name = f'_PyExc_{excname}'
isdecl = False
kind = 'static'
else:
isdecl = True
if static:
kind = 'static'
elif extern:
kind = 'extern'
elif capi:
kind = 'capi'
else:
kind = None
return name, isdecl, kind
class BuiltinTypeDecl(namedtuple('BuiltinTypeDecl', 'file lno name kind')):
KINDS = {
'static',
'extern',
'capi',
'forward',
}
@classmethod
def from_line(cls, line, filename, lno):
# This is similar to ._capi.CAPIItem.from_line().
parsed = _parse_line(line)
if not parsed:
return None
name, isdecl, kind = parsed
if not isdecl:
return None
return cls.from_parsed(name, kind, filename, lno)
@classmethod
def from_parsed(cls, name, kind, filename, lno):
if not kind:
kind = 'forward'
return cls.from_values(filename, lno, name, kind)
@classmethod
def from_values(cls, filename, lno, name, kind):
if kind not in cls.KINDS:
raise ValueError(f'unsupported kind {kind!r}')
self = cls(filename, lno, name, kind)
if self.kind not in ('extern', 'capi') and self.api:
raise NotImplementedError(self)
elif self.kind == 'capi' and not self.api:
raise NotImplementedError(self)
return self
@property
def relfile(self):
return self.file[len(REPO_ROOT) + 1:]
@property
def api(self):
return self.relfile.startswith(CAPI_PREFIX)
@property
def internal(self):
return self.relfile.startswith(INTERNAL_PREFIX)
@property
def private(self):
if not self.name.startswith('_'):
return False
return self.api and not self.internal
@property
def public(self):
if self.kind != 'capi':
return False
return not self.internal and not self.private
class BuiltinTypeInfo(namedtuple('BuiltinTypeInfo', 'file lno name static decl')):
@classmethod
def from_line(cls, line, filename, lno, *, decls=None):
parsed = _parse_line(line)
if not parsed:
return None
name, isdecl, kind = parsed
if isdecl:
return None
return cls.from_parsed(name, kind, filename, lno, decls=decls)
@classmethod
def from_parsed(cls, name, kind, filename, lno, *, decls=None):
if not kind:
static = False
elif kind == 'static':
static = True
else:
raise NotImplementedError((filename, line, kind))
decl = decls.get(name) if decls else None
return cls(filename, lno, name, static, decl)
@property
def relfile(self):
return self.file[len(REPO_ROOT) + 1:]
@property
def exported(self):
return not self.static
@property
def api(self):
if not self.decl:
return False
return self.decl.api
@property
def internal(self):
if not self.decl:
return False
return self.decl.internal
@property
def private(self):
if not self.decl:
return False
return self.decl.private
@property
def public(self):
if not self.decl:
return False
return self.decl.public
@property
def inmodule(self):
return self.relfile.startswith('Modules' + os.path.sep)
def render_rowvalues(self, kinds):
row = {
'name': self.name,
**{k: '' for k in kinds},
'filename': f'{self.relfile}:{self.lno}',
}
if self.static:
kind = 'static'
else:
if self.internal:
kind = 'internal'
elif self.private:
kind = 'private'
elif self.public:
kind = 'public'
else:
kind = 'global'
row['kind'] = kind
row[kind] = kind
return row
def _ensure_decl(decl, decls):
prev = decls.get(decl.name)
if prev:
if decl.kind == 'forward':
return None
if prev.kind != 'forward':
if decl.kind == prev.kind and decl.file == prev.file:
assert decl.lno != prev.lno, (decl, prev)
return None
raise NotImplementedError(f'duplicate {decl} (was {prev}')
decls[decl.name] = decl
def iter_builtin_types(filenames=None):
decls = {}
seen = set()
for filename in iter_header_files():
seen.add(filename)
with open(filename) as infile:
for lno, line in enumerate(infile, 1):
decl = BuiltinTypeDecl.from_line(line, filename, lno)
if not decl:
continue
_ensure_decl(decl, decls)
srcfiles = []
for filename in iter_filenames():
if filename.endswith('.c'):
srcfiles.append(filename)
continue
if filename in seen:
continue
with open(filename) as infile:
for lno, line in enumerate(infile, 1):
decl = BuiltinTypeDecl.from_line(line, filename, lno)
if not decl:
continue
_ensure_decl(decl, decls)
for filename in srcfiles:
with open(filename) as infile:
localdecls = {}
for lno, line in enumerate(infile, 1):
parsed = _parse_line(line)
if not parsed:
continue
name, isdecl, kind = parsed
if isdecl:
decl = BuiltinTypeDecl.from_parsed(name, kind, filename, lno)
if not decl:
raise NotImplementedError((filename, line))
_ensure_decl(decl, localdecls)
else:
builtin = BuiltinTypeInfo.from_parsed(
name, kind, filename, lno,
decls=decls if name in decls else localdecls)
if not builtin:
raise NotImplementedError((filename, line))
yield builtin
def resolve_matcher(showmodules=False):
def match(info, *, log=None):
if not info.inmodule:
return True
if log is not None:
log(f'ignored {info.name!r}')
return False
return match
##################################
# CLI rendering
def resolve_format(fmt):
if not fmt:
return 'table'
elif isinstance(fmt, str) and fmt in _FORMATS:
return fmt
else:
raise NotImplementedError(fmt)
def get_renderer(fmt):
fmt = resolve_format(fmt)
if isinstance(fmt, str):
try:
return _FORMATS[fmt]
except KeyError:
raise ValueError(f'unsupported format {fmt!r}')
else:
raise NotImplementedError(fmt)
def render_table(types):
types = sorted(types, key=(lambda t: t.name))
colspecs = tables.resolve_columns(
'name:<33 static:^ global:^ internal:^ private:^ public:^ filename:<30')
header, div, rowfmt = tables.build_table(colspecs)
leader = ' ' * sum(c.width+2 for c in colspecs[:3]) + ' '
yield leader + f'{"API":^29}'
yield leader + '-' * 29
yield header
yield div
kinds = [c[0] for c in colspecs[1:-1]]
counts = {k: 0 for k in kinds}
base = {k: '' for k in kinds}
for t in types:
row = t.render_rowvalues(kinds)
kind = row['kind']
yield rowfmt.format(**row)
counts[kind] += 1
yield ''
yield f'total: {sum(counts.values()):>3}'
for kind in kinds:
yield f' {kind:>10}: {counts[kind]:>3}'
def render_repr(types):
for t in types:
yield repr(t)
_FORMATS = {
'table': render_table,
'repr': render_repr,
}