This repository has been archived by the owner on Apr 29, 2023. It is now read-only.
/
generate.py
2910 lines (2529 loc) · 130 KB
/
generate.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
# -*- coding: utf-8 -*-
# Copyright 2009-2013, Peter A. Bigot
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain a
# copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""The really ugly code that generates the Python bindings. This
whole thing is going to be refactored once customized generation makes
it to the top of the task queue."""
import sys
import os.path
import logging
import logging.config
import io
import datetime
import errno
import pyxb
import pyxb.xmlschema as xs
from pyxb.utils import utility, templates, six
from pyxb.utils.utility import repr2to3
from pyxb.binding import basis, datatypes, facets
_log = logging.getLogger(__name__)
def PrefixModule (value, text=None):
if text is None:
text = value.__name__
if value.__module__ == datatypes.__name__:
return 'pyxb.binding.datatypes.%s' % (text,)
if value.__module__ == facets.__name__:
return 'pyxb.binding.facets.%s' % (text,)
raise ValueError('No standard name for module of value', value)
class ReferenceLiteral (object):
"""Base class for something that requires fairly complex activity
in order to generate its literal value."""
# Either a STD or a subclass of _Enumeration_mixin, this is the
# class in which the referenced object is a member.
__ownerClass = None
# The value to be used as a literal for this object
__literal = None
def __init__ (self, **kw):
# NB: Pre-extend __init__
self.__ownerClass = kw.get('type_definition')
def setLiteral (self, literal):
self.__literal = literal
return literal
def asLiteral (self):
return self.__literal
def _addTypePrefix (self, text, **kw):
if self.__ownerClass is not None:
text = '%s.%s' % (pythonLiteral(self.__ownerClass, **kw), text)
return text
class ReferenceFacetMember (ReferenceLiteral):
__facetClass = None
def __init__ (self, **kw):
variable = kw.get('variable')
assert (variable is None) or isinstance(variable, facets.Facet)
if variable is not None:
kw.setdefault('type_definition', variable.ownerTypeDefinition())
self.__facetClass = type(variable)
self.__facetClass = kw.get('facet_class', self.__facetClass)
super(ReferenceFacetMember, self).__init__(**kw)
self.setLiteral(self._addTypePrefix('_CF_%s' % (self.__facetClass.Name(),), **kw))
class ReferenceWildcard (ReferenceLiteral):
__wildcard = None
def __init__ (self, wildcard, **kw):
self.__wildcard = wildcard
super(ReferenceWildcard, self).__init__(**kw)
template_map = { }
template_map['Wildcard'] = 'pyxb.binding.content.Wildcard'
if (xs.structures.Wildcard.NC_any == wildcard.namespaceConstraint()):
template_map['nc'] = templates.replaceInText('%{Wildcard}.NC_any', **template_map)
elif isinstance(wildcard.namespaceConstraint(), (set, frozenset)):
namespaces = []
for ns in wildcard.namespaceConstraint():
if ns is None:
namespaces.append(None)
else:
namespaces.append(ns.uri())
template_map['nc'] = 'set([%s])' % (",".join( [ repr2to3(_ns) for _ns in namespaces ]))
else:
assert isinstance(wildcard.namespaceConstraint(), tuple)
ns = wildcard.namespaceConstraint()[1]
if ns is not None:
ns = ns.uri()
template_map['nc'] = templates.replaceInText('(%{Wildcard}.NC_not, %{namespace})', namespace=repr2to3(ns), **template_map)
template_map['pc'] = wildcard.processContents()
self.setLiteral(templates.replaceInText('%{Wildcard}(process_contents=%{Wildcard}.PC_%{pc}, namespace_constraint=%{nc})', **template_map))
class ReferenceSchemaComponent (ReferenceLiteral):
__component = None
def __init__ (self, component, **kw):
self.__component = component
binding_module = kw['binding_module']
in_class = kw.get('in_class', False)
super(ReferenceSchemaComponent, self).__init__(**kw)
rv = binding_module.referenceSchemaComponent(component, in_class)
self.setLiteral(rv)
class ReferenceNamespace (ReferenceLiteral):
__namespace = None
def __init__ (self, **kw):
self.__namespace = kw['namespace']
binding_module = kw['binding_module']
super(ReferenceNamespace, self).__init__(**kw)
rv = binding_module.referenceNamespace(self.__namespace)
self.setLiteral(rv)
class ReferenceExpandedName (ReferenceLiteral):
__expandedName = None
def __init__ (self, **kw):
self.__expandedName = kw['expanded_name']
super(ReferenceExpandedName, self).__init__(**kw)
self.setLiteral('pyxb.namespace.ExpandedName(%s, %s)' % (pythonLiteral(self.__expandedName.namespace(), **kw), pythonLiteral(self.__expandedName.localName(), **kw)))
class ReferenceFacet (ReferenceLiteral):
__facet = None
def __init__ (self, **kw):
self.__facet = kw['facet']
super(ReferenceFacet, self).__init__(**kw)
self.setLiteral('%s._CF_%s' % (pythonLiteral(self.__facet.ownerTypeDefinition(), **kw), self.__facet.Name()))
class ReferenceEnumerationMember (ReferenceLiteral):
enumerationElement = None
def __init__ (self, **kw):
# NB: Pre-extended __init__
# All we really need is the enumeration element, so we can get
# its tag, and a type definition or datatype, so we can create
# the proper prefix.
# See if we were given a value, from which we can extract the
# other information.
value = kw.get('enum_value')
assert (value is None) or isinstance(value, facets._Enumeration_mixin)
# Must provide facet_instance, or a value from which it can be
# obtained.
facet_instance = kw.get('facet_instance')
if facet_instance is None:
assert isinstance(value, facets._Enumeration_mixin)
facet_instance = value._CF_enumeration
assert isinstance(facet_instance, facets.CF_enumeration)
# Must provide the enumeration_element, or a facet_instance
# and value from which it can be identified.
self.enumerationElement = kw.get('enumeration_element')
if self.enumerationElement is None:
assert value is not None
self.enumerationElement = facet_instance.elementForValue(value)
assert isinstance(self.enumerationElement, facets._EnumerationElement)
assert self.enumerationElement.tag() is not None
# If no type definition was provided, use the value datatype
# for the facet.
kw.setdefault('type_definition', facet_instance.valueDatatype())
super(ReferenceEnumerationMember, self).__init__(**kw)
self.setLiteral(self._addTypePrefix(self.enumerationElement.tag(), **kw))
def pythonLiteral (value, **kw):
# For dictionaries, apply translation to all values (not keys)
if isinstance(value, six.dictionary_type):
return ', '.join([ '%s=%s' % (k, pythonLiteral(v, **kw)) for (k, v) in six.iteritems(value) ])
# For lists, apply translation to all members
if isinstance(value, six.list_type):
return [ pythonLiteral(_v, **kw) for _v in value ]
# ExpandedName is a tuple, but not here
if isinstance(value, pyxb.namespace.ExpandedName):
return pythonLiteral(ReferenceExpandedName(expanded_name=value, **kw))
# For other collection types, do what you do for list
if isinstance(value, (six.tuple_type, set)):
return type(value)(pythonLiteral(list(value), **kw))
# Value is a binding value for which there should be an
# enumeration constant. Return that constant.
if isinstance(value, facets._Enumeration_mixin):
return pythonLiteral(ReferenceEnumerationMember(enum_value=value, **kw))
# Value is an instance of a Python binding, e.g. one of the
# XMLSchema datatypes. Use its value, applying the proper prefix
# for the module.
if isinstance(value, basis.simpleTypeDefinition):
return PrefixModule(value, value.pythonLiteral())
if isinstance(value, pyxb.namespace.Namespace):
return pythonLiteral(ReferenceNamespace(namespace=value, **kw))
if isinstance(value, type):
if issubclass(value, basis.simpleTypeDefinition):
return PrefixModule(value)
if issubclass(value, facets.Facet):
return PrefixModule(value)
if isinstance(value, facets.Facet):
return pythonLiteral(ReferenceFacet(facet=value, **kw))
# Treat pattern elements as their value
if isinstance(value, facets._PatternElement):
return pythonLiteral(value.pattern)
# Treat enumeration elements as their value
if isinstance(value, facets._EnumerationElement):
return pythonLiteral(value.value())
# Wildcards expand to a pyxb.binding.content.Wildcard instance
if isinstance(value, xs.structures.Wildcard):
return pythonLiteral(ReferenceWildcard(value, **kw))
# Schema components have a single name through their lifespan
if isinstance(value, xs.structures._SchemaComponent_mixin):
return pythonLiteral(ReferenceSchemaComponent(value, **kw))
# Other special cases
if isinstance(value, ReferenceLiteral):
return value.asLiteral()
# Represent namespaces by their URI
if isinstance(value, pyxb.namespace.Namespace):
return repr2to3(value.uri())
# Standard Python types, including string types
if isinstance(value, (six.none_type, six.boolean_type, six.float_type, six.integer_types, six.string_types)):
return pyxb.utils.utility.repr2to3(value)
raise Exception('Unexpected literal type %s' % (type(value),))
def _GenerateAutomaton (automaton, template_map, containing_state, lines, **kw):
binding_module = kw['binding_module']
name = utility.PrepareIdentifier('BuildAutomaton', binding_module.uniqueInModule(), protected=True)
au_src = []
au_src.append(templates.replaceInText('''
def %{name} ():
# Remove this helper function from the namespace after it is invoked
global %{name}
del %{name}
import pyxb.utils.fac as fac
''', name=name))
def stateSortKey (st):
if isinstance(st.symbol, xs.structures.ModelGroup):
return st.symbol.facStateSortKey()
return st.symbol[0].facStateSortKey()
def counterConditionSortKey (cc):
return cc.metadata.facStateSortKey()
def updateInstructionSortKey (ui):
return counterConditionSortKey(ui.counterCondition)
def transitionSortKey (xit):
# The destination of a transition is not unique; need to
# differentiate using the update instructions. Which
# themselves should be sorted.
st = xit.consumingState()
# Transitions into/out-of subautomata might not include a
# consuming state. Give those a sort value -1, which python3
# considers comparable with the non-negative integer sort key
# used for states.
ssk = -1
if st is not None:
ssk = stateSortKey(st)
keys = [ ssk ]
keys.extend(map(updateInstructionSortKey, sorted(xit.updateInstructions, key=updateInstructionSortKey)))
return tuple(keys)
au_src.append(' counters = set()')
counter_map = {}
sorted_counter_conditions = sorted(automaton.counterConditions, key=counterConditionSortKey)
for cc in sorted_counter_conditions:
cc_id = 'cc_%u' % (len(counter_map),)
counter_map[cc] = cc_id
au_src.append(' %s = fac.CounterCondition(min=%s, max=%s, metadata=%r)' % (cc_id, repr2to3(cc.min), repr2to3(cc.max), cc.metadata._location()))
au_src.append(' counters.add(%s)' % (cc_id,))
state_map = {}
au_src.append(' states = []')
sorted_states = sorted(automaton.states, key=stateSortKey)
for st in sorted_states:
st_id = 'st_%u' % (len(state_map),)
state_map[st] = st_id
if st.subAutomata is not None:
au_src.append(' sub_automata = []')
for sa in st.subAutomata:
au_src.append(' sub_automata.append(%s)' % (_GenerateAutomaton(sa, template_map, st_id, lines, **kw),))
if st.finalUpdate is None:
au_src.append(' final_update = None')
else:
au_src.append(' final_update = set()')
for ui in sorted(st.finalUpdate, key=updateInstructionSortKey):
au_src.append(' final_update.add(fac.UpdateInstruction(%s, %r))' % (counter_map[ui.counterCondition], ui.doIncrement))
if isinstance(st.symbol, xs.structures.ModelGroup):
au_src.append(' symbol = %r' % (st.symbol._location(),))
else:
(particle, symbol) = st.symbol
if isinstance(symbol, xs.structures.Wildcard):
au_src.append(templates.replaceInText(' symbol = pyxb.binding.content.WildcardUse(%{wildcard}, %{location})', wildcard=binding_module.literal(symbol, **kw), location=repr2to3(particle._location())))
elif isinstance(symbol, xs.structures.ElementDeclaration):
binding_module.importForDeclaration(symbol)
au_src.append(templates.replaceInText(' symbol = pyxb.binding.content.ElementUse(%{ctd}._UseForTag(%{field_tag}), %{location})', field_tag=binding_module.literal(symbol.expandedName(), **kw), location=repr2to3(particle._location()), **template_map))
au_src.append(' %s = fac.State(symbol, is_initial=%r, final_update=final_update, is_unordered_catenation=%r)' % (st_id, st.isInitial, st.isUnorderedCatenation))
if st.subAutomata is not None:
au_src.append(' %s._set_subAutomata(*sub_automata)' % (st_id,))
au_src.append(' states.append(%s)' % (st_id,))
for st in sorted_states:
au_src.append(' transitions = []')
for xit in sorted(st.transitionSet, key=transitionSortKey):
au_src.append(' transitions.append(fac.Transition(%s, [' % (state_map[xit.destination],))
sorted_ui = sorted(xit.updateInstructions, key=updateInstructionSortKey)
au_src.append(' %s ]))' % (',\n '.join(map(lambda _ui: 'fac.UpdateInstruction(%s, %r)' % (counter_map[_ui.counterCondition], _ui.doIncrement), sorted_ui))))
au_src.append(' %s._set_transitionSet(transitions)' % (state_map[st],))
au_src.append(' return fac.Automaton(states, counters, %r, containing_state=%s)' % (automaton.nullable, containing_state))
lines.extend(au_src)
return '%s()' % (name,)
def GenerateAutomaton (ctd, **kw):
aux = _CTDAuxData.Get(ctd)
binding_module = kw['binding_module']
template_map = { 'ctd' : binding_module.literal(ctd, **kw) }
automaton = aux.automaton
if automaton is None:
return None
lines = []
name = _GenerateAutomaton(automaton, template_map, 'None', lines, **kw)
return (name, lines)
def _useEnumerationTags (td):
if td is None:
return False
assert isinstance(td, xs.structures.SimpleTypeDefinition)
ptd = td.baseTypeDefinition()
python_support = None
# Atomic types that use strings as their representation
if (ptd.VARIETY_atomic == ptd.variety()):
python_support = ptd.primitiveTypeDefinition().pythonSupport()
return issubclass(python_support, six.string_types)
# Derivations from anySimpleType use strings too
if (ptd.VARIETY_absent == ptd.variety()):
return True
# Union types? Yeah, I suppose so. Though this only applies to
# members lifted up into the union.
if (ptd.VARIETY_union == ptd.variety()):
return True
# List types have spaces so no tags.
return False
def GenerateFacets (td, generator, **kw):
binding_module = kw['binding_module']
outf = binding_module.bindingIO()
facet_instances = []
gen_enum_tag = _useEnumerationTags(td)
for (fc, fi) in six.iteritems(td.facets()):
#if (fi is None) or (fi.ownerTypeDefinition() != td):
# continue
if (fi is None) and (fc in td.baseTypeDefinition().facets()):
# Nothing new here
continue
if (fi is not None) and (fi.ownerTypeDefinition() != td):
# Did this one in an ancestor
continue
argset = { }
is_collection = issubclass(fc, facets._CollectionFacet_mixin)
if issubclass(fc, facets._LateDatatype_mixin):
vdt = td
if fc.LateDatatypeBindsSuperclass():
vdt = vdt.baseTypeDefinition()
argset['value_datatype'] = vdt
if fi is not None:
if not is_collection:
argset['value'] = fi.value()
if isinstance(fi, facets.CF_enumeration):
argset['enum_prefix'] = fi.enumPrefix()
facet_var = ReferenceFacetMember(type_definition=td, facet_class=fc, **kw)
outf.write("%s = %s(%s)\n" % binding_module.literal( (facet_var, fc, argset ), **kw))
facet_instances.append(binding_module.literal(facet_var, **kw))
if (fi is not None) and is_collection:
for i in six.iteritems(fi):
if isinstance(i, facets._EnumerationElement):
if isinstance(i.value(), pyxb.namespace.ExpandedName):
enum_config = '%s.addEnumeration(value=%s, tag=%s)' % binding_module.literal( ( facet_var, i.value(), i.tag() ), **kw)
else:
enum_config = '%s.addEnumeration(unicode_value=%s, tag=%s)' % binding_module.literal( ( facet_var, i.unicodeValue(), i.tag() ), **kw)
if gen_enum_tag and (i.tag() is not None):
enum_member = ReferenceEnumerationMember(type_definition=td, facet_instance=fi, enumeration_element=i, **kw)
outf.write("%s = %s\n" % (binding_module.literal(enum_member, **kw), enum_config))
if fi.enumPrefix() is not None:
outf.write("%s_%s = %s\n" % (fi.enumPrefix(), i.tag(), binding_module.literal(enum_member, **kw)))
else:
outf.write("%s\n" % (enum_config,))
if isinstance(i, facets._PatternElement):
outf.write("%s.addPattern(pattern=%s)\n" % binding_module.literal( (facet_var, i.pattern ), **kw))
if gen_enum_tag and (xs.structures.SimpleTypeDefinition.VARIETY_union == td.variety()):
# If the union has enumerations of its own, there's no need to
# inherit anything, because they supersede anything implicitly
# inherited.
fi = td.facets().get(facets.CF_enumeration)
if fi is None:
# Need to expose any enumerations in members up in this class
for mtd in td.memberTypeDefinitions():
if not _useEnumerationTags(mtd):
continue
fi = mtd.facets().get(facets.CF_enumeration)
if fi is None:
continue
for i in six.iteritems(fi):
assert isinstance(i, facets._EnumerationElement)
etd = i.enumeration().ownerTypeDefinition()
enum_member = ReferenceEnumerationMember(type_definition=td, facet_instance=fi, enumeration_element=i, **kw)
outf.write("%-50s%s\n" % ('%s = %s' % binding_module.literal( (enum_member, i.unicodeValue()) ),
'# originally %s.%s' % (binding_module.literal(etd), i.tag())))
if 2 <= len(facet_instances):
map_args = ",\n ".join(facet_instances)
else:
map_args = ','.join(facet_instances)
outf.write("%s._InitializeFacetMap(%s)\n" % (binding_module.literal(td, **kw), map_args))
def _VCAppendAuxInit (vc_source, aux_init, binding_module, kw):
if vc_source.fixed() is not None:
aux_init.append('fixed=True')
aux_init.append('unicode_default=%s' % (binding_module.literal(vc_source.fixed(), **kw),))
elif vc_source.default() is not None:
aux_init.append('unicode_default=%s' % (binding_module.literal(vc_source.default(), **kw),))
# If std is a simple type that requires an enumeration mixin, return the
# corresponding facet; otherwise return None.
def simpleTypeOwnedEnumerationFacet (std):
if not isinstance(std, xs.structures.SimpleTypeDefinition):
return None
enum_facet = std.facets().get(facets.CF_enumeration)
if (enum_facet is not None) and (enum_facet.ownerTypeDefinition() == std):
return enum_facet
return None
def GenerateSTD (std, generator):
binding_module = generator.moduleForComponent(std)
outf = binding_module.bindingIO()
class_keywords = frozenset(basis.simpleTypeDefinition._ReservedSymbols)
class_unique = set()
kw = { }
kw['binding_module'] = binding_module
kw['class_keywords'] = class_keywords
kw['class_unique'] = class_unique
parent_classes = [ binding_module.literal(std.baseTypeDefinition(), **kw) ]
if simpleTypeOwnedEnumerationFacet(std) is not None:
parent_classes.append('pyxb.binding.basis.enumeration_mixin')
template_map = { }
binding_name = template_map['std'] = binding_module.literal(std, **kw)
if (std.expandedName() is not None) and (std.expandedName().localName() != binding_name):
_log.warning('Simple type %s renamed to %s', std.expandedName(), binding_name)
template_map['superclasses'] = ''
if 0 < len(parent_classes):
template_map['superclasses'] = ', '.join(parent_classes)
template_map['expanded_name'] = binding_module.literal(std.expandedName(), **kw)
if std.expandedName() is not None:
template_map['qname'] = six.text_type(std.expandedName())
else:
template_map['qname'] = '[anonymous]'
template_map['namespaceReference'] = binding_module.literal(std.bindingNamespace(), **kw)
template_map['xsd_location'] = repr2to3(std._location())
if std.annotation() is not None:
template_map['documentation'] = std.annotation().asDocString()
template_map['documentation_expr'] = binding_module.literal(std.annotation().text())
else:
template_map['documentation'] = ''
template_map['documentation_expr'] = binding_module.literal(None)
# @todo: Extensions of LIST will be wrong in below
common_template = '''
"""%{documentation}"""
_ExpandedName = %{expanded_name}
_XSDLocation = %{xsd_location}
_Documentation = %{documentation_expr}
'''
if xs.structures.SimpleTypeDefinition.VARIETY_absent == std.variety():
template = '''
# The ur simple type: %{qname}
class %{std} (%{superclasses}):
''' + common_template
if not template_map['documentation']:
template_map['documentation'] = 'The ur simple type.'
elif xs.structures.SimpleTypeDefinition.VARIETY_atomic == std.variety():
template = '''
# Atomic simple type: %{qname}
class %{std} (%{superclasses}):
''' + common_template
if not template_map['documentation']:
template_map['documentation'] = 'An atomic simple type.'
elif xs.structures.SimpleTypeDefinition.VARIETY_list == std.variety():
template = '''
# List simple type: %{qname}
# superclasses %{superclasses}
class %{std} (pyxb.binding.basis.STD_list):
''' + common_template + '''
_ItemType = %{itemtype}
'''
template_map['itemtype'] = binding_module.literal(std.itemTypeDefinition(), **kw)
if not template_map['documentation']:
template_map['documentation'] = templates.replaceInText('Simple type that is a list of %{itemtype}.', **template_map)
elif xs.structures.SimpleTypeDefinition.VARIETY_union == std.variety():
template = '''
# Union simple type: %{qname}
# superclasses %{superclasses}
class %{std} (pyxb.binding.basis.STD_union):
''' + common_template + '''
_MemberTypes = ( %{membertypes}, )
'''
template_map['membertypes'] = ", ".join( [ binding_module.literal(_mt, **kw) for _mt in std.memberTypeDefinitions() ])
if not template_map['documentation']:
template_map['documentation'] = templates.replaceInText('Simple type that is a union of %{membertypes}.', **template_map)
else:
raise pyxb.LogicError("Unhandled STD variety")
outf.write(templates.replaceInText(template, **template_map))
GenerateFacets(std, generator, **kw)
if std.name() is not None:
outf.write(templates.replaceInText("%{namespaceReference}.addCategoryObject('typeBinding', %{localName}, %{std})\n",
localName=binding_module.literal(std.name(), **kw), **template_map))
outf.write(templates.replaceInText('_module_typeBindings.%{std} = %{std}\n', **template_map))
def elementDeclarationMap (ed, binding_module, **kw):
template_map = { }
template_map['qname'] = six.text_type(ed.expandedName())
template_map['decl_location'] = repr2to3(ed._location())
template_map['namespaceReference'] = binding_module.literal(ed.bindingNamespace(), **kw)
if (ed.SCOPE_global == ed.scope()):
binding_name = template_map['class'] = binding_module.literal(ed, **kw)
if ed.expandedName().localName() != binding_name:
_log.warning('Element %s renamed to %s', ed.expandedName(), binding_name)
template_map['localName'] = binding_module.literal(ed.name(), **kw)
template_map['map_update'] = templates.replaceInText("%{namespaceReference}.addCategoryObject('elementBinding', %{localName}, %{class})", **template_map)
else:
template_map['scope'] = binding_module.literal(ed.scope(), **kw)
if ed.annotation() is not None:
template_map['documentation'] = binding_module.literal(six.text_type(ed.annotation()))
if ed.abstract():
template_map['abstract'] = binding_module.literal(ed.abstract(), **kw)
if ed.nillable():
template_map['nillable'] = binding_module.literal(ed.nillable(), **kw)
if ed.default():
template_map['defaultValue'] = binding_module.literal(ed.default(), **kw)
template_map['typeDefinition'] = binding_module.literal(ed.typeDefinition(), **kw)
if ed.substitutionGroupAffiliation():
template_map['substitution_group'] = binding_module.literal(ed.substitutionGroupAffiliation(), **kw)
aux_init = []
for k in ( 'nillable', 'abstract', 'scope', 'documentation' ):
if k in template_map:
aux_init.append('%s=%s' % (k, template_map[k]))
aux_init.append('location=%s' % (template_map['decl_location'],))
_VCAppendAuxInit(ed, aux_init, binding_module, kw)
template_map['element_aux_init'] = ''
if 0 < len(aux_init):
template_map['element_aux_init'] = ', ' + ', '.join(aux_init)
return template_map
import pyxb.utils.fac
import operator
import functools
# A Symbol in the term tree is a pair consisting of the containing
# particle (for location information) and one of an
# ElementDeclaration, Wildcard, or tuple of sub-term-trees for All
# model groups.
def BuildTermTree (node):
"""Construct a L{FAC term tree<pyxb.utils.fac.Node>} for a L{particle<xs.structures.Particle>}.
This translates the XML schema content model of particles, model
groups, element declarations, and wildcards into a tree expressing
the corresponding content as a regular expression with numerical
constraints.
@param node: An instance of L{xs.structures.Particle}
@return: An instance of L{pyxb.utils.fac.Node}
"""
def _generateTermTree_visitor (node, entered, arg):
"""Helper for constructing a L{FAC term tree<pyxb.utils.fac.Node>}.
This is passed to L{xs.structures.Particle.walkParticleTree}.
@param node: An instance of L{xs.structures._ParticleTree_mixin}
@param entered: C{True} entering an interior tree node, C{False}
leaving an interior tree node, C{None} at a leaf node.
@param arg: A list of pairs C{(particle, terms)} where C{particle}
is the L{xs.structures.Particle} instance containing a list of
L{term trees<pyxb.utils.fac.Node>}.
"""
if entered is None:
(parent_particle, terms) = arg.peekNodeTermPair()
assert isinstance(parent_particle, xs.structures.Particle)
assert isinstance(node, (xs.structures.ElementDeclaration, xs.structures.Wildcard))
node._setFacStateSortKey(arg.nextSequenceNumber())
terms.append(pyxb.utils.fac.Symbol((parent_particle, node)))
elif entered:
node._setFacStateSortKey(arg.nextSequenceNumber())
arg.addNode(node)
else:
(xnode, terms) = arg.popNodeTermPair()
assert xnode == node
(parent_particle, siblings) = arg.peekNodeTermPair()
if 1 == len(terms):
term = terms[0]
# Either node is a Particle, or it's a single-member model
# group. If it's a non-trivial particle we need a
# numerical constraint; if it's a single-member model
# group or a trivial particle we can use the term
# directly.
if isinstance(node, xs.structures.Particle) and ((1 != node.minOccurs()) or (1 != node.maxOccurs())):
term = pyxb.utils.fac.NumericalConstraint(term, node.minOccurs(), node.maxOccurs(), metadata=node)
else:
assert isinstance(parent_particle, xs.structures.Particle), 'unexpected %s' % (parent_particle,)
assert isinstance(node, xs.structures.ModelGroup)
if node.C_CHOICE == node.compositor():
term = pyxb.utils.fac.Choice(*terms, metadata=node)
elif node.C_SEQUENCE == node.compositor():
term = pyxb.utils.fac.Sequence(*terms, metadata=node)
else:
# The quadratic state explosion and need to clone
# terms that results from a naive transformation of
# unordered catenation to choices among sequences of
# nodes and recursively-defined catenation expressions
# is not worth the pain. Create a "symbol" for the
# state and hold the alternatives in it.
assert node.C_ALL == node.compositor()
assert functools.reduce(operator.and_, map(lambda _s: isinstance(_s, pyxb.utils.fac.Node), terms), True)
term = pyxb.utils.fac.All(*terms, metadata=node)
siblings.append(term)
class TermTreeArg (object):
__sequenceNumber = None
__termTreeList = None
__nodeTermPairs = None
def __init__ (self, node):
self.__sequenceNumber = 0
self.__termTreeList = []
self.__nodeTermPairs = [ (node, self.__termTreeList) ]
def termTree (self):
assert 1 == len(self.__nodeTermPairs)
assert 1 == len(self.__termTreeList)
return self.__termTreeList[0]
def peekNodeTermPair (self):
return self.__nodeTermPairs[-1]
def popNodeTermPair (self):
return self.__nodeTermPairs.pop()
def addNode (self, node):
self.__nodeTermPairs.append((node, []))
def nextSequenceNumber (self):
rv = self.__sequenceNumber
self.__sequenceNumber += 1
return rv
assert isinstance(node, xs.structures.Particle)
ttarg = TermTreeArg(node)
node.walkParticleTree(_generateTermTree_visitor, ttarg)
term_tree = ttarg.termTree()
return term_tree
def BuildPluralityData (term_tree):
"""Walk a term tree to determine which element declarations may
appear multiple times.
The bindings need to use a list for any Python attribute
corresponding to an element declaration that can occur multiple
times in the content model. The number of occurrences is
determined by the occurrence constraints on parent particles and
the compositors of containing model groups. All this information
is available in the term tree used for the content model
automaton.
@param term_tree: A L{FAC term tree<pyxb.utils.fac.Node>}
representing the content model for a complex data type.
@return: Plurality data, as a pair C{(singles, multiples)} where
C{singles} is a set of base L{element
declarations<xs.structures.ElementDeclaration>} that are known to
occur at least once and at most once in a region of the content,
and C{multiples} is a similar set of declarations that are known
to potentially occur more than once."""
def _ttMergeSets (parent, child):
(p1, pm) = parent
(c1, cm) = child
# Anything multiple in the child becomes multiple in the parent.
pm.update(cm)
# Anything independently occuring once in both parent and child
# becomes multiple in the parent.
pm.update(c1.intersection(p1))
# Anything that was single in the parent (child) but is now
# multiple is no longer single.
p1.difference_update(pm)
c1.difference_update(pm)
# Anything that was single in the parent and also single in the
# child is no longer single in the parent.
p1.symmetric_difference_update(c1)
def _ttPrePluralityWalk (node, pos, arg):
# If there are multiple children, create a new list on which they
# will be placed.
if isinstance(node, pyxb.utils.fac.MultiTermNode):
arg.append([])
def _ttPostPluralityWalk (node, pos, arg):
# Initialize a fresh result for this node
singles = set()
multiples = set()
combined = (singles, multiples)
if isinstance(node, pyxb.utils.fac.MultiTermNode):
# Get the list of children, and examine
term_list = arg.pop()
if isinstance(node, pyxb.utils.fac.Choice):
# For choice we aggregate the singles and multiples
# separately.
for (t1, tm) in term_list:
multiples.update(tm)
singles.update(t1)
else:
# For sequence (ordered or not) we merge the children
assert isinstance(node, (pyxb.utils.fac.Sequence, pyxb.utils.fac.All))
for tt in term_list:
_ttMergeSets(combined, tt)
elif isinstance(node, pyxb.utils.fac.Symbol):
(particle, term) = node.metadata
if isinstance(term, xs.structures.ElementDeclaration):
# One instance of the base declaration for the element
singles.add(term.baseDeclaration())
elif isinstance(term, xs.structures.Wildcard):
pass
else:
assert isinstance(term, list)
# Unordered catenation is the same as ordered catenation.
for tt in term:
_ttMergeSets(combined, BuildPluralityData(tt))
else:
assert isinstance(node, pyxb.utils.fac.NumericalConstraint)
# Grab the data for the topmost tree and adjust it based on
# occurrence data.
combined = arg[-1].pop()
(singles, multiples) = combined
if 0 == node.max:
# If the node can't match at all, there are no occurrences
# at all
multiples.clear()
singles.clear()
elif 1 == node.max:
# If the node can only match once, what we've got is right
pass
else:
# If the node can match multiple times, there are no
# singles.
multiples.update(singles)
singles.clear()
arg[-1].append(combined)
# Initialize state with an implied parent that currently has no
# children
arg = [[]]
term_tree.walkTermTree(_ttPrePluralityWalk, _ttPostPluralityWalk, arg)
# The result term tree is the single child of that implied parent
assert 1 == len(arg)
arg = arg[0]
assert 1 == len(arg)
return arg[0]
class _CTDAuxData (object):
"""Helper class holding information need in both preparation and generation."""
contentBasis = None
termTree = None
edSingles = None
edMultiples = None
automaton = None
ctd = None
def __init__ (self, ctd):
self.ctd = ctd
ctd.__auxData = self
self.contentBasis = ctd.contentType()[1]
if isinstance(self.contentBasis, xs.structures.Particle):
self.termTree = BuildTermTree(self.contentBasis)
self.automaton = self.termTree.buildAutomaton()
(self.edSingles, self.edMultiples) = BuildPluralityData(self.termTree)
else:
self.edSingles = set()
self.edMultiples = set()
@classmethod
def Create (cls, ctd):
return cls(ctd)
@classmethod
def Get (cls, ctd):
return ctd.__auxData
def GenerateCTD (ctd, generator, **kw):
binding_module = generator.moduleForComponent(ctd)
outf = binding_module.bindingIO()
prolog_template = None
template_map = { }
binding_name = template_map['ctd'] = binding_module.literal(ctd, **kw)
if (ctd.expandedName() is not None) and (ctd.expandedName().localName() != binding_name):
_log.warning('Complex type %s renamed to %s', ctd.expandedName(), binding_name)
base_type = ctd.baseTypeDefinition()
content_type_tag = ctd._contentTypeTag()
template_map['base_type'] = binding_module.literal(base_type, **kw)
template_map['namespaceReference'] = binding_module.literal(ctd.bindingNamespace(), **kw)
template_map['expanded_name'] = binding_module.literal(ctd.expandedName(), **kw)
if ctd.expandedName() is not None:
template_map['qname'] = six.text_type(ctd.expandedName())
else:
template_map['qname'] = '[anonymous]'
template_map['xsd_location'] = repr2to3(ctd._location())
template_map['simple_base_type'] = binding_module.literal(None, **kw)
template_map['contentTypeTag'] = content_type_tag
template_map['is_abstract'] = repr2to3(not not ctd.abstract())
content_basis = None
if (ctd.CT_SIMPLE == content_type_tag):
content_basis = ctd.contentType()[1]
template_map['simple_base_type'] = binding_module.literal(content_basis, **kw)
elif (ctd.CT_MIXED == content_type_tag):
content_basis = ctd.contentType()[1]
elif (ctd.CT_ELEMENT_ONLY == content_type_tag):
content_basis = ctd.contentType()[1]
if ctd.annotation() is not None:
template_map['documentation'] = ctd.annotation().asDocString()
elif isinstance(ctd.owner(), xs.structures.ElementDeclaration) \
and ctd.owner().annotation() is not None:
template_map['documentation'] = ctd.owner().annotation().asDocString()
else:
template_map['documentation'] = templates.replaceInText("Complex type %{qname} with content type %{contentTypeTag}", **template_map)
prolog_template = '''
# Complex type %{qname} with content type %{contentTypeTag}
class %{ctd} (%{superclass}):
"""%{documentation}"""
_TypeDefinition = %{simple_base_type}
_ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_%{contentTypeTag}
_Abstract = %{is_abstract}
_ExpandedName = %{expanded_name}
_XSDLocation = %{xsd_location}
'''
# Complex types that inherit from non-ur-type complex types should
# have their base type as their Python superclass, so pre-existing
# elements and attributes can be re-used.
inherits_from_base = True
template_map['superclass'] = binding_module.literal(base_type, **kw)
if ctd._isHierarchyRoot():
inherits_from_base = False
template_map['superclass'] = 'pyxb.binding.basis.complexTypeDefinition'
assert base_type.nameInBinding() is not None
if inherits_from_base:
prolog_template += ''' _ElementMap = %{superclass}._ElementMap.copy()
_AttributeMap = %{superclass}._AttributeMap.copy()
'''
else:
prolog_template += ''' _ElementMap = {}
_AttributeMap = {}
'''
# Support for deconflicting attributes, elements, and reserved symbols
class_keywords = frozenset(basis.complexTypeDefinition._ReservedSymbols)
class_unique = set()
# Deconflict elements first, attributes are lower priority.
# Expectation is that all elements that have the same tag in the
# XML are combined into the same instance member, even if they
# have different types. Determine what name that should be, and
# whether there might be multiple instances of elements of that
# name.
element_uses = []
definitions = []
definitions.append('# Base type is %{base_type}')
# Retain in the ctd the information about the element
# infrastructure, so it can be inherited where appropriate in
# subclasses.
if isinstance(content_basis, xs.structures.Particle):
aux = _CTDAuxData.Get(ctd)
elements = aux.edSingles.union(aux.edMultiples)
outf.postscript().append("\n\n")
for ed in sorted(elements, key=lambda _c: _c.schemaOrderSortKey()):
is_plural = ed in aux.edMultiples
# @todo Detect and account for plurality change between this and base
ef_map = ed._templateMap()
if ed.scope() == ctd:
ef_map.update(elementDeclarationMap(ed, binding_module, **kw))
aux_init = []
ef_map['is_plural'] = repr2to3(is_plural)
element_uses.append(templates.replaceInText('%{use}.name() : %{use}', **ef_map))
if 0 == len(aux_init):
ef_map['aux_init'] = ''
else:
ef_map['aux_init'] = ', ' + ', '.join(aux_init)
ef_map['element_binding'] = utility.PrepareIdentifier('%s_elt' % (ef_map['id'],), class_unique, class_keywords, private=True)
if ed.annotation() is not None:
ef_map['documentation'] = binding_module.literal(six.text_type(ed.annotation()))
else:
ef_map['documentation'] = binding_module.literal(None)
if ed.scope() != ctd:
definitions.append(templates.replaceInText('''
# Element %{id} (%{qname}) inherited from %{decl_type_en}''', decl_type_en=six.text_type(ed.scope().expandedName()), **ef_map))
continue
binding_module.importForDeclaration(ed)
if ed.expandedName().localName() != ef_map['id']:
_log.warning('Element use %s.%s renamed to %s', ctd.expandedName(), ed.expandedName(), ef_map['id'])
definitions.append(templates.replaceInText('''
# Element %{qname} uses Python identifier %{id}
%{use} = pyxb.binding.content.ElementDeclaration(%{name_expr}, '%{id}', '%{key}', %{is_plural}, %{decl_location}, %{aux_init})
''', name_expr=binding_module.literal(ed.expandedName(), **kw), **ef_map))
definitions.append(templates.replaceInText('''
%{inspector} = property(%{use}.value, %{use}.set, None, %{documentation})
''', **ef_map))
outf.postscript().append(templates.replaceInText('''
%{ctd}._AddElement(pyxb.binding.basis.element(%{name_expr}, %{typeDefinition}%{element_aux_init}))
''', name_expr=binding_module.literal(ed.expandedName(), **kw), ctd=template_map['ctd'], **ef_map))
auto_defn = GenerateAutomaton(ctd, binding_module=binding_module, **kw)
if auto_defn is not None:
(automaton_ctor, lines) = auto_defn
if lines:
outf.postscript().append("\n".join(lines))
outf.postscript().append("\n")
outf.postscript().append(templates.replaceInText('%{ctd}._Automaton = %{automaton_ctor}\n', ctd=template_map['ctd'], automaton_ctor=automaton_ctor))
outf.postscript().append("\n")
# Create definitions for all attributes.
attribute_uses = []