File: builders.py

package info (click to toggle)
python-xmlschema 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 5,208 kB
  • sloc: python: 39,174; xml: 1,282; makefile: 36
file content (831 lines) | stat: -rw-r--r-- 32,250 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#
# Copyright (c), 2016-2024, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@sissa.it>
#
import copy
from abc import abstractmethod
from collections import Counter
from collections.abc import Callable, ItemsView, Iterator, Mapping, ValuesView, Iterable
from copy import copy as shallow_copy
from operator import attrgetter
from types import MappingProxyType
from typing import Any, cast, NamedTuple, Optional, Union, Type, TypeVar
from xml.etree.ElementTree import Element

import xmlschema.names as nm
from xmlschema.aliases import BaseXsdType, ElementType, LoadedItemType, \
    SchemaType, StagedItemType, SchemaGlobalType
from xmlschema.exceptions import XMLSchemaAttributeError, XMLSchemaKeyError, \
    XMLSchemaTypeError, XMLSchemaValueError
from xmlschema.translation import gettext as _
from xmlschema.utils.qnames import local_name, get_qname

from .helpers import get_xsd_derivation_attribute
from .exceptions import XMLSchemaCircularityError
from .xsdbase import XsdComponent, XsdAnnotation
from .builtins import BUILTIN_TYPES
from .facets import XsdFacet, FACETS_CLASSES
from .identities import XsdIdentity, XsdUnique, XsdKey, XsdKeyref, Xsd11Unique, \
    Xsd11Key, Xsd11Keyref
from .simple_types import XsdSimpleType, XsdAtomicBuiltin, XsdAtomicRestriction, \
    Xsd11AtomicRestriction, XsdUnion, Xsd11Union, XsdList

from .notations import XsdNotation
from .attributes import XsdAttribute, Xsd11Attribute, XsdAttributeGroup
from .complex_types import XsdComplexType, Xsd11ComplexType
from .wildcards import XsdAnyElement, Xsd11AnyElement, XsdAnyAttribute, Xsd11AnyAttribute
from .groups import XsdGroup, Xsd11Group
from .elements import XsdElement, Xsd11Element
from .assertions import XsdAssert

CT = TypeVar('CT', bound=XsdComponent)

BuilderType = Callable[[ElementType, SchemaType, Optional[XsdComponent]], CT]

# Elements for building dummy groups
ATTRIBUTE_GROUP_ELEMENT = Element(nm.XSD_ATTRIBUTE_GROUP)
ANY_ATTRIBUTE_ELEMENT = Element(
    nm.XSD_ANY_ATTRIBUTE, attrib={'namespace': '##any', 'processContents': 'lax'}
)
SEQUENCE_ELEMENT = Element(nm.XSD_SEQUENCE)
ANY_ELEMENT = Element(
    nm.XSD_ANY,
    attrib={
        'namespace': '##any',
        'processContents': 'lax',
        'minOccurs': '0',
        'maxOccurs': 'unbounded'
    })

GLOBAL_TAGS = frozenset((
    nm.XSD_NOTATION, nm.XSD_SIMPLE_TYPE, nm.XSD_COMPLEX_TYPE,
    nm.XSD_ATTRIBUTE, nm.XSD_ATTRIBUTE_GROUP, nm.XSD_GROUP, nm.XSD_ELEMENT
))

GLOBAL_MAP_INDEX = MappingProxyType({
    nm.XSD_SIMPLE_TYPE: 0,
    nm.XSD_COMPLEX_TYPE: 0,
    nm.XSD_NOTATION: 1,
    nm.XSD_ATTRIBUTE: 2,
    nm.XSD_ATTRIBUTE_GROUP: 3,
    nm.XSD_ELEMENT: 4,
    nm.XSD_GROUP: 5,
})

GLOBAL_MAP_ATTRIBUTE = MappingProxyType({
    nm.XSD_SIMPLE_TYPE: attrgetter('types'),
    nm.XSD_COMPLEX_TYPE: attrgetter('types'),
    nm.XSD_ATTRIBUTE: attrgetter('attributes'),
    nm.XSD_ATTRIBUTE_GROUP: attrgetter('attribute_groups'),
    nm.XSD_NOTATION: attrgetter('notations'),
    nm.XSD_ELEMENT: attrgetter('elements'),
    nm.XSD_GROUP: attrgetter('groups'),
})


class XsdBuilders:
    """
    A descriptor that is bound to a schema class for providing versioned builders
    for XSD components.
    """
    components: dict[str, Type[XsdComponent]]
    facets: dict[str, Type[XsdFacet]]
    identities: dict[str, Type[XsdIdentity]]
    simple_types: dict[str, Type[XsdSimpleType]]
    local_types: dict[str, Union[Type[BaseXsdType], BuilderType[XsdSimpleType]]]
    builtins: tuple[dict[str, Any], ...]

    __slots__ = ('_name', '_xsd_version', 'components', 'facets', 'identities',
                 'simple_types', 'local_types', 'builtins', 'simple_type_class',
                 'notation_class', 'attribute_group_class', 'complex_type_class',
                 'attribute_class', 'group_class', 'element_class', 'any_element_class',
                 'any_attribute_class', 'atomic_restriction_class', 'list_class',
                 'union_class', 'unique_class', 'key_class', 'keyref_class')

    def __init__(self, xsd_version: Optional[str] = None,
                 *facets_classes: Type[XsdFacet],
                 **classes: Type[XsdComponent]) -> None:
        if xsd_version is not None:
            self._xsd_version = xsd_version

        self.components = {}
        self.facets = {}

        if facets_classes:
            for cls in facets_classes:
                self.facets[cls.meta_tag()] = self.components[cls.meta_tag()] = cls

        for k, v in classes.items():
            if k.endswith('_class'):
                setattr(self, k, v)

    def __set_name__(self, cls: Type[SchemaType], name: str) -> None:
        self._name = name
        self._xsd_version = getattr(cls, 'XSD_VERSION', '1.0')

        if not self.facets:
            self.facets.update(FACETS_CLASSES[self._xsd_version])
        else:
            facets = FACETS_CLASSES[self._xsd_version].copy()
            facets.update(self.facets)
            self.facets = facets

        self.builtins = BUILTIN_TYPES[self._xsd_version]

        self.simple_type_class = XsdSimpleType
        self.notation_class = XsdNotation
        self.attribute_group_class = XsdAttributeGroup
        self.list_class = XsdList

        if self._xsd_version == '1.0':
            self.complex_type_class = XsdComplexType
            self.attribute_class = XsdAttribute
            self.group_class = XsdGroup
            self.element_class = XsdElement
            self.any_element_class = XsdAnyElement
            self.any_attribute_class = XsdAnyAttribute
            self.atomic_restriction_class = XsdAtomicRestriction
            self.union_class = XsdUnion
            self.unique_class = XsdUnique
            self.key_class = XsdKey
            self.keyref_class = XsdKeyref
        else:
            self.complex_type_class = Xsd11ComplexType
            self.attribute_class = Xsd11Attribute
            self.group_class = Xsd11Group
            self.element_class = Xsd11Element
            self.any_element_class = Xsd11AnyElement
            self.any_attribute_class = Xsd11AnyAttribute
            self.atomic_restriction_class = Xsd11AtomicRestriction
            self.union_class = Xsd11Union
            self.unique_class = Xsd11Unique
            self.key_class = Xsd11Key
            self.keyref_class = Xsd11Keyref

        self.identities = {
            nm.XSD_UNIQUE: self.unique_class,
            nm.XSD_KEY: self.key_class,
            nm.XSD_KEYREF: self.keyref_class,
        }
        self.simple_types = {
            nm.XSD_RESTRICTION: self.atomic_restriction_class,
            nm.XSD_LIST: self.list_class,
            nm.XSD_UNION: self.union_class,
        }
        self.local_types = {
            nm.XSD_COMPLEX_TYPE: self.complex_type_class,
            nm.XSD_SIMPLE_TYPE: self.simple_type_factory,
        }

    def __setattr__(self, name: str, value: Any) -> None:
        if name == '_xsd_version':
            if value not in ('1.0', '1.1'):
                raise XMLSchemaValueError(f"wrong or unsupported XSD version {value!r}")
            elif hasattr(self, '_xsd_version') and self._xsd_version != value:
                raise XMLSchemaValueError("XSD version mismatch")

        elif name.endswith('_class'):
            if not isinstance(value, type) or not issubclass(value, XsdComponent):
                raise XMLSchemaTypeError(f"{name} must be a subclass of XsdComponent")
            if hasattr(self, name):
                return  # Skip changing a component class already set at __init__
            self.components[value.meta_tag()] = value

        super().__setattr__(name, value)

    def __get__(self, instance: Optional[Any], cls: type[Any]) -> 'XsdBuilders':
        return self

    def __set__(self, instance: Any, value: Any) -> None:
        raise XMLSchemaAttributeError(_("Can't set attribute {}").format(self._name))

    def __delete__(self, instance: Any) -> None:
        raise XMLSchemaAttributeError(_("Can't delete attribute {}").format(self._name))

    @property
    def xsd_version(self) -> str:
        return self._xsd_version

    def create_any_content_group(self, parent: Union[XsdComplexType, XsdGroup],
                                 any_element: Optional[XsdAnyElement] = None) -> XsdGroup:
        """
        Creates a local child model group for a complex type or a group that accepts any content.

        :param parent: the parent complex type or group for the content group.
        :param any_element: an optional any element to use for the content group. \
        When provided it's copied, linked to the group and the minOccurs/maxOccurs \
        are set to 0 and 'unbounded'.
        """
        schema = parent.schema
        group: XsdGroup = self.group_class(SEQUENCE_ELEMENT, schema, parent)

        if isinstance(any_element, XsdAnyElement):
            particle = shallow_copy(any_element)
            particle.min_occurs = 0
            particle.max_occurs = None
            particle.parent = group
            group.append(particle)
        else:
            group.append(self.any_element_class(ANY_ELEMENT, schema, group))

        return group

    def create_empty_content_group(self, parent: Union[XsdComplexType, XsdGroup],
                                   model: str = 'sequence', **attrib: Any) -> XsdGroup:
        """
        Creates an empty local child content group for a complex type or a group.
        """
        if model == 'sequence':
            group_elem = Element(nm.XSD_SEQUENCE, **attrib)
        elif model == 'choice':
            group_elem = Element(nm.XSD_CHOICE, **attrib)
        elif model == 'all':
            group_elem = Element(nm.XSD_ALL, **attrib)
        else:
            msg = _("'model' argument must be (sequence | choice | all)")
            raise XMLSchemaValueError(msg)

        group_elem.text = '\n    '
        return self.group_class(group_elem, parent.schema, parent)

    def create_any_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \
            -> XsdAttributeGroup:
        """
        Creates a local child attribute group for a complex type or an element
        that accepts any attribute.
        """
        attribute_group = self.attribute_group_class(
            ATTRIBUTE_GROUP_ELEMENT, parent.schema, parent
        )
        attribute_group[None] = self.any_attribute_class(
            ANY_ATTRIBUTE_ELEMENT, parent.schema, attribute_group
        )
        return attribute_group

    def create_empty_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \
            -> XsdAttributeGroup:
        """
        Creates an empty local child attribute group for a complex type or an element.
        """
        return self.attribute_group_class(ATTRIBUTE_GROUP_ELEMENT, parent.schema, parent)

    def create_any_type(self, schema: SchemaType) -> XsdComplexType:
        """
        Creates a xs:anyType equivalent type related with the wildcards
        connected to global maps of the schema instance in order to do a
        correct namespace lookup during wildcards validation.
        """
        maps = schema.maps
        if schema.meta_schema is not None and schema.target_namespace != nm.XSD_NAMESPACE:
            schema = schema.meta_schema

        any_type = self.complex_type_class(
            elem=Element(nm.XSD_COMPLEX_TYPE, name=nm.XSD_ANY_TYPE),
            schema=schema, parent=None, mixed=True, block='', final=''
        )
        assert isinstance(any_type.content, XsdGroup)
        any_type.content.append(self.any_element_class(
            ANY_ELEMENT, schema, any_type.content
        ))
        any_type.attributes[None] = self.any_attribute_class(
            ANY_ATTRIBUTE_ELEMENT, schema, any_type.attributes
        )
        any_type.maps = any_type.content.maps = any_type.content[0].maps = \
            any_type.attributes[None].maps = maps
        return any_type

    def create_element(self, name: str,
                       schema: SchemaType,
                       parent: Optional[XsdComponent] = None,
                       text: Optional[str] = None, **attrib: Any) -> XsdElement:
        """
        Creates a xs:element instance related to schema component.
        Used as dummy element for validation/decoding/encoding
        operations of wildcards and complex types.
        """
        elem = Element(nm.XSD_ELEMENT, name=name, **attrib)
        if text is not None:
            elem.text = text
        return self.element_class(elem, schema, parent)

    def simple_type_factory(self, elem: Element,
                            schema: SchemaType,
                            parent: Optional[XsdComponent] = None) -> XsdSimpleType:
        """
        Factory function for XSD simple types. Parses the xs:simpleType element and its
        child component, that can be a restriction, a list or a union. Annotations are
        linked to simple type instance, omitting the inner annotation if both are given.
        """
        annotation: Optional[XsdAnnotation] = None
        try:
            child = elem[0]
        except IndexError:
            return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE])
        else:
            if child.tag == nm.XSD_ANNOTATION:
                annotation = XsdAnnotation(child, schema, parent)
                try:
                    child = elem[1]
                except IndexError:
                    msg = _("(restriction | list | union) expected")
                    schema.parse_error(msg, elem)
                    return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE])

        xsd_type: XsdSimpleType
        try:
            xsd_type = self.simple_types[child.tag](child, schema, parent)
        except KeyError:
            msg = _("(restriction | list | union) expected")
            schema.parse_error(msg, elem)
            return cast(XsdSimpleType, schema.maps.types[nm.XSD_ANY_SIMPLE_TYPE])

        if annotation is not None:
            setattr(xsd_type, 'annotation', annotation)

        try:
            xsd_type.name = get_qname(schema.target_namespace, elem.attrib['name'])
        except KeyError:
            if parent is None:
                msg = _("missing attribute 'name' in a global simpleType")
                schema.parse_error(msg, elem)
                xsd_type.name = 'nameless_%s' % str(id(xsd_type))
        else:
            if parent is not None:
                msg = _("attribute 'name' not allowed for a local simpleType")
                schema.parse_error(msg, elem)
                xsd_type.name = None

        if 'final' in elem.attrib:
            try:
                xsd_type._final = get_xsd_derivation_attribute(elem, 'final')
            except ValueError as err:
                xsd_type.parse_error(err, elem)

        return xsd_type


class StagedMap(Mapping[str, CT]):
    label = 'component'

    @abstractmethod
    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> CT:
        """Returns the builder class or method used to build the global map."""

    __slots__ = ('_store', '_staging', '_builders')

    def __init__(self, builders: XsdBuilders):
        self._store: dict[str, CT] = {}
        self._staging: dict[str, StagedItemType] = {}
        self._builders = builders

    def __getitem__(self, qname: str) -> CT:
        try:
            return self._store[qname]
        except KeyError:
            if qname in self._staging:
                return self._build_global(qname)

            msg = _('global {} {!r} not found').format(self.label, qname)
            raise XMLSchemaKeyError(msg) from None

    def __iter__(self) -> Iterator[str]:
        yield from self._store

    def __len__(self) -> int:
        return len(self._store)

    def __repr__(self) -> str:
        return repr(self._store)

    def copy(self) -> 'StagedMap[CT]':
        obj = object.__new__(self.__class__)
        obj._builders = self._builders
        obj._staging = self._staging.copy()
        obj._store = self._store.copy()
        return obj

    __copy__ = copy

    def clear(self) -> None:
        self._store.clear()
        self._staging.clear()

    def update(self, other: 'StagedMap[CT]') -> None:
        self._store.update(other._store)

    @property
    def total_staged(self) -> int:
        return len(self._staging)

    @property
    def staged(self) -> list[str]:
        return list(self._staging)

    @property
    def staged_items(self) -> ItemsView[str, StagedItemType]:
        return self._staging.items()

    @property
    def staged_values(self) -> ValuesView[StagedItemType]:
        return self._staging.values()

    def load(self, qname: str, elem: ElementType, schema: SchemaType) -> None:
        if qname in self._store:
            comp = self._store[qname]
            if comp.schema is schema:
                msg = _("global xs:{} with name={!r} is already built")
            elif comp.schema.maps is schema.maps or comp.schema.meta_schema is None:
                msg = _("global xs:{} with name={!r} is already defined")
            else:
                # Allows rebuilding of parent maps components for descendant maps
                # but not allows substitution of meta-schema components.
                self._staging[qname] = elem, schema
                return

        elif qname in self._staging:
            obj = self._staging[qname]

            if len(obj) == 2 and isinstance(obj, tuple):
                _elem, _schema = obj  # type:ignore[misc]
                if _elem is elem and _schema is schema:
                    return  # ignored: it's the same component
                elif schema is _schema.override:
                    return  # ignored: the loaded component is overridden
                elif schema.override is _schema:
                    # replaced: the loaded component is an override
                    self._staging[qname] = (elem, schema)
                    return
                elif schema.meta_schema is None and _schema.meta_schema is not None:
                    return  # ignore merged meta-schema components
                elif _schema.meta_schema is None and schema.meta_schema is not None:
                    # Override merged meta-schema component
                    self._staging[qname] = (elem, schema)
                    return

            msg = _("global xs:{} with name={!r} is already loaded")
        else:
            self._staging[qname] = elem, schema
            return

        schema.parse_error(
            error=msg.format(local_name(elem.tag), qname),
            elem=elem
        )

    def load_redefine(self, qname: str, elem: ElementType, schema: SchemaType) -> None:
        try:
            item = self._staging[qname]
        except KeyError:
            schema.parse_error(_("not a redefinition!"), elem)
        else:
            if isinstance(item, list):
                item.append((elem, schema))
            else:
                self._staging[qname] = [cast(LoadedItemType, item), (elem, schema)]

    def load_override(self, qname: str, elem: ElementType, schema: SchemaType) -> None:
        if qname not in self._staging:
            # Overrides that match nothing in the target schema are ignored. See the
            # period starting with "Source declarations not present in the target set"
            # of the paragraph https://www.w3.org/TR/xmlschema11-1/#override-schema.
            return

        self._staging[qname] = elem, schema

    def build(self) -> None:
        for name in [x for x in self._staging]:
            if name in self._staging:
                self._build_global(name)

    def _build_global(self, qname: str) -> CT:
        obj = self._staging[qname]
        if isinstance(obj, tuple):
            # Not built XSD global component without redefinitions
            try:
                elem, schema = obj  # type: ignore[misc]
            except ValueError:
                raise XMLSchemaCircularityError(qname, *obj[0])

            # Encapsulate into a tuple to catch circular builds
            self._staging[qname] = cast(LoadedItemType, (obj,))

            self._store[qname] = self._factory_or_class(elem, schema)
            self._staging.pop(qname)
            return self._store[qname]

        elif isinstance(obj, list):
            # Not built XSD global component with redefinitions
            try:
                elem, schema = obj[0]
            except ValueError:
                if not isinstance(obj, tuple):
                    raise
                raise XMLSchemaCircularityError(qname, *obj[0][0])

            self._staging[qname] = obj[0],  # To catch circular builds
            self._store[qname] = component = self._factory_or_class(elem, schema)
            self._staging.pop(qname)

            # Apply redefinitions (changing elem involve reparse of the component)
            for elem, schema in obj[1:]:
                if component.schema.target_namespace != schema.target_namespace:
                    msg = _("redefined schema {!r} has a different targetNamespace")
                    raise XMLSchemaValueError(msg.format(schema))

                component.redefine = copy.copy(component)
                component.redefine.parent = component
                component.schema = schema
                component.parse(elem)

            return self._store[qname]

        else:
            msg = _("unexpected instance {!r} in XSD {} global map")
            raise XMLSchemaTypeError(msg.format(obj, self.label))


class TypesMap(StagedMap[BaseXsdType]):

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> BaseXsdType:
        if elem.tag == nm.XSD_COMPLEX_TYPE:
            return self._builders.complex_type_class(elem, schema)
        else:
            return self._builders.simple_type_factory(elem, schema)

    def build_builtins(self, schema: SchemaType) -> None:
        if schema.meta_schema is not None and nm.XSD_ANY_TYPE in self._store:
            # builtin types already provided, rebuild only xs:anyType for wildcards
            self._store[nm.XSD_ANY_TYPE] = self._builders.create_any_type(schema)
            return

        #
        # Special builtin types.
        #
        # xs:anyType
        # Ref: https://www.w3.org/TR/xmlschema11-1/#builtin-ctd
        self._store[nm.XSD_ANY_TYPE] = self._builders.create_any_type(schema)

        # xs:anySimpleType
        # Ref: https://www.w3.org/TR/xmlschema11-2/#builtin-stds
        any_simple_type = self._store[nm.XSD_ANY_SIMPLE_TYPE] = XsdSimpleType(
            elem=Element(nm.XSD_SIMPLE_TYPE, name=nm.XSD_ANY_SIMPLE_TYPE),
            schema=schema,
            parent=None,
            name=nm.XSD_ANY_SIMPLE_TYPE
        )

        # xs:anyAtomicType
        # Ref: https://www.w3.org/TR/xmlschema11-2/#builtin-stds
        self._store[nm.XSD_ANY_ATOMIC_TYPE] = \
            self._builders.atomic_restriction_class(
                elem=Element(nm.XSD_SIMPLE_TYPE, name=nm.XSD_ANY_ATOMIC_TYPE),
                schema=schema,
                parent=None,
                name=nm.XSD_ANY_ATOMIC_TYPE,
                base_type=any_simple_type,
            )

        for item in self._builders.builtins:
            item = item.copy()
            name: str = item['name']
            try:
                value = self._staging.pop(name)
            except KeyError:
                # If builtin type element is missing create a dummy element. Necessary for the
                # meta-schema XMLSchema.xsd of XSD 1.1, that not includes builtins declarations.
                elem = Element(nm.XSD_SIMPLE_TYPE, name=name, id=name)
            else:
                if not isinstance(value, tuple) or len(value) != 2:
                    continue
                elem, schema = value

            base_type: Optional[BaseXsdType]
            if 'base_type' in item:
                base_type = item['base_type'] = self._store[item['base_type']]
            else:
                base_type = None

            facets = item.pop('facets', None)
            xsd_type = XsdAtomicBuiltin(elem, schema, **item)
            if isinstance(facets, Iterable):
                built_facets = xsd_type.facets
                for e in facets:
                    try:
                        cls = self._builders.facets[e.tag]
                    except AttributeError:
                        built_facets[None] = e
                    else:
                        built_facets[e.tag] = cls(e, schema, xsd_type, base_type)
                xsd_type.facets = built_facets

            self._store[name] = xsd_type


class NotationsMap(StagedMap[XsdNotation]):
    label = 'notation'

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdNotation:
        return self._builders.notation_class(elem, schema)


class AttributesMap(StagedMap[XsdAttribute]):
    label = 'attribute'

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdAttribute:
        return self._builders.attribute_class(elem, schema)


class AttributeGroupsMap(StagedMap[XsdAttributeGroup]):
    label = 'attribute group'

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdAttributeGroup:
        return self._builders.attribute_group_class(elem, schema)


class ElementsMap(StagedMap[XsdElement]):
    label = 'element'

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdElement:
        return self._builders.element_class(elem, schema)


class GroupsMap(StagedMap[XsdGroup]):
    label = 'model group'

    def _factory_or_class(self, elem: ElementType, schema: SchemaType) -> XsdGroup:
        return self._builders.group_class(elem, schema)


class GlobalMaps(NamedTuple):
    types: TypesMap
    notations: NotationsMap
    attributes: AttributesMap
    attribute_groups: AttributeGroupsMap
    elements: ElementsMap
    groups: GroupsMap

    @classmethod
    def from_builders(cls, builders: XsdBuilders) -> 'GlobalMaps':
        return cls(
            TypesMap(builders),
            NotationsMap(builders),
            AttributesMap(builders),
            AttributeGroupsMap(builders),
            ElementsMap(builders),
            GroupsMap(builders)
        )

    def clear(self) -> None:
        for item in self:
            item.clear()

    def update(self, other: 'GlobalMaps') -> None:
        for m1, m2 in zip(self, other):
            m1.update(m2)  # type: ignore[attr-defined]

    def copy(self) -> 'GlobalMaps':
        return GlobalMaps(*[m.copy() for m in self])  # type: ignore[arg-type]

    def iter_globals(self) -> Iterator[SchemaGlobalType]:
        for item in self:
            yield from item.values()

    def iter_staged(self) -> Iterator[StagedItemType]:
        for item in self:
            yield from item.staged_values

    @property
    def total(self) -> int:
        """Total number of global components, fully or partially built."""
        return sum(len(m) for m in self)

    @property
    def total_built(self) -> int:
        """Total number of fully built global components."""
        return sum(1 for c in self.iter_globals() if c.built)

    @property
    def total_unbuilt(self) -> int:
        """Total number of not built or partially built global components."""
        return sum(1 for c in self.iter_globals() if not c.built)

    @property
    def total_staged(self) -> int:
        """Total number of staged global components."""
        return sum(m.total_staged for m in self)

    def load(self, schemas: Iterable[SchemaType]) -> None:
        """Loads global XSD components for the given schemas."""
        redefinitions = []

        for schema in schemas:
            if schema.target_namespace:
                ns_prefix = f'{{{schema.target_namespace}}}'
            else:
                ns_prefix = ''

            for elem in schema.root:
                if (tag := elem.tag) in (nm.XSD_REDEFINE, nm.XSD_OVERRIDE):
                    location = elem.get('schemaLocation')
                    if location is None:
                        continue

                    for child in elem:
                        try:
                            qname = ns_prefix + child.attrib['name']
                        except KeyError:
                            continue

                        try:
                            redefinitions.append(
                                (qname, elem, child, schema, schema.includes[location])
                            )
                        except KeyError:
                            if schema.partial:
                                redefinitions.append((qname, elem, child, schema, schema))

                elif tag in GLOBAL_TAGS:
                    try:
                        qname = ns_prefix + elem.attrib['name']
                    except KeyError:
                        continue  # Invalid global: skip

                    self[GLOBAL_MAP_INDEX[tag]].load(qname, elem, schema)

        redefined_names = Counter(x[0] for x in redefinitions)
        for qname, elem, child, schema, redefined_schema in reversed(redefinitions):

            # Checks multiple redefinitions
            if redefined_names[qname] > 1:
                redefined_names[qname] = 1

                redefined_schemas: Any
                redefined_schemas = [x[-1] for x in redefinitions if x[0] == qname]
                if any(redefined_schemas.count(x) > 1 for x in redefined_schemas):
                    msg = _("multiple redefinition for {} {!r}")
                    schema.parse_error(
                        error=msg.format(local_name(child.tag), qname),
                        elem=child
                    )
                else:
                    redefined_schemas = {x[-1]: x[-2] for x in redefinitions if x[0] == qname}
                    for rs, s in redefined_schemas.items():
                        while True:
                            try:
                                s = redefined_schemas[s]
                            except KeyError:
                                break

                            if s is rs:
                                msg = _("circular redefinition for {} {!r}")
                                schema.parse_error(
                                    error=msg.format(local_name(child.tag), qname),
                                    elem=child
                                )
                                break

            if elem.tag == nm.XSD_REDEFINE:
                self[GLOBAL_MAP_INDEX[child.tag]].load_redefine(qname, child, schema)
            else:
                self[GLOBAL_MAP_INDEX[child.tag]].load_override(qname, child, schema)

    def build(self, schemas: Iterable[SchemaType]) -> None:
        """Builds global XSD components for the given schemas."""
        self.notations.build()
        self.attributes.build()
        self.attribute_groups.build()

        for schema in schemas:
            if not isinstance(schema.default_attributes, str):
                continue

            try:
                attributes = schema.maps.attribute_groups[schema.default_attributes]
            except KeyError:
                schema.default_attributes = None
                msg = _("defaultAttributes={0!r} doesn't match any attribute group of {1!r}")
                schema.parse_error(
                    error=msg.format(schema.root.get('defaultAttributes'), schema),
                    elem=schema.root
                )
            else:
                schema.default_attributes = attributes

        self.types.build()
        self.elements.build()
        self.groups.build()

        # Build element declarations inside model groups.
        for schema in schemas:
            for group in schema.iter_components(XsdGroup):
                group.build()

        # Build identity references and XSD 1.1 assertions
        for schema in schemas:
            for obj in schema.iter_components((XsdIdentity, XsdAssert)):
                obj.build()