_REGEX_NS_PREFIX = re.compile(r'ns\d+$')
class SafeXMLParser(PyElementTree.XMLParser):
    def __init__(self, target: Optional[Any] = None, encoding: Optional[str] = None) -> None:
    def entity_declaration(self, entity_name, is_parameter_entity, value, base,  # type: ignore
                           system_id, public_id, notation_name):
    def unparsed_entity_declaration(self, entity_name, base, system_id,  # type: ignore
                                    public_id, notation_name):
    def external_entity_reference(self, context, base, system_id, public_id):  # type: ignore
def is_etree_element(obj: Any) -> bool:
def etree_tostring(elem: etree_element,
                   namespaces: Optional[MutableMapping[str, str]] = None,
                   indent: str = '',
                   max_lines: Optional[int] = None,
                   spaces_for_tab: Optional[int] = None,
                   xml_declaration: Optional[bool] = None,
                   encoding: str = 'unicode',
                   method: str = 'xml') -> Union[str, bytes]:
    def reindent(line: str) -> str: C = TypeVar('C')
D = TypeVar('D')
E = TypeVar('E')
T = TypeVar('T') class XMLSchemaTypeError(XMLSchemaException, TypeError):
    pass class XMLSchemaValueError(XMLSchemaException, ValueError):
    pass XSD_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' XSD_ANY_TYPE = _XSD_TEMPLATE % 'anyType' XSD_SIMPLE_TYPE = _XSD_TEMPLATE % 'simpleType' XSD_PATTERN = _XSD_TEMPLATE % 'pattern'              # lexical facet XSD_ANY_ATOMIC_TYPE = _XSD_TEMPLATE % 'anyAtomicType' XSD_ATTRIBUTE = _XSD_TEMPLATE % 'attribute' XSD_ATTRIBUTE_GROUP = _XSD_TEMPLATE % 'attributeGroup' XSD_ANY_ATTRIBUTE = _XSD_TEMPLATE % 'anyAttribute' XSD_MIN_INCLUSIVE = _XSD_TEMPLATE % 'minInclusive' XSD_MIN_EXCLUSIVE = _XSD_TEMPLATE % 'minExclusive' XSD_MAX_INCLUSIVE = _XSD_TEMPLATE % 'maxInclusive' XSD_MAX_EXCLUSIVE = _XSD_TEMPLATE % 'maxExclusive' XSD_LENGTH = _XSD_TEMPLATE % 'length' XSD_MIN_LENGTH = _XSD_TEMPLATE % 'minLength' XSD_MAX_LENGTH = _XSD_TEMPLATE % 'maxLength' XSD_WHITE_SPACE = _XSD_TEMPLATE % 'whiteSpace'       # pre-lexical facet XSD_ENUMERATION = _XSD_TEMPLATE % 'enumeration' XSD_LIST = _XSD_TEMPLATE % 'list' XSD_ANY_SIMPLE_TYPE = _XSD_TEMPLATE % 'anySimpleType' XSD_UNION = _XSD_TEMPLATE % 'union' XSD_RESTRICTION = _XSD_TEMPLATE % 'restriction' XSD_ANNOTATION = _XSD_TEMPLATE % 'annotation' XSD_ASSERTION = _XSD_TEMPLATE % 'assertion'                      # facets XSD_ID = _XSD_TEMPLATE % 'ID' XSD_IDREF = _XSD_TEMPLATE % 'IDREF' XSD_FRACTION_DIGITS = _XSD_TEMPLATE % 'fractionDigits' XSD_TOTAL_DIGITS = _XSD_TEMPLATE % 'totalDigits' XSD_EXPLICIT_TIMEZONE = _XSD_TEMPLATE % 'explicitTimezone' XSD_ERROR = _XSD_TEMPLATE % 'error' XSD_ASSERT = _XSD_TEMPLATE % 'assert'                            # complex type assertions XSD_QNAME = _XSD_TEMPLATE % 'QName' XSD_UNTYPED_ATOMIC = _XSD_TEMPLATE % 'untypedAtomic' def get_prefixed_qname(qname: str,
                       namespaces: Optional[MutableMapping[str, str]],
                       use_empty: bool = True) -> str:
    """
    Get the prefixed form of a QName, using a namespace map.

    :param qname: an extended QName or a local name or a prefixed QName.
    :param namespaces: an optional mapping from prefixes to namespace URIs.
    :param use_empty: if `True` use the empty prefix for mapping.
    """
    if not namespaces or not qname or qname[0] != '{':
        return qname

    namespace = get_namespace(qname)
    prefixes = [x for x in namespaces if namespaces[x] == namespace]

    if not prefixes:
        return qname
    elif prefixes[0]:
        return '%s:%s' % (prefixes[0], qname.split('}', 1)[1])
    elif len(prefixes) > 1:
        return '%s:%s' % (prefixes[1], qname.split('}', 1)[1])
    elif use_empty:
        return qname.split('}', 1)[1]
    else:
        return qname def local_name(qname: str) -> str:
    """
    Return the local part of an expanded QName or a prefixed name. If the name
    is `None` or empty returns the *name* argument.

    :param qname: an expanded QName or a prefixed name or a local name.
    """
    try:
        if qname[0] == '{':
            _, qname = qname.split('}')
        elif ':' in qname:
            _, qname = qname.split(':')
    except IndexError:
        return ''
    except ValueError:
        raise XMLSchemaValueError("the argument 'qname' has a wrong format: %r" % qname)
    except TypeError:
        raise XMLSchemaTypeError("the argument 'qname' must be a string")
    else:
        return qname class XMLSchemaValidationError(XMLSchemaValidatorError, ValueError):
    """
    Raised when the XML data is not validated with the XSD component or schema.
    It's used by decoding and encoding methods. Encoding validation errors do
    not include XML data element and source, so the error is limited to a message
    containing object representation and a reason.

    :param validator: the XSD validator.
    :param obj: the not validated XML data.
    :param reason: the detailed reason of failed validation.
    :param source: the XML resource that contains the error.
    :param namespaces: is an optional mapping from namespace prefix to URI.
    """
    def __init__(self,
                 validator: ValidatorType,
                 obj: Any,
                 reason: Optional[str] = None,
                 source: Optional['XMLResource'] = None,
                 namespaces: Optional[NamespacesType] = None) -> None:
        if not isinstance(obj, str):
            _obj = obj
        else:
            _obj = obj.encode('ascii', 'xmlcharrefreplace').decode('utf-8')

        super(XMLSchemaValidationError, self).__init__(
            validator=validator,
            message="failed validating {!r} with {!r}".format(_obj, validator),
            elem=obj if is_etree_element(obj) else None,
            source=source,
            namespaces=namespaces,
        )
        self.obj = obj
        self.reason = reason

    def __repr__(self) -> str:
        return '%s(reason=%r)' % (self.__class__.__name__, self.reason)

    def __str__(self) -> str:
        msg = ['%s:\n' % self.message]

        if self.reason is not None:
            msg.append('Reason: %s\n' % self.reason)

        if hasattr(self.validator, 'tostring'):
            chunk = self.validator.tostring('  ', 20)  # type: ignore[union-attr]
            msg.append("Schema:\n\n%s\n" % chunk)

        if self.elem is not None and is_etree_element(self.elem):
            try:
                elem_as_string = cast(str, etree_tostring(self.elem, self.namespaces, '  ', 20))
            except (ValueError, TypeError):        # pragma: no cover
                elem_as_string = repr(self.elem)   # pragma: no cover

            if hasattr(self.elem, 'sourceline'):
                line = getattr(self.elem, 'sourceline')
                msg.append("Instance (line %r):\n\n%s\n" % (line, elem_as_string))
            else:
                msg.append("Instance:\n\n%s\n" % elem_as_string)

        if self.path is not None:
            msg.append("Path: %s\n" % self.path)

        if len(msg) == 1:
            return msg[0][:-2]

        return '\n'.join(msg) class XMLSchemaEncodeError(XMLSchemaValidationError):
    """
    Raised when an object is not encodable to an XML data string.

    :param validator: the XSD validator.
    :param obj: the not validated XML data.
    :param encoder: the XML encoder.
    :param reason: the detailed reason of failed validation.
    :param source: the XML resource that contains the error.
    :param namespaces: is an optional mapping from namespace prefix to URI.
    """
    message = "failed encoding {!r} with {!r}.\n"

    def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]],
                 obj: Any,
                 encoder: Any,
                 reason: Optional[str] = None,
                 source: Optional['XMLResource'] = None,
                 namespaces: Optional[NamespacesType] = None) -> None:
        super(XMLSchemaEncodeError, self).__init__(validator, obj, reason, source, namespaces)
        self.encoder = encoder class XMLSchemaDecodeError(XMLSchemaValidationError):
    """
    Raised when an XML data string is not decodable to a Python object.

    :param validator: the XSD validator.
    :param obj: the not validated XML data.
    :param decoder: the XML data decoder.
    :param reason: the detailed reason of failed validation.
    :param source: the XML resource that contains the error.
    :param namespaces: is an optional mapping from namespace prefix to URI.
    """
    message = "failed decoding {!r} with {!r}.\n"

    def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]],
                 obj: Any,
                 decoder: Any,
                 reason: Optional[str] = None,
                 source: Optional['XMLResource'] = None,
                 namespaces: Optional[NamespacesType] = None) -> None:
        super(XMLSchemaDecodeError, self).__init__(validator, obj, reason, source, namespaces)
        self.decoder = decoder class XMLSchemaParseError(XMLSchemaValidatorError, SyntaxError):  # type: ignore[misc]
    """
    Raised when an error is found during the building of an XSD validator.

    :param validator: the XSD validator.
    :param message: the error message.
    :param elem: the element that contains the error.
    """
    def __init__(self, validator: 'XsdValidator', message: str,
                 elem: Optional[ElementType] = None) -> None:
        super(XMLSchemaParseError, self).__init__(
            validator=validator,
            message=message,
            elem=elem if elem is not None else getattr(validator, 'elem', None),
            source=getattr(validator, 'source', None),
            namespaces=getattr(validator, 'namespaces', None),
        ) class XsdComponent(XsdValidator):
    """
    Class for XSD components. See: https://www.w3.org/TR/xmlschema-ref/

    :param elem: ElementTree's node containing the definition.
    :param schema: the XMLSchema object that owns the definition.
    :param parent: the XSD parent, `None` means that is a global component that \
    has the schema as parent.
    :param name: name of the component, maybe overwritten by the parse of the `elem` argument.

    :cvar qualified: for name matching, unqualified matching may be admitted only \
    for elements and attributes.
    :vartype qualified: bool
    """
    _REGEX_SPACE = re.compile(r'\s')
    _REGEX_SPACES = re.compile(r'\s+')
    _ADMITTED_TAGS: Union[Set[str], Tuple[str, ...], Tuple[()]] = ()

    elem: etree_element
    parent = None
    name = None
    ref: Optional['XsdComponent'] = None
    qualified = True
    redefine = None
    _annotation = None
    _target_namespace: Optional[str]

    def __init__(self, elem: etree_element,
                 schema: SchemaType,
                 parent: Optional['XsdComponent'] = None,
                 name: Optional[str] = None) -> None:

        super(XsdComponent, self).__init__(schema.validation)
        if name:
            self.name = name
        if parent is not None:
            self.parent = parent
        self.schema = schema
        self.maps: XsdGlobals = schema.maps
        self.elem = elem

    def __setattr__(self, name: str, value: Any) -> None:
        if name == 'elem':
            if value.tag not in self._ADMITTED_TAGS:
                msg = "wrong XSD element {!r} for {!r}, must be one of {!r}"
                raise XMLSchemaValueError(
                    msg.format(value.tag, self.__class__, self._ADMITTED_TAGS)
                )
            super(XsdComponent, self).__setattr__(name, value)
            if self.errors:
                self.errors.clear()
            self._parse()
        else:
            super(XsdComponent, self).__setattr__(name, value)

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

    def is_global(self) -> bool:
        """Returns `True` if the instance is a global component, `False` if it's local."""
        return self.parent is None

    def is_override(self) -> bool:
        """Returns `True` if the instance is an override of a global component."""
        if self.parent is not None:
            return False
        return any(self.elem in x for x in self.schema.root if x.tag == XSD_OVERRIDE)

    @property
    def schema_elem(self) -> ElementType:
        """The reference element of the schema for the component instance."""
        return self.elem

    @property
    def source(self) -> XMLResource:
        """Property that references to schema source."""
        return self.schema.source

    @property
    def target_namespace(self) -> str:
        """Property that references to schema's targetNamespace."""
        return self.schema.target_namespace if self.ref is None else self.ref.target_namespace

    @property
    def default_namespace(self) -> Optional[str]:
        """Property that references to schema's default namespaces."""
        return self.schema.namespaces.get('')

    @property
    def namespaces(self) -> NamespacesType:
        """Property that references to schema's namespace mapping."""
        return self.schema.namespaces

    @property
    def any_type(self) -> 'XsdComplexType':
        """Property that references to the xs:anyType instance of the global maps."""
        return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE])

    @property
    def any_simple_type(self) -> 'XsdSimpleType':
        """Property that references to the xs:anySimpleType instance of the global maps."""
        return cast('XsdSimpleType', self.maps.types[XSD_ANY_SIMPLE_TYPE])

    @property
    def any_atomic_type(self) -> 'XsdSimpleType':
        """Property that references to the xs:anyAtomicType instance of the global maps."""
        return cast('XsdSimpleType', self.maps.types[XSD_ANY_ATOMIC_TYPE])

    @property
    def annotation(self) -> Optional['XsdAnnotation']:
        if '_annotation' not in self.__dict__:
            for child in self.elem:
                if child.tag == XSD_ANNOTATION:
                    self._annotation = XsdAnnotation(child, self.schema, self)
                    break
                elif not callable(child.tag):
                    self._annotation = None
                    break
            else:
                self._annotation = None

        return self._annotation

    def __repr__(self) -> str:
        if self.ref is not None:
            return '%s(ref=%r)' % (self.__class__.__name__, self.prefixed_name)
        else:
            return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name)

    def _parse(self) -> None:
        return

    def _parse_reference(self) -> Optional[bool]:
        """
        Helper method for referable components. Returns `True` if a valid reference QName
        is found without any error, otherwise returns `None`. Sets an id-related name for
        the component ('nameless_<id of the instance>') if both the attributes 'ref' and
        'name' are missing.
        """
        ref = self.elem.get('ref')
        if ref is None:
            if 'name' in self.elem.attrib:
                return None
            elif self.parent is None:
                self.parse_error("missing attribute 'name' in a global %r" % type(self))
            else:
                self.parse_error(
                    "missing both attributes 'name' and 'ref' in local %r" % type(self)
                )
        elif 'name' in self.elem.attrib:
            self.parse_error("attributes 'name' and 'ref' are mutually exclusive")
        elif self.parent is None:
            self.parse_error("attribute 'ref' not allowed in a global %r" % type(self))
        else:
            try:
                self.name = self.schema.resolve_qname(ref)
            except (KeyError, ValueError, RuntimeError) as err:
                self.parse_error(err)
            else:
                if self._parse_child_component(self.elem, strict=False) is not None:
                    self.parse_error("a reference component cannot have "
                                     "child definitions/declarations")
                return True

        return None

    def _parse_child_component(self, elem: ElementType, strict: bool = True) \
            -> Optional[ElementType]:
        child = None
        for e in elem:
            if e.tag == XSD_ANNOTATION or callable(e.tag):
                continue
            elif not strict:
                return e
            elif child is not None:
                msg = "too many XSD components, unexpected {!r} found at position {}"
                self.parse_error(msg.format(child, elem[:].index(e)), elem)
                break
            else:
                child = e
        return child

    def _parse_target_namespace(self) -> None:
        """
        XSD 1.1 targetNamespace attribute in elements and attributes declarations.
        """
        if 'targetNamespace' not in self.elem.attrib:
            return

        self._target_namespace = self.elem.attrib['targetNamespace'].strip()
        if 'name' not in self.elem.attrib:
            self.parse_error("attribute 'name' must be present when "
                             "'targetNamespace' attribute is provided")
        if 'form' in self.elem.attrib:
            self.parse_error("attribute 'form' must be absent when "
                             "'targetNamespace' attribute is provided")
        if self._target_namespace != self.schema.target_namespace:
            if self.parent is None:
                self.parse_error("a global %s must have the same namespace as "
                                 "its parent schema" % self.__class__.__name__)

            xsd_type = self.get_parent_type()
            if xsd_type is None or xsd_type.parent is not None:
                pass
            elif xsd_type.derivation != 'restriction' or \
                    getattr(xsd_type.base_type, 'name', None) == XSD_ANY_TYPE:
                self.parse_error("a declaration contained in a global complexType "
                                 "must have the same namespace as its parent schema")

        if self.name is None:
            pass  # pragma: no cover
        elif not self._target_namespace:
            self.name = local_name(self.name)
        else:
            self.name = '{%s}%s' % (self._target_namespace, local_name(self.name))

    @property
    def local_name(self) -> Optional[str]:
        """The local part of the name of the component, or `None` if the name is `None`."""
        return None if self.name is None else local_name(self.name)

    @property
    def qualified_name(self) -> Optional[str]:
        """The name of the component in extended format, or `None` if the name is `None`."""
        return None if self.name is None else get_qname(self.target_namespace, self.name)

    @property
    def prefixed_name(self) -> Optional[str]:
        """The name of the component in prefixed format, or `None` if the name is `None`."""
        return None if self.name is None else get_prefixed_qname(self.name, self.namespaces)

    @property
    def id(self) -> Optional[str]:
        """The ``'id'`` attribute of the component tag, ``None`` if missing."""
        return self.elem.get('id')

    @property
    def validation_attempted(self) -> str:
        return 'full' if self.built else 'partial'

    def build(self) -> None:
        """
        Builds components that are not fully parsed at initialization, like model groups
        or internal local elements in model groups. Otherwise does nothing.
        """

    @property
    def built(self) -> bool:
        raise NotImplementedError()

    def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None,
                    **kwargs: Any) -> bool:
        """
        Returns `True` if the component name is matching the name provided as argument,
        `False` otherwise. For XSD elements the matching is extended to substitutes.

        :param name: a local or fully-qualified name.
        :param default_namespace: used if it's not None and not empty for completing \
        the name argument in case it's a local name.
        :param kwargs: additional options that can be used by certain components.
        """
        if not name:
            return self.name == name
        elif name[0] == '{':
            return self.qualified_name == name
        elif not default_namespace:
            return self.name == name or not self.qualified and self.local_name == name
        else:
            qname = '{%s}%s' % (default_namespace, name)
            return self.qualified_name == qname or not self.qualified and self.local_name == name

    def match(self, name: Optional[str], default_namespace: Optional[str] = None,
              **kwargs: Any) -> Optional['XsdComponent']:
        """
        Returns the component if its name is matching the name provided as argument,
        `None` otherwise.
        """
        return self if self.is_matching(name, default_namespace, **kwargs) else None

    def get_matching_item(self, mapping: MutableMapping[str, Any],
                          ns_prefix: str = 'xmlns',
                          match_local_name: bool = False) -> Optional[Any]:
        """
        If a key is matching component name, returns its value, otherwise returns `None`.
        """
        if self.name is None:
            return None
        elif not self.target_namespace:
            return mapping.get(self.name)
        elif self.qualified_name in mapping:
            return mapping[cast(str, self.qualified_name)]
        elif self.prefixed_name in mapping:
            return mapping[cast(str, self.prefixed_name)]

        # Try a match with other prefixes
        target_namespace = self.target_namespace
        suffix = ':%s' % self.local_name

        for k in filter(lambda x: x.endswith(suffix), mapping):
            prefix = k.split(':')[0]
            if self.namespaces.get(prefix) == target_namespace:
                return mapping[k]

            # Match namespace declaration within value
            ns_declaration = '{}:{}'.format(ns_prefix, prefix)
            try:
                if mapping[k][ns_declaration] == target_namespace:
                    return mapping[k]
            except (KeyError, TypeError):
                pass
        else:
            if match_local_name:
                return mapping.get(self.local_name)  # type: ignore[arg-type]
            return None

    def get_global(self) -> 'XsdComponent':
        """Returns the global XSD component that contains the component instance."""
        if self.parent is None:
            return self
        component = self.parent
        while component is not self:  # pragma: no cover
            if component.parent is None:
                return component
            component = component.parent
        else:
            raise XMLSchemaValueError(f"parent circularity from {self}")  # pragma: no cover

    def get_parent_type(self) -> Optional['XsdType']:
        """
        Returns the nearest XSD type that contains the component instance,
        or `None` if the component doesn't have an XSD type parent.
        """
        component = self.parent
        while component is not self and component is not None:
            if isinstance(component, XsdType):
                return component
            component = component.parent
        return None

    def iter_components(self, xsd_classes: ComponentClassType = None) \
            -> Iterator['XsdComponent']:
        """
        Creates an iterator for XSD subcomponents.

        :param xsd_classes: provide a class or a tuple of classes to iterates over only a \
        specific classes of components.
        """
        if xsd_classes is None or isinstance(self, xsd_classes):
            yield self

    def iter_ancestors(self, xsd_classes: ComponentClassType = None)\
            -> Iterator['XsdComponent']:
        """
        Creates an iterator for XSD ancestor components, schema excluded. Stops when the component
        is global or if the ancestor is not an instance of the specified class/classes.

        :param xsd_classes: provide a class or a tuple of classes to iterates over only a \
        specific classes of components.
        """
        ancestor = self
        while True:
            if ancestor.parent is None:
                break
            ancestor = ancestor.parent
            if xsd_classes is not None and not isinstance(ancestor, xsd_classes):
                break
            yield ancestor

    def tostring(self, indent: str = '', max_lines: Optional[int] = None,
                 spaces_for_tab: int = 4) -> Union[str, bytes]:
        """Serializes the XML elements that declare or define the component to a string."""
        return etree_tostring(self.schema_elem, self.namespaces, indent, max_lines, spaces_for_tab) class XsdType(XsdComponent):
    """Common base class for XSD types."""

    abstract = False
    base_type: Optional[BaseXsdType] = None
    derivation: Optional[str] = None
    _final: Optional[str] = None

    @property
    def final(self) -> str:
        return self.schema.final_default if self._final is None else self._final

    @property
    def built(self) -> bool:
        raise NotImplementedError()

    @property
    def content_type_label(self) -> str:
        """The content type classification."""
        raise NotImplementedError()

    @property
    def sequence_type(self) -> str:
        """The XPath sequence type associated with the content."""
        raise NotImplementedError()

    @property
    def root_type(self) -> BaseXsdType:
        """
        The root type of the type definition hierarchy. For an atomic type
        is the primitive type. For a list is the primitive type of the item.
        For a union is the base union type. For a complex type is xs:anyType.
        """
        if getattr(self, 'attributes', None):
            return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE])
        elif self.base_type is None:
            if self.is_simple():
                return cast('XsdSimpleType', self)
            return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE])

        primitive_type: BaseXsdType
        try:
            if self.base_type.is_simple():
                primitive_type = self.base_type.primitive_type  # type: ignore[union-attr]
            else:
                primitive_type = self.base_type.content.primitive_type  # type: ignore[union-attr]
        except AttributeError:
            # The type has complex or XsdList content
            return self.base_type.root_type
        else:
            return primitive_type

    @property
    def simple_type(self) -> Optional['XsdSimpleType']:
        """
        Property that is the instance itself for a simpleType. For a
        complexType is the instance's *content* if this is a simpleType
        or `None` if the instance's *content* is a model group.
        """
        raise NotImplementedError()

    @property
    def model_group(self) -> Optional['XsdGroup']:
        """
        Property that is `None` for a simpleType. For a complexType is
        the instance's *content* if this is a model group or `None` if
        the instance's *content* is a simpleType.
        """
        return None

    @staticmethod
    def is_simple() -> bool:
        """Returns `True` if the instance is a simpleType, `False` otherwise."""
        raise NotImplementedError()

    @staticmethod
    def is_complex() -> bool:
        """Returns `True` if the instance is a complexType, `False` otherwise."""

    def is_atomic(self) -> bool:
        """Returns `True` if the instance is an atomic simpleType, `False` otherwise."""
        return False

    def is_list(self) -> bool:
        """Returns `True` if the instance is a list simpleType, `False` otherwise."""
        return False

    def is_union(self) -> bool:
        """Returns `True` if the instance is a union simpleType, `False` otherwise."""
        return False

    def is_datetime(self) -> bool:
        """
        Returns `True` if the instance is a datetime/duration XSD builtin-type, `False` otherwise.
        """
        return False

    def is_empty(self) -> bool:
        """Returns `True` if the instance has an empty content, `False` otherwise."""
        raise NotImplementedError()

    def is_emptiable(self) -> bool:
        """Returns `True` if the instance has an emptiable value or content, `False` otherwise."""
        raise NotImplementedError()

    def has_simple_content(self) -> bool:
        """
        Returns `True` if the instance has a simple content, `False` otherwise.
        """
        raise NotImplementedError()

    def has_complex_content(self) -> bool:
        """
        Returns `True` if the instance is a complexType with mixed or element-only
        content, `False` otherwise.
        """
        raise NotImplementedError()

    def has_mixed_content(self) -> bool:
        """
        Returns `True` if the instance is a complexType with mixed content, `False` otherwise.
        """
        raise NotImplementedError()

    def is_element_only(self) -> bool:
        """
        Returns `True` if the instance is a complexType with element-only content,
        `False` otherwise.
        """
        raise NotImplementedError()

    def is_derived(self, other: Union[BaseXsdType, Tuple[ElementType, SchemaType]],
                   derivation: Optional[str] = None) -> bool:
        """
        Returns `True` if the instance is derived from *other*, `False` otherwise.
        The optional argument derivation can be a string containing the words
        'extension' or 'restriction' or both.
        """
        raise NotImplementedError()

    def is_extension(self) -> bool:
        return self.derivation == 'extension'

    def is_restriction(self) -> bool:
        return self.derivation == 'restriction'

    def is_blocked(self, xsd_element: 'XsdElement') -> bool:
        """
        Returns `True` if the base type derivation is blocked, `False` otherwise.
        """
        xsd_type = xsd_element.type
        if self is xsd_type:
            return False

        block = ('%s %s' % (xsd_element.block, xsd_type.block)).strip()
        if not block:
            return False

        _block = {x for x in block.split() if x in ('extension', 'restriction')}
        return any(self.is_derived(xsd_type, derivation) for derivation in _block)

    def is_dynamic_consistent(self, other: Any) -> bool:
        return other.name == XSD_ANY_TYPE or self.is_derived(other) or \
            hasattr(other, 'member_types') and \
            any(self.is_derived(mt) for mt in other.member_types)  # pragma: no cover

    def is_key(self) -> bool:
        return self.name == XSD_ID or self.is_derived(self.maps.types[XSD_ID])

    def is_qname(self) -> bool:
        return self.name == XSD_QNAME or self.is_derived(self.maps.types[XSD_QNAME])

    def is_notation(self) -> bool:
        return self.name == XSD_NOTATION_TYPE or self.is_derived(self.maps.types[XSD_NOTATION_TYPE])

    def is_decimal(self) -> bool:
        return self.name == XSD_DECIMAL or self.is_derived(self.maps.types[XSD_DECIMAL])

    def text_decode(self, text: str) -> Any:
        raise NotImplementedError() class ValidationMixin(Generic[ST, DT]):
    """
    Mixin for implementing XML data validators/decoders on XSD components.
    A derived class must implement the methods `iter_decode` and `iter_encode`.
    """
    def validate(self, obj: ST,
                 use_defaults: bool = True,
                 namespaces: Optional[NamespacesType] = None,
                 max_depth: Optional[int] = None,
                 extra_validator: Optional[ExtraValidatorType] = None) -> None:
        """
        Validates XML data against the XSD schema/component instance.

        :param obj: the XML data. Can be a string for an attribute or a simple type \
        validators, or an ElementTree's Element otherwise.
        :param use_defaults: indicates whether to use default values for filling missing data.
        :param namespaces: is an optional mapping from namespace prefix to URI.
        :param max_depth: maximum level of validation, for default there is no limit.
        :param extra_validator: an optional function for performing non-standard \
        validations on XML data. The provided function is called for each traversed \
        element, with the XML element as 1st argument and the corresponding XSD \
        element as 2nd argument. It can be also a generator function and has to \
        raise/yield :exc:`XMLSchemaValidationError` exceptions.
        :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid.
        """
        for error in self.iter_errors(obj, use_defaults, namespaces,
                                      max_depth, extra_validator):
            raise error

    def is_valid(self, obj: ST,
                 use_defaults: bool = True,
                 namespaces: Optional[NamespacesType] = None,
                 max_depth: Optional[int] = None,
                 extra_validator: Optional[ExtraValidatorType] = None) -> bool:
        """
        Like :meth:`validate` except that does not raise an exception but returns
        ``True`` if the XML data instance is valid, ``False`` if it is invalid.
        """
        error = next(self.iter_errors(obj, use_defaults, namespaces,
                                      max_depth, extra_validator), None)
        return error is None

    def iter_errors(self, obj: ST,
                    use_defaults: bool = True,
                    namespaces: Optional[NamespacesType] = None,
                    max_depth: Optional[int] = None,
                    extra_validator: Optional[ExtraValidatorType] = None) \
            -> Iterator[XMLSchemaValidationError]:
        """
        Creates an iterator for the errors generated by the validation of an XML data against
        the XSD schema/component instance. Accepts the same arguments of :meth:`validate`.
        """
        kwargs: Dict[str, Any] = {
            'use_defaults': use_defaults,
            'namespaces': namespaces,
        }
        if max_depth is not None:
            kwargs['max_depth'] = max_depth
        if extra_validator is not None:
            kwargs['extra_validator'] = extra_validator

        for result in self.iter_decode(obj, **kwargs):
            if isinstance(result, XMLSchemaValidationError):
                yield result
            else:
                del result

    def decode(self, obj: ST, validation: str = 'strict', **kwargs: Any) -> DecodeType[DT]:
        """
        Decodes XML data.

        :param obj: the XML data. Can be a string for an attribute or for simple type \
        components or a dictionary for an attribute group or an ElementTree's \
        Element for other components.
        :param validation: the validation mode. Can be 'lax', 'strict' or 'skip.
        :param kwargs: optional keyword arguments for the method :func:`iter_decode`.
        :return: a dictionary like object if the XSD component is an element, a \
        group or a complex type; a list if the XSD component is an attribute group; \
        a simple data type object otherwise. If *validation* argument is 'lax' a 2-items \
        tuple is returned, where the first item is the decoded object and the second item \
        is a list containing the errors.
        :raises: :exc:`XMLSchemaValidationError` if the object is not decodable by \
        the XSD component, or also if it's invalid when ``validation='strict'`` is provided.
        """
        check_validation_mode(validation)

        result: Union[DT, XMLSchemaValidationError]
        errors: List[XMLSchemaValidationError] = []
        for result in self.iter_decode(obj, validation, **kwargs):  # pragma: no cover
            if not isinstance(result, XMLSchemaValidationError):
                return (result, errors) if validation == 'lax' else result
            elif validation == 'strict':
                raise result
            else:
                errors.append(result)

        return (None, errors) if validation == 'lax' else None  # fallback: pragma: no cover

    def encode(self, obj: Any, validation: str = 'strict', **kwargs: Any) -> EncodeType[Any]:
        """
        Encodes data to XML.

        :param obj: the data to be encoded to XML.
        :param validation: the validation mode. Can be 'lax', 'strict' or 'skip.
        :param kwargs: optional keyword arguments for the method :func:`iter_encode`.
        :return: An element tree's Element if the original data is a structured data or \
        a string if it's simple type datum. If *validation* argument is 'lax' a 2-items \
        tuple is returned, where the first item is the encoded object and the second item \
        is a list containing the errors.
        :raises: :exc:`XMLSchemaValidationError` if the object is not encodable by the XSD \
        component, or also if it's invalid when ``validation='strict'`` is provided.
        """
        check_validation_mode(validation)
        result, errors = None, []
        for result in self.iter_encode(obj, validation=validation, **kwargs):  # pragma: no cover
            if not isinstance(result, XMLSchemaValidationError):
                break
            elif validation == 'strict':
                raise result
            else:
                errors.append(result)

        return (result, errors) if validation == 'lax' else result

    def iter_decode(self, obj: ST, validation: str = 'lax', **kwargs: Any) \
            -> IterDecodeType[DT]:
        """
        Creates an iterator for decoding an XML source to a Python object.

        :param obj: the XML data.
        :param validation: the validation mode. Can be 'lax', 'strict' or 'skip.
        :param kwargs: keyword arguments for the decoder API.
        :return: Yields a decoded object, eventually preceded by a sequence of \
        validation or decoding errors.
        """
        raise NotImplementedError()

    def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \
            -> IterEncodeType[Any]:
        """
        Creates an iterator for encoding data to an Element tree.

        :param obj: The data that has to be encoded.
        :param validation: The validation mode. Can be 'lax', 'strict' or 'skip'.
        :param kwargs: keyword arguments for the encoder API.
        :return: Yields an Element, eventually preceded by a sequence of validation \
        or encoding errors.
        """
        raise NotImplementedError() class XsdFacet(XsdComponent):
class XsdWhiteSpaceFacet(XsdFacet):
class XsdLengthFacet(XsdFacet):
class XsdMinLengthFacet(XsdFacet):
class XsdMaxLengthFacet(XsdFacet):
class XsdMinInclusiveFacet(XsdFacet):
class XsdMinExclusiveFacet(XsdFacet):
class XsdMaxInclusiveFacet(XsdFacet):
class XsdMaxExclusiveFacet(XsdFacet):
class XsdTotalDigitsFacet(XsdFacet):
class XsdFractionDigitsFacet(XsdFacet):
class XsdExplicitTimezoneFacet(XsdFacet):
class XsdEnumerationFacets(MutableSequence[ElementType], XsdFacet):
class XsdPatternFacets(MutableSequence[ElementType], XsdFacet):
class XsdAssertionXPathParser(XPath2Parser):
class XsdAssertionFacet(XsdFacet):
    def __init__(self, elem: ElementType,
                 schema: SchemaType,
                 parent: Union['XsdList', 'XsdAtomicRestriction'],
                 base_type: Optional[BaseXsdType]) -> None:
    def __repr__(self) -> str:
    def __call__(self, value: Any) -> None:
    def _validator(_: Any) -> None:
    def _parse(self) -> None:
    def _parse_value(self, elem: ElementType) -> Union[None, AtomicValueType, Pattern[str]]:
    def built(self) -> bool:
    def base_facet(self) -> Optional['XsdFacet']:
    def _parse_value(self, elem: ElementType) -> None:
    def replace_white_space_validator(self, value: str) -> None:
    def collapse_white_space_validator(self, value: str) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def _length_validator(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def _min_length_validator(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def _max_length_validator(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def __init__(self, elem: ElementType,
                 schema: SchemaType,
                 parent: 'XsdAtomicRestriction',
                 base_type: BaseXsdType) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def __call__(self, value: Any) -> None:
    def _parse_value(self, elem: ElementType) -> None:
    def _required_timezone_validator(self, value: Any) -> None:
    def _prohibited_timezone_validator(self, value: Any) -> None:
    def __init__(self, elem: ElementType,
                 schema: SchemaType,
                 parent: 'XsdAtomicRestriction',
                 base_type: BaseXsdType) -> None:
    def _parse(self) -> None:
    def _parse_value(self, elem: ElementType) -> Optional[AtomicValueType]:
    def __getitem__(self, i: int) -> ElementType: ...
    def __getitem__(self, s: slice) -> MutableSequence[ElementType]: ...
    def __getitem__(self, i: Union[int, slice]) \
    def __setitem__(self, i: Union[int, slice], o: Any) -> None:
    def __delitem__(self, i: Union[int, slice]) -> None:
    def __len__(self) -> int:
    def insert(self, i: int, elem: ElementType) -> None:
    def __repr__(self) -> str:
    def __call__(self, value: Any) -> None:
    def get_annotation(self, i: int) -> Optional[XsdAnnotation]:
    def __init__(self, elem: ElementType,
                 schema: SchemaType,
                 parent: 'XsdAtomicRestriction',
                 base_type: Optional[BaseXsdType]) -> None:
    def _parse(self) -> None:
    def _parse_value(self, elem: ElementType) -> Pattern[str]:
    def __getitem__(self, i: int) -> ElementType: ...
    def __getitem__(self, s: slice) -> MutableSequence[ElementType]: ...
    def __getitem__(self, i: Union[int, slice]) \
    def __setitem__(self, i: Union[int, slice], o: Any) -> None:
    def __delitem__(self, i: Union[int, slice]) -> None:
    def __len__(self) -> int:
    def insert(self, i: int, elem: ElementType) -> None:
    def __repr__(self) -> str:
    def __call__(self, text: str) -> None:
    def regexps(self) -> List[str]:
    def get_annotation(self, i: int) -> Optional[XsdAnnotation]:
def evaluate_last(self, context=None):  # type: ignore[no-untyped-def]
def evaluate_position(self, context=None):  # type: ignore[no-untyped-def]
    def __repr__(self) -> str:
    def _parse(self) -> None:
    def __call__(self, value: AtomicValueType) -> None:
    _ADMITTED_TAGS = XSD_WHITE_SPACE,
    _ADMITTED_TAGS = XSD_LENGTH,
    _ADMITTED_TAGS = XSD_MIN_LENGTH,
    _ADMITTED_TAGS = XSD_MAX_LENGTH,
    _ADMITTED_TAGS = XSD_MIN_INCLUSIVE,
    _ADMITTED_TAGS = XSD_MIN_EXCLUSIVE,
    _ADMITTED_TAGS = XSD_MAX_INCLUSIVE,
    _ADMITTED_TAGS = XSD_MAX_EXCLUSIVE,
    _ADMITTED_TAGS = XSD_TOTAL_DIGITS,
    _ADMITTED_TAGS = XSD_FRACTION_DIGITS,
    _ADMITTED_TAGS = XSD_EXPLICIT_TIMEZONE,
    _ADMITTED_TAGS = {XSD_ENUMERATION}
    _ADMITTED_TAGS = {XSD_PATTERN}
    _ADMITTED_TAGS = {XSD_ASSERTION}
XSD_10_FACETS_BUILDERS = {
    XSD_WHITE_SPACE: XsdWhiteSpaceFacet,
    XSD_LENGTH: XsdLengthFacet,
    XSD_MIN_LENGTH: XsdMinLengthFacet,
    XSD_MAX_LENGTH: XsdMaxLengthFacet,
    XSD_MIN_INCLUSIVE: XsdMinInclusiveFacet,
    XSD_MIN_EXCLUSIVE: XsdMinExclusiveFacet,
    XSD_MAX_INCLUSIVE: XsdMaxInclusiveFacet,
    XSD_MAX_EXCLUSIVE: XsdMaxExclusiveFacet,
    XSD_TOTAL_DIGITS: XsdTotalDigitsFacet,
    XSD_FRACTION_DIGITS: XsdFractionDigitsFacet,
    XSD_ENUMERATION: XsdEnumerationFacets,
    XSD_PATTERN: XsdPatternFacets
}
XSD_11_FACETS_BUILDERS = XSD_10_FACETS_BUILDERS.copy()
XSD_10_FACETS = set(XSD_10_FACETS_BUILDERS)
XSD_11_FACETS = set(XSD_11_FACETS_BUILDERS)
XSD_10_LIST_FACETS = {XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_PATTERN,
                      XSD_ENUMERATION, XSD_WHITE_SPACE}
XSD_11_LIST_FACETS = XSD_10_LIST_FACETS | {XSD_ASSERTION}
XSD_10_UNION_FACETS = {XSD_PATTERN, XSD_ENUMERATION}
XSD_11_UNION_FACETS = MULTIPLE_FACETS = {XSD_PATTERN, XSD_ENUMERATION, XSD_ASSERTION}
from decimal import DecimalException
from typing import cast, Any, Callable, Dict, Iterator, List, \
    Optional, Set, Union, Tuple, Type
from ..etree import etree_element
from ..aliases import ElementType, AtomicValueType, ComponentClassType, \
    IterDecodeType, IterEncodeType, BaseXsdType, SchemaType, DecodedValueType, \
    EncodedValueType
from ..exceptions import XMLSchemaTypeError, XMLSchemaValueError
from ..names import XSD_NAMESPACE, XSD_ANY_TYPE, XSD_SIMPLE_TYPE, XSD_PATTERN, \
    XSD_ANY_ATOMIC_TYPE, XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE, \
    XSD_MIN_INCLUSIVE, XSD_MIN_EXCLUSIVE, XSD_MAX_INCLUSIVE, XSD_MAX_EXCLUSIVE, \
    XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_WHITE_SPACE, XSD_ENUMERATION,\
    XSD_LIST, XSD_ANY_SIMPLE_TYPE, XSD_UNION, XSD_RESTRICTION, XSD_ANNOTATION, \
    XSD_ASSERTION, XSD_ID, XSD_IDREF, XSD_FRACTION_DIGITS, XSD_TOTAL_DIGITS, \
    XSD_EXPLICIT_TIMEZONE, XSD_ERROR, XSD_ASSERT, XSD_QNAME, XSD_UNTYPED_ATOMIC
from ..helpers import get_prefixed_qname, local_name
from .exceptions import XMLSchemaValidationError, XMLSchemaEncodeError, \
    XMLSchemaDecodeError, XMLSchemaParseError
from .xsdbase import XsdComponent, XsdType, ValidationMixin
from .facets import XsdFacet, XsdWhiteSpaceFacet, XsdPatternFacets, \
    XsdEnumerationFacets, XsdAssertionFacet, XSD_10_FACETS_BUILDERS, \
    XSD_11_FACETS_BUILDERS, XSD_10_FACETS, XSD_11_FACETS, XSD_10_LIST_FACETS, \
    XSD_11_LIST_FACETS, XSD_10_UNION_FACETS, XSD_11_UNION_FACETS, MULTIPLE_FACETS
            reason = "no type suitable for decoding the values %r." % not_decodable
            yield XMLSchemaDecodeError(self, obj, self.member_types, reason)

        yield items if len(items) > 1 else items[0] if items else None

    def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \
            -> IterEncodeType[EncodedValueType]:

        for member_type in self.member_types:
            for result in member_type.iter_encode(obj, validation='lax', **kwargs):
                if result is not None and not isinstance(result, XMLSchemaValidationError):
                    yield result
                    return
                elif validation == 'strict':
                    # In 'strict' mode avoid lax encoding by similar types
                    # (eg. float encoded by int)
                    break

        if hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)):
            for member_type in self.member_types:
                results = []
                for item in obj:
                    for result in member_type.iter_encode(item, validation='lax', **kwargs):
                        if result is not None and not isinstance(result, XMLSchemaValidationError):
                            results.append(result)
                            break
                        elif validation == 'strict':
                            break

                if len(results) == len(obj):
                    yield results
                    break

        if validation != 'skip':
            reason = "no type suitable for encoding the object."
            yield XMLSchemaEncodeError(self, obj, self.member_types, reason)
            yield None
        else:
            yield str(obj)


class Xsd11Union(XsdUnion):
    _ADMITTED_TYPES = XsdAtomic, XsdList, XsdUnion


class XsdAtomicRestriction(XsdAtomic):
    """
    Class for XSD 1.0 atomic simpleType and complexType's simpleContent restrictions.

    ..  <restriction
          base = QName
          id = ID
          {any attributes with non-schema namespace . . .}>
          Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive |
          maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength |
          enumeration | whiteSpace | pattern)*))
        </restriction>
    """
    parent: 'XsdSimpleType'
    base_type: BaseXsdType
    derivation = 'restriction'
    _FACETS_BUILDERS = XSD_10_FACETS_BUILDERS
    _CONTENT_TAIL_TAGS = {XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ANY_ATTRIBUTE}

    def __setattr__(self, name: str, value: Any) -> None:
        if name == 'elem' and value is not None:
            if self.name != XSD_ANY_ATOMIC_TYPE and value.tag != XSD_RESTRICTION:
                if not (value.tag == XSD_SIMPLE_TYPE and value.get('name') is not None):
                    raise XMLSchemaValueError(
                        "an xs:restriction definition required for %r." % self
                    )
        super(XsdAtomicRestriction, self).__setattr__(name, value)

    def _parse(self) -> None:
        elem = self.elem
        if elem.get('name') == XSD_ANY_ATOMIC_TYPE:
            return  # skip special type xs:anyAtomicType
        elif elem.tag == XSD_SIMPLE_TYPE and elem.get('name') is not None:
            # Global simpleType with internal restriction
            elem = cast(ElementType, self._parse_child_component(elem))

        if self.name is not None and self.parent is not None:
            self.parse_error("'name' attribute in a local simpleType definition")

        base_type: Any = None
        facets: Any = {}
        has_attributes = False
        has_simple_type_child = False

        if 'base' in elem.attrib:
            try:
                base_qname = self.schema.resolve_qname(elem.attrib['base'])
            except (KeyError, ValueError, RuntimeError) as err:
                self.parse_error(err)
                base_type = self.any_atomic_type
            else:
                if base_qname == self.name:
                    if self.redefine is None:
                        self.parse_error("wrong definition with self-reference")
                        base_type = self.any_atomic_type
                    else:
                        base_type = self.base_type
                else:
                    if self.redefine is not None:
                        self.parse_error("wrong redefinition without self-reference")

                    try:
                        base_type = self.maps.lookup_type(base_qname)
                    except KeyError:
                        self.parse_error("unknown type %r" % elem.attrib['base'])
                        base_type = self.any_atomic_type
                    except XMLSchemaParseError as err:
                        self.parse_error(err)
                        base_type = self.any_atomic_type
                    else:
                        if isinstance(base_type, tuple):
                            msg = "circularity definition between {!r} and {!r}"
                            self.parse_error(msg.format(self, base_qname))
                            base_type = self.any_atomic_type


            if base_type.is_simple() and base_type.name == XSD_ANY_SIMPLE_TYPE: