def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        target = self._name.evaluate(context)
        if target.lower() == 'xml':
            raise XsltRuntimeException(Error.ILLEGAL_XML_PI, self)

        processor.pushResultString()
        had_nontext = 0
        try:
            for child in self.children:
                child.instantiate(context, processor)
                if processor.writers[-1].had_nontext:
                    had_nontext = 1
        finally:
            if had_nontext:
                raise XsltRuntimeException(Error.NONTEXT_IN_PI, self)
            content = processor.popResult()

        # Per the spec, PI data can't contain '?>', but we are allowed
        # to replace it with '? >' instead of signalling an error.
        data = content.replace(u'?>', u'? >')
        processor.writers[-1].processingInstruction(target, data)

        return
    def instantiate(self, context, processor, used=None):
        if used is None:
            used = []

        if self in used:
            raise XsltRuntimeException(Error.CIRCULAR_ATTRIBUTE_SET, self,
                                       self._name)
        else:
            used.append(self)

        old_vars = context.varBindings
        context.varBindings = processor.stylesheet.getGlobalVariables()

        for attr_set_name in self._use_attribute_sets:
            try:
                attr_set = processor.attributeSets[attr_set_name]
            except KeyError:
                raise XsltRuntimeException(Error.UNDEFINED_ATTRIBUTE_SET, self,
                                           attr_set_name)
            attr_set.instantiate(context, processor, used)

        for child in self.children:
            child.instantiate(context, processor)

        context.varBindings = old_vars
        used.remove(self)

        return
Beispiel #3
0
    def instantiate(self, context, processor):
        # setup parameters for called template

        # This handles the case of top-level variables using call-templates
        if not self._called_template:
            self.prime(processor, context)
            self._called_template = processor._namedTemplates.get(self._name)
            if not self._called_template:
                raise XsltRuntimeException(Error.NAMED_TEMPLATE_NOT_FOUND,
                                           self, self._name)
            self._called_template.prime(processor, context)

        # We need to calculate the parameters before the variable context
        # is changed back in the template element
        params = {}
        for (param, name, expr) in self._params:
            context.processorNss = param.namespaces
            context.currentInstruction = param
            params[name] = expr.evaluate(context)

        if self._tail_recursive:
            context.recursiveParams = params
        else:
            context.currentNode = context.node
            self._called_template.instantiate(context, processor, params)
        return
Beispiel #4
0
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        processor.pushResultString()
        had_nontext = 0
        try:
            for child in self.children:
                child.instantiate(context, processor)
                if processor.writers[-1].had_nontext:
                    had_nontext = 1
        finally:
            if had_nontext:
                raise XsltRuntimeException(Error.NONTEXT_IN_COMMENT, self)
            content = processor.popResult()

        # Per the spec, comment data can't contain '--' or end with '-',
        # but we are allowed to add a space. (XSLT 1.0 sec. 7.4)
        content = content.replace(u'--', u'- -')
        if content[-1:] == u'-':
            content += u' '

        processor.writers[-1].comment(content)

        return
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        (prefix, local) = self._name.evaluate(context)
        if prefix is not None:
            name = prefix + u':' + local
        else:
            name = local

        # From sec. 7.1.2 of the XSLT spec,
        #  1. if 'namespace' attr is not present, use ns in scope, based on prefix
        #    from the element QName in the 'name' attr value; if no prefix, use
        #    default ns in scope
        #  2. if 'namespace' attr is present and empty string, use empty ns ALWAYS
        #  3. if 'namespace' attr is present, namespace is attr value
        #
        if not self._namespace:
            if prefix is not None:
                if not self.namespaces.has_key(prefix):
                    raise XsltRuntimeException(Error.UNDEFINED_PREFIX, self,
                                               prefix)
                namespace = self.namespaces[prefix]
            else:
                namespace = self.namespaces[None]

        else:
            namespace = (self._namespace and self._namespace.evaluate(context)
                         or EMPTY_NAMESPACE)

        self.execute(context, processor, name, namespace)
        return
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        with_params = {}
        for (param, name, expr) in self._params:
            context.processorNss = param.namespaces
            context.currentInstruction = param
            with_params[name] = expr.evaluate(context)

        if self._select:
            node_set = self._select.evaluate(context)
            # it must really be a node-set, and if XSLT 1.0, not a result tree fragment
            if not isinstance(node_set, list):
                raise XsltRuntimeException(Error.ILLEGAL_APPLYTEMPLATE_NODESET,
                                           self)
        else:
            node_set = context.node.childNodes

        # Iterate over the nodes
        state = context.copy()
        mode = context.mode
        context.mode = self._instantiate_mode(context)

        pos = 1
        size = len(node_set)
        for node in node_set:
            context.node, context.position, context.size = node, pos, size
            processor.applyTemplates(context, with_params)
            pos += 1

        context.mode = mode
        context.set(state)
        return
def FormatNumber(context, number, formatString, decimalFormatName=None):
    """
    Implementation of format-number().

    Converts its first argument to a string using the format pattern
    string specified by the second argument and the decimal-format
    named by the third argument (see the xsl:decimal-format element),
    or the default decimal-format, if there is no third argument.

    The format pattern string is in the syntax specified by the JDK 1.1
    DecimalFormat class. The decimal-format name must be a QName. It is
    an error if the stylesheet does not contain a declaration of the
    decimal-format with the specified expanded-name.
    """
    num = Conversions.NumberValue(number)

    format_string = Conversions.StringValue(formatString)

    if decimalFormatName is not None:
        format_name = context.expandQName(decimalFormatName)
    else:
        format_name = None
    try:
        decimal_format = context.stylesheet.decimalFormats[format_name]
    except KeyError:
        raise XsltRuntimeException(Error.UNDEFINED_DECIMAL_FORMAT,
                                   decimalFormatName)

    return routines.FormatNumber(num, format_string, decimal_format)
def Key(context, qname, keyList):
    """
    Implementation of key().

    The first argument specifies the name of the key. When the second
    argument to the key function is of type node-set, then the result
    is the union of the result of applying the key function to the
    string value of each of the nodes in the argument node-set.
    When the second argument to key is of any other type, the argument
    is converted to a string as if by a call to the string function; it
    returns a node-set containing the nodes in the same document as the
    context node that have a value for the named key equal to this string.
    """
    qname = Conversions.StringValue(qname)
    if not qname:
        raise XsltRuntimeException(Error.INVALID_QNAME_ARGUMENT,
                                   context.currentInstruction, qname)
    split_name = context.expandQName(Conversions.StringValue(qname))
    doc = context.node.rootNode
    try:
        keys_for_context_doc = context.processor.keys[doc]
        requested_key = keys_for_context_doc[split_name]
    except KeyError:
        sheet = context.processor.stylesheet
        sheet.updateKey(doc, split_name, context.processor)
        keys_for_context_doc = context.processor.keys[doc]
        requested_key = keys_for_context_doc[split_name]

    result = []
    if not isinstance(keyList, NodesetType):
        keyList = [keyList]
    for key in keyList:
        key = Conversions.StringValue(key)
        result.extend(requested_key.get(key, []))
    return result
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        (prefix, local) = self._name.evaluate(context)
        if prefix is not None:
            name = prefix + ':' + local
        else:
            name = local
        if name == 'xmlns':
            raise XsltRuntimeException(Error.BAD_ATTRIBUTE_NAME, self, name)

        # From sec. 7.1.3 of the XSLT spec,
        #  1. if 'namespace' attr is not present, use ns in scope, based on prefix
        #    from the element QName in the 'name' attr value; if no prefix, use
        #    empty namespace
        #  2. if 'namespace' attr is present and empty string, use empty ns ALWAYS
        #  3. if 'namespace' attr is present, namespace is attr value
        #
        if not self._namespace:
            if prefix is not None:
                if not self.namespaces.has_key(prefix):
                    raise XsltRuntimeException(Error.UNDEFINED_PREFIX, self,
                                               prefix)
                namespace = self.namespaces[prefix]
            else:
                namespace = EMPTY_NAMESPACE
        else:
            namespace = (self._namespace and self._namespace.evaluate(context)
                         or EMPTY_NAMESPACE)

        processor.pushResultString()
        had_nontext = 0
        try:
            for child in self.children:
                child.instantiate(context, processor)
                if processor.writers[-1].had_nontext:
                    had_nontext = 1
        finally:
            if had_nontext:
                raise XsltRuntimeException(Error.NONTEXT_IN_ATTRIBUTE, self)
            content = processor.popResult()

        processor.writers[-1].attribute(name, content, namespace)
        return
    def instantiate(self, context, processor):
        if not context.stylesheet:
            raise XsltRuntimeException(
                Error.APPLYIMPORTS_WITH_NULL_CURRENT_TEMPLATE, self)

        context.stylesheet.applyTemplates(context,
                                          processor,
                                          maxImport=self.importIndex)
        return
Beispiel #11
0
def Intersection(context, ns1, ns2):
    """
    The set:intersection function returns a node set comprising the nodes that
    are within both the node sets passed as arguments to it. 
    """
    if type(ns1) != type([]) != type(ns2):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    return filter(lambda node, other=ns2: node in other, ns1)
Beispiel #12
0
def Min(context, nodeset):
    """
    The math:min function returns the minimum value of the nodes passed as
    the argument.
    """
    if type(nodeset) != type([]):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    numbers = map(Conversions.NumberValue, nodeset)
    return _min(numbers)
Beispiel #13
0
    def prime(self, processor, context):
        self._function = None
        current = self.parent
        while current:
            # this loop will stop when it hits the top of the tree
            if current.expandedName == (EXSL_FUNCTIONS_NS, 'function'):
                self._function = current
                break
            current = current.parent

        if not self._function:
            raise XsltRuntimeException(ExsltError.RESULT_NOT_IN_FUNCTION, self)

        if not self.isLastChild():
            siblings = self.parent.children
            for node in siblings[siblings.index(self) + 1:]:
                if node.expandedName != (XSL_NAMESPACE, 'fallback'):
                    raise XsltRuntimeException(
                        ExsltError.ILLEGAL_RESULT_SIBLINGS, self)
        return
Beispiel #14
0
def Difference(context, nodes1, nodes2):
    """
    The set:difference function returns the difference between two node
    sets - those nodes that are in the node set passed as the first argument
    that are not in the node set passed as the second argument.
    """
    if type(nodes1) != type([]) != type(nodes2):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    result = filter(lambda node, other=nodes2: node not in other, nodes1)
    return result
Beispiel #15
0
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces

        node = context.node
        if node.nodeType == Node.TEXT_NODE:
            processor.writers[-1].text(node.data)

        elif node.nodeType == Node.ELEMENT_NODE:
            #FIXME: Use proper pysax AttributeList objects
            extraNss = {}
            for (namespace, local), attr in node.attributes.items():
                # Namespace nodes are automatically copied as well
                # See XSLT 1.0 Sect 7.5
                if namespace == XMLNS_NAMESPACE:
                    extraNss[local] = attr.value
            processor.writers[-1].startElement(node.nodeName,
                                               node.namespaceURI, extraNss)
            for attr_set_name in self._use_attribute_sets:
                try:
                    attr_set = processor.attributeSets[attr_set_name]
                except KeyError:
                    raise XsltRuntimeException(Error.UNDEFINED_ATTRIBUTE_SET,
                                               self, attr_set_name)
                attr_set.instantiate(context, processor)
            for child in self.children:
                child.instantiate(context, processor)
            processor.writers[-1].endElement(node.nodeName, node.namespaceURI)

        elif node.nodeType == Node.DOCUMENT_NODE:
            for child in self.children:
                child.instantiate(context, processor)

        elif node.nodeType == Node.ATTRIBUTE_NODE:
            if node.namespaceURI != XMLNS_NAMESPACE:
                processor.writers[-1].attribute(node.nodeName, node.nodeValue,
                                                node.namespaceURI)

        elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
            processor.writers[-1].processingInstruction(node.target, node.data)

        elif node.nodeType == Node.COMMENT_NODE:
            processor.writers[-1].comment(node.data)

        elif node.nodeType == NAMESPACE_NODE:
            #Relies on XmlWriter rules, which is very close to spec:
            #http://www.w3.org/1999/11/REC-xslt-19991116-errata/#E25
            processor.writers[-1]._namespaces[-1][
                node.nodeName] = node.nodeValue

        else:
            raise Exception("Unknown Node Type %d" % node.nodeType)

        return
Beispiel #16
0
def Concat(context, nodeset):
    """
    The str:concat function takes a node set and returns the concatenation of
    the string values of the nodes in that node set. If the node set is empty,
    it returns an empty string.
    """
    if type(nodeset) != type([]):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)

    strings = map(Conversions.StringValue, nodeset)
    return u''.join(strings)
Beispiel #17
0
def HasSameNode(context, ns1, ns2):
    """
    The set:has-same-node function returns true if the node set passed as the
    first argument shares any nodes with the node set passed as the second
    argument. If there are no nodes that are in both node sets, then it
    returns false. 
    """
    if type(ns1) != type([]) != type(ns2):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    common = filter(lambda node, other=ns2: node in other, ns1)
    return common and boolean.true or boolean.false
Beispiel #18
0
    def createFormatter(self, format, language=None, letterValue=None):
        """
        Creates a formatter appropriate for the given language and
        letterValue, or a default, English-based formatter. Raises an
        exception if the language or letterValue is unsupported.
        Currently, if the language value is given, it must indicate
        English.
        """
        # lang specifies the language whose alphabet is to be used
        #  for numbering when a format token is alphabetic.
        #
        # "if no lang value is specified, the language should be
        # determined from the system environment." -- unsupported;
        # we just default to English.
        if language and not language.lower().startswith('en'):
            raise XsltRuntimeException(Error.UNSUPPORTED_NUMBER_LANG_VALUE,
                                       self, language)

        # letter-value says how to resolve the ambiguity that arises when
        # you want alphabetic numbering to start with some letter, but
        # that letter, when used in a format token, normally indicates
        # some other numbering system. e.g., in English, the format token
        # "A" means to use the letter "A" for 1, "B" for 2, etc., and
        # "B" means to use the letter "B" for 1, "C" for 2, etc.,
        # but "I" indicates Roman numbering. letter-value="alphabetic" can
        # force the interpretation to be that "I" instead means to use the
        # letter "I" for 1, "J" for 2, etc.
        # Valid values are 'traditional' or 'alphabetic'.
        #
        # Our DefaultFormatter only supports English language and
        # traditional, not alphabetic, letter-value.
        if letterValue and letterValue != 'traditional':
            if not language or language.lower().startswith('en'):
                raise XsltRuntimeException(
                    Error.UNSUPPORTED_NUMBER_LETTER_FOR_LANG, self,
                    letterValue, language or 'en')

        return DefaultFormatter(format)
    def execute(self, context, processor, name, namespace):
        #FIXME: Use proper pysax AttributeList objects
        processor.writers[-1].startElement(name, namespace)
        for attr_set_name in self._use_attribute_sets:
            try:
                attr_set = processor.attributeSets[attr_set_name]
            except KeyError:
                raise XsltRuntimeException(Error.UNDEFINED_ATTRIBUTE_SET, self,
                                           attr_set_name)
            attr_set.instantiate(context, processor)

        for child in self.children:
            child.instantiate(context, processor)

        processor.writers[-1].endElement(name, namespace)
        return
Beispiel #20
0
 def prepare(self, element, value):
     # a 'token' is really an XPath NameTest; '*' | NCName ':' '*' | QName
     # From XPath 1.0 section 2.3:
     #  if the QName does not have a prefix, then the namespace URI is null
     index = value.rfind(':')
     if index == -1:
         namespace = None
         local = value
     else:
         prefix = value[:index]
         local = value[index+1:]
         try:
             namespace = element.namespaces[prefix]
         except KeyError:
             raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                        element, prefix)
     return (namespace, local)
Beispiel #21
0
 def expandQName(self, qname, refNode=None):
     """DEPRECATED: specify an attribute in 'legalAttrs' instead."""
     if not qname: return None
     if refNode:
         namespaces = GetAllNs(refNode)
     else:
         namespaces = self.namespaces
     prefix, local = self.splitQName(qname)
     if prefix:
         try:
             expanded = (namespaces[prefix], local)
         except KeyError:
             raise XsltRuntimeException(Error.UNDEFINED_PREFIX, self,
                                        prefix)
     else:
         expanded = (EMPTY_NAMESPACE, local)
     return expanded
Beispiel #22
0
    def instantiate(self, context, processor):
        context.processorNss = self.namespaces
        context.currentInstruction = self

        # this uses attributes directly from self
        self._output_parameters.avtParse(self, context)
        href = self._href.evaluate(context)

        if Uri.IsAbsolute(href):
            uri = href
        else:
            try:
                uri = Uri.Absolutize(href,
                  Uri.OsPathToUri(processor.writer.getStream().name))
            except Exception, e:
                raise XsltRuntimeException(
                        ExsltError.NO_EXSLTDOCUMENT_BASE_URI,
                        context.currentInstruction, href)
Beispiel #23
0
    def prepare(self, element, value):
        if value is None:
            if self.default is None:
                return None
            value = self.default
        elif not IsQName(value):
            raise XsltException(Error.INVALID_QNAME_ATTR, value)

        prefix, local = SplitQName(value)
        if prefix:
            try:
                namespace = element.namespaces[prefix]
            except KeyError:
                raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                           element, prefix)
        else:
            namespace = EMPTY_NAMESPACE
        return (namespace, local)
Beispiel #24
0
def Distinct(context, nodeset):
    """
    The set:distinct function returns a subset of the nodes contained in the
    node-set NS passed as the first argument. Specifically, it selects a node
    N if there is no node in NS that has the same string value as N, and that
    precedes N in document order.
    """
    if type(nodeset) != type([]):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    values = map(Conversions.StringValue, nodeset)
    found = {}
    result = []
    for node, value in map(None, nodeset, values):
        if not found.has_key(value):
            result.append(node)
            found[value] = 1
    return result
Beispiel #25
0
    def prepare(self, element, value):
        if value is None:
            if self.default is None:
                return None
            value = self.default
        elif not value:
            raise XsltException(Error.QNAME_BUT_NOT_NCNAME, value)

        try:
            index = value.index(':')
        except ValueError:
            raise XsltException(Error.QNAME_BUT_NOT_NCNAME, value)
        prefix, local = value[:index], value[index+1:]
        try:
            namespace = element.namespaces[prefix]
        except KeyError:
            raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                       element, prefix)
        return (namespace, local)
Beispiel #26
0
def Trailing(context, ns1, ns2):
    """
    The set:trailing function returns the nodes in the node set passed as the
    first argument that follow, in document order, the first node in the node
    set passed as the second argument. If the first node in the second node
    set is not contained in the first node set, then an empty node set is
    returned. If the second node set is empty, then the first node set is
    returned. 
    """
    if type(ns1) != type([]) != type(ns2):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    if not ns2:
        return ns1

    # L.index(item) raises an exception if 'item' is not in L
    if ns2[0] not in ns1:
        return []

    ns1.sort()
    return ns1[ns1.index(ns2[0]) + 1:]
Beispiel #27
0
    def instantiate(self, context, processor):
        op = OutputParameters.OutputParameters()
        op.method = "xml"
        op.encoding = processor.writers[-1]._outputParams.encoding
        op.omitXmlDeclaration = 1
        stream = cStringIO.StringIO()
        processor.pushResult(XmlWriter.XmlWriter(op, stream))
        try:
            for child in self.children:
                child.instantiate(context, processor)
        finally:
            processor.popResult()
        msg = stream.getvalue()

        if self._terminate:
            raise XsltRuntimeException(Error.STYLESHEET_REQUESTED_TERMINATION,
                                       self, msg)
        else:
            processor.xslMessage(msg)

        return
Beispiel #28
0
def Map(context, nodeset, string):
    """
    The dyn:map function evaluates the expression passed as the second
    argument for each of the nodes passed as the first argument, and returns
    a node set of those values.

    http://www.exslt.org/dyn/functions/map/index.html
    """
    if type(nodeset) != type([]):
        raise XsltRuntimeException(Error.WRONG_ARGUMENT_TYPE,
                                   context.currentInstruction)
    string = Conversions.StringValue(string)
    try:
        expr = parser.new().parse(string)
    except SyntaxError:
        tb = handle_traceback()
        msg = 'Syntax error in XPath "%s", masked by empty node set return:\n%s' % (
            string, tb.getvalue())
        context.processor.warning(msg)
        return []
    return MapImpl(context, nodeset, expr)
def Map(context, funcname, *nodesets):
    """
    Apply the function serially over the given node sets.
    In iteration i, the function is passed N parameters
    where N is the number of argument node sets.  Each
    parameter is a node set of size 1, whose node is
    the ith node of the corresponding argument node set.
    The return value is a node set consisting of a series
    of result-tree nodes, each of which is a text node
    whose value is the string value of the result of the
    ith function invocation.
    Warning: this function uses the implied ordering of the node set
    Based on its implementation as a Python list.  But in reality
    There is no reliable ordering of XPath node sets.
    Therefore this function is not recommended for use with
    more than one node set parameter.
    """
    (prefix, local) = SplitQName(funcname)
    uri = context.processorNss.get(prefix)
    if prefix and not uri:
        raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                   context.currentInstruction, prefix)
    expanded = (prefix and uri or '', local)
    func = context.functions.get(expanded)
    if not func:
        raise Exception('Dynamically invoked function %s not found.' %
                        funcname)

    flist = [func] * len(nodesets)
    lf = lambda x, f, *args: apply(f, args)
    retlist = apply(map, (lf, flist) + nodesets)

    processor = context.processor
    processor.pushResultTree(context.currentInstruction.baseUri)
    try:
        for ret in retlist:
            processor.writers[-1].text(Conversions.StringValue(ret))
    finally:
        rtf = processor.popResult()
    return rtf.childNodes
Beispiel #30
0
def SystemProperty(context, qname):
    """
    Implementation of system-property().

    Returns an object representing the value of the system property
    identified by the given QName. If there is no such system property,
    the empty string is returned. Supports the required properties in
    the XSLT namespace: xsl:version, xsl:vendor, and xsl:vendor-url;
    plus the following 4Suite-specific properties:

    FOO in namespace http://xmlns.4suite.org/xslt/env-system-property,
    where FOO is an environment variable; and version, tempdir,
    and platform in the %s namespace.
    """ % FT_EXT_NAMESPACE
    qname = Conversions.StringValue(qname)
    #FIXME: actual test should ensure split_name is a QName
    if not qname:
        raise XsltRuntimeException(Error.INVALID_QNAME_ARGUMENT,
                                   context.currentInstruction, qname)
    (uri, local) = context.expandQName(qname)
    if uri == XSL_NAMESPACE:
        if local == 'version':
            return 1.0
        if local == 'vendor':
            return u"Fourthought Inc."
        if local == 'vendor-url':
            return u"http://4Suite.org"
    elif uri == 'http://xmlns.4suite.org/xslt/env-system-property':
        return unicode(os.environ.get(local, ''))
    elif uri == FT_EXT_NAMESPACE:
        if local == 'version':
            return __version__
        if local == 'tempdir':
            #Returns the directory used by the OS for temporary files
            import tempfile
            return unicode(tempfile.gettempdir())
        if local == 'platform':
            return unicode(sys.platform)
    return u''