# 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 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', '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

    @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:
            if cls == simpleTypeDefinition:
                nm = '_%s__FacetMap' % (cls.__name__.strip('_'),)
            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, cls.__name__.strip('_')))
            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):
            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 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)
        if pyxb._ParsingRequiresValid:
            rv.validateBinding()
        return rv

    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 ContentModel 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.ContentModel.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 _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

    @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)

    __dfaStack = 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.__dfaStack = self._ContentModel.initialDFAStack()
        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.__dfaStack 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:
                if self.__dfaStack.step(self, value, element_use):
                    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 starting with %s' % (self._ExpandedName, 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 _setContentFromDOM (self, node, _fallback_namespace):
        """Initialize the content of this element from the content of the DOM node."""

        self.extend(node.childNodes[:], _fallback_namespace)
        if self._PerformValidation() and (not self._isNil()) and (self.__dfaStack is not None) and (not self.__dfaStack.isTerminal()):
            raise pyxb.MissingContentError()
        return self

    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:
    
