-
Notifications
You must be signed in to change notification settings - Fork 39
/
ServiceGenerator.py
2542 lines (2436 loc) · 128 KB
/
ServiceGenerator.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
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
import os
import time
import logging
import textwrap
def CamelCase(input):
words = input.replace('_', '-').split('-')
name = ''
for w in words:
name += w.capitalize()
return name
def escape_string(instring):
s1 = instring
s1 = s1.replace('\\', '\\\\')
s1 = s1.replace("'", "\\'")
return s1
class ServiceApiGenerator(object):
def __init__(self, parser_generator, root):
self._PGenr = parser_generator
self._genStandAlone = True
self._xsd_root = root
def setLanguage(self, lang):
if (lang == 'py'):
self._LangGenr = PyGenerator(self._PGenr)
elif (lang == 'c++'):
self._LangGenr = CppGenerator(self._PGenr)
def Generate(self, gen_filepath_pfx):
self.generate(self._xsd_root, None, gen_filepath_pfx + ".py", genStandAlone = False)
def generate(self, root, infile, outfileName, genStandAlone = True):
self._genStandAlone = genStandAlone
# Create an output file.
# Note that even if the user does not request an output file,
# we still need to go through the process of generating classes
# because it produces data structures needed during generation of
# subclasses.
outfile = None
if outfileName:
outfile = self._PGenr.makeFile(outfileName)
if not outfile:
outfile = os.tmpfile()
wrt = outfile.write
processed = []
if genStandAlone:
self._LangGenr.generateHeader(wrt, self._PGenr.prefix)
#generateSimpleTypes(outfile, prefix, SimpleTypeDict)
self._PGenr.DelayedElements = []
self._PGenr.DelayedElements_subclass = []
elements = root.getChildren()
outfile.write('"""\n')
outfile.write("This module defines the classes for types defined in :doc:`services.xsd`\n")
outfile.write('"""\n')
outfile.write("import json\n")
#outfile.write("from generatedssuper import *\n")
self._generateFromTree(wrt, self._PGenr.prefix, elements, processed)
while 1:
if len(self._PGenr.DelayedElements) <= 0:
break
element = self._PGenr.DelayedElements.pop()
name = element.getCleanName()
if name not in processed:
processed.append(name)
self._generateClasses(wrt, prefix, element, 1)
#
# Generate the elements that were postponed because we had not
# yet generated their base class.
while 1:
if len(self._PGenr.PostponedExtensions) <= 0:
break
element = self._PGenr.PostponedExtensions.pop()
parentName, parent = self._PGenr.getParentName(element)
if parentName:
if (parentName in self._PGenr.AlreadyGenerated or
parentName in self._PGenr.SimpleTypeDict.keys()):
self._generateClasses(wrt, prefix, element, 1)
else:
self._PGenr.PostponedExtensions.insert(0, element)
#
# Disable the generation of SAX handler/parser.
# It failed when we stopped putting simple types into ElementDict.
# When there are duplicate names, the SAX parser probably does
# not work anyway.
#NN self._generateMain(outfile, self._PGenr.prefix, root)
if genStandAlone:
self._LangGenr.generateMain(outfile, self._PGenr.prefix, root)
outfile.close()
if self._PGenr.subclassFilename:
self._generateSubclasses(root, self._PGenr.subclassFilename, behaviorFilename,
prefix, superModule)
# Generate __all__. When using the parser as a module it is useful
# to isolate important classes from internal ones. This way one
# can do a reasonably safe "from parser import *"
if outfileName:
exportableClassList = ['"%s"' % self._PGenr.mapName(self._PGenr.cleanupName(CamelCase(name)))
for name in self._PGenr.AlreadyGenerated]
exportableClassList.sort()
exportableClassNames = ',\n '.join(exportableClassList)
exportLine = "\n__all__ = [\n %s\n ]\n" % exportableClassNames
outfile = open(outfileName, "a")
outfile.write(exportLine)
outfile.close()
def _generateMain(self, outfile, prefix, root):
name = self._PGenr.RootElement or root.getChildren()[0].getName()
elType = self._PGenr.cleanupName(root.getChildren()[0].getType())
if self._PGenr.RootElement:
rootElement = self._PGenr.RootElement
else:
rootElement = elType
params = {
'prefix': prefix,
'cap_name': self._PGenr.cleanupName(self._PGenr.make_gs_name(name)),
'name': name,
'cleanname': self._PGenr.cleanupName(name),
'module_name': os.path.splitext(os.path.basename(outfile.name))[0],
'root': rootElement,
'namespacedef': self._PGenr.Namespacedef,
}
s1 = self._PGenr.TEMPLATE_MAIN % params
outfile.write(s1)
def _generateFromTree(self, wrt, prefix, elements, processed):
for element in elements:
name = element.getCleanName()
if 1: # if name not in processed:
processed.append(name)
self._generateClasses(wrt, prefix, element, 0)
children = element.getChildren()
if children:
self._generateFromTree(wrt, prefix, element.getChildren(), processed)
def _generateClasses(self, wrt, prefix, element, delayed):
logging.debug("Generating class for: %s" % element)
parentName, base = self._PGenr.getParentName(element)
logging.debug("Element base: %s" % base)
if not element.isExplicitDefine():
logging.debug("Not an explicit define, returning.")
return
# If this element is an extension (has a base) and the base has
# not been generated, then postpone it.
if parentName:
if (parentName not in self._PGenr.AlreadyGenerated and
parentName not in self._PGenr.SimpleTypeDict.keys()):
self._PGenr.PostponedExtensions.append(element)
return
if element.getName() in self._PGenr.AlreadyGenerated:
return
self._PGenr.AlreadyGenerated.append(element.getName())
if element.getMixedExtensionError():
err_msg('*** Element %s extension chain contains mixed and non-mixed content. Not generated.\n' % (
element.getName(), ))
return
self._PGenr.ElementsForSubclasses.append(element)
name = element.getCleanName()
self._LangGenr.generateClassDefLine(wrt, parentName, prefix, name)
# If this element has documentation, generate a doc-string.
if element.documentation:
self._LangGenr.generateElemDoc(wrt, element)
if self._PGenr.UserMethodsModule or self._PGenr.MemberSpecs:
self._LangGenr.generateMemberSpec(wrt, element)
#LG wrt(' subclass = None\n')
parentName, parent = self._PGenr.getParentName(element)
superclass_name = 'None'
if parentName and parentName in self._PGenr.AlreadyGenerated:
superclass_name = self._PGenr.mapName(self._PGenr.cleanupName(parentName))
self._LangGenr.generateSubSuperInit(wrt, superclass_name)
self._LangGenr.generateClassVars(wrt, element.getName())
s4 = self._LangGenr.generateCtor(wrt, element)
self._LangGenr.generateFactory(wrt, prefix, name)
self._generateGettersAndSetters(wrt, element)
if self._PGenr.Targetnamespace in self._PGenr.NamespacesDict:
namespace = self._PGenr.NamespacesDict[self._PGenr.Targetnamespace]
else:
namespace = ''
#self._generateExportFn(wrt, prefix, element, namespace)
#self._generateExportLiteralFn(wrt, prefix, element)
self._generateExportDictFn(wrt, prefix, element)
self._generateExportDict2Fn(wrt, prefix, element)
#self._generateBuildFn(wrt, prefix, element, delayed)
#self._generateUserMethods(wrt, element)
self._LangGenr.generateEnd(wrt, name, s4)
# end _generateClasses
def _generateGettersAndSetters(self, wrt, element):
generatedSimpleTypes = []
childCount = self._PGenr.countChildren(element, 0)
for child in element.getChildren():
if child.getType() == self._PGenr.AnyTypeIdentifier:
self._LangGenr.generateGetterAnyType(wrt)
self._LangGenr.generateSetterAnyType(wrt)
if child.getMaxOccurs() > 1:
self._LangGenr.generateAdderAnyType(wrt)
self._LangGenr.generateInserterAnyType(wrt)
else:
name = self._PGenr.cleanupName(child.getCleanName())
unmappedName = self._PGenr.cleanupName(child.getName())
capName = self._PGenr.make_gs_name(unmappedName)
getMaxOccurs = child.getMaxOccurs()
childType = child.getType()
self._LangGenr.generateGetter(wrt, capName, name, childType)
self._LangGenr.generateSetter(wrt, capName, name, childType)
if child.getMaxOccurs() > 1:
self._LangGenr.generateAdder(wrt, capName, name)
self._LangGenr.generateInserter(wrt, capName, name)
if self._PGenr.GenerateProperties:
self._LangGenr.generateProperty(wrt, unmappedName, capName, name)
#
# If this child is defined in a simpleType, then generate
# a validator method.
typeName = None
name = self._PGenr.cleanupName(child.getName())
mappedName = self._PGenr.mapName(name)
childType = child.getType()
childType1 = child.getSimpleType()
if not child.isComplex() and childType1 and childType1 in self._PGenr.SimpleTypeDict:
childType = self._PGenr.SimpleTypeDict[childType1].getBase()
elif mappedName in self._PGenr.ElementDict:
childType = self._PGenr.ElementDict[mappedName].getType()
typeName = child.getSimpleType()
if (typeName and
typeName in self._PGenr.SimpleTypeDict and
typeName not in generatedSimpleTypes):
generatedSimpleTypes.append(typeName)
self._LangGenr.generateValidator(wrt, typeName)
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = self._PGenr.cleanupName(attrDef.getName().replace(':', '_'))
mappedName = self._PGenr.mapName(name)
gsName = self._PGenr.make_gs_name(name)
self._LangGenr.generateGetter(wrt, gsName, mappedName)
self._LangGenr.generateSetter(wrt, gsName, mappedName)
if self._PGenr.GenerateProperties:
self._LangGenr.generateProperty(wrt, name, gsName, gsName)
typeName = attrDef.getType()
if (typeName and
typeName in self._PGenr.SimpleTypeDict and
typeName not in generatedSimpleTypes):
generatedSimpleTypes.append(typeName)
self._LangGenr.generateValidator(wrt, typeName)
#LG TODO put in lang specific parts for these if needed
if element.getSimpleContent() or element.isMixed():
wrt(' def get%s_(self): return self.valueOf_\n' % (
self._PGenr.make_gs_name('valueOf'), ))
wrt(' def set%s_(self, valueOf_): self.valueOf_ = valueOf_\n' % (
self._PGenr.make_gs_name('valueOf'), ))
if element.getAnyAttribute():
wrt(' def get%s_(self): return self.anyAttributes_\n' % (
self._PGenr.make_gs_name('anyAttributes'), ))
wrt(' def set%s_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_\n' % (
self._PGenr.make_gs_name('anyAttributes'), ))
if element.getExtended():
wrt(' def get%s_(self): return self.extensiontype_\n' % (
self._PGenr.make_gs_name('extensiontype'), ))
wrt(' def set%s_(self, extensiontype_): self.extensiontype_ = extensiontype_\n' % (
self._PGenr.make_gs_name('extensiontype'), ))
def _generateSubclasses(root, subclassFilename, behaviorFilename,
prefix, superModule='xxx'):
name = root.getChildren()[0].getName()
subclassFile = makeFile(subclassFilename)
wrt = subclassFile.write
if subclassFile:
# Read in the XMLBehavior file.
xmlbehavior = None
behaviors = None
baseUrl = None
if behaviorFilename:
try:
# Add the currect working directory to the path so that
# we use the user/developers local copy.
sys.path.insert(0, '.')
import xmlbehavior_sub as xmlbehavior
except ImportError:
err_msg('*** You have requested generation of extended methods.\n')
err_msg('*** But, no xmlbehavior module is available.\n')
err_msg('*** Generation of extended behavior methods is omitted.\n')
if xmlbehavior:
behaviors = xmlbehavior.parse(behaviorFilename)
behaviors.make_class_dictionary(self._PGenr.cleanupName)
baseUrl = behaviors.getBase_impl_url()
wrt = subclassFile.write
tstamp = (not NoDates and time.ctime()) or ''
if NoVersion:
version = ''
else:
version = ' version %s' % VERSION
wrt(TEMPLATE_SUBCLASS_HEADER % (tstamp, version,
superModule, ExternalEncoding, ))
for element in self._PGenr.ElementsForSubclasses:
generateSubclass(wrt, element, prefix, xmlbehavior, behaviors, baseUrl)
name = root.getChildren()[0].getName()
elType = self._PGenr.cleanupName(root.getChildren()[0].getType())
if self._PGenr.RootElement:
rootElement = self._PGenr.RootElement
else:
rootElement = elType
params = {
'cap_name': self._PGenr.make_gs_name(self._PGenr.cleanupName(name)),
'name': name,
'cleanname': self._PGenr.cleanupName(name),
'module_name': os.path.splitext(os.path.basename(subclassFilename))[0],
'root': rootElement,
'namespacedef': Namespacedef,
'super': superModule,
}
wrt(TEMPLATE_SUBCLASS_FOOTER % params)
subclassFile.close()
def _generateExportFn(self, wrt, prefix, element, namespace):
self._LangGenr.generateExport(wrt, namespace, element)
self._LangGenr.generateExportAttributesFn(wrt, namespace, element)
self._LangGenr.generateExportChildrenFn(wrt, namespace, element)
def _generateExportLiteralFn(self, wrt, prefix, element):
base = element.getBase()
wrt(" def exportLiteral(self, outfile, level, name_='%s'):\n" % element.getName())
wrt(" level += 1\n")
wrt(" self.exportLiteralAttributes(outfile, level, [], name_)\n")
wrt(" if self.hasContent_():\n")
wrt(" self.exportLiteralChildren(outfile, level, name_)\n")
childCount = self._PGenr.countChildren(element, 0)
if element.getSimpleContent() or element.isMixed():
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('valueOf_ = \"\"\"%s\"\"\",\\n' % (self.valueOf_,))\n")
wrt(" def exportLiteralAttributes(self, outfile, level, already_processed, name_):\n")
count = 0
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
count += 1
name = attrDef.getName()
cleanName = self._PGenr.cleanupName(name)
capName = self._PGenr.make_gs_name(cleanName)
mappedName = mapName(cleanName)
data_type = attrDef.getData_type()
attrType = attrDef.getType()
if attrType in self._PGenr.SimpleTypeDict:
attrType = self._PGenr.SimpleTypeDict[attrType].getBase()
if attrType in self._PGenr.SimpleTypeDict:
attrType = self._PGenr.SimpleTypeDict[attrType].getBase()
wrt(" if self.%s is not None and '%s' not in already_processed:\n" % (
mappedName, mappedName, ))
wrt(" already_processed.append('%s')\n" % (
mappedName, ))
wrt(" showIndent(outfile, level)\n")
if attrType in self._PGenr.StringType or \
attrType in self._PGenr.IDTypes or \
attrType == self._PGenr.TokenType or \
attrType == self._PGenr.DateTimeType or \
attrType == self._PGenr.TimeType or \
attrType == self._PGenr.DateType or \
attrType == self._PGenr.NCNameType:
wrt(" outfile.write('%s = \"%%s\",\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
elif attrType in self._PGenr.IntegerType or \
attrType == self._PGenr.PositiveIntegerType or \
attrType == self._PGenr.NonPositiveIntegerType or \
attrType == self._PGenr.NegativeIntegerType or \
attrType == self._PGenr.NonNegativeIntegerType:
wrt(" outfile.write('%s = %%d,\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
elif attrType == self._PGenr.BooleanType:
wrt(" outfile.write('%s = %%s,\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
elif attrType == self._PGenr.FloatType or \
attrType == self._PGenr.DecimalType:
wrt(" outfile.write('%s = %%f,\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
elif attrType == self._PGenr.DoubleType:
wrt(" outfile.write('%s = %%e,\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
else:
wrt(" outfile.write('%s = %%s,\\n' %% (self.%s,))\n" % \
(mappedName, mappedName,))
if element.getAnyAttribute():
count += 1
wrt(' for name, value in self.anyAttributes_.items():\n')
wrt(' showIndent(outfile, level)\n')
wrt(" outfile.write('%s = \"%s\",\\n' % (name, value,))\n")
parentName, parent = self._PGenr.getParentName(element)
if parentName:
count += 1
elName = element.getCleanName()
wrt(" super(%s, self).exportLiteralAttributes(outfile, level, already_processed, name_)\n" % \
(elName, ))
if count == 0:
wrt(" pass\n")
wrt(" def exportLiteralChildren(self, outfile, level, name_):\n")
parentName, parent = self._PGenr.getParentName(element)
if parentName:
elName = element.getCleanName()
wrt(" super(%s, self).exportLiteralChildren(outfile, level, name_)\n" % \
(elName, ))
for child in element.getChildren():
name = child.getName()
name = self._PGenr.cleanupName(name)
mappedName = self._PGenr.mapName(name)
if element.isMixed():
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('content_ = [\\n')\n")
wrt(' for item_ in self.content_:\n')
wrt(' item_.exportLiteral(outfile, level, name_)\n')
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('],\\n')\n")
else:
# fix_abstract
type_element = None
abstract_child = False
type_name = child.getAttrs().get('type')
if type_name:
type_element = self._PGenr.ElementDict.get(type_name)
if type_element and type_element.isAbstract():
abstract_child = True
if abstract_child:
pass
else:
type_name = name
if child.getMaxOccurs() > 1:
if child.getType() == self._PGenr.AnyTypeIdentifier:
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('anytypeobjs_=[\\n')\n")
wrt(" level += 1\n")
wrt(" for anytypeobjs_ in self.anytypeobjs_:\n")
wrt(" anytypeobjs_.exportLiteral(outfile, level)\n")
wrt(" level -= 1\n")
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('],\\n')\n")
else:
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('%s=[\\n')\n" % (mappedName, ))
wrt(" level += 1\n")
wrt(" for %s_ in self.%s:\n" % (name, mappedName))
self._generateExportLiteralFn_2(wrt, child, name, ' ')
wrt(" level -= 1\n")
wrt(" showIndent(outfile, level)\n")
wrt(" outfile.write('],\\n')\n")
else:
self._generateExportLiteralFn_1(wrt, child, type_name, '')
if childCount == 0 or element.isMixed():
wrt(" pass\n")
def _generateExportLiteralFn_1(self, wrt, child, name, fill):
cleanName = self._PGenr.cleanupName(name)
mappedName = self._PGenr.mapName(cleanName)
childType = child.getType()
if childType == self._PGenr.AnyTypeIdentifier:
wrt('%s if self.anytypeobjs_ is not None:\n' % (fill, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('anytypeobjs_=model_.anytypeobjs_(\\n')\n" % \
(fill, ))
wrt("%s self.anytypeobjs_.exportLiteral(outfile, level)\n" % (
fill, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('),\\n')\n" % (fill, ))
else:
wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
if childType in self._PGenr.StringType or \
childType in self._PGenr.IDTypes or \
childType == self._PGenr.TokenType or \
childType == self._PGenr.DateTimeType or \
childType == self._PGenr.TimeType or \
childType == self._PGenr.DateType:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
if (child.getSimpleType() in self._PGenr.SimpleTypeDict and
self._PGenr.SimpleTypeDict[child.getSimpleType()].isListType()):
wrt("%s if self.%s:\n" % (fill, mappedName, ))
wrt("%s outfile.write('%s=%%s,\\n' %% quote_python(' '.join(self.%s)).encode(ExternalEncoding)) \n" % \
(fill, mappedName, mappedName, ))
wrt("%s else:\n" % (fill, ))
wrt("%s outfile.write('%s=None,\\n')\n" % \
(fill, mappedName, ))
else:
wrt("%s outfile.write('%s=%%s,\\n' %% quote_python(self.%s).encode(ExternalEncoding))\n" % \
(fill, mappedName, mappedName, ))
elif childType in self._PGenr.IntegerType or \
childType == self._PGenr.PositiveIntegerType or \
childType == self._PGenr.NonPositiveIntegerType or \
childType == self._PGenr.NegativeIntegerType or \
childType == self._PGenr.NonNegativeIntegerType:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('%s=%%d,\\n' %% self.%s)\n" % \
(fill, mappedName, mappedName, ))
elif childType == self._PGenr.BooleanType:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('%s=%%s,\\n' %% self.%s)\n" % \
(fill, mappedName, mappedName, ))
elif childType == self._PGenr.FloatType or \
childType == self._PGenr.DecimalType:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('%s=%%f,\\n' %% self.%s)\n" % \
(fill, mappedName, mappedName, ))
elif childType == self._PGenr.DoubleType:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('%s=%%e,\\n' %% self.%s)\n" % \
(fill, name, mappedName, ))
else:
# wrt('%s if self.%s is not None:\n' % (fill, mappedName, ))
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('%s=model_.%s(\\n')\n" % \
(fill, mappedName, self._PGenr.mapName(self._PGenr.cleanupName(child.getType()))))
if name == child.getType():
s1 = "%s self.%s.exportLiteral(outfile, level)\n" % \
(fill, mappedName)
else:
s1 = "%s self.%s.exportLiteral(outfile, level, name_='%s')\n" % \
(fill, mappedName, name)
wrt(s1)
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('),\\n')\n" % (fill, ))
def _generateExportLiteralFn_2(self, wrt, child, name, fill):
cleanName = self._PGenr.cleanupName(name)
mappedName = self._PGenr.mapName(cleanName)
childType = child.getType()
wrt('%s showIndent(outfile, level)\n' % fill)
if childType in self._PGenr.StringType or \
childType == self._PGenr.TokenType or \
childType == self._PGenr.DateTimeType or \
childType == self._PGenr.TimeType or \
childType == self._PGenr.DateType:
wrt("%s outfile.write('%%s,\\n' %% quote_python(%s_).encode(ExternalEncoding))\n" % \
(fill, name))
elif childType in self._PGenr.IntegerType or \
childType == self._PGenr.PositiveIntegerType or \
childType == self._PGenr.NonPositiveIntegerType or \
childType == self._PGenr.NegativeIntegerType or \
childType == self._PGenr.NonNegativeIntegerType:
wrt("%s outfile.write('%%d,\\n' %% %s)\n" % (fill, name))
elif childType == self._PGenr.BooleanType:
wrt("%s outfile.write('%%s,\\n' %% %s)\n" % (fill, name))
elif childType == self._PGenr.FloatType or \
childType == self._PGenr.DecimalType:
wrt("%s outfile.write('%%f,\\n' %% %s_)\n" % (fill, name))
elif childType == self._PGenr.DoubleType:
wrt("%s outfile.write('%%e,\\n' %% %s)\n" % (fill, name))
else:
name1 = self._PGenr.mapName(self._PGenr.cleanupName(child.getType()))
wrt("%s outfile.write('model_.%s(\\n')\n" % (fill, name1, ))
if name == child.getType():
s1 = "%s %s_.exportLiteral(outfile, level)\n" % (
fill, self._PGenr.cleanupName(child.getType()), )
else:
s1 = "%s %s_.exportLiteral(outfile, level, name_='%s')\n" % \
(fill, name, child.getType(), )
wrt(s1)
wrt('%s showIndent(outfile, level)\n' % fill)
wrt("%s outfile.write('),\\n')\n" % (fill, ))
def _generateExportDictFn(self, wrt, prefix, element):
self._LangGenr.generateExportDict(wrt, element)
def _generateExportDict2Fn(self, wrt, prefix, element):
self._LangGenr.generateExportDict2(wrt, element)
def generateSubclass(self, wrt, element, prefix, xmlbehavior, behaviors, baseUrl):
self._LangGenr.generateSubclass()
if not element.isComplex():
return
if element.getName() in AlreadyGenerated_subclass:
return
AlreadyGenerated_subclass.append(element.getName())
name = element.getCleanName()
wrt('class %s%s%s(supermod.%s):\n' % (prefix, name, SubclassSuffix, name))
childCount = self._PGenr.countChildren(element, 0)
s1 = buildCtorArgs_multilevel(element, childCount)
wrt(' def __init__(self%s):\n' % s1)
args = buildCtorParams(element, element, childCount)
s1 = ''.join(args)
if len(args) > 254:
wrt(' arglist_ = (%s)\n' % (s1, ))
wrt(' super(%s%s%s, self).__init__(*arglist_)\n' % (prefix, name, SubclassSuffix, ))
else:
#wrt(' supermod.%s%s.__init__(%s)\n' % (prefix, name, s1))
wrt(' super(%s%s%s, self).__init__(%s)\n' % (prefix, name, SubclassSuffix, s1, ))
if xmlbehavior and behaviors:
wrt('\n')
wrt(' #\n')
wrt(' # XMLBehaviors\n')
wrt(' #\n')
# Get a list of behaviors for this class/subclass.
classDictionary = behaviors.get_class_dictionary()
if name in classDictionary:
classBehaviors = classDictionary[name]
else:
classBehaviors = None
if classBehaviors:
generateClassBehaviors(wrt, classBehaviors, baseUrl)
wrt('supermod.%s.subclass = %s%s\n' % (name, name, SubclassSuffix))
wrt('# end class %s%s%s\n' % (prefix, name, SubclassSuffix))
wrt('\n\n')
def _generateBuildFn(self, wrt, prefix, element, delayed):
self._LangGenr.generateBuild(wrt, element)
self._LangGenr.generateBuildAttributesFn(wrt, element)
self._LangGenr.generateBuildChildren(wrt, element, prefix, delayed)
def _generateUserMethods(self, wrt, element):
if not self._PGenr.UserMethodsModule:
return
specs = self._PGenr.UserMethodsModule.METHOD_SPECS
name = self._PGenr.cleanupName(element.getCleanName())
values_dict = {'class_name': name, }
for spec in specs:
if spec.match_name(name):
source = spec.get_interpolated_source(values_dict)
wrt(source)
#
# Generators for Language specific parts
#
class PyGenerator(object):
def __init__(self, parser_generator):
self._PGenr = parser_generator
def generateHeader(self, wrt, prefix):
tstamp = (not self._PGenr.NoDates and time.ctime()) or ''
if self._PGenr.NoVersion:
version = ''
else:
version = ' version %s' % self._PGenr.Version
s1 = self._PGenr.TEMPLATE_HEADER % (tstamp, version, self._PGenr.ExternalEncoding, )
wrt(s1)
def generateClassDefLine(self, wrt, parentName, prefix, name):
if parentName:
s1 = 'class %s%s(%s):\n' % (prefix, CamelCase(name), parentName,)
else:
#s1 = 'class %s%s(GeneratedsSuper):\n' % (prefix, CamelCase(name))
s1 = 'class %s%s(object):\n' % (prefix, CamelCase(name))
wrt(s1)
wrt(' """\n')
wrt(' %s%s class definition from :doc:`services.xsd`\n' %(prefix, name))
wrt(' """\n')
def generateClassVars(self, wrt, name):
wrt(" service_type = '%s'\n" % (CamelCase(name)))
wrt(" token = None\n")
def generateSubclass(self):
if not element.isComplex():
return
if element.getName() in AlreadyGenerated_subclass:
return
AlreadyGenerated_subclass.append(element.getName())
name = element.getCleanName()
wrt('class %s%s%s(supermod.%s):\n' % (prefix, name, SubclassSuffix, name))
childCount = self._PGenr.countChildren(element, 0)
s1 = buildCtorArgs_multilevel(element, childCount)
wrt(' def __init__(self%s):\n' % s1)
args = buildCtorParams(element, element, childCount)
s1 = ''.join(args)
if len(args) > 254:
wrt(' arglist_ = (%s)\n' % (s1, ))
wrt(' super(%s%s%s, self).__init__(*arglist_)\n' % (prefix, name, SubclassSuffix, ))
else:
#wrt(' supermod.%s%s.__init__(%s)\n' % (prefix, name, s1))
wrt(' super(%s%s%s, self).__init__(%s)\n' % (prefix, name, SubclassSuffix, s1, ))
if xmlbehavior and behaviors:
wrt('\n')
wrt(' #\n')
wrt(' # XMLBehaviors\n')
wrt(' #\n')
# Get a list of behaviors for this class/subclass.
classDictionary = behaviors.get_class_dictionary()
if name in classDictionary:
classBehaviors = classDictionary[name]
else:
classBehaviors = None
if classBehaviors:
generateClassBehaviors(wrt, classBehaviors, baseUrl)
wrt('supermod.%s.subclass = %s%s\n' % (name, name, SubclassSuffix))
wrt('# end class %s%s%s\n' % (prefix, name, SubclassSuffix))
wrt('\n\n')
def generateFactory(self, wrt, prefix, name):
wrt(' def factory(*args_, **kwargs_):\n')
wrt(' if %s%s.subclass:\n' % (prefix, CamelCase(name)))
wrt(' return %s%s.subclass(*args_, **kwargs_)\n' % (prefix, CamelCase(name)))
wrt(' else:\n')
wrt(' return %s%s(*args_, **kwargs_)\n' % (prefix, CamelCase(name)))
wrt(' factory = staticmethod(factory)\n')
def generateElemDoc(self, wrt, element):
s2 = ' '.join(element.documentation.strip().split())
s2 = s2.encode('utf-8')
s2 = textwrap.fill(s2, width=68, subsequent_indent=' ')
if s2[0] == '"' or s2[-1] == '"':
s2 = ' """ %s """\n' % (s2, )
else:
s2 = ' """%s"""\n' % (s2, )
wrt(s2)
#
# Generate a class variable whose value is a list of tuples, one
# tuple for each member data item of the class.
# Each tuble has 3 elements: (1) member name, (2) member data type,
# (3) container/list or not (maxoccurs > 1).
def generateMemberSpec(wrt, element):
generateDict = MemberSpecs and MemberSpecs == 'dict'
if generateDict:
content = [' member_data_items_ = {']
else:
content = [' member_data_items_ = [']
add = content.append
for attrName, attrDef in element.getAttributeDefs().items():
item1 = attrName
item2 = attrDef.getType()
item3 = 0
if generateDict:
item = " '%s': MemberSpec_('%s', '%s', %d)," % (
item1, item1, item2, item3, )
else:
item = " MemberSpec_('%s', '%s', %d)," % (
item1, item2, item3, )
add(item)
for child in element.getChildren():
name = self._PGenr.cleanupName(child.getCleanName())
item1 = name
simplebase = child.getSimpleBase()
if simplebase:
if len(simplebase) == 1:
item2 = "'%s'" % (simplebase[0], )
else:
item2 = simplebase
else:
element1 = self._PGenr.ElementDict.get(name)
if element1:
item2 = "'%s'" % element1.getType()
else:
item2 = "'%s'" % (child.getType(), )
if child.getMaxOccurs() > 1:
item3 = 1
else:
item3 = 0
if generateDict:
item = " '%s': MemberSpec_('%s', %s, %d)," % (
item1, item1, item2, item3, )
else:
#item = " ('%s', '%s', %d)," % (item1, item2, item3, )
item = " MemberSpec_('%s', %s, %d)," % (
item1, item2, item3, )
add(item)
simplebase = element.getSimpleBase()
childCount = self._PGenr.countChildren(element, 0)
if element.getSimpleContent() or element.isMixed():
if len(simplebase) == 1:
simplebase = "'%s'" % (simplebase[0], )
if generateDict:
item = " 'valueOf_': MemberSpec_('valueOf_', %s, 0)," % (
simplebase, )
else:
item = " MemberSpec_('valueOf_', %s, 0)," % (
simplebase, )
add(item)
elif element.isMixed():
if generateDict:
item = " 'valueOf_': MemberSpec_('valueOf_', '%s', 0)," % (
'xs:string', )
else:
item = " MemberSpec_('valueOf_', '%s', 0)," % (
'xs:string', )
add(item)
if generateDict:
add(' }')
else:
add(' ]')
wrt('\n'.join(content))
wrt('\n')
def generateSubSuperInit(self, wrt, superclass_name):
wrt(' subclass = None\n')
wrt(' superclass = %s\n' % (superclass_name, ))
def generateCtor(self, wrt, element):
elName = element.getCleanName()
childCount = self._PGenr.countChildren(element, 0)
s2 = self.buildCtorArgs_multilevel(element, childCount)
wrt(' def __init__(self%s, **kwargs):\n' % s2)
base = element.getBase()
parentName, parent = self._PGenr.getParentName(element)
if parentName:
if parentName in self._PGenr.AlreadyGenerated:
args = self.buildCtorParams(element, parent, childCount)
s2 = ''.join(args)
if len(args) > 254:
wrt(' arglist_ = (%s)\n' % (s2, ))
wrt(' super(%s, self).__init__(*arglist_)\n' % (elName, ))
else:
wrt(' super(%s, self).__init__(%s)\n' % (elName, s2, ))
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
mappedName = self._PGenr.cleanupName(attrDef.getName())
mappedName = mapName(mappedName)
logging.debug("Constructor attribute: %s" % mappedName)
pythonType = SchemaToPythonTypeMap.get(attrDef.getType())
attrVal = "cast_(%s, %s)" % (pythonType, mappedName)
wrt(' self.%s = %s\n' % (mappedName, attrVal))
member = 1
# Generate member initializers in ctor.
# wrt(" self.service_type = '%s'\n" % (elName))
member = 0
nestedElements = 0
for child in element.getChildren():
name = self._PGenr.cleanupName(child.getCleanName())
logging.debug("Constructor child: %s" % name)
logging.debug("Dump: %s" % child.__dict__)
if child.getType() == self._PGenr.AnyTypeIdentifier:
if child.getMaxOccurs() > 1:
wrt(' if anytypeobjs_ is None:\n')
wrt(' self.anytypeobjs_ = []\n')
wrt(' else:\n')
wrt(' self.anytypeobjs_ = anytypeobjs_\n')
else:
wrt(' self.anytypeobjs_ = anytypeobjs_\n')
else:
if child.getMaxOccurs() > 1:
child_type = child.getType()
wrt(' if (%s is None) or (%s == []):\n' % (name, name))
wrt(' self.%s = []\n' % (name, ))
wrt(' else:\n')
if (child.isComplex()):
wrt(' if isinstance(%s[0], dict):\n' %(name))
wrt(' objs = [%s(**elem) for elem in %s]\n' \
%(child_type, name))
wrt(' self.%s = objs\n' % (name))
wrt(' else:\n')
wrt(' self.%s = %s\n' % (name, name))
else:
wrt(' self.%s = %s\n' % (name, name))
else:
typeObj = self._PGenr.ElementDict.get(child.getType())
if (child.getDefault() and
typeObj is not None and
typeObj.getSimpleContent()):
wrt(' if %s is None:\n' % (name, ))
wrt(" self.%s = globals()['%s']('%s')\n" % (name,
child.getType(), child.getDefault(), ))
wrt(' else:\n')
wrt(' self.%s = %s\n' % (name, name))
else:
child_type = child.getType()
if (child.isComplex()):
wrt(' if isinstance(%s, dict):\n' %(name))
wrt(' obj = %s(**%s)\n' %(child_type, name))
wrt(' self.%s = obj\n' % (name))
wrt(' else:\n')
wrt(' self.%s = %s\n' % (name, name))
else:
wrt(' self.%s = %s\n' % (name, name))
member = 1
nestedElements = 1
eltype = element.getType()
if (element.getSimpleContent() or
element.isMixed() or
eltype in self._PGenr.SimpleTypeDict or
self._PGenr.CurrentNamespacePrefix + eltype in self._PGenr.OtherSimpleTypes
):
wrt(' self.valueOf_ = valueOf_\n')
member = 1
if element.getAnyAttribute():
wrt(' self.anyAttributes_ = {}\n')
member = 1
if element.getExtended():
wrt(' self.extensiontype_ = extensiontype_\n')
member = 1
if not member:
wrt(' pass\n')
if element.isMixed():
wrt(MixedCtorInitializers)
# end generateCtor
def buildCtorArgs_multilevel(self, element, childCount):
content = []
addedArgs = {}
add = content.append
self.buildCtorArgs_multilevel_aux(addedArgs, add, element)
eltype = element.getType()
if (element.getSimpleContent() or
element.isMixed() or
eltype in self._PGenr.SimpleTypeDict or
self._PGenr.CurrentNamespacePrefix + eltype in self._PGenr.OtherSimpleTypes
):
print "SimpleContent()"
add(", valueOf_=None")
if element.isMixed():
print "Mixed"
add(', mixedclass_=None')
add(', content_=None')
if element.getExtended():
print "Extended"
add(', extensiontype_=None')
s1 = ''.join(content)
return s1
def buildCtorArgs_multilevel_aux(self, addedArgs, add, element):
parentName, parentObj = self._PGenr.getParentName(element)
if parentName:
self.buildCtorArgs_multilevel_aux(addedArgs, add, parentObj)
self.buildCtorArgs_aux(addedArgs, add, element)
def buildCtorArgs_aux(self, addedArgs, add, element):
attrDefs = element.getAttributeDefs()
for key in attrDefs:
attrDef = attrDefs[key]
name = attrDef.getName()
default = attrDef.getDefault()
mappedName = name.replace(':', '_')
mappedName = self._PGenr.cleanupName(mapName(mappedName))
if mappedName in addedArgs:
continue
addedArgs[mappedName] = 1
try:
atype = attrDef.getData_type()
except KeyError:
atype = self._PGenr.StringType
if atype in self._PGenr.StringType or \
atype == self._PGenr.TokenType or \
atype == self._PGenr.DateTimeType or \
atype == self._PGenr.TimeType or \
atype == self._PGenr.DateType:
if default is None:
add(", %s=None" % mappedName)
else:
default1 = escape_string(default)
add(", %s='%s'" % (mappedName, default1))
elif atype in IntegerType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
elif atype == PositiveIntegerType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
elif atype == NonPositiveIntegerType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
elif atype == NegativeIntegerType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
elif atype == NonNegativeIntegerType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
elif atype == BooleanType:
if default is None:
add(', %s=None' % mappedName)
else:
if default in ('false', '0'):
add(', %s=%s' % (mappedName, "False"))
else:
add(', %s=%s' % (mappedName, "True"))
elif atype == FloatType or atype == DoubleType or atype == DecimalType:
if default is None:
add(', %s=None' % mappedName)
else:
add(', %s=%s' % (mappedName, default))
else:
if default is None:
add(', %s=None' % mappedName)
else:
add(", %s='%s'" % (mappedName, default, ))
nestedElements = 0
for child in element.getChildren():
cleanName = child.getCleanName()
if cleanName in addedArgs:
continue
addedArgs[cleanName] = 1
default = child.getDefault()
nestedElements = 1
if child.getType() == self._PGenr.AnyTypeIdentifier:
add(', anytypeobjs_=None')
elif child.getMaxOccurs() > 1:
add(', %s=None' % cleanName)
else:
childType = child.getType()
if childType in self._PGenr.StringType or \
childType == self._PGenr.TokenType or \