summaryrefslogtreecommitdiff
path: root/pyxb/binding/basis.py
blob: 53059556a06e0f61f8922a59f5d95eceb7526601 (plain)
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
# Copyright 2009, 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.

"""This module contains support classes from which schema-specific bindings
inherit, and that describe the content models of those schema."""

import pyxb
import xml.dom
import pyxb.utils.domutils as domutils
import pyxb.utils.utility as utility
import types
import re
import random
import pyxb.namespace
from pyxb.namespace.builtin import XMLSchema_instance as XSI

BINDING_STYLE_ACCESSOR = 'accessor'
BINDING_STYLE_PROPERTY = 'property'

BINDING_STYLES = (BINDING_STYLE_ACCESSOR, BINDING_STYLE_PROPERTY)
DEFAULT_BINDING_STYLE = BINDING_STYLE_PROPERTY
CURRENT_BINDING_STYLE = None

def ConfigureBindingStyle (style):
    global CURRENT_BINDING_STYLE
    simpleTypeDefinition._ConfigureBindingStyle(style)
    complexTypeDefinition._ConfigureBindingStyle(style)
    CURRENT_BINDING_STYLE = style

class _TypeBinding_mixin (utility.Locatable_mixin):

    @classmethod
    def _PerformValidation (cls):
        """Determine whether the content model should be validated.

        Proper validation is not yet supported in PyXB.  The low level binding
        material consults this function, but not always in a context where the
        direction of translation is clear.  Conseequently, this method
        indicates that validation should be performed only when both
        generation and parsing validation are enabled."""
        #    return True
        return pyxb._GenerationRequiresValid and pyxb._ParsingRequiresValid
    
    _ExpandedName = None
    """The expanded name of the component."""

    _ReservedSymbols = set([ 'validateBinding', 'iterateBinding', 'toDOM', 'toxml', 'Factory', 'property' ])

    if pyxb._CorruptionDetectionEnabled:
        def __setattr__ (self, name, value):
            if name in self._ReservedSymbols:
                raise pyxb.BindingError('Attempt to set reserved name %s in instance of %s' % (name, type(self)))
            return super(_TypeBinding_mixin, self).__setattr__(name, value)

    # @todo: We don't actually use this anymore; get rid of it, just leaving a
    # comment describing each keyword.
    _PyXBFactoryKeywords = ( '_dom_node', '_fallback_namespace', '_apply_whitespace_facet', '_validate_constraints', '_require_value', '_nil', '_element', '_convert_string_values' )
    """Keywords that are interpreted by __new__ or __init__ in one or more
    classes in the PyXB type hierarchy.  All these keywords must be removed
    before invoking base Python __init__ or __new__."""

    # While simple type definitions cannot be abstract, they can appear in
    # many places where complex types can, so we want it to be legal to test
    # for abstractness without checking whether the object is a complex type.
    _Abstract = False

    def _namespaceContext (self):
        """Return a L{namespace context <pyxb.binding.NamespaceContext>}
        associated with the binding instance.

        This will return C{None} unless something has provided a context to
        the instance.  Context is provided when instances are generated by the
        DOM and SAX-based translators."""
        return self.__namespaceContext
    def _setNamespaceContext (self, namespace_context):
        """Associate a L{namespace context <pyxb.binding.NamespaceContext>}
        with the binding instance."""
        self.__namespaceContext = namespace_context
        return self
    __namespaceContext = None

    def _setElement (self, element):
        """Associate a L{pyxb.binding.basis.element} with the instance."""
        self.__element = element
        return self
    def _element (self):
        """Return a L{pyxb.binding.basis.element} associated with the binding
        instance.

        This will return C{None} unless an element has been associated.
        Constructing a binding instance using the element instance will add
        this association.
        """
        return self.__element
    __element = None

    __xsiNil = None
    def _isNil (self):
        """Indicate whether this instance is U{nil
        <http://www.w3.org/TR/xmlschema-1/#xsi_nil>}.

        The value is set by the DOM and SAX parsers when building an instance
        from a DOM element with U{xsi:nil
        <http://www.w3.org/TR/xmlschema-1/#xsi_nil>} set to C{true}.

        @return: C{None} if the element used to create the instance is not
        U{nillable<http://www.w3.org/TR/xmlschema-1/#nillable>}. 
        If it is nillable, returns C{True} or C{False} depending on
        whether the instance itself is U{nil<http://www.w3.org/TR/xmlschema-1/#xsi_nil>}.
        """
        return self.__xsiNil
    def _setIsNil (self):
        """Set the xsi:nil property of the instance.

        @raise pyxb.NoNillableSupportError: the instance is not associated
        with an element that is L{nillable
        <pyxb.binding.basis.element.nillable>}.
        """
        if self.__xsiNil is None:
            raise pyxb.NoNillableSupportError(type(self))
        self.__xsiNil = True
        self._resetContent()

    def _resetContent (self):
        pass

    __constructedWithValue = False
    def __checkNilCtor (self, args):
        self.__constructedWithValue = (0 < len(args))
        if self.__xsiNil:
            if self.__constructedWithValue:
                raise pyxb.ContentInNilElementError(args[0])
        else:
            # Types that descend from string will, when constructed from an
            # element with empty content, appear to have no constructor value,
            # while in fact an empty string should have been passed.
            if issubclass(type(self), basestring):
                self.__constructedWithValue = True
    def _constructedWithValue (self):
        return self.__constructedWithValue

    # Flag used to control whether we print a warning when creating a complex
    # type instance that does not have an associated element.  Not sure yet
    # whether that'll be common practice or common error.
    __WarnedUnassociatedElement = False

    def __init__ (self, *args, **kw):
        # Strip keyword not used above this level.
        element = kw.pop('_element', None)
        is_nil = kw.pop('_nil', False)
        super(_TypeBinding_mixin, self).__init__(*args, **kw)
        if (element is None) or element.nillable():
            self.__xsiNil = is_nil
        self.__checkNilCtor(args)
        if element is not None:
            self._setElement(element)

    @classmethod
    def _PreFactory_vx (cls, args, kw):
        """Method invoked upon entry to the Factory method.

        This method is entitled to modify the keywords array.  It can also
        return a state value which is passed to _postFactory_vx."""
        return None

    def _postFactory_vx (cls, state):
        """Method invoked prior to leaving the Factory method.

        This is an instance method, and is given the state that was returned
        by _PreFactory_vx."""
        return None

    @classmethod
    def Factory (cls, *args, **kw):
        """Provide a common mechanism to create new instances of this type.

        The class constructor won't do, because you can't create
        instances of union types.

        This method may be overridden in subclasses (like STD_union).  Pre-
        and post-creation actions can be customized on a per-class instance by
        overriding the L{_PreFactory_vx} and L{_postFactory_vx} methods.

        @keyword _dom_node: If provided, the value must be a DOM node, the
        content of which will be used to set the value of the instance.

        @keyword _apply_whitespace_facet: If C{True} and this is a
        simpleTypeDefinition with a whiteSpace facet, the first argument will
        be normalized in accordance with that facet prior to invoking the
        parent constructor.

        @keyword _validate_constraints: If C{True}, any constructed value is
        checked against constraints applied to the union as well as the member
        type.

        @keyword _require_value: If C{False} (default), it is permitted to
        create a value without an initial value.  If C{True} and no initial
        value was provided, causes L{pyxb.MissingContentError} to be raised.
        Only applies to simpleTypeDefinition instances; this is used when
        creating values from DOM nodes.
        """
        # Invoke _PreFactory_vx for the superseding class, which is where
        # customizations will be found.
        dom_node = kw.get('_dom_node')
        used_cls = cls._SupersedingClass()
        state = used_cls._PreFactory_vx(args, kw)
        rv = cls._DynamicCreate(*args, **kw)
        rv._postFactory_vx(state)
        if isinstance(dom_node, utility.Locatable_mixin):
            rv._setLocation(dom_node.location)
        return rv

    def _substitutesFor (self, element):
        if (element is None) or (self._element() is None):
            return False
        return self._element().substitutesFor(element)

    @classmethod
    def _RequireXSIType (cls, value_type):
        return cls._Abstract and value_type != cls._SupersedingClass()

    @classmethod
    def _CompatibleValue (cls, value, **kw):
        """Return a variant of the value that is compatible with this type.

        Compatibility is defined relative to the type definition associated
        with the element.  The value C{None} is always compatible.  If
        C{value} has a Python type (e.g., C{int}) that is a superclass of the
        required L{_TypeBinding_mixin} class (e.g., C{xs:byte}), C{value} is
        used as a constructor parameter to return a new instance of the
        required type.  Note that constraining facets are applied here if
        necessary (e.g., although a Python C{int} with value C{500} is
        type-compatible with C{xs:byte}, it is outside the value space, and
        compatibility will fail.

        @keyword _convert_string_values: If C{True} (default) and the incoming value is
        a string, an attempt will be made to form a compatible value by using
        the string as a constructor argument to the this class.  This flag is
        set to C{False} when testing automaton transitions.

        @raise pyxb.BadTypeValueError: if the value is not both
        type-consistent and value-consistent with the element's type.
        """
        convert_string_values = kw.get('_convert_string_values', True)
        # None is always None
        if value is None:
            return None
        # Already an instance?
        if isinstance(value, cls):
            # @todo: Consider whether we should change the associated _element
            # of this value.  (**Consider** it, don't just do it.)
            return value
        value_type = type(value)
        # All string-based PyXB binding types use unicode, not str
        if str == value_type:
            value_type = unicode

        # See if we got passed a Python value which needs to be "downcasted"
        # to the _TypeBinding_mixin version.
        if issubclass(cls, value_type):
            return cls(value)

        # See if we have a numeric type that needs to be cast across the
        # numeric hierarchy.  int to long is the *only* conversion we accept.
        if isinstance(value, int) and issubclass(cls, long):
            return cls(value)

        # Same, but for boolean, which Python won't let us subclass
        if isinstance(value, bool) and issubclass(cls, pyxb.binding.datatypes.boolean):
            return cls(value)

        # See if we have convert_string_values on, and have a string type that
        # somebody understands.
        if convert_string_values and (unicode == value_type):
            return cls(value)

        # Maybe this is a union?
        if issubclass(cls, STD_union):
            for mt in cls._MemberTypes:
                try:
                    return mt._CompatibleValue(value, **kw)
                except:
                    pass

        # Any type is compatible with the corresponding ur-type
        if (pyxb.binding.datatypes.anySimpleType == cls) and issubclass(value_type, simpleTypeDefinition):
            return value
        if (pyxb.binding.datatypes.anyType == cls) and issubclass(value_type, complexTypeDefinition):
            return value

        # Is this the wrapper class that indicates we should create a binding
        # from arguments?
        if isinstance(value, pyxb.BIND):
            return value.createInstance(cls.Factory, **kw)

        # There may be other things that can be converted to the desired type,
        # but we can't tell that from the type hierarchy.  Too many of those
        # things result in an undesirable loss of information: for example,
        # when an all model supports both numeric and string transitions, the
        # candidate is a number, and the string transition is tested first.
        raise pyxb.BadTypeValueError('No conversion from %s to %s' % (value_type, cls))

    @classmethod
    def _IsSimpleTypeContent (cls):
        """Return True iff the content of this binding object is a simple type.

        This is true only for descendents of simpleTypeDefinition and instances
        of complexTypeDefinition that have simple type content."""
        raise pyxb.LogicError('Failed to override _TypeBinding_mixin._IsSimpleTypeContent')

    def toDOM (self, bds=None, parent=None, element_name=None):
        """Convert this instance to a DOM node.

        The name of the top-level element is either the name of the L{element}
        instance associated with this instance, or the XML name of the type of
        this instance.

        @param bds: Support for customizing the generated document
        @type bds: L{pyxb.utils.domutils.BindingDOMSupport}
        @param parent: If C{None}, a standalone document is created;
        otherwise, the created element is a child of the given element.
        @type parent: C{xml.dom.Element} or C{None}
        @rtype: C{xml.dom.Document}
        """

        if bds is None:
            bds = domutils.BindingDOMSupport()
        need_xsi_type = bds.requireXSIType()
        if isinstance(element_name, (str, unicode)):
            element_name = pyxb.namespace.ExpandedName(bds.defaultNamespace(), element_name)
        if (element_name is None) and (self._element() is not None):
            element_binding = self._element()
            element_name = element_binding.name()
            need_xsi_type = need_xsi_type or element_binding.typeDefinition()._RequireXSIType(type(self))
        if element_name is None:
            element_name = self._ExpandedName
        element = bds.createChildElement(element_name, parent)
        if need_xsi_type:
            val_type_qname = self._ExpandedName.localName()
            tns_prefix = bds.namespacePrefix(self._ExpandedName.namespace())
            if tns_prefix is not None:
                val_type_qname = '%s:%s' % (tns_prefix, val_type_qname)
            bds.addAttribute(element, XSI.type, val_type_qname)
        self._toDOM_csc(bds, element)
        bds.finalize()
        return bds.document()

    def toxml (self, bds=None, root_only=False):
        """Shorthand to get the object as an XML document.

        If you want to set the default namespace, pass in a pre-configured
        C{bds}.

        @param bds: Optional L{pyxb.utils.domutils.BindingDOMSupport} instance
        to use for creation. If not provided (default), a new generic one is
        created.
        """
        dom = self.toDOM(bds)
        if root_only:
            dom = dom.documentElement
        return dom.toxml()

    def _toDOM_csc (self, dom_support, parent):
        assert parent is not None
        if self.__xsiNil:
            dom_support.addAttribute(parent, XSI.nil, 'true')
        return getattr(super(_TypeBinding_mixin, self), '_toDOM_csc', lambda *_args,**_kw: dom_support)(dom_support, parent)

    def _validateBinding_vx (self):
        """Override in subclasses for type-specific validation of instance
        content.

        @return: C{True} if the instance validates
        @raise pyxb.BindingValidationError: complex content does not match model
        @raise pyxb.BadTypeValueError: simple content fails to satisfy constraints
        """
        raise pyxb.IncompleteImplementationError('%s did not override _validateBinding_vx' % (type(self),))

    def validateBinding (self):
        """Check whether the binding content matches its content model.

        @return: C{True} if validation succeeds.
        @raise pyxb.BindingValidationError: complex content does not match model
        @raise pyxb.BadTypeValueError: simple content fails to satisfy constraints
        """
        if self._PerformValidation():
            self._validateBinding_vx()
        return True

    def _iterateBinding_vx (self, namesRegExp):
        """Override in subclasses for type-specific iteration of instance
        content.

        @return: C{True} if the iteration succeeded
        @raise pyxb.BindingValidationError: complex content does not match model
        @raise pyxb.BadTypeValueError: simple content fails to satisfy constraints
        """
        raise pyxb.IncompleteImplementationError('%s did not override _iterateBinding_vx' % (type(self),))

    def iterateBinding (self, namesRegExp):
        """Perform one iteration on permissible binding values.

        Prerequisite: a schema-valid document. Names list can be any (sub)string
        of XSD entity, like type, or element/attribute name. Iteration respects
        permissible simple and complex type value ranges.
        
        @return: C{True} if iteration succeeds.
        @raise pyxb.BindingValidationError: complex content does not match model
        @raise pyxb.BadTypeValueError: simple content fails to satisfy constraints
        """
        self.validateBinding()
        for i in self._iterateBinding_vx(namesRegExp):
            yield i

    def _postDOMValidate (self):
        self.validateBinding()
        return self

    @classmethod
    def _Name (cls):
        if cls._ExpandedName is not None:
            name = str(cls._ExpandedName)
        else:
            name = str(type(cls))
        return name

class _DynamicCreate_mixin (pyxb.cscRoot):
    """Helper to allow overriding the implementation class.

    Generally we'll want to augment the generated bindings by subclassing
    them, and adding functionality to the subclass.  This mix-in provides a
    way to communicate the existence of the superseding subclass back to the
    binding infrastructure, so that when it creates an instance it uses the
    subclass rather than the unaugmented binding class.

    When a raw generated binding is subclassed, L{_SetSupersedingClass} should be
    invoked on the raw class passing in the superseding subclass.  E.g.::

      class mywsdl (raw.wsdl):
        pass
      raw.wsdl._SetSupersedingClass(mywsdl)

    """
    
    @classmethod
    def __SupersedingClassAttribute (cls):
        return '_%s__SupersedingClass' % (cls.__name__,)

    @classmethod
    def __AlternativeConstructorAttribute (cls):
        return '_%s__AlternativeConstructor' % (cls.__name__,)

    @classmethod
    def _SupersedingClass (cls):
        """Return the class stored in the class reference attribute."""
        return getattr(cls, cls.__SupersedingClassAttribute(), cls)

    @classmethod
    def _AlternativeConstructor (cls):
        """Return the class stored in the class reference attribute."""
        rv = getattr(cls, cls.__AlternativeConstructorAttribute(), None)
        if isinstance(rv, tuple):
            rv = rv[0]
        return rv

    @classmethod
    def _SetSupersedingClass (cls, superseding):
        """Set the class reference attribute.

        @param superseding: A Python class that is a subclass of this class.
        """
        assert (superseding is None) or issubclass(superseding, cls)
        if superseding is None:
            cls.__dict__.pop(cls.__SupersedingClassAttribute(), None)
        else:
            setattr(cls, cls.__SupersedingClassAttribute(), superseding)
        return superseding

    @classmethod
    def _SetAlternativeConstructor (cls, alternative_constructor):
        attr = cls.__AlternativeConstructorAttribute()
        if alternative_constructor is None:
            cls.__dict__.pop(attr, None)
        else:
            # Need to use a tuple as the value: if you use an invokable, this
            # ends up converting it from a function to an unbound method,
            # which is not what we want.
            setattr(cls, attr, (alternative_constructor,))
        assert cls._AlternativeConstructor() == alternative_constructor
        return alternative_constructor

    @classmethod
    def _DynamicCreate (cls, *args, **kw):
        """Invoke the constructor for this class or the one that supersedes it."""
        ctor = cls._AlternativeConstructor()
        if ctor is None:
            ctor = cls._SupersedingClass()
        try:
            return ctor(*args, **kw)
        except TypeError, e:
            raise pyxb.BadTypeValueError(e)

class simpleTypeDefinition (_TypeBinding_mixin, utility._DeconflictSymbols_mixin, _DynamicCreate_mixin):
    """L{simpleTypeDefinition} is a base class that is part of the
    hierarchy of any class that represents the Python datatype for a
    L{SimpleTypeDefinition<pyxb.xmlschema.structures.SimpleTypeDefinition>}.

    @note: This class, or a descendent of it, must be the first class
    in the method resolution order when a subclass has multiple
    parents.  Otherwise, constructor keyword arguments may not be
    removed before passing them on to Python classes that do not
    accept them.
    """

    # A map from leaf classes in the facets module to instance of
    # those classes that constrain or otherwise affect the datatype.
    # Note that each descendent of simpleTypeDefinition has its own map.
    __FacetMap = {}

    _ReservedSymbols = _TypeBinding_mixin._ReservedSymbols.union(set([ 'XsdLiteral', 'xsdLiteral',
                            'XsdSuperType', 'XsdPythonType', 'XsdConstraintsOK',
                            'xsdConstraintsOK', 'XsdValueLength', 'xsdValueLength',
                            'PythonLiteral', 'pythonLiteral',
                            'SimpleTypeDefinition' ]))
    """Symbols that remain the responsibility of this class.  Any
    public symbols in generated binding subclasses are deconflicted
    by providing an alternative name in the subclass.  (There
    currently are no public symbols in generated SimpleTypeDefinion
    bindings."""


    @classmethod
    def _ConfigureBindingStyle (cls, style):
        if BINDING_STYLE_PROPERTY == style:
            pass
        elif BINDING_STYLE_ACCESSOR == style:
            pass
        else:
            raise pyxb.LogicError('Unrecognized binding style %s' % (style,))

    # Determine the name of the class-private facet map.  For the base class
    # this should produce the same attribute name as Python's privatization
    # scheme.
    __FacetMapAttributeNameMap = { }
    @classmethod
    def __FacetMapAttributeName (cls):
        """ """
        '''
        if cls == simpleTypeDefinition:
            return '_%s__FacetMap' % (cls.__name__.strip('_'),)

        # It is not uncommon for a class in one namespace to extend a class of
        # the same name in a different namespace, so encode the namespace URI
        # in the attribute name (if it is part of a namespace).
        ns_uri = ''
        try:
            ns_uri = cls._ExpandedName.namespaceURI()
        except Exception, e:
            pass
        nm = '_' + utility.MakeIdentifier('%s_%s_FacetMap' % (ns_uri, cls.__name__.strip('_')))
        '''
        nm = cls.__FacetMapAttributeNameMap.get(cls)
        if nm is None:
            nm = cls.__name__
            if nm.endswith('_'):
                nm += '1'
            if cls == simpleTypeDefinition:
                nm = '_%s__FacetMap' % (nm,)
            else:
                # It is not uncommon for a class in one namespace to extend a class of
                # the same name in a different namespace, so encode the namespace URI
                # in the attribute name (if it is part of a namespace).
                ns_uri = ''
                try:
                    ns_uri = cls._ExpandedName.namespaceURI()
                except Exception, e:
                    pass
                nm = '_' + utility.MakeIdentifier('%s_%s_FacetMap' % (ns_uri, nm))
            cls.__FacetMapAttributeNameMap[cls] = nm
        return nm

    @classmethod
    def _FacetMap (cls):
        """Return a reference to the facet map for this datatype.

        The facet map is a map from leaf facet classes to instances of those
        classes that constrain or otherwise apply to the lexical or value
        space of the datatype.  Classes may inherit their facet map from their
        superclass, or may create a new class instance if the class adds a new
        constraint type.

        :raise AttributeError: if the facet map has not been defined"""
        return getattr(cls, cls.__FacetMapAttributeName())
    
    @classmethod
    def _InitializeFacetMap (cls, *args):
        """Initialize the facet map for this datatype.

        This must be called exactly once, after all facets belonging to the
        datatype have been created.

        :raise pyxb.LogicError: if called multiple times (on the same class)
        :raise pyxb.LogicError: if called when a parent class facet map has not been initialized
        :return: the facet map"""
        fm = None
        try:
            fm = cls._FacetMap()
        except AttributeError:
            pass
        if fm is not None:
            raise pyxb.LogicError('%s facet map initialized multiple times: %s' % (cls.__name__, cls.__FacetMapAttributeName()))

        # Search up the type hierarchy to find the nearest ancestor that has a
        # facet map.  This gets a bit tricky: if we hit the ceiling early
        # because the PSTD hierarchy re-based itself on a new Python type, we
        # have to jump to the XsdSuperType.
        source_class = cls
        while fm is None:
            # Assume we're staying in this hierarchy.  Include source_class in
            # the candidates, since we might have jumped to it.
            for super_class in source_class.mro():
                #print 'Superclass for %s is %s' % (source_class, super_class)
                assert super_class is not None
                if (super_class == simpleTypeDefinition): # and (source_class.XsdSuperType() is not None):
                    break
                if issubclass(super_class, simpleTypeDefinition):
                    try:
                        fm = super_class._FacetMap()
                        #print 'Selected facet map for %s from %s: %s' % (cls, super_class, fm)
                        break
                    except AttributeError:
                        pass
            if fm is None:
                try:
                    source_class = source_class.XsdSuperType()
                except AttributeError:
                    source_class = None
                #print 'Nothing acceptable found, jumped to %s' % (source_class,)
                if source_class is None:
                    fm = { }
        #print 'Done with set'
        if fm is None:
            raise pyxb.LogicError('%s is not a child of simpleTypeDefinition' % (cls.__name__,))
        fm = fm.copy()
        #print 'Augmenting %s map had %d elts with %d from args' % (cls, len(fm), len(args))
        for facet in args:
            fm[type(facet)] = facet
        #for (fc, fi) in fm.items():
        #    print ' %s : %s' % (fc, fi)
        setattr(cls, cls.__FacetMapAttributeName(), fm)
        return fm

    @classmethod
    def _ConvertArguments_vx (cls, args, kw):
        return args

    @classmethod
    def _ConvertArguments (cls, args, kw):
        """Pre-process the arguments.

        This is used before invoking the parent constructor.  One application
        is to apply the whitespace facet processing; if such a request is in
        the keywords, it is removed so it does not propagate to the
        superclass.  Another application is to convert the arguments from a
        string to a list.  Binding-specific applications are performed in the
        overloaded L{_ConvertArguments_vx} method."""
        dom_node = kw.pop('_dom_node', None)
        if dom_node is not None:
            text_content = domutils.ExtractTextContent(dom_node)
            if text_content is not None:
                args = (domutils.ExtractTextContent(dom_node),) + args
                kw['_apply_whitespace_facet'] = True
        apply_whitespace_facet = kw.pop('_apply_whitespace_facet', True)
        if (0 < len(args)) and isinstance(args[0], types.StringTypes) and apply_whitespace_facet:
            cf_whitespace = getattr(cls, '_CF_whiteSpace', None)
            if cf_whitespace is not None:
                #print 'Apply whitespace %s to "%s"' % (cf_whitespace, args[0])
                norm_str = unicode(cf_whitespace.normalizeString(args[0]))
                args = (norm_str,) + args[1:]
        return cls._ConvertArguments_vx(args, kw)

    # Must override new, because new gets invoked before init, and usually
    # doesn't accept keywords.  In case it does (e.g., datetime.datetime),
    # only remove the ones that would normally be interpreted by this class.
    # Do the same argument conversion as is done in init.  Trap errors and
    # convert them to BadTypeValue errors.
    #
    # Note: We explicitly do not validate constraints here.  That's
    # done in the normal constructor; here, we might be in the process
    # of building a value that eventually will be legal, but isn't
    # yet.
    def __new__ (cls, *args, **kw):
        # PyXBFactoryKeywords
        kw.pop('_validate_constraints', None)
        kw.pop('_require_value', None)
        kw.pop('_element', None)
        kw.pop('_fallback_namespace', None)
        kw.pop('_nil', None)
        # ConvertArguments will remove _element and _apply_whitespace_facet
        args = cls._ConvertArguments(args, kw)
        assert issubclass(cls, _TypeBinding_mixin)
        try:
            rv = super(simpleTypeDefinition, cls).__new__(cls, *args, **kw)
            return rv
        except ValueError, e:
            raise pyxb.BadTypeValueError(e)
        except OverflowError, e:
            raise pyxb.BadTypeValueError(e)

    # Validate the constraints after invoking the parent constructor,
    # unless told not to.
    def __init__ (self, *args, **kw):
        """Initialize a newly created STD instance.
        
        Usually there is one positional argument, which is a value that can be
        converted to the underlying Python type.

        @keyword _validate_constraints: If True (default), the newly
        constructed value is checked against its constraining facets.
        @type _validate_constraints: C{bool}
        """
        # PyXBFactoryKeywords
        validate_constraints = kw.pop('_validate_constraints', self._PerformValidation())
        require_value = kw.pop('_require_value', False)
        # _ConvertArguments handles _dom_node and _apply_whitespace_facet
        # TypeBinding_mixin handles _nil and _element
        args = self._ConvertArguments(args, kw)
        try:
            super(simpleTypeDefinition, self).__init__(*args, **kw)
        except OverflowError, e:
            raise pyxb.BadTypeValueError(e)
        if require_value and (not self._constructedWithValue()):
            raise pyxb.MissingContentError('missing value')
            
        if validate_constraints:
            self.xsdConstraintsOK()


    # The class attribute name used to store the reference to the STD
    # component instance must be unique to the class, not to this base class.
    # Otherwise we mistakenly believe we've already associated a STD instance
    # with a class (e.g., xsd:normalizedString) when in fact it's associated
    # with the superclass (e.g., xsd:string)
    @classmethod
    def __STDAttrName (cls):
        return '_%s__SimpleTypeDefinition' % (cls.__name__,)

    @classmethod
    def _SimpleTypeDefinition (cls, std):
        """Set the L{pyxb.xmlschema.structures.SimpleTypeDefinition} instance
        associated with this binding."""
        attr_name = cls.__STDAttrName()
        if hasattr(cls, attr_name):
            old_value = getattr(cls, attr_name)
            if old_value != std:
                raise pyxb.LogicError('%s: Attempt to override existing STD %s with %s' % (cls, old_value.name(), std.name()))
        setattr(cls, attr_name, std)

    @classmethod
    def SimpleTypeDefinition (cls):
        """Return the SimpleTypeDefinition instance for the given
        class.

        This should only be invoked when generating bindings.

        @raise pyxb.IncompleteImplementationError: no STD instance has been
        associated with the class.

        """
        attr_name = cls.__STDAttrName()
        if hasattr(cls, attr_name):
            return getattr(cls, attr_name)
        raise pyxb.IncompleteImplementationError('%s: No STD available' % (cls,))

    @classmethod
    def XsdLiteral (cls, value):
        """Convert from a python value to a string usable in an XML
        document.

        This should be implemented in the subclass."""
        raise pyxb.LogicError('%s does not implement XsdLiteral' % (cls,))

    def xsdLiteral (self):
        """Return text suitable for representing the value of this
        instance in an XML document.

        The base class implementation delegates to the object class's
        XsdLiteral method."""
        if self._isNil():
            return ''
        return self.XsdLiteral(self)

    @classmethod
    def XsdSuperType (cls):
        """Find the nearest parent class in the PST hierarchy.

        The value for anySimpleType is None; for all others, it's a
        primitive or derived PST descendent (including anySimpleType)."""
        for sc in cls.mro():
            if sc == cls:
                continue
            if simpleTypeDefinition == sc:
                # If we hit the PST base, this is a primitive type or
                # otherwise directly descends from a Python type; return
                # the recorded XSD supertype.
                return cls._XsdBaseType
            if issubclass(sc, simpleTypeDefinition):
                return sc
        raise pyxb.LogicError('No supertype found for %s' % (cls,))

    @classmethod
    def _XsdConstraintsPreCheck_vb (cls, value):
        """Pre-extended class method to verify other things before
        checking constraints.

        This is used for list types, to verify that the values in the
        list are acceptable, and for token descendents, to check the
        lexical/value space conformance of the input.
        """
        super_fn = getattr(super(simpleTypeDefinition, cls), '_XsdConstraintsPreCheck_vb', lambda *a,**kw: value)
        return super_fn(value)

    # Cache of pre-computed sequences of class facets in the order required
    # for constraint validation
    __ClassFacetSequence = { }

    @classmethod
    def XsdConstraintsOK (cls, value):
        """Validate the given value against the constraints on this class.
        
        @raise pyxb.BadTypeValueError: if any constraint is violated.
        """

        value = cls._XsdConstraintsPreCheck_vb(value)

        facet_values = cls.__ClassFacetSequence.get(cls)
        if facet_values is None:
            # Constraints for simple type definitions are inherited.  Check them
            # from least derived to most derived.
            classes = [ _x for _x in cls.mro() if issubclass(_x, simpleTypeDefinition) ]
            classes.reverse()
            cache_result = True
            facet_values = []
            for clazz in classes:
                # When setting up the datatypes, if we attempt to validate
                # something before the facets have been initialized (e.g., a
                # nonNegativeInteger used as a length facet for the parent
                # integer datatype), just ignore that for now.  Don't cache
                # the value, though, since a subsequent check after
                # initialization should succceed.
                try:
                    clazz_facets = clazz._FacetMap().values()
                except AttributeError, e:
                    cache_result = False
                    clazz_facets = []
                for v in clazz_facets:
                    if not (v in facet_values):
                        facet_values.append(v)
            if cache_result:
                cls.__ClassFacetSequence[cls] = facet_values
        for f in facet_values:
            if not f.validateConstraint(value):
                raise pyxb.BadTypeValueError('%s violation for %s in %s' % (f.Name(), value, cls.__name__))
            #print '%s ok for %s' % (f, value)
        return value

    def xsdConstraintsOK (self):
        """Validate the value of this instance against its constraints."""
        return self.XsdConstraintsOK(self)

    def _validateBinding_vx (self):
        if not self._isNil():
            self._checkValidValue()
        return True

    @classmethod
    def iterateValue (cls, value):
        """Iterate the given value within the constraints on this class.
        
        @raise pyxb.BadTypeValueError: if any constraint is violated by trying to.
        """
        value_ = None
        facet_values = cls.__ClassFacetSequence.get(cls);
        for fac in facet_values:
            try:
                val = fac.iterateValue(value)
                if val is not None and val != value:
                    cls.XsdConstraintsOK(val) #Adding complexity
                    value_ = cls.Factory(val)
                    break
            except (pyxb.PyXBError, BaseException):
                pass

        # TODO: nasty special case. can't we do that via polymorphism?
        if value_ is None:
            value_ = value._fuzz_vx(value)
        cls.XsdConstraintsOK(value_)
        return value_

    def _iterateBinding_vx (self, namesRegExp):
        for pat in namesRegExp:
            if re.match(pat, str(self.__class__)):
                yield lambda inst=self: inst._fuzz_vx(inst)

    @classmethod
    def XsdValueLength (cls, value):
        """Return the length of the given value.

        The length is calculated by a subclass implementation of
        _XsdValueLength_vx in accordance with
        http://www.w3.org/TR/xmlschema-2/#rf-length.

        The return value is a non-negative integer, or C{None} if length
        constraints should be considered trivially satisfied (as with
        QName and NOTATION).

        :raise pyxb.LogicError: the provided value is not an instance of cls.
        :raise pyxb.LogicError: an attempt is made to calculate a length for
        an instance of a type that does not support length calculations.
        """
        assert isinstance(value, cls)
        if not hasattr(cls, '_XsdValueLength_vx'):
            raise pyxb.LogicError('Class %s does not support length validation' % (cls.__name__,))
        return cls._XsdValueLength_vx(value)

    def xsdValueLength (self):
        """Return the length of this instance within its value space.

        See XsdValueLength."""
        return self.XsdValueLength(self)

    @classmethod
    def PythonLiteral (cls, value):
        """Return a string which can be embedded into Python source to
        represent the given value as an instance of this class."""
        class_name = cls.__name__
        return '%s(%s)' % (class_name, repr(value))

    def pythonLiteral (self):
        """Return a string which can be embedded into Python source to
        represent the value of this instance."""
        return self.PythonLiteral(self)

    def _toDOM_csc (self, dom_support, parent):
        assert parent is not None
        parent.appendChild(dom_support.document().createTextNode(self.xsdLiteral()))
        return getattr(super(simpleTypeDefinition, self), '_toDOM_csc', lambda *_args,**_kw: dom_support)(dom_support, parent)

    @classmethod
    def _IsSimpleTypeContent (cls):
        """STDs have simple type content."""
        return True

    @classmethod
    def _IsValidValue (self, value):
        try:
            self._CheckValidValue(value)
            return True
        except pyxb.PyXBException, e:
            pass
        return False

    @classmethod
    def _CheckValidValue (cls, value):

        """NB: Invoking this on a value that is a list will, if necessary,
        replace the members of the list with new values that are of the
        correct item type.  This is permitted because only with lists is it
        possible to bypass the normal content validation (by invoking
        append/extend on the list instance)."""
        if value is None:
            raise pyxb.BadTypeValueError('None is not a valid instance of %s' % (cls,))
        #print 'testing value %s type %s against %s' % (value, type(value), cls)
        value_class = cls
        if issubclass(cls, STD_list):
            #print ' -- checking list of %s' % (cls._ItemType,)
            try:
                iter(value)
            except TypeError, e:
                raise pyxb.BadTypeValueError('%s cannot have non-iterable value type %s' % (cls, type(value)))
            for v in value:
                if not cls._ItemType._IsValidValue(v):
                    raise pyxb.BadTypeValueError('%s cannot have member of type %s (want %s)' % (cls, type(v), cls._ItemType))
        else:
            if issubclass(cls, STD_union):
                #print ' -- checking union with %d types' % (len(cls._MemberTypes),)
                value_class = None
                for mt in cls._MemberTypes:
                    if mt._IsValidValue(value):
                        value_class = mt
                        break
                if value_class is None:
                    raise pyxb.BadTypeValueError('%s cannot have value type %s' % (cls, type(value)))
            #if not (isinstance(value, value_class) or issubclass(value_class, type(value))):
            if not isinstance(value, value_class):
                raise pyxb.BadTypeValueError('Value type %s is not valid for %s' % (type(value), cls))
        value_class.XsdConstraintsOK(value)

    def _checkValidValue (self):
        self._CheckValidValue(self)

    def _isValidValue (self):
        self._IsValidValue(self)

    @classmethod
    def _description (cls, name_only=False, user_documentation=True):
        name = cls._Name()
        if name_only:
            return name
        desc = [ name, ' restriction of ', cls.XsdSuperType()._description(name_only=True) ]
        if user_documentation and (cls._Documentation is not None):
            desc.extend(["\n", cls._Documentation])
        return ''.join(desc)

class STD_union (simpleTypeDefinition):
    """Base class for union datatypes.

    This class descends only from simpleTypeDefinition.  A pyxb.LogicError is
    raised if an attempt is made to construct an instance of a subclass of
    STD_union.  Values consistent with the member types are constructed using
    the Factory class method.  Values are validated using the _ValidatedMember
    class method.

    Subclasses must provide a class variable _MemberTypes which is a
    tuple of legal members of the union."""

    _MemberTypes = None
    """A list of classes which are permitted as values of the union."""

    # Ick: If we don't declare this here, this class's map doesn't get
    # initialized.  Alternative is to not descend from simpleTypeDefinition.
    # @todo Ensure that pattern and enumeration are valid constraints
    __FacetMap = {}

    @classmethod
    def Factory (cls, *args, **kw):
        """Given a value, attempt to create an instance of some member of this
        union.  The first instance which can be legally created is returned.

        @keyword _validate_constraints: If True (default), any constructed
        value is checked against constraints applied to the union as well as
        the member type.

        @raise pyxb.BadTypeValueError: no member type will permit creation of
        an instance from the parameters in C{args} and C{kw}.
        """

        used_cls = cls._SupersedingClass()
        state = used_cls._PreFactory_vx(args, kw)

        rv = None
        # NB: get, not pop: preserve it for the member type invocations
        validate_constraints = kw.get('_validate_constraints', cls._PerformValidation())
        assert isinstance(validate_constraints, bool)
        if 0 < len(args):
            arg = args[0]
            try:
                rv = cls._ValidatedMember(arg)
            except pyxb.BadTypeValueError, e:
                pass
        if rv is None:
            kw['_validate_constraints'] = True
            for mt in cls._MemberTypes:
                try:
                    rv = mt.Factory(*args, **kw)
                    break
                except pyxb.BadTypeValueError:
                    pass
                except ValueError:
                    pass
                except:
                    pass
        if rv is not None:
            if validate_constraints:
                cls.XsdConstraintsOK(rv)
            rv._postFactory_vx(state)
            return rv
        raise pyxb.BadTypeValueError('%s cannot construct union member from args %s' % (cls.__name__, args))

    @classmethod
    def _ValidatedMember (cls, value):
        """Validate the given value as a potential union member.

        @raise pyxb.BadTypeValueError: the value is not an instance of a
        member type."""
        if not isinstance(value, cls._MemberTypes):
            for mt in cls._MemberTypes:
                try:
                    # Force validation so we get the correct type, otherwise
                    # first member will be accepted.
                    value = mt.Factory(value, _validate_constraints=True)
                    return value
                except (TypeError, pyxb.BadTypeValueError):
                    pass
            raise pyxb.BadTypeValueError('%s cannot hold a member of type %s' % (cls.__name__, value.__class__.__name__))
        return value

    def __init__ (self, *args, **kw):
        raise pyxb.LogicError('%s: cannot construct instances of union' % (self.__class__.__name__,))

    @classmethod
    def _description (cls, name_only=False, user_documentation=True):
        name = cls._Name()
        if name_only:
            return name
        desc = [ name, ', union of ']
        desc.append(', '.join([ _td._description(name_only=True) for _td in cls._MemberTypes ]))
        return ''.join(desc)

    @classmethod
    def XsdLiteral (cls, value):
        """Convert from a binding value to a string usable in an XML document."""
        return cls._ValidatedMember(value).xsdLiteral()


class STD_list (simpleTypeDefinition, types.ListType):
    """Base class for collection datatypes.

    This class descends from the Python list type, and incorporates
    simpleTypeDefinition.  Subclasses must define a class variable _ItemType
    which is a reference to the class of which members must be instances."""

    _ItemType = None
    """A reference to the binding class for items within this list."""

    # Ick: If we don't declare this here, this class's map doesn't get
    # initialized.  Alternative is to not descend from simpleTypeDefinition.
    __FacetMap = {}

    @classmethod
    def _ValidatedItem (cls, value):
        """Verify that the given value is permitted as an item of this list.

        This may convert the value to the proper type, if it is
        compatible but not an instance of the item type.  Returns the
        value that should be used as the item, or raises an exception
        if the value cannot be converted."""
        if isinstance(value, cls._ItemType):
            pass
        elif issubclass(cls._ItemType, STD_union):
            value = cls._ItemType._ValidatedMember(value)
        else:
            try:
                value = cls._ItemType(value)
            except (pyxb.BadTypeValueError, TypeError):
                raise pyxb.BadTypeValueError('Type %s has member of type %s, must be %s' % (cls.__name__, type(value).__name__, cls._ItemType.__name__))
        return value

    @classmethod
    def _ConvertArguments_vx (cls, args, kw):
        # If the first argument is a string, split it on spaces and use the
        # resulting list of tokens.
        if 0 < len(args):
            arg1 = args[0]
            if isinstance(arg1, types.StringTypes):
                args = (arg1.split(),) + args[1:]
                arg1 = args[0]
            is_iterable = False
            try:
                iter(arg1)
                is_iterable = True
            except TypeError:
                pass
            if is_iterable:
                new_arg1 = []
                for i in range(len(arg1)):
                    new_arg1.append(cls._ValidatedItem(arg1[i]))
                args = (new_arg1,) + args[1:]
        super_fn = getattr(super(STD_list, cls), '_ConvertArguments_vx', lambda *a,**kw: args)
        return super_fn(args, kw)

    @classmethod
    def _XsdValueLength_vx (cls, value):
        return len(value)

    @classmethod
    def XsdLiteral (cls, value):
        """Convert from a binding value to a string usable in an XML document."""
        return ' '.join([ cls._ItemType.XsdLiteral(_v) for _v in value ])

    @classmethod
    def _description (cls, name_only=False, user_documentation=True):
        name = cls._Name()
        if name_only:
            return name
        desc = [ name, ', list of ', cls._ItemType._description(name_only=True) ]
        return ''.join(desc)

    # Convert a single value to the required type, if not already an instance
    @classmethod
    def __ConvertOne (cls, v):
        return cls._ValidatedItem(v)

    # Convert a sequence of values to the required type, if not already instances
    def __convertMany (self, values):
        return [ self._ValidatedItem(_v) for _v in values ]

    def __setitem__ (self, key, value):
        if isinstance(key, slice):
            super(STD_list, self).__setitem__(key, self.__convertMany(values))
        else:
            super(STD_list, self).__setitem__(key, self._ValidatedItem(value))

    def __setslice__ (self, start, end, values):
        super(STD_list, self).__setslice__(start, end, self.__convertMany(values))

    def __contains__ (self, item):
        return super(STD_list, self).__contains__(self._ValidatedItem(item))

    # Standard mutable sequence methods, per Python Library Reference "Mutable Sequence Types"

    def append (self, x):
        super(STD_list, self).append(self._ValidatedItem(x))

    def extend (self, x):
        super(STD_list, self).extend(self.__convertMany(x))

    def count (self, x):
        return super(STD_list, self).count(self._ValidatedItem(x))

    def index (self, x, *args):
        return super(STD_list, self).index(self._ValidatedItem(x), *args)

    def insert (self, i, x):
        super(STD_list, self).insert(i, self._ValidatedItem(x))

    def remove (self, x):
        super(STD_list, self).remove(self._ValidatedItem(x))

class element (utility._DeconflictSymbols_mixin, _DynamicCreate_mixin):
    """Class that represents a schema element.

    Global and local elements are represented by instances of this class.
    """

    def name (self):
        """The expanded name of the element within its scope."""
        return self.__name
    __name = None

    def typeDefinition (self):
        """The L{_TypeBinding_mixin} subclass for values of this element."""
        return self.__typeDefinition._SupersedingClass()
    __typeDefinition = None

    def scope (self):
        """The scope of the element.  This is either C{None}, representing a
        top-level element, or an instance of C{complexTypeDefinition} for
        local elements."""
        return self.__scope
    __scope = None

    def nillable (self):
        """Indicate whether values matching this element can have U{nil
        <http://www.w3.org/TR/xmlschema-1/#xsi_nil>} set."""
        return self.__nillable
    __nillable = False

    def abstract (self):
        """Indicate whether this element is abstract (must use substitution
        group members for matches)."""
        return self.__abstract
    __abstract = False

    def documentation (self):
        """Contents of any documentation annotation in the definition."""
        return self.__documentation
    __documentation = None

    def defaultValue (self):
        return self.__defaultValue
    __defaultValue = None

    def substitutionGroup (self):
        """The L{element} instance to whose substitution group this element
        belongs.  C{None} if this element is not part of a substitution
        group."""
        return self.__substitutionGroup
    def _setSubstitutionGroup (self, substitution_group):
        self.__substitutionGroup = substitution_group
        if substitution_group is not None:
            self.substitutesFor = self._real_substitutesFor
        return self
    __substitutionGroup = None

    def findSubstituendUse (self, ctd_class):
        eu = ctd_class._ElementMap.get(self.name())
        if eu is not None:
            return eu
        if self.substitutionGroup() is None:
            return None
        return self.substitutionGroup().findSubstituendUse(ctd_class)

    def _real_substitutesFor (self, other):
        """Determine whether an instance of this element can substitute for the other element.
        
        See U{Substitution Group OK<http://www.w3.org/TR/xmlschema-1/#cos-equiv-derived-ok-rec>)}.

        @todo: Do something about blocking constraints.  This ignores them, as
        does everything leading to this point.
        """
        if self.substitutionGroup() is None:
            return False
        if other is None:
            return False
        assert isinstance(other, element)
        # On the first call, other is likely to be the local element.  We need
        # the global one.
        if other.scope() is not None:
            other = other.name().elementBinding()
            if other is None:
                return False
            assert other.scope() is None
        # Do both these refer to the same (top-level) element?
        if self.name().elementBinding() == other:
            return True
        return (self.substitutionGroup() == other) or self.substitutionGroup().substitutesFor(other)

    def substitutesFor (self, other):
        """Stub replaced by _real_substitutesFor when element supports substitution groups."""
        return False

    def memberElement (self, name):
        """Return a reference to the element instance used for the given name
        within this element.

        The type for this element must be a complex type definition."""
        return self.typeDefinition()._UseForTag(name).elementBinding()

    def __init__ (self, name, type_definition, scope=None, nillable=False, abstract=False, default_value=None, substitution_group=None, documentation=None):
        """Create a new element binding.
        """
        assert isinstance(name, pyxb.namespace.ExpandedName)
        self.__name = name
        self.__typeDefinition = type_definition
        self.__scope = scope
        self.__nillable = nillable
        self.__abstract = abstract
        self.__defaultValue = default_value
        self.__substitutionGroup = substitution_group
        self.__documentation = documentation
        
    def __call__ (self, *args, **kw):
        """Invoke the Factory method on the type associated with this element.

        @keyword _dom_node: If set, specifies a DOM node that should be used
        for initialization.  In that case, the L{createFromDOM} method is
        invoked instead of the type definition Factory method.

        @raise pyxb.AbstractElementError: This element is abstract and no DOM
        node was provided.
        """
        dom_node = kw.pop('_dom_node', None)
        assert dom_node is None, 'Cannot pass DOM node directly to element constructor; use createFromDOM'
        if '_element' in kw:
            raise pyxb.LogicError('Cannot set _element in element-based instance creation')
        kw['_element'] = self
        # Can't create instances of abstract elements.
        if self.abstract():
            raise pyxb.AbstractElementError(self)
        return self.typeDefinition().Factory(*args, **kw)

    def compatibleValue (self, value, **kw):
        """Return a variant of the value that is compatible with this element.

        This mostly defers to L{_TypeBinding_mixin._CompatibleValue}.

        @raise pyxb.BadTypeValueError: if the value is not both
        type-consistent and value-consistent with the element's type.
        """
        # None is always None
        if value is None:
            return None
        is_plural = kw.pop('is_plural', False)
        #print 'validating %s against %s, isPlural %s' % (type(value), self.typeDefinition(), is_plural)
        if is_plural:
            try:
                iter(value)
            except TypeError:
                raise pyxb.BadTypeValueError('Expected plural value, got %s' % (type(value),))
            return [ self.compatibleValue(_v) for _v in value ]
        if isinstance(value, _TypeBinding_mixin) and (value._element() is not None) and value._element().substitutesFor(self):
            return value
        return self.typeDefinition()._CompatibleValue(value, **kw)

    # element
    @classmethod
    def AnyCreateFromDOM (cls, node, _fallback_namespace):
        if xml.dom.Node.DOCUMENT_NODE == node.nodeType:
            node = node.documentElement
        expanded_name = pyxb.namespace.ExpandedName(node, fallback_namespace=_fallback_namespace)
        elt = expanded_name.elementBinding()
        if elt is None:
            raise pyxb.UnrecognizedElementError(dom_node=node, element_name=expanded_name)
        assert isinstance(elt, pyxb.binding.basis.element)
        # Pass on the namespace to use when resolving unqualified qnames as in
        # xsi:type
        return elt._createFromDOM(node, expanded_name, _fallback_namespace=_fallback_namespace)
        
    def elementForName (self, name):
        """Return the element that should be used if this element binding is
        permitted and an element with the given name is encountered.

        Normally, the incoming name matches the name of this binding, and
        C{self} is returned.  If the incoming name is different, it is
        expected to be the name of a global element which is within this
        element's substitution group.  In that case, the binding corresponding
        to the named element is return.

        @return: An instance of L{element}, or C{None} if no element with the
        given name can be found.
        """

        # Name match means OK.
        if self.name() == name:
            return self
        # No name match means only hope is a substitution group, for which the
        # element must be top-level.
        top_elt = self.name().elementBinding()
        if top_elt is None:
            return None
        # Members of the substitution group must also be top-level.  NB: If
        # named_elt == top_elt, then the adoptName call below improperly
        # associated the global namespace with a local element of the same
        # name; cf. test-namespace-uu:testBad.
        elt_en = top_elt.name().adoptName(name)
        assert 'elementBinding' in elt_en.namespace()._categoryMap(), 'No element bindings in %s' % (elt_en.namespace(),)
        named_elt = elt_en.elementBinding()
        if (named_elt is None) or (named_elt == top_elt):
            return None
        if named_elt.substitutesFor(top_elt):
            return named_elt
        return None

    def createFromDOM (self, node, expanded_name=None, fallback_namespace=None, **kw):
        """Create a binding instance from the given DOM node.

        @keyword expanded_name: Optional name for the DOM node.  If not
        present, is inferred from C{node}.

        @keyword fallback_namespace: Optional namespace to use when resolving
        unqualified names.
        """
        if xml.dom.Node.DOCUMENT_NODE == node.nodeType:
            node = node.documentElement
        if expanded_name is None:
            expanded_name = pyxb.namespace.ExpandedName(node, fallback_namespace=fallback_namespace)
        return self._createFromDOM(node, expanded_name, **kw)

    def _createFromDOM (self, node, expanded_name, **kw):
        """Create a binding instance from the given DOM node, using the
        provided name to identify the correct binding.

        The context and information associated with this element is used to
        identify the actual element binding to use.  By default, C{self} is
        used.  If this element represents a term in a content model, the name
        and namespace of the incoming node may identify a different element.
        If that element is a member of this element's substitution group, the
        binding associated with the node's name will be used instead.

        The type of object returned is determined by the type definition
        associated with the element binding and the value of any U{xsi:type
        <http://www.w3.org/TR/xmlschema-1/#xsi_type>} attribute found in the
        node, modulated by the configuration of L{XSI.ProcessTypeAttribute<pyxb.namespace.builtin._XMLSchema_instance.ProcessTypeAttribute>}.

        Keyword parameters are passed to the factory method of the type
        associated with the selected element binding.  See
        L{_TypeBinding_mixin} and any specializations of it.

        @param expanded_name: The expanded name of the node.  If the value is
        C{None}, defaults to the name of this element.  (In the case of
        substitution groups, the default is wrong, but correct inference
        depends on context not available here.)

        @keyword _fallback_namespace: Optional namespace to use when resolving
        unqualified type names.

        @param node: The DOM node specifying the element content.  If this is
        a (top-level) Document node, its element node is used.
        @type node: C{xml.dom.Node}
        @return: An instance of L{_TypeBinding_mixin}
        @raise pyxb.StructuralBadDocumentError: The node's name does identify an element binding.
        @raise pyxb.AbstractElementError: The element binding associated with the node is abstract.
        @raise pyxb.BadDocumentError: An U{xsi:type <http://www.w3.org/TR/xmlschema-1/#xsi_type>} attribute in the node fails to resolve to a recognized type
        @raise pyxb.BadDocumentError: An U{xsi:type <http://www.w3.org/TR/xmlschema-1/#xsi_type>} attribute in the node resolves to a type that is not a subclass of the type of the element binding.
        """

        # Bypass the useless top-level node and start with the element beneath
        # it.
        if xml.dom.Node.DOCUMENT_NODE == node.nodeType:
            node = node.documentElement

        # Identify the element binding to be used for the given node.  NB:
        # Even if found, this may not be equal to self, since we allow you to
        # use an abstract substitution group head to create instances from DOM
        # nodes that are in that group.
        fallback_namespace = kw.pop('_fallback_namespace', None)
        element_binding = self.elementForName(expanded_name)
        if element_binding is None:
            raise pyxb.StructuralBadDocumentError('Element %s cannot create from node %s' % (self.name(), expanded_name))

        # Can't create instances of abstract elements.  @todo: Is there any
        # way this could be legal given an xsi:type attribute?  I'm pretty
        # sure "no"...
        if element_binding.abstract():
            raise pyxb.AbstractElementError(element_binding)

        # Record the element to be associated with the created binding
        # instance.
        if '_element' in kw:
            raise pyxb.LogicError('Cannot set _element in element-based instance creation')
        kw['_element'] = element_binding

        # Now determine the type binding for the content.  If xsi:type is
        # used, it won't be the one built into the element binding.
        type_class = element_binding.typeDefinition()
        elt_ns = element_binding.name().namespace()
 
        # Get the namespace context for the value being created.  If none is
        # associated, one will be created.  Do not make assumptions about the
        # namespace context; if the user cared, she should have assigned a
        # context before calling this.
        ns_ctx = pyxb.namespace.resolution.NamespaceContext.GetNodeContext(node)
        (did_replace, type_class) = XSI._InterpretTypeAttribute(XSI.type.getAttribute(node), ns_ctx, fallback_namespace, type_class)
            
        # Pass xsi:nil on to the constructor regardless of whether the element
        # is nillable.  Another sop to SOAP-encoding WSDL fans who don't
        # bother to provide valid schema for their message content.
        is_nil = XSI.nil.getAttribute(node)
        if is_nil is not None:
            kw['_nil'] = pyxb.binding.datatypes.boolean(is_nil)

        rv = type_class.Factory(_dom_node=node, _fallback_namespace=fallback_namespace, **kw)
        assert rv._element() == element_binding
        rv._setNamespaceContext(ns_ctx)
        return rv._postDOMValidate()

    def __str__ (self):
        return 'Element %s' % (self.name(),)

    def _description (self, name_only=False, user_documentation=True):
        name = str(self.name())
        if name_only:
            return name
        desc = [ name, ' (', self.typeDefinition()._description(name_only=True), ')' ]
        if self.scope() is not None:
            desc.extend([', local to ', self.scope()._description(name_only=True) ])
        if self.nillable():
            desc.append(', nillable')
        if self.substitutionGroup() is not None:
            desc.extend([', substitutes for ', self.substitutionGroup()._description(name_only=True) ])
        if user_documentation and (self.documentation() is not None):
            desc.extend(["\n", self.documentation() ])
        return ''.join(desc)

class enumeration_mixin (pyxb.cscRoot):
    """Marker in case we need to know that a PST has an enumeration constraint facet."""
    pass

class complexTypeDefinition (_TypeBinding_mixin, utility._DeconflictSymbols_mixin, _DynamicCreate_mixin):
    """Base for any Python class that serves as the binding for an
    XMLSchema complexType.

    Subclasses should define a class-level _AttributeMap variable which maps
    from the unicode tag of an attribute to the AttributeUse instance that
    defines it.  Similarly, subclasses should define an _ElementMap variable.
    """

    _CT_EMPTY = 'EMPTY'                 #<<< No content
    _CT_SIMPLE = 'SIMPLE'               #<<< Simple (character) content
    _CT_MIXED = 'MIXED'                 #<<< Children may be elements or other (e.g., character) content
    _CT_ELEMENT_ONLY = 'ELEMENT_ONLY'   #<<< Expect only element content.

    _ContentTypeTag = None

    _TypeDefinition = None
    """Subclass of simpleTypeDefinition that corresponds to the type content.
    Only valid if _ContentTypeTag is _CT_SIMPLE"""

    # If the type supports wildcard attributes, this describes their
    # constraints.  (If it doesn't, this should remain None.)  Supporting
    # classes should override this value.
    _AttributeWildcard = None

    _AttributeMap = { }
    """Map from expanded names to AttributeUse instances."""

    # A value that indicates whether the content model for this type supports
    # wildcard elements.  Supporting classes should override this value.
    _HasWildcardElement = False

    # Map from expanded names to ElementUse instances
    _ElementMap = { }
    """Map from expanded names to ElementUse instances."""

    # Per-instance map from tags to attribute values for wildcard attributes.
    # Value is C{None} if the type does not support wildcard attributes.
    __wildcardAttributeMap = None

    def wildcardAttributeMap (self):
        """Obtain access to wildcard attributes.

        The return value is C{None} if this type does not support wildcard
        attributes.  If wildcard attributes are allowed, the return value is a
        map from QNames to the unicode string value of the corresponding
        attribute.

        @todo: The map keys should be namespace extended names rather than
        QNames, as the in-scope namespace may not be readily available to the
        user.
        """
        return self.__wildcardAttributeMap

    # Per-instance list of DOM nodes interpreted as wildcard elements.
    # Value is None if the type does not support wildcard elements.
    __wildcardElements = None

    def wildcardElements (self):
        """Obtain access to wildcard elements.

        The return value is C{None} if the content model for this type does not
        support wildcard elements.  If wildcard elements are allowed, the
        return value is a list of values corresponding to conformant
        unrecognized elements, in the order in which they were encountered.
        If the containing binding was created from an XML document and enough
        information was present to determine the binding of the member
        element, the value is a binding instance.  Otherwise, the value is the
        original DOM Element node.
        """
        return self.__wildcardElements

    @classmethod
    def _ConfigureBindingStyle (cls, style):
        if BINDING_STYLE_PROPERTY == style:
            pass
        elif BINDING_STYLE_ACCESSOR == style:
            pass
        else:
            raise pyxb.LogicError('Unrecognized binding style %s' % (style,))

    def __init__ (self, *args, **kw):
        """Create a new instance of this binding.

        Arguments are used as transition values along the content model.
        Keywords are passed to the constructor of any simple content, or used
        to initialize attribute and element values whose L{id
        <content.ElementUse.id>} (not L{name <content.ElementUse.name>})
        matches the keyword.

        @keyword _dom_node: The node to use as the source of binding content.
        @type _dom_node: C{xml.dom.Element}

        """

        fallback_namespace = kw.pop('_fallback_namespace', None)
        is_nil = False
        dom_node = kw.pop('_dom_node', None)
        if dom_node is not None:
            if isinstance(dom_node, pyxb.utils.utility.Locatable_mixin):
                self._setLocation(dom_node.location)
            if xml.dom.Node.DOCUMENT_NODE == dom_node.nodeType:
                dom_node = dom_node.documentElement
            #kw['_validate_constraints'] = False
            is_nil = XSI.nil.getAttribute(dom_node)
            if is_nil is not None:
                is_nil = kw['_nil'] = pyxb.binding.datatypes.boolean(is_nil)
        if self._AttributeWildcard is not None:
            self.__wildcardAttributeMap = { }
        if self._HasWildcardElement:
            self.__wildcardElements = []
        if self._Abstract:
            raise pyxb.AbstractInstantiationError(type(self))
        super(complexTypeDefinition, self).__init__(**kw)
        self.reset()
        # Extract keywords that match field names
        attribute_settings = { }
        if dom_node is not None:
            attribute_settings.update(self.__AttributesFromDOM(dom_node))
        for fu in self._AttributeMap.values():
            iv = kw.pop(fu.id(), None)
            if iv is not None:
                attribute_settings[fu.name()] = iv
        for (attr_en, value) in attribute_settings.items():
            au = self._setAttribute(attr_en, value)
        for fu in self._ElementMap.values():
            iv = kw.pop(fu.id(), None)
            if iv is not None:
                fu.set(self, iv)
        if kw and kw.pop('_strict_keywords', True):
            [ kw.pop(_fkw, None) for _fkw in self._PyXBFactoryKeywords ]
            if kw:
                raise pyxb.ExtraContentError(kw)
        if dom_node is not None:
            if self._CT_SIMPLE == self._ContentTypeTag:
                self.__initializeSimpleContent(args, dom_node)
            else:
                self._setContentFromDOM(dom_node, fallback_namespace)
        elif 0 < len(args):
            self.extend(args)
        else:
            if self._CT_SIMPLE == self._ContentTypeTag:
                self.__initializeSimpleContent(args, dom_node)

    def __initializeSimpleContent (self, args, dom_node=None):
        # Don't propagate the keywords.  Python base simple types usually
        # don't like them, and even if they do we're not using them here.  (Do
        # need to propagate _nil, though, to correctly handle types derived
        # from basestring.)
        value = self._TypeDefinition.Factory(_require_value=not self._isNil(), _dom_node=dom_node, _nil=self._isNil(), *args)
        if value._constructedWithValue():
            if self._isNil():
                raise pyxb.ContentInNilElementError(value)
            else:
                self.append(value)

    # Specify the symbols to be reserved for all CTDs.
    _ReservedSymbols = _TypeBinding_mixin._ReservedSymbols.union(set([ 'wildcardElements', 'wildcardAttributeMap',
                             'xsdConstraintsOK', 'content', 'append', 'extend', 'value', 'reset' ]))

    # None, or a reference to a ParticleModel instance that defines how to
    # reduce a DOM node list to the body of this element.
    _ContentModel = None

    @classmethod
    def _AddElement (cls, element):
        """Method used by generated code to associate the element binding with a use in this type.

        This is necessary because all complex type classes appear in the
        module prior to any of the element instances (which reference type
        classes), so the association must be formed after the element
        instances are available."""
        return cls._UseForTag(element.name())._setElementBinding(element)

    @classmethod
    def _UseForTag (cls, tag, raise_if_fail=True):
        """Return the ElementUse object corresponding to the element name.

        @param tag: The L{ExpandedName} of an element in the class."""
        rv = cls._ElementMap.get(tag)
        if (rv is None) and raise_if_fail:
            raise pyxb.NotAnElementError(tag, cls)
        return rv

    def __childrenForDOM (self):
        """Generate a list of children in the order in which they should be
        added to the parent when creating a DOM representation of this
        object.

        @note: This is not currently used; it is retained as an example of one
        way to override L{_validatedChildren} in cases where content model
        validation is not required.
        """
        order = []
        for eu in self._ElementMap.values():
            value = eu.value(self)
            if value is None:
                continue
            if isinstance(value, list):
                order.extend([ (eu, _v) for _v in value ])
                continue
            order.append( (eu, value) )
        return order

    def _validatedChildren (self):
        """Provide the child elements and non-element content in an order
        consistent with the content model.
        
        Returns a sequence of tuples representing a valid path through the
        content model where each transition corresponds to one of the member
        element instances within this instance.  The tuple is a pair
        comprising the L{content.ElementUse} instance and the value for the
        transition.

        If the content of the instance does not validate against the content
        model, C{None} is returned.

        The base class implementation uses the
        L{content.ParticleModel.validate} method.  Subclasses may desire to
        override this in cases where the desired order is not maintained by
        model interpretation (for example, when an "all" model is used and the
        original element order is desired).  See L{__childrenForDOM} as an
        example of an alternative approach.

        @return: C{None} or a list as described above.
        """
        if self._ContentTypeTag in (self._CT_EMPTY, self._CT_SIMPLE):
            return []
        
        if  self._ContentModel is None:
            raise pyxb.NoContentModel(self)
        path = self._ContentModel.validate(self._symbolSet())
        if path is not None:
            ( symbols, sequence ) = path
            if 0 == len(symbols):
                return sequence
            raise pyxb.BindingValidationError('Ungenerated symbols: %s' % (symbols,) )
        return None

    def _symbolSet (self):
        """Return a map from L{content.ElementUse} instances to a list of
        values associated with that use.

        This is used as the set of symbols available for transitions when
        validating content against a model.  Note that the order of values
        within a use is likely to be significant, although the model cannot
        detect this.

        The value C{None} should be used to provide a list of wildcard
        members.

        If an element use has no associated values, it must not appear in the
        returned map.
        """
        rv = { }
        for eu in self._ElementMap.values():
            value = eu.value(self)
            if value is None:
                continue
            res = None
            converter = eu.elementBinding().compatibleValue
            if eu.isPlural():
                if 0 < len(value):
                    rv[eu] = [ converter(_v) for _v in value ]
            else:
                rv[eu] = [ converter(value)]
        wce = self.wildcardElements()
        if (wce is not None) and (0 < len(wce)):
            rv[None] = wce[:]
        return rv

    def _validateAttributes (self):
        for au in self._AttributeMap.values():
            au.validate(self)
        
    def _iterateAttributes (self, namesRegExp):
        for (key, au) in self._AttributeMap.items():
            for pat in namesRegExp:
                if re.match(pat, str(key)) and au.iterable(self):
                    yield lambda a=au, ctd_inst=self: a.iterate(ctd_inst)

    def _validateBinding_vx (self):
        if self._isNil():
            if (self._IsSimpleTypeContent() and (self.__content is not None)) or self.__content:
                raise pyxb.ContentInNilElementError(self._ExpandedName)
            return True
        if self._IsSimpleTypeContent() and (self.__content is None):
            raise pyxb.MissingContentError(self._TypeDefinition)
        try:
            order = self._validatedChildren()
        except Exception, e:
            raise pyxb.BindingValidationError('Error matching content to binding model: %s' % (e,))
        if order is None:
            raise pyxb.BindingValidationError('Unable to match content to binding model')
        for (eu, value) in order:
            if isinstance(value, _TypeBinding_mixin):
                value.validateBinding()
            elif eu is not None:
                print 'WARNING: Cannot validate value %s in field %s' % (value, eu.id())
        self._validateAttributes()
        return True

    def _iterateBinding_vx (self, namesRegExp):
        try:
            order = self._validatedChildren()
        except Exception, e:
            raise pyxb.BindingValidationError('Error matching content to binding model: %s' % (e,))
        for (eu, value) in order:
            if isinstance(value, _TypeBinding_mixin):
                for i in value.iterateBinding(namesRegExp):
                    yield i
            elif eu is not None:
                print 'WARNING: Cannot iterate value %s in field %s' % (value, eu.id())
        for pat in namesRegExp:
            if re.match(pat, str(self.__class__)):
                for i in self._iterateAttributes(namesRegExp):
                    yield i

    @classmethod
    def __AttributesFromDOM (cls, node):
        attribute_settings = { }
        for ai in range(0, node.attributes.length):
            attr = node.attributes.item(ai)
            # NB: Specifically do not consider attr's NamespaceContext, since
            # attributes do not accept a default namespace.
            attr_en = pyxb.namespace.ExpandedName(attr)

            # Ignore xmlns and xsi attributes; we've already handled those
            if attr_en.namespace() in ( pyxb.namespace.XMLNamespaces, XSI ):
                continue

            value = attr.value
            au = cls._AttributeMap.get(attr_en)
            if au is None:
                if cls._AttributeWildcard is None:
                    raise pyxb.UnrecognizedAttributeError('Attribute %s is not permitted in type %s' % (attr_en, cls._ExpandedName))
            attribute_settings[attr_en] = value
        return attribute_settings

    def _setAttribute (self, attr_en, value):
        au = self._AttributeMap.get(attr_en, None)
        if au is None:
            if self._AttributeWildcard is None:
                raise pyxb.UnrecognizedAttributeError('Attribute %s is not permitted in type %s' % (attr_en, self._ExpandedName))
            self.__wildcardAttributeMap[attr_en] = value
        else:
            au.set(self, value)
        return au

    def __setAttributes (self, attribute_settings, dom_node):
        """Initialize the attributes of this element from those of the DOM node.

        @raise pyxb.UnrecognizedAttributeError: if the DOM node has attributes
        that are not allowed in this type
        @raise pyxb.ProhibitedAttributeError: a prohibited attribute was encountered
        @raise pyxb.MissingAttributeError: a required attribute could not be found
        """
        
        # Handle all the attributes that are present in the node
        attrs_available = set(self._AttributeMap.values())
        for (attr_en, value) in attribute_settings.items():
            au = self._setAttribute(attr_en, value)
            if au is not None:
                attrs_available.remove(au)

        return self

    def xsdConstraintsOK (self):
        """Validate the content against the simple type.

        @return: C{True} if the content validates against its type.
        @raise pyxb.NotSimpleContentError: this type does not have simple content.
        @raise pyxb.MissingContentError: the content of this type has not been set
        """
        # @todo: type check
        if self._CT_SIMPLE != self._ContentTypeTag:
            raise pyxb.NotSimpleContentError(self)
        if self._isNil():
            return True
        if self.value() is None:
            raise pyxb.MissingContentError(self)
        return self.value().xsdConstraintsOK()

    __content = None
    def content (self):
        """Return the content of the element.

        This must be a complex type with complex content.  The return value is
        a list of the element and non-element content in the order in which it
        was added.
        @raise pyxb.NotComplexContentError: this is not a complex type with mixed or element-only content
        """
        if self._ContentTypeTag in (self._CT_EMPTY, self._CT_SIMPLE):
            raise pyxb.NotComplexContentError(str(self._ExpandedName))
        return self.__content

    def value (self):
        """Return the value of the element.

        This must be a complex type with simple content.  The returned value
        is expected to be an instance of some L{simpleTypeDefinition} class.

        @raise pyxb.NotSimpleContentError: this is not a complex type with simple content
        """
        if self._CT_SIMPLE != self._ContentTypeTag:
            raise pyxb.NotSimpleContentError('%s (%s)' % (str(self._ExpandedName), type(self)))
        return self.__content

    def _resetContent (self):
        if self._ContentTypeTag in (self._CT_MIXED, self._CT_ELEMENT_ONLY):
            self.__setContent([])
        else:
            self.__setContent(None)

    __modelState = None
    def reset (self):
        """Reset the instance.

        This resets all element and attribute fields, and discards any
        recorded content.  It resets the DFA to the initial state of the
        content model.
        """
        
        self._resetContent()
        for au in self._AttributeMap.values():
            au.reset(self)
        for eu in self._ElementMap.values():
            eu.reset(self)
        if self._ContentModel is not None:
            self.__modelState = self._ContentModel.newState()
        return self

    @classmethod
    def _ElementBindingUseForName (cls, element_name):
        """Determine what the given name means as an element in this type.

        Normally, C{element_name} identifies an element definition within this
        type.  If so, the returned C{element_use} identifies that definition,
        and the C{element_binding} is extracted from that use.

        It may also be that the C{element_name} does not appear as an element
        definition, but that it identifies a global element.  In that case,
        the returned C{element_binding} identifies the global element.  If,
        further, that element is a member of a substitution group which does
        have an element definition in this class, then the returned
        C{element_use} identifies that definition.

        If a non-C{None} C{element_use} is returned, there will be an
        associated C{element_binding}.  However, it is possible to return a
        non-C{None} C{element_binding}, but C{None} as the C{element_use}.  In
        that case, the C{element_binding} can be used to create a binding
        instance, but the content model will have to treat it as a wildcard.

        @param element_name: The name of the element in this type, either an
        expanded name or a local name if the element has an absent namespace.

        @return: C{( element_binding, element_use )}
        """
        element_use = cls._ElementMap.get(element_name)
        element_binding = None
        if element_use is None:
            try:
                element_binding = element_name.elementBinding()
            except pyxb.NamespaceError:
                pass
            if element_binding is not None:
                element_use = element_binding.findSubstituendUse(cls)
        else:
            element_binding = element_use.elementBinding()
        return (element_binding, element_use)
        
    def append (self, value, element_use=None, maybe_element=True, _fallback_namespace=None, require_validation=True):
        """Add the value to the instance.

        The value should be a DOM node or other value that is or can be
        converted to a binding instance.  If the instance has a DFA state, the
        value must be permitted by the content model.

        @raise pyxb.ExtraContentError: the value is not permitted at the
        current state of the content model.
        """
        
        # @todo: Allow caller to provide default element use; it's available
        # in saxer.
        element_binding = None
        if element_use is not None:
            import content
            assert isinstance(element_use, content.ElementUse)
            element_binding = element_use.elementBinding()
            assert element_binding is not None
        # Convert the value if it's XML and we recognize it.
        if isinstance(value, xml.dom.Node):
            assert maybe_element
            assert element_binding is None
            node = value
            require_validation = pyxb._ParsingRequiresValid
            if xml.dom.Node.COMMENT_NODE == node.nodeType:
                # @todo: Note that we're allowing comments inside the bodies
                # of simple content elements, which isn't really Hoyle.
                return self
            if node.nodeType in (xml.dom.Node.TEXT_NODE, xml.dom.Node.CDATA_SECTION_NODE):
                value = node.data
                maybe_element = False
            else:
                # Do type conversion here
                assert xml.dom.Node.ELEMENT_NODE == node.nodeType
                expanded_name = pyxb.namespace.ExpandedName(node, fallback_namespace=_fallback_namespace)
                (element_binding, element_use) = self._ElementBindingUseForName(expanded_name)
                if element_binding is not None:
                    value = element_binding._createFromDOM(node, expanded_name, _fallback_namespace=_fallback_namespace)
                else:
                    # Might be a resolvable wildcard.  See if we can convert it to an
                    # element.
                    #print 'Attempting to create element from node %s' % (expanded_name,)
                    try:
                        ns = expanded_name.namespace()
                        if ns is not None:
                            for mr in ns.moduleRecords():
                                try:
                                    if (mr.module() is None) and (mr.modulePath() is not None):
                                        print 'Importing %s to get binding for wildcard %s' % (mr.modulePath(), expanded_name)
                                        mod = __import__(mr.modulePath())
                                        for c in mr.modulePath().split('.')[1:]:
                                            mod = getattr(mod, c)
                                        mr._setModule(mod)
                                    value = mr.module().CreateFromDOM(node)
                                    break
                                except pyxb.PyXBException, e:
                                    print 'Ignoring error when creating binding for wildcard %s: %s' % (expanded_name, e)
                                except AttributeError, e:
                                    # The module holding XMLSchema bindnigs does not
                                    # have a CreateFromDOM method, and shouldn't since
                                    # we need to convert schema instances to DOM more
                                    # carefully.
                                    if mr.namespace() != pyxb.namespace.XMLSchema:
                                        raise
                    except Exception, e:
                        print 'WARNING: Unable to convert DOM node %s to Python instance: %s' % (expanded_name, e)
        if (not maybe_element) and isinstance(value, basestring) and (self._ContentTypeTag in (self._CT_EMPTY, self._CT_ELEMENT_ONLY)):
            if (0 == len(value.strip())) and not self._isNil():
                return self
        if self._isNil() and not self._IsSimpleTypeContent():
            raise pyxb.ExtraContentError('%s: Content %s present in element with xsi:nil' % (type(self), value))
        if maybe_element and (self.__modelState is not None):
            # Allows element content.
            if not require_validation:
                if element_use is not None:
                    element_use.setOrAppend(self, value)
                    return self
                raise pyxb.StructuralBadDocumentError('Validation is required when no element_use can be found')
                if self.wildcardElements() is not None:
                    self._appendWildcardElement(value)
                    return self
            else:
                #print 'SSStep %s %s' % (value, element_use)
                ( consumed, underflow_exc ) = self.__modelState.step(self, value, element_use)
                if consumed:
                    return self
        # If what we have is element content, we can't accept it, either
        # because the type doesn't accept element content or because it does
        # and what we got didn't match the content model.
        if (element_binding is not None) or isinstance(value, xml.dom.Node):
            raise pyxb.ExtraContentError('%s: Extra content %s starting with %s' % (self._ExpandedName, element_binding, value,))

        # We have something that doesn't seem to be an element.  Are we
        # expecting simple content?
        if self._IsSimpleTypeContent():
            if self.__content is not None:
                raise pyxb.ExtraContentError('Extra content starting with %s (already have %s)' % (value, self.__content))
            if not self._isNil():
                if not isinstance(value, self._TypeDefinition):
                    value = self._TypeDefinition.Factory(value)
                self.__setContent(value)
                if require_validation:
                    # NB: This only validates the value, not any associated
                    # attributes, which is correct to be parallel to complex
                    # content validation.
                    self.xsdConstraintsOK()
            return self

        # Do we allow non-element content?
        if not self._IsMixed():
            raise pyxb.UnexpectedNonElementContentError(value)
        if isinstance(value, _TypeBinding_mixin):
            raise pyxb.ExtraContentError('Extra content starting with %s' % (value,))

        self._addContent(value, element_binding)
        return self

    def _appendWildcardElement (self, value):
        wcl = self.wildcardElements()
        if wcl is None:
            raise pyxb.UnrecognizedContentError(value, container=self)
        wcl.append(value)
        
    def extend (self, value_list, _fallback_namespace=None):
        """Invoke L{append} for each value in the list, in turn."""
        [ self.append(_v, _fallback_namespace=_fallback_namespace) for _v in value_list ]
        return self

    def __setContent (self, value):
        self.__content = value

    def _addContent (self, child, element_binding):
        # This assert is inadequate in the case of plural/non-plural elements with an STD_list base type.
        # Trust that validation elsewhere was done correctly.
        #assert self._IsMixed() or (not self._PerformValidation()) or isinstance(child, _TypeBinding_mixin) or isinstance(child, types.StringTypes), 'Unrecognized child %s type %s' % (child, type(child))
        assert not (self._ContentTypeTag in (self._CT_EMPTY, self._CT_SIMPLE))
        if isinstance(child, _TypeBinding_mixin) and (child._element() is None):
            child._setElement(element_binding)
        self.__content.append(child)

    @classmethod
    def _IsMixed (cls):
        return (cls._CT_MIXED == cls._ContentTypeTag)
    
    def _postDOMValidate (self):
        if self._PerformValidation() and (not self._isNil()) and (self.__modelState is not None):
            self.__modelState.verifyComplete()
            self._validateAttributes()
        return self

    def _setContentFromDOM (self, node, _fallback_namespace):
        """Initialize the content of this element from the content of the DOM node."""

        self.extend(node.childNodes[:], _fallback_namespace)
        return self._postDOMValidate()

    def _setDOMFromAttributes (self, dom_support, element):
        """Add any appropriate attributes from this instance into the DOM element."""
        for au in self._AttributeMap.values():
            au.addDOMAttribute(dom_support, self, element)
        return element

    def _toDOM_csc (self, dom_support, parent):
        """Create a DOM element with the given tag holding the content of this instance."""
        element = parent
        self._setDOMFromAttributes(dom_support, element)
        if self._isNil():
            pass
        elif self._CT_EMPTY == self._ContentTypeTag:
            pass
        elif self._CT_SIMPLE == self._ContentTypeTag:
            assert self.value() is not None, '%s has no value' % (self,)
            element.appendChild(dom_support.document().createTextNode(self.value().xsdLiteral()))
        else:
            if pyxb._GenerationRequiresValid:
                order = self._validatedChildren()
            else:
                order = self.__childrenForDOM()
            if order is None:
                raise pyxb.DOMGenerationError('Binding value inconsistent with content model')
            for (eu, v) in order:
                assert v != self
                if eu is None:
                    if isinstance(v, xml.dom.Node):
                        element.appendChild(v)
                    else:
                        v.toDOM(dom_support, parent)
                else:
                    eu.toDOM(dom_support, parent, v)
            mixed_content = self.content()
            for mc in mixed_content:
                pass
        return getattr(super(complexTypeDefinition, self), '_toDOM_csc', lambda *_args,**_kw: dom_support)(dom_support, parent)

    @classmethod
    def _IsSimpleTypeContent (cls):
        """CTDs with simple content are simple; other CTDs are not."""
        return cls._CT_SIMPLE == cls._ContentTypeTag

    @classmethod
    def _description (cls, name_only=False, user_documentation=True):
        name = cls._Name()
        if name_only:
            return name
        desc = [ name ]
        if cls._CT_EMPTY == cls._ContentTypeTag:
            desc.append(', empty content')
        elif cls._CT_SIMPLE == cls._ContentTypeTag:
            desc.extend([', simple content type ', cls._TypeDefinition._description(name_only=True)])
        else:
            if cls._CT_MIXED == cls._ContentTypeTag:
                desc.append(', mixed content')
            else:
                assert cls._CT_ELEMENT_ONLY == cls._ContentTypeTag
                desc.append(', element-only content')
        if (0 < len(cls._AttributeMap)) or (cls._AttributeWildcard is not None):
            desc.append("\nAttributes:\n  ")
            desc.append("\n  ".join([ _au._description(user_documentation=False) for _au in cls._AttributeMap.values() ]))
            if cls._AttributeWildcard is not None:
                desc.append("\n  Wildcard attribute(s)")
        if (0 < len(cls._ElementMap)) or cls._HasWildcardElement:
            desc.append("\nElements:\n  ")
            desc.append("\n  ".join([ _eu._description(user_documentation=False) for _eu in cls._ElementMap.values() ]))
            if cls._HasWildcardElement:
                desc.append("\n  Wildcard element(s)")
        return ''.join(desc)

ConfigureBindingStyle(DEFAULT_BINDING_STYLE)

## Local Variables:
## fill-column:78
## End: