forked from wxWidgets/Phoenix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpi_generator.py
585 lines (491 loc) · 22.3 KB
/
pi_generator.py
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#---------------------------------------------------------------------------
# Name: etgtools/pi_generator.py
# Author: Robin Dunn
#
# Created: 18-Oct-2011
# Copyright: (c) 2011-2020 by Total Control Software
# License: wxWindows License
#---------------------------------------------------------------------------
"""
This generator will create "Python Interface" files, which define a skeleton
version of the classes, functions, attributes, docstrings, etc. as Python
code. This is useful for enabling some introspection of things located in
extension modules where there is less information available for
introspection. The .pi files are used by WingIDE for assisting with code
completion, displaying docstrings in the source assistant panel, etc.
NOTE: PyCharm has a similar feature but the file extension is .pyi in that
case. For now we'll just make a copy of the .pi file, but PyCharm also
supports Python 3.5 style type annotations in the interface files so we may
want to add some type info to that version of the file eventually...
"""
import sys, os, re
import etgtools.extractors as extractors
import etgtools.generators as generators
from etgtools.generators import nci, Utf8EncodingStream, textfile_open
from etgtools.tweaker_tools import FixWxPrefix, magicMethods, \
guessTypeInt, guessTypeFloat, guessTypeStr
phoenixRoot = os.path.abspath(os.path.split(__file__)[0]+'/..')
#---------------------------------------------------------------------------
SKIP_PI_FILE = True
header_pi = """\
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# This file is generated by wxPython's PI generator. Do not edit by hand.
#
# The *.pi files are used by WingIDE to provide more information than it is
# able to glean from introspection of extension types and methods. They are
# not intended to be imported, executed or used for any other purpose other
# than providing info to the IDE. If you don't use WingIDE you can safely
# ignore this file.
#
# See: https://wingware.com/doc/edit/helping-wing-analyze-code
#
# Copyright: (c) 2020 by Total Control Software
# License: wxWindows License
#---------------------------------------------------------------------------
"""
SKIP_PYI_FILE = False
header_pyi = """\
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# This file is generated by wxPython's PI generator. Do not edit by hand.
#
# The *.pyi files are used by PyCharm and other development tools to provide
# more information, such as PEP 484 type hints, than it is able to glean from
# introspection of extension types and methods. They are not intended to be
# imported, executed or used for any other purpose other than providing info
# to the tools. If you don't use use a tool that makes use of .pyi files then
# you can safely ignore this file.
#
# See: https://www.python.org/dev/peps/pep-0484/
# https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html
#
# Copyright: (c) 2020 by Total Control Software
# License: wxWindows License
#---------------------------------------------------------------------------
"""
#---------------------------------------------------------------------------
def piIgnored(obj):
return getattr(obj, 'piIgnored', False)
#---------------------------------------------------------------------------
class PiWrapperGenerator(generators.WrapperGeneratorBase, FixWxPrefix):
def generate(self, module, destFile=None):
stream = Utf8EncodingStream()
# process the module object and its child objects
self.generateModule(module, stream)
# Write the contents of the stream to the destination file
if not destFile:
name = module.module
if name.startswith('_'):
name = name[1:]
destFile = os.path.join(phoenixRoot, 'wx', name)
destFile_pi = destFile + '.pi'
destFile_pyi = destFile + '.pyi'
def _checkAndWriteHeader(destFile, header, docstring):
if not os.path.exists(destFile):
# create the file and write the header
with textfile_open(destFile, 'wt') as f:
f.write(header)
if docstring:
f.write('\n"""\n%s"""\n' % docstring)
if not SKIP_PI_FILE:
_checkAndWriteHeader(destFile_pi, header_pi, module.docstring)
self.writeSection(destFile_pi, module.name, stream.getvalue())
if not SKIP_PYI_FILE:
_checkAndWriteHeader(destFile_pyi, header_pyi, module.docstring)
self.writeSection(destFile_pyi, module.name, stream.getvalue())
def writeSection(self, destFile, sectionName, sectionText):
"""
Read all the lines from destFile, remove those currently between
begin/end markers for sectionName (if any), and write the lines back
to the file with the new text in sectionText.
"""
sectionBeginLine = -1
sectionEndLine = -1
sectionBeginMarker = '#-- begin-%s --#' % sectionName
sectionEndMarker = '#-- end-%s --#' % sectionName
with textfile_open(destFile, 'rt') as fid:
lines = fid.readlines()
for idx, line in enumerate(lines):
if line.startswith(sectionBeginMarker):
sectionBeginLine = idx
if line.startswith(sectionEndMarker):
sectionEndLine = idx
if sectionBeginLine == -1:
# not there already, add to the end
lines.append(sectionBeginMarker + '\n')
lines.append(sectionText)
lines.append(sectionEndMarker + '\n')
else:
# replace the existing lines
lines[sectionBeginLine+1:sectionEndLine] = [sectionText]
with textfile_open(destFile, 'wt') as f:
f.writelines(lines)
#-----------------------------------------------------------------------
def generateModule(self, module, stream):
"""
Generate code for each of the top-level items in the module.
"""
assert isinstance(module, extractors.ModuleDef)
self.isCore = module.module == '_core'
for item in module.imports:
if item.startswith('_'):
item = item[1:]
if item == 'core':
continue
stream.write('import wx.%s\n' % item)
# Move all PyCode items with an order value to the beginning of the
# list as they most likely should appear before everything else.
pycode = list()
for item in module:
if isinstance(item, extractors.PyCodeDef) and item.order is not None:
pycode.append(item)
for item in pycode:
module.items.remove(item)
module.items = pycode + module.items
methodMap = {
extractors.ClassDef : self.generateClass,
extractors.DefineDef : self.generateDefine,
extractors.FunctionDef : self.generateFunction,
extractors.EnumDef : self.generateEnum,
extractors.GlobalVarDef : self.generateGlobalVar,
extractors.TypedefDef : self.generateTypedef,
extractors.WigCode : self.generateWigCode,
extractors.PyCodeDef : self.generatePyCode,
extractors.PyFunctionDef : self.generatePyFunction,
extractors.PyClassDef : self.generatePyClass,
extractors.CppMethodDef : self.generateCppMethod,
extractors.CppMethodDef_sip : self.generateCppMethod_sip,
}
for item in module:
if item.ignored or piIgnored(item):
continue
function = methodMap[item.__class__]
function(item, stream)
#-----------------------------------------------------------------------
def generateEnum(self, enum, stream, indent=''):
assert isinstance(enum, extractors.EnumDef)
if enum.ignored or piIgnored(enum):
return
for v in enum.items:
if v.ignored or piIgnored(v):
continue
name = v.pyName or v.name
stream.write('%s%s = 0\n' % (indent, name))
#-----------------------------------------------------------------------
def generateGlobalVar(self, globalVar, stream):
assert isinstance(globalVar, extractors.GlobalVarDef)
if globalVar.ignored or piIgnored(globalVar):
return
name = globalVar.pyName or globalVar.name
if guessTypeInt(globalVar):
valTyp = '0'
elif guessTypeFloat(globalVar):
valTyp = '0.0'
elif guessTypeStr(globalVar):
valTyp = '""'
else:
valTyp = globalVar.type
valTyp = valTyp.replace('const ', '')
valTyp = valTyp.replace('*', '')
valTyp = valTyp.replace('&', '')
valTyp = valTyp.replace(' ', '')
valTyp = self.fixWxPrefix(valTyp)
valTyp += '()'
stream.write('%s = %s\n' % (name, valTyp))
#-----------------------------------------------------------------------
def generateDefine(self, define, stream):
assert isinstance(define, extractors.DefineDef)
if define.ignored or piIgnored(define):
return
# we're assuming that all #defines that are not ignored are integer or string values
if '"' in define.value:
stream.write('%s = ""\n' % (define.pyName or define.name))
else:
stream.write('%s = 0\n' % (define.pyName or define.name))
#-----------------------------------------------------------------------
def generateTypedef(self, typedef, stream, indent=''):
assert isinstance(typedef, extractors.TypedefDef)
if typedef.ignored or piIgnored(typedef):
return
# If it's not a template instantiation, or has not been flagged by
# the tweaker script that it should be treated as a class, then just
# ignore the typedef and return.
if not ('<' in typedef.type and '>' in typedef.type) and not typedef.docAsClass:
return
# Otherwise write a mock class for it that combines the template and class.
# First, extract the info we need.
if typedef.docAsClass:
bases = [self.fixWxPrefix(b, True) for b in typedef.bases]
name = self.fixWxPrefix(typedef.name)
elif '<' in typedef.type and '>' in typedef.type:
t = typedef.type.replace('>', '')
t = t.replace(' ', '')
bases = t.split('<')
bases = [self.fixWxPrefix(b, True) for b in bases]
name = self.fixWxPrefix(typedef.name)
# Now write the Python equivalent class for the typedef
if not bases:
bases = ['object'] # this should not happpen, but just in case...
stream.write('%sclass %s(%s):\n' % (indent, name, ', '.join(bases)))
indent2 = indent + ' '*4
if typedef.briefDoc:
stream.write('%s"""\n' % indent2)
stream.write(nci(typedef.briefDoc, len(indent2)))
stream.write('%s"""\n' % indent2)
else:
stream.write('%spass\n\n' % indent2)
#-----------------------------------------------------------------------
def generateWigCode(self, wig, stream, indent=''):
assert isinstance(wig, extractors.WigCode)
# write nothing for this one
#-----------------------------------------------------------------------
def generatePyCode(self, pc, stream, indent=''):
assert isinstance(pc, extractors.PyCodeDef)
code = pc.code
if hasattr(pc, 'klass'):
code = code.replace(pc.klass.pyName+'.', '')
stream.write('\n')
stream.write(nci(code, len(indent)))
#-----------------------------------------------------------------------
def generatePyFunction(self, pf, stream, indent=''):
assert isinstance(pf, extractors.PyFunctionDef)
stream.write('\n')
if pf.deprecated:
stream.write('%[email protected]\n' % indent)
if pf.isStatic:
stream.write('%s@staticmethod\n' % indent)
stream.write('%sdef %s%s:\n' % (indent, pf.name, pf.argsString))
indent2 = indent + ' '*4
if pf.briefDoc:
stream.write('%s"""\n' % indent2)
stream.write(nci(pf.briefDoc, len(indent2)))
stream.write('%s"""\n' % indent2)
stream.write('%spass\n' % indent2)
#-----------------------------------------------------------------------
def generatePyClass(self, pc, stream, indent=''):
assert isinstance(pc, extractors.PyClassDef)
# write the class declaration and docstring
if pc.deprecated:
stream.write('%[email protected]\n' % indent)
stream.write('%sclass %s' % (indent, pc.name))
if pc.bases:
stream.write('(%s):\n' % ', '.join(pc.bases))
else:
stream.write('(object):\n')
indent2 = indent + ' '*4
if pc.briefDoc:
stream.write('%s"""\n' % indent2)
stream.write(nci(pc.briefDoc, len(indent2)))
stream.write('%s"""\n' % indent2)
# these are the only kinds of items allowed to be items in a PyClass
dispatch = {
extractors.PyFunctionDef : self.generatePyFunction,
extractors.PyPropertyDef : self.generatePyProperty,
extractors.PyCodeDef : self.generatePyCode,
extractors.PyClassDef : self.generatePyClass,
}
for item in pc.items:
item.klass = pc
f = dispatch[item.__class__]
f(item, stream, indent2)
#-----------------------------------------------------------------------
def generateFunction(self, function, stream):
assert isinstance(function, extractors.FunctionDef)
if not function.pyName:
return
stream.write('\ndef %s' % function.pyName)
if function.hasOverloads():
stream.write('(*args, **kw)')
else:
argsString = function.pyArgsString
if not argsString:
argsString = '()'
if '->' in argsString:
pos = argsString.find(')')
argsString = argsString[:pos+1]
if '(' != argsString[0]:
pos = argsString.find('(')
argsString = argsString[pos:]
argsString = argsString.replace('::', '.')
stream.write(argsString)
stream.write(':\n')
stream.write(' """\n')
stream.write(nci(function.pyDocstring, 4))
stream.write(' """\n')
def generateParameters(self, parameters, stream, indent):
def _lastParameter(idx):
if idx == len(parameters)-1:
return True
for i in range(idx+1, len(parameters)):
if not (parameters[i].ignored or piIgnored(parameters[i])):
return False
return True
for idx, param in enumerate(parameters):
if param.ignored or piIgnored(param):
continue
stream.write(param.name)
if param.default:
stream.write('=%s' % param.default)
if not _lastParameter(idx):
stream.write(', ')
#-----------------------------------------------------------------------
def generateClass(self, klass, stream, indent=''):
assert isinstance(klass, extractors.ClassDef)
if klass.ignored or piIgnored(klass):
return
# check if there is a pi-customized version of the base class names
if hasattr(klass, 'piBases'):
bases = klass.piBases
else:
# check if it's a template with the template parameter as the base class
bases = klass.bases[:]
for tp in klass.templateParams:
if tp in bases:
bases.remove(tp)
# write class declaration
klassName = klass.pyName or klass.name
stream.write('\n%sclass %s' % (indent, klassName))
if bases:
stream.write('(')
bases = [self.fixWxPrefix(b, True) for b in bases]
stream.write(', '.join(bases))
stream.write(')')
else:
stream.write('(object)')
stream.write(':\n')
indent2 = indent + ' '*4
# docstring
stream.write('%s"""\n' % indent2)
stream.write(nci(klass.pyDocstring, len(indent2)))
stream.write('%s"""\n' % indent2)
# generate nested classes
for item in klass.innerclasses:
self.generateClass(item, stream, indent2)
# Split the items into public and protected groups
enums = [i for i in klass if
isinstance(i, extractors.EnumDef) and
i.protection == 'public']
ctors = [i for i in klass if
isinstance(i, extractors.MethodDef) and
i.protection == 'public' and (i.isCtor or i.isDtor)]
public = [i for i in klass if i.protection == 'public' and
i not in ctors and i not in enums]
protected = [i for i in klass if i.protection == 'protected']
dispatch = {
extractors.MemberVarDef : self.generateMemberVar,
extractors.TypedefDef : lambda a,b,c: None,
extractors.PropertyDef : self.generateProperty,
extractors.PyPropertyDef : self.generatePyProperty,
extractors.MethodDef : self.generateMethod,
extractors.EnumDef : self.generateEnum,
extractors.CppMethodDef : self.generateCppMethod,
extractors.CppMethodDef_sip : self.generateCppMethod_sip,
extractors.PyMethodDef : self.generatePyMethod,
extractors.PyCodeDef : self.generatePyCode,
extractors.WigCode : self.generateWigCode,
}
for item in enums:
item.klass = klass
self.generateEnum(item, stream, indent2)
for item in ctors:
if item.isCtor:
item.klass = klass
self.generateMethod(item, stream, indent2,
name='__init__', docstring=klass.pyDocstring)
for item in public:
item.klass = klass
f = dispatch[item.__class__]
f(item, stream, indent2)
for item in protected:
item.klass = klass
f = dispatch[item.__class__]
f(item, stream, indent2)
stream.write('%s# end of class %s\n\n' % (indent, klassName))
def generateMemberVar(self, memberVar, stream, indent):
assert isinstance(memberVar, extractors.MemberVarDef)
if memberVar.ignored or piIgnored(memberVar):
return
stream.write('%s%s = property(None, None)\n' % (indent, memberVar.name))
def generateProperty(self, prop, stream, indent):
assert isinstance(prop, extractors.PropertyDef)
if prop.ignored or piIgnored(prop):
return
stream.write('%s%s = property(None, None)\n' % (indent, prop.name))
def generatePyProperty(self, prop, stream, indent):
assert isinstance(prop, extractors.PyPropertyDef)
if prop.ignored or piIgnored(prop):
return
stream.write('%s%s = property(None, None)\n' % (indent, prop.name))
def generateMethod(self, method, stream, indent, name=None, docstring=None):
assert isinstance(method, extractors.MethodDef)
for m in method.all(): # use the first not ignored if there are overloads
if not m.ignored or piIgnored(m):
method = m
break
else:
return
if method.isDtor:
return
name = name or method.pyName or method.name
if name in magicMethods:
name = magicMethods[name]
# write the method declaration
if method.isStatic:
stream.write('\n%s@staticmethod' % indent)
stream.write('\n%sdef %s' % (indent, name))
if method.hasOverloads():
if not method.isStatic:
stream.write('(self, *args, **kw)')
else:
stream.write('(*args, **kw)')
else:
argsString = method.pyArgsString
if not argsString:
argsString = '()'
if '->' in argsString:
pos = argsString.find(') ->')
argsString = argsString[:pos+1]
if '(' != argsString[0]:
pos = argsString.find('(')
argsString = argsString[pos:]
if not method.isStatic:
if argsString == '()':
argsString = '(self)'
else:
argsString = '(self, ' + argsString[1:]
argsString = argsString.replace('::', '.')
stream.write(argsString)
stream.write(':\n')
indent2 = indent + ' '*4
# docstring
if not docstring:
if hasattr(method, 'pyDocstring'):
docstring = method.pyDocstring
else:
docstring = ""
stream.write('%s"""\n' % indent2)
if docstring.strip():
stream.write(nci(docstring, len(indent2)))
stream.write('%s"""\n' % indent2)
def generateCppMethod(self, method, stream, indent=''):
assert isinstance(method, extractors.CppMethodDef)
self.generateMethod(method, stream, indent)
def generateCppMethod_sip(self, method, stream, indent=''):
assert isinstance(method, extractors.CppMethodDef_sip)
self.generateMethod(method, stream, indent)
def generatePyMethod(self, pm, stream, indent):
assert isinstance(pm, extractors.PyMethodDef)
if pm.ignored or piIgnored(pm):
return
if pm.isStatic:
stream.write('\n%s@staticmethod' % indent)
stream.write('\n%sdef %s' % (indent, pm.name))
stream.write(getattr(pm, 'piArgsString', pm.argsString))
stream.write(':\n')
indent2 = indent + ' '*4
stream.write('%s"""\n' % indent2)
stream.write(nci(pm.pyDocstring, len(indent2)))
stream.write('%s"""\n' % indent2)
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------