File: sip_generator.py

package info (click to toggle)
wxpython4.0 4.2.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 221,752 kB
  • sloc: cpp: 962,555; python: 230,573; ansic: 170,731; makefile: 51,756; sh: 9,342; perl: 1,564; javascript: 584; php: 326; xml: 200
file content (1059 lines) | stat: -rw-r--r-- 42,901 bytes parent folder | download
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
#---------------------------------------------------------------------------
# Name:        etgtools/sip_generator.py
# Author:      Robin Dunn
#
# Created:     3-Nov-2010
# Copyright:   (c) 2010-2020 by Total Control Software
# License:     wxWindows License
#---------------------------------------------------------------------------

"""
The generator class for creating SIP definition files from the data
objects produced by the ETG scripts.
"""

import sys, os, re
import etgtools.extractors as extractors
import etgtools.generators as generators
from etgtools.generators import nci, Utf8EncodingStream, textfile_open, wrapText


from buildtools.config import Config
cfg = Config(noWxConfig=True)

divider = '//' + '-'*75 + '\n'
phoenixRoot = cfg.ROOT_DIR

class SipGeneratorError(RuntimeError):
    pass



# This is a list of types that are used as return by value or by reference
# function return types that we need to ensure are actually using pointer
# types in their CppMethodDef or cppCode wrappers.
forcePtrTypes = [ 'wxString',
                  ]

#---------------------------------------------------------------------------

class SipWrapperGenerator(generators.WrapperGeneratorBase):

    def generate(self, module, destFile=None):
        stream = Utf8EncodingStream()

        # generate SIP code from the module and its objects
        self.generateModule(module, stream)

        # Write the contents of the stream to the destination file
        if not destFile:
            destFile = os.path.join(phoenixRoot, 'sip/gen', module.name + '.sip')
        with textfile_open(destFile, 'wt') as f:
            f.write(stream.getvalue())

    #-----------------------------------------------------------------------
    def generateModule(self, module, stream):
        assert isinstance(module, extractors.ModuleDef)

        # write the file header
        stream.write(divider + """\
// This file is generated by wxPython's SIP generator.  Do not edit by hand.
//
// Copyright: (c) 2020 by Total Control Software
// License:   wxWindows License
""")
        if module.name == module.module:
            stream.write("""
%%Module( name=%s.%s,
         keyword_arguments="All",
         use_argument_names=True,
         all_raise_py_exception=True,
         language="C++")
{
    %%AutoPyName(remove_leading="wx")
};

%%Copying
    Copyright: (c) 2020 by Total Control Software
    License:   wxWindows License
%%End

%%DefaultDocstringFormat(name="deindented")

""" % (module.package, module.name))

            if module.name.startswith('_'):
                doc = ''
                if module.docstring:
                    doc = '\n"""\n%s"""\n' % module.docstring
                stream.write("""\
%%Extract(id=pycode%s, order=5)
# This file is generated by wxPython's SIP generator.  Do not edit by hand.
#
# Copyright: (c) 2020 by Total Control Software
# License:   wxWindows License
%s
from .%s import *

%%End

""" % ( module.name, doc, module.name))

        else:
            stream.write("//\n// This file will be included by %s.sip\n//\n" % module.module)

        stream.write(divider)

        self.module_name = module.module
        # C++ code to be written to the module's header
        if module.headerCode:
            stream.write("\n%ModuleHeaderCode\n")
            for c in module.headerCode:
                stream.write('%s\n' % c)
            stream.write("%End\n\n")

        # %Imports and %Includes
        if module.imports:
            for i in module.imports:
                stream.write("%%Import %s.sip\n" % i)
            stream.write("\n")
        if module.includes:
            for i in module.includes:
                stream.write("%%Include %s.sip\n" % i)
            stream.write("\n")

        # C++ code to be written out to the generated module
        if module.cppCode:
            stream.write("%ModuleCode\n")
            for c in module.cppCode:
                stream.write('%s\n' % c)
            stream.write("%End\n")

        stream.write('\n%s\n' % divider)

        # Now generate each of the items in the module
        self.generateModuleItems(module, stream)

        # Add code for the module initialization sections.
        if module.preInitializerCode:
            stream.write('\n%s\n\n%%PreInitialisationCode\n' % divider)
            for i in module.preInitializerCode:
                stream.write('%s\n' % i)
            stream.write('%End\n')
        if module.initializerCode:
            stream.write('\n%s\n\n%%InitialisationCode\n' % divider)
            for i in module.initializerCode:
                stream.write('%s\n' % i)
            stream.write('%End\n')
        if module.postInitializerCode:
            stream.write('\n%s\n\n%%PostInitialisationCode\n' % divider)
            for i in module.postInitializerCode:
                stream.write('%s\n' % i)
            stream.write('%End\n')

        stream.write('\n%s\n' % divider)



    def generateModuleItems(self, module, stream):
        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:
                continue
            function = methodMap[item.__class__]
            function(item, stream)


    #-----------------------------------------------------------------------
    def generateFunction(self, function, stream, _needDocstring=True):
        assert isinstance(function, extractors.FunctionDef)
        if not function.ignored:
            stream.write('%s %s(' % (function.type, function.name))
            if function.items:
                stream.write('\n')
                self.generateParameters(function.items, stream, ' '*4)
            stream.write(')%s;\n' % self.annotate(function))

            if  _needDocstring:
                self.generateDocstring(function, stream, '')
                # We only write a docstring for the first overload, otherwise
                # SIP appends them all together.
                _needDocstring = False

            if function.preMethodCode:
                stream.write('%PreMethodCode\n')
                stream.write(nci(function.preMethodCode, 4))
                stream.write('%End\n')

            if function.cppCode:
                code, codeType = function.cppCode
                if codeType == 'sip':
                    stream.write('%MethodCode\n')
                    stream.write(nci(code, 4))
                    stream.write('%End\n')
                elif codeType == 'function':
                    ## raise NotImplementedError() # TODO: See generateMethod for an example, refactor to share code...
                    cm = extractors.CppMethodDef.FromMethod(function)
                    cm.body = code
                    self.generateCppMethod(cm, stream, "", skipDeclaration=True)
                    # generateCppMethod will have already done the overloads
                    # and virtual catcher code, so we can just return from
                    # here.
                    return
        for f in function.overloads:
            self.generateFunction(f, stream, _needDocstring)
        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:
                    return False
            return True

        for idx, param in enumerate(parameters):
            if param.ignored:
                continue
            stream.write(indent)
            stream.write('%s %s' % (param.type, param.name))
            stream.write(self.annotate(param))
            if param.default:
                stream.write(' = %s' % param.default)
            if not _lastParameter(idx):
                stream.write(',')
            stream.write('\n')


    #-----------------------------------------------------------------------
    def generateEnum(self, enum, stream, indent=''):
        assert isinstance(enum, extractors.EnumDef)
        if enum.ignored:
            return
        name = enum.name
        if name.startswith('@'):
            name = ''
        stream.write('%senum %s%s\n%s{\n' % (indent, name, self.annotate(enum), indent))
        values = []
        for v in enum.items:
            if v.ignored:
                continue
            values.append("%s    %s%s" % (indent, v.name, self.annotate(v)))
        stream.write(',\n'.join(values))
        stream.write('%s\n%s};\n\n' % (indent, indent))


    #-----------------------------------------------------------------------
    def generateGlobalVar(self, globalVar, stream):
        assert isinstance(globalVar, extractors.GlobalVarDef)
        if globalVar.ignored:
            return

        stream.write('%s %s' % (globalVar.type, globalVar.name))
        stream.write('%s;\n\n' % self.annotate(globalVar))


    #-----------------------------------------------------------------------
    def generateDefine(self, define, stream):
        assert isinstance(define, extractors.DefineDef)
        if define.ignored:
            return
        # We're assuming that the #define is either an integer or a string value,
        # so tell sip that's what it is.
        if '"' in define.value:
            stream.write('const char* %s;\n' % define.name)
        elif hasattr(define, 'type'):
            stream.write('const %s %s;\n' % (define.type, define.name))
        elif getattr(define, 'forcedInt', False):
            stream.write('%PostInitialisationCode\n')
            #stream.write('printf("**** %s: %%d\\n", %s);\n' % (define.name, define.name))
            stream.write(('    PyDict_SetItemString(sipModuleDict, "%s", '
                          'wxPyInt_FromLong(static_cast<int>(%s)));\n') %
                         (define.pyName, define.name))
            stream.write('%End\n')

        else:
            stream.write('const int %s;\n' % define.name)


    #-----------------------------------------------------------------------
    def generateTypedef(self, typedef, stream, indent=''):
        assert isinstance(typedef, extractors.TypedefDef)
        if typedef.ignored:
            return
        stream.write('%stypedef %s %s' % (indent, typedef.type, typedef.name))
        stream.write('%s;\n\n' % self.annotate(typedef))


    #-----------------------------------------------------------------------
    def generateWigCode(self, wig, stream, indent=''):
        assert isinstance(wig, extractors.WigCode)
        stream.write(nci(wig.code, len(indent), False))
        stream.write('\n\n')


    #-----------------------------------------------------------------------
    def generatePyCode(self, pc, stream, indent=''):
        assert isinstance(pc, extractors.PyCodeDef)
        if hasattr(pc, 'klass') and isinstance(pc.klass, extractors.ClassDef) and pc.klass.generatingInClass:
            pc.klass.generateAfterClass.append(pc)
        else:
            if len(indent) == 0:
                stream.write('%%Extract(id=pycode%s' % self.module_name)
                if pc.order is not None:
                    stream.write(', order=%d' % pc.order)
                stream.write(')\n')

            stream.write(nci(pc.code, len(indent)))

            if len(indent) == 0:
                stream.write('\n%End\n\n')

    #-----------------------------------------------------------------------
    def generatePyProperty(self, prop, stream, indent=''):
        assert isinstance(prop, extractors.PyPropertyDef)
        if prop.ignored:
            return
        if isinstance(prop.klass, extractors.ClassDef) and prop.klass.generatingInClass:
            prop.klass.generateAfterClass.append(prop)
        elif isinstance(prop.klass, extractors.PyClassDef):
            stream.write('%s%s = property(%s' % (indent, prop.name, prop.getter))
            if prop.setter:
                stream.write(', %s' % prop.setter)
            stream.write(')\n')
        else:
            klassName = prop.klass.pyName or prop.klass.name
            if '.' in prop.getter:
                getter = prop.getter
            else:
                getter = '%s.%s' % (klassName, prop.getter)
            if prop.setter:
                if '.' in prop.setter:
                    setter = prop.setter
                else:
                    setter = '%s.%s' % (klassName, prop.setter)

            stream.write("%%Extract(id=pycode%s)\n" % self.module_name)
            stream.write("%s.%s = property(%s" % (klassName, prop.name, getter))
            if prop.setter:
                stream.write(", %s" % setter)
            stream.write(")\n")
            stream.write('%End\n\n')


    #-----------------------------------------------------------------------
    def generatePyFunction(self, pf, stream, indent=''):
        assert isinstance(pf, extractors.PyFunctionDef)
        if len(indent) == 0:
            stream.write('%%Extract(id=pycode%s' % self.module_name)
            if pf.order is not None:
                stream.write(', order=%d' % pf.order)
            stream.write(')\n')
        if pf.deprecated:
            if isinstance(pf.deprecated, int):
                stream.write('%s@wx.deprecated\n' % indent)
            else:
                stream.write('%s@wx.deprecatedMsg("%s")\n' % (indent, pf.deprecated))
        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(nci(pf.body, len(indent2)))
        if len(indent) == 0:
            stream.write('\n%End\n')
        stream.write('\n')


    #-----------------------------------------------------------------------
    def generatePyClass(self, pc, stream, indent=''):
        assert isinstance(pc, extractors.PyClassDef)
        if len(indent) == 0:
            stream.write('%%Extract(id=pycode%s' % self.module_name)
            if pc.order is not None:
                stream.write(', order=%d' % pc.order)
            stream.write(')\n')

        # write the class declaration and docstring
        if pc.deprecated:
            if isinstance(pc.deprecated, int):
                stream.write('%s@wx.deprecated\n' % indent)
            else:
                stream.write('%s@wx.deprecatedMsg("%s")\n' % (indent, pc.deprecated))
        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)

        if len(indent) == 0:
            stream.write('\n%End\n')
        stream.write('\n')


    #-----------------------------------------------------------------------
    def generateClass(self, klass, stream, indent=''):
        assert isinstance(klass, extractors.ClassDef)
        if klass.ignored:
            return

        # Propagate preMethodCode setting to the ctors
        if klass.preMethodCode:
            for item in klass.allItems():
                if isinstance(item, extractors.MethodDef) and item.isCtor:
                    item.preMethodCode = klass.preMethodCode

        # write the class header
        if klass.templateParams:
            stream.write('%stemplate<%s>\n' % (indent, ', '.join(klass.templateParams)))
        stream.write('%s%s %s' % (indent, klass.kind, klass.name))
        if klass.bases:
            stream.write(' : ')
            stream.write(', '.join(klass.bases))
        stream.write(self.annotate(klass))
        stream.write('\n%s{\n' % indent)
        indent2 = indent + ' '*4

        if klass.briefDoc is not None:
            self.generateDocstring(klass, stream, indent2)

        if klass.includes:
            stream.write('%s%%TypeHeaderCode\n' % indent2)
            for inc in klass.includes:
                stream.write('%s    #include <%s>\n' % (indent2, inc))
            stream.write('%s%%End\n\n' % indent2)

        # C++ code to be written to the Type's header
        if klass.headerCode:
            stream.write("%s%%TypeHeaderCode\n" % indent2)
            for c in klass.headerCode:
                stream.write(nci(c, len(indent2)+4))
            stream.write("%s%%End\n" % indent2)

        # C++ code to be written out to the this Type's wrapper code module
        if klass.cppCode:
            stream.write("%s%%TypeCode\n" % indent2)
            for c in klass.cppCode:
                stream.write(nci(c, len(indent2)+4))
            stream.write("%s%%End\n" % indent2)

        # C++ code to create a new instance of this class
        if klass.instanceCode:
            stream.write("%s%%InstanceCode\n" % indent2)
            stream.write(nci(klass.instanceCode, len(indent2)+4))
            stream.write("%s%%End\n" % indent2)

        # is the generator currently inside the class or after it?
        klass.generatingInClass = True

        # Split the items into public and protected groups
        ctors = [i for i in klass if
                    isinstance(i, extractors.MethodDef) and
                    i.protection == 'public' and (i.isCtor or i.isDtor)]
        enums = [i for i in klass if
                    isinstance(i, extractors.EnumDef) and
                    i.protection == 'public']
        public = [i for i in klass if i.protection == 'public' and i not in ctors+enums]
        protected = [i for i in klass if i.protection == 'protected']
        private = [i for i in klass if i.protection == 'private']

        if klass.kind == 'class':
            stream.write('%spublic:\n' % indent)

        # Write enums first since they may be used as default values in
        # methods or in nested classes
        for item in enums:
            self.dispatchClassItem(klass, item, stream, indent2)

        # Next do inner classes
        for item in klass.innerclasses:
            if klass.kind == 'class':
                stream.write('%s%s:\n' % (indent, item.protection))
            item.klass = klass
            self.generateClass(item, stream, indent2)

        # and then the ctors and the rest of the items in the class
        for item in ctors:
            self.dispatchClassItem(klass, item, stream, indent2)

        for item in public:
            self.dispatchClassItem(klass, item, stream, indent2)

        if protected and [i for i in protected if not i.ignored]:
            stream.write('\nprotected:\n')
            for item in protected:
                self.dispatchClassItem(klass, item, stream, indent2)

        if private and [i for i in private if not i.ignored]:
            stream.write('\nprivate:\n')
            for item in private:
                self.dispatchClassItem(klass, item, stream, indent2)

        if klass.convertFromPyObject:
            self.generateConvertCode('%ConvertToTypeCode',
                                     klass.convertFromPyObject,
                                     stream, indent + ' '*4)

        if klass.convertToPyObject:
            self.generateConvertCode('%ConvertFromTypeCode',
                                     klass.convertToPyObject,
                                     stream, indent + ' '*4)

        stream.write('%s};  // end of class %s\n\n\n' % (indent, klass.name))

        # Now generate anything that was deferred until after the class is finished
        klass.generatingInClass = False
        for item in klass.generateAfterClass:
            self.dispatchClassItem(klass, item, stream, indent)



    def dispatchClassItem(self, klass, item, stream, indent):
        dispatch = {
            extractors.TypedefDef       : self.generateTypedef,
            extractors.MemberVarDef     : self.generateMemberVar,
            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,
            }
        item.klass = klass
        f = dispatch[item.__class__]
        f(item, stream, indent)


    def generateConvertCode(self, kind, code, stream, indent):
        stream.write('%s%s\n' % (indent, kind))
        stream.write(nci(code, len(indent)+4))
        stream.write('%s%%End\n' % indent)


    def generateMemberVar(self, memberVar, stream, indent):
        assert isinstance(memberVar, extractors.MemberVarDef)
        if memberVar.ignored:
            return
        stream.write('%s%s %s' % (indent, memberVar.type, memberVar.name))
        stream.write(self.annotate(memberVar))
        if memberVar.getCode or memberVar.setCode:
            stream.write('\n%s{\n' % (indent,))
            if memberVar.getCode:
                stream.write('%s%%GetCode\n' % (indent))
                stream.write(nci(memberVar.getCode, len(indent)+4))
                stream.write('%s%%End\n' % (indent))
            if memberVar.setCode:
                stream.write('%s%%SetCode\n' % (indent))
                stream.write(nci(memberVar.setCode, len(indent)+4))
                stream.write('%s%%End\n' % (indent))
            stream.write('%s}' % (indent,))
        stream.write(';\n\n')


    def generateProperty(self, prop, stream, indent):
        assert isinstance(prop, extractors.PropertyDef)
        if prop.ignored:
            return
        stream.write('%s%%Property(name=%s, get=%s' % (indent, prop.name, prop.getter))
        if prop.setter:
            stream.write(', set=%s' % prop.setter)
        stream.write(')')
        if prop.briefDoc:
            stream.write(' // %s' % prop.briefDoc)
        stream.write('\n')


    def generateDocstring(self, item, stream, indent):
        item.pyDocstring = ""

        if item.name.startswith('operator'):
            return  # Apparently sip doesn't like operators to have docstrings...

        # get the docstring text
        text = nci(extractors.flattenNode(item.briefDoc, False))
        text = wrapText(text, item.pyName or item.name)


        #if isinstance(item, extractors.ClassDef):
        #    # append the function signatures for the class constructors (if any) to the class' docstring
        #    try:
        #        ctor = item.find(item.name)
        #        sigs = ctor.collectPySignatures()
        #        if sigs:
        #            text += '\n' + '\n'.join(sigs)
        #    except extractors.ExtractorError:
        #        pass
        #else:
        #    # Prepend function signature string(s) for functions and methods
        #    sigs = item.collectPySignatures()
        #    if sigs:
        #        if text:
        #            text = '\n\n' + text
        #        text = '\n'.join(sigs) + text

        sigs = None
        if isinstance(item, extractors.ClassDef):
            try:
                ctor = item.find(item.name)
                sigs = ctor.collectPySignatures()
            except extractors.ExtractorError:
                pass
        else:
            sigs = item.collectPySignatures()
        if sigs:
            if text:
                text = '\n\n' + text
            text = '\n'.join(sigs) + text

        # write the docstring directive and the text
        stream.write('%s%%Docstring\n' % indent)
        stream.write(nci(text, len(indent)+4))
        stream.write('%s%%End\n' % indent)

        # and save the docstring back into item in case it is needed by other
        # generators later on
        item.pyDocstring = nci(text)


    def generateMethod(self, method, stream, indent):
        assert isinstance(method, extractors.MethodDef)
        _needDocstring = getattr(method, '_needDocstring', True)
        checkOverloads = True
        if not method.ignored:
            if method.isVirtual:
                stream.write("%svirtual\n" % indent)
            if method.isStatic:
                stream.write("%sstatic\n" % indent)
            if method.isCtor or method.isDtor:
                stream.write('%s%s(' % (indent, method.name))
            else:
                stream.write('%s%s %s(' % (indent, method.type, method.name))
            if method.items:
                stream.write('\n')
                self.generateParameters(method.items, stream, indent+' '*4)
                stream.write(indent)
            stream.write(')')
            if method.isConst:
                stream.write(' const')
            if method.isPureVirtual:
                stream.write(' = 0')
            cppSig = " [ %s ]" % method.cppSignature if method.cppSignature else ""
            if cppSig:
                stream.write(cppSig)
            stream.write('%s;\n' % self.annotate(method))

            if  _needDocstring and not (method.isCtor or method.isDtor):
                self.generateDocstring(method, stream, indent)
                # We only write a docstring for the first overload, otherwise
                # SIP appends them all together.
                _needDocstring = False

            if method.preMethodCode:
                stream.write('%s%%PreMethodCode\n' % indent)
                stream.write(nci(method.preMethodCode, len(indent)+4))
                stream.write('%s%%End\n' % indent)

            if method.cppCode:
                #checkOverloads = False   ## SIP now allows overloads to have %MethodCode
                code, codeType = method.cppCode
                if codeType == 'sip':
                    stream.write('%s%%MethodCode\n' % indent)
                    stream.write(nci(code, len(indent)+4))
                    stream.write('%s%%End\n' % indent)
                elif codeType == 'function':
                    cm = extractors.CppMethodDef.FromMethod(method)
                    cm.body = code
                    self.generateCppMethod(cm, stream, indent, skipDeclaration=True)
                    # generateCppMethod will have already done the overloads
                    # and virtual catcher code, so we can just return from
                    # here.
                    return

            if method.virtualCatcherCode:
                stream.write('%s%%VirtualCatcherCode\n' % indent)
                stream.write(nci(method.virtualCatcherCode, len(indent)+4))
                stream.write('%s%%End\n' % indent)

            stream.write('\n')

        if checkOverloads and method.overloads:
            for m in method.overloads:
                m._needDocstring = _needDocstring
                self.dispatchClassItem(method.klass, m, stream, indent)


    def generateCppMethod(self, method, stream, indent='', skipDeclaration=False):
        # Add a new C++ method to a class. This one adds the code as a
        # separate function and then adds a call to that function in the
        # MethodCode directive.

        def _removeIgnoredParams(argsString, paramList):
            # if there are ignored parameters adjust the argsString to match
            lastP = argsString.rfind(')')
            args = argsString[:lastP].strip('()').split(',')
            for idx, p in enumerate(paramList):
                if p.ignored:
                    args[idx] = ''
            args = [a for a in args if a != '']
            return '(' + ', '.join(args) + ')'

        assert isinstance(method, extractors.CppMethodDef)
        if method.ignored:
            return

        _needDocstring = getattr(method, '_needDocstring', True)
        argsString = _removeIgnoredParams(method.argsString, method.items)
        lastP = argsString.rfind(')')
        pnames = argsString[:lastP].strip('()').split(',')
        for idx, pn in enumerate(pnames):
            # take only the part before the =, if there is one
            name = pn.split('=')[0].strip()
            # remove annotations
            name = re.sub('/[A-Za-z]*/', '', name)
            name = name.strip()
            # now get just the part after any space, * or &, which should be
            # the parameter name
            name = re.split(r'[ \*\&]+', name)[-1]
            pnames[idx] = name
        pnames = ', '.join(pnames)
        typ = method.type

        if not skipDeclaration:
            cppSig = " [ %s ]" % method.cppSignature if method.cppSignature else ""
            # First insert the method declaration
            if method.isCtor or method.isDtor:
                virtual = 'virtual ' if method.isVirtual else ''
                stream.write('%s%s%s%s%s%s;\n' %
                             (indent, virtual, method.name, argsString, self.annotate(method), cppSig))
            else:
                constMod = " const" if method.isConst else ""
                static = "static " if method.isStatic else ""
                virtual = "virtual " if method.isVirtual else ""
                pure = " = 0" if method.isPureVirtual else ""
                stream.write('%s%s%s%s %s%s%s%s%s%s;\n' %
                             (indent, static, virtual, typ,
                              method.name, argsString, constMod, pure, self.annotate(method), cppSig))

            # write the docstring
            if  _needDocstring and not (method.isCtor or method.isDtor):
                self.generateDocstring(method, stream, indent)
                # We only write a docstring for the first overload, otherwise
                # SIP appends them all together.
                _needDocstring = False

        klass = method.klass
        if klass:
            assert isinstance(klass, extractors.ClassDef)

        # create the new function
        fstream = Utf8EncodingStream()  # using a new stream so we can do the actual write a little later
        lastP = argsString.rfind(')')
        fargs = argsString[:lastP].strip('()').split(',')
        for idx, arg in enumerate(fargs):
            # take only the part before the =, if there is one
            arg = arg.split('=')[0].strip()
            arg = arg.replace('&', '*')  # SIP will always want to use pointers for parameters
            arg = re.sub('/[A-Za-z]*/', '', arg)  # remove annotations
            fargs[idx] = arg
        fargs = ', '.join(fargs)
        if method.isCtor:
            fname = '_%s_ctor' % klass.name
            fargs = '(%s)' % fargs
            fstream.write('%s%%TypeCode\n' % indent)
            typ = klass.name
            if method.useDerivedName:
                typ = 'sip'+klass.name
                fstream.write('%sclass %s;\n' % (indent, typ))   # forward declare the derived class
            fstream.write('%s%s* %s%s\n%s{\n' % (indent, typ, fname, fargs, indent))
            fstream.write(nci(method.body, len(indent)+4))
            fstream.write('%s}\n' % indent)
            fstream.write('%s%%End\n' % indent)

        elif method.isDtor:
            fname = '_%s_dtor' % klass.name
            fargs = '(%s* self)' % klass.name
            fstream.write('%s%%TypeCode\n' % indent)
            fstream.write('%svoid %s%s\n%s{\n' % (indent, fname, fargs, indent))
            fstream.write(nci(method.body, len(indent)+4))
            fstream.write('%s}\n' % indent)
            fstream.write('%s%%End\n' % indent)

        else:
            if klass:
                fname = '_%s_%s' % (klass.name, method.name)
                if method.isStatic:
                    # If the method is static then there is no sipCpp to send to
                    # the new function, so it should not have a self parameter.
                    fargs = '(%s)' % fargs
                else:
                    if fargs:
                        fargs = ', ' + fargs
                    selfConst = ''
                    if method.isConst:
                        selfConst = 'const '
                    fargs = '(%s%s* self%s)' % (selfConst, klass.name, fargs)
                fstream.write('%s%%TypeCode\n' % indent)
            else:
                fname = '_%s_function' % method.name
                fargs = '(%s)' % fargs
                fstream.write('%s%%ModuleCode\n' % indent)

            # If the return type is in the forcePtrTypes list then make sure
            # that it is a pointer, not a return by value or reference, since
            # SIP almost always deals with pointers to newly allocated
            # objects.
            typPtr = method.type
            if typPtr in forcePtrTypes:
                if '&' in typPtr:
                    typPtr.replace('&', '*')
                elif '*' not in typPtr:
                    typPtr += '*'

            fstream.write('%s%s %s%s\n%s{\n' % (indent, typPtr, fname, fargs, indent))
            fstream.write(nci(method.body, len(indent)+4))
            fstream.write('%s}\n' % indent)
            fstream.write('%s%%End\n' % indent)

        # Write the code that will call the new function
        stream.write('%s%%MethodCode\n' % indent)
        stream.write(indent+' '*4)
        if method.isCtor:
            # _THREAD macros are intentionally not used in this case
            stream.write('PyErr_Clear();\n')
            stream.write('%ssipCpp = %s(%s);\n' % (indent+' '*4, fname, pnames))

        elif method.isDtor:
            stream.write('PyErr_Clear();\n')
            stream.write('%sPy_BEGIN_ALLOW_THREADS\n' % (indent+' '*4))
            stream.write(indent+' '*4)
            stream.write('%s(sipCpp);\n' % fname)
            stream.write('%sPy_END_ALLOW_THREADS\n' % (indent+' '*4))

        else:
            stream.write('PyErr_Clear();\n')
            stream.write('%sPy_BEGIN_ALLOW_THREADS\n' % (indent+' '*4))
            stream.write(indent+' '*4)
            if method.type != 'void':
                stream.write('sipRes = ')
            if klass:
                if method.isStatic:
                    # If the method is static then there is no sipCpp to send to
                    # the new function, so it should not have a self parameter.
                    stream.write('%s(%s);\n' % (fname, pnames))
                else:
                    if pnames:
                        pnames = ', ' + pnames
                    if method.isSlot:
                        argname = 'a0'
                    else:
                        argname = 'sipCpp'
                    stream.write('%s(%s%s);\n' % (fname, argname, pnames))
            else:
                stream.write('%s(%s);\n' % (fname, pnames))
            stream.write('%sPy_END_ALLOW_THREADS\n' % (indent+' '*4))
            stream.write('%sif (PyErr_Occurred()) sipIsErr = 1;\n' % (indent+' '*4))
        stream.write('%s%%End\n' % indent)

        if method.virtualCatcherCode:
            stream.write('%s%%VirtualCatcherCode\n' % indent)
            stream.write(nci(method.virtualCatcherCode, len(indent)+4))
            stream.write('%s%%End\n' % indent)

        # and finally, add the new function itself
        stream.write(fstream.getvalue())
        stream.write('\n')

        if method.overloads:
            for m in method.overloads:
                m._needDocstring = _needDocstring
                self.dispatchClassItem(method.klass, m, stream, indent)



    def generateCppMethod_sip(self, method, stream, indent=''):
        # Add a new C++ method to a class without the extra generated
        # function, so SIP specific stuff can be done in the function body.
        assert isinstance(method, extractors.CppMethodDef_sip)
        if method.ignored:
            return
        _needDocstring = getattr(method, '_needDocstring', True)
        cppSig = " [ %s ]" % method.cppSignature if method.cppSignature else ""
        if method.isCtor:
            stream.write('%s%s%s%s%s;\n' %
                         (indent, method.name, method.argsString, self.annotate(method), cppSig))
        else:
            virtual = "virtual " if method.isVirtual else ""
            stream.write('%s%s%s %s%s%s%s;\n' %
                         (indent, virtual, method.type, method.name, method.argsString,
                          self.annotate(method), cppSig))
        # write the docstring
        if  _needDocstring and not (method.isCtor or method.isDtor):
            self.generateDocstring(method, stream, indent)
            # We only write a docstring for the first overload, otherwise
            # SIP appends them all together.
            _needDocstring = False
        stream.write('%s%%MethodCode\n' % indent)
        if not (method.isCtor or method.isDtor):
            stream.write('%sPyErr_Clear();\n' % (indent+' '*4))
            stream.write('%sPy_BEGIN_ALLOW_THREADS\n' % (indent+' '*4))
        stream.write(nci(method.body, len(indent)+4))
        if not (method.isCtor or method.isDtor):
            stream.write('%sPy_END_ALLOW_THREADS\n' % (indent+' '*4))
            stream.write('%sif (PyErr_Occurred()) sipIsErr = 1;\n' % (indent+' '*4))
        stream.write('%s%%End\n\n' % indent)



    def generatePyMethod(self, pm, stream, indent):
        assert isinstance(pm, extractors.PyMethodDef)
        if pm.ignored:
            return
        if pm.klass.generatingInClass:
            pm.klass.generateAfterClass.append(pm)
        else:
            klassName = pm.klass.pyName or pm.klass.name
            stream.write("%%Extract(id=pycode%s)\n" % self.module_name)
            stream.write("def _%s_%s%s:\n" % (klassName, pm.name, pm.argsString))
            pm.pyDocstring = ""
            if pm.briefDoc:
                doc = nci(pm.briefDoc)
                pm.pyDocstring = doc
                stream.write(nci('"""\n%s"""\n' % doc, 4))
            stream.write(nci(pm.body, 4))
            stream.write('%s.%s = ' % (klassName, pm.name))
            end = '\n'
            if pm.isStatic:
                stream.write('staticmethod(')
                end = ')' + end
            if pm.deprecated:
                stream.write('wx.deprecated(')
                end = ')' + end
            stream.write('_%s_%s' % (klassName, pm.name))
            if pm.deprecated and not isinstance(pm.deprecated, int):
                stream.write(', "%s"' % pm.deprecated)
            stream.write(end)
            stream.write('del _%s_%s\n' % (klassName, pm.name))
            stream.write('%End\n\n')


    #-----------------------------------------------------------------------

    def annotate(self, item):
        annotations = []
        if item.pyName:
            if not getattr(item, 'wxDropped', False):
                annotations.append('PyName=%s' % item.pyName)

        if isinstance(item, extractors.ParamDef):
            if item.out:
                annotations.append('Out')
            if item.inOut:
                annotations.extend(['In', 'Out'])
            if item.array:
                annotations.append('Array')
            if item.arraySize:
                annotations.append('ArraySize')
            if item.keepReference:
                annotations.append('KeepReference')
            if item.constrained:
                annotations.append('Constrained')

        if isinstance(item, (extractors.ParamDef, extractors.FunctionDef)):
            if item.transfer:
                annotations.append('Transfer')
            if item.transferBack:
                annotations.append('TransferBack')
            if item.transferThis:
                annotations.append('TransferThis')
            if item.pyInt:
                annotations.append('PyInt')

        if isinstance(item, extractors.VariableDef):
            if item.pyInt:
                annotations.append('PyInt')
            if item.noSetter:
                annotations.append('NoSetter')

        if isinstance(item, extractors.TypedefDef):
            if item.noTypeName:
                annotations.append('NoTypeName')

        if isinstance(item, extractors.FunctionDef):
            if item.deprecated:
                annotations.append('Deprecated')
            if item.factory:
                annotations.append('Factory')
            if item.pyReleaseGIL:
                annotations.append('ReleaseGIL')
            if item.pyHoldGIL:
                annotations.append('HoldGIL')
            if item.noCopy:
                annotations.append('NoCopy')
            if item.noArgParser:
                annotations.append('NoArgParser')

        if isinstance(item, extractors.MethodDef):
            if item.defaultCtor:
                annotations.append('Default')
            if item.noDerivedCtor:
                annotations.append('NoDerived')

        if isinstance(item, extractors.ClassDef):
            if item.abstract:
                annotations.append('Abstract')
            if item.allowNone:
                annotations.append('AllowNone')
            if item.deprecated:
                annotations.append('Deprecated')
            if item.external:
                annotations.append('External')
            if item.noDefCtor:
                annotations.append('NoDefaultCtors')
            if item.singleton:
                annotations.append('DelayDtor')

        if annotations:
            return '   /%s/' % ', '.join(annotations)
        else:
            return ''

#---------------------------------------------------------------------------