Ejemplo n.º 1
0
    def _assign(self, variable, value, stream):
        stream.annotate(value)
        symbols = stream.symbols.as_dict()
        variable = variable % symbols

        if isinstance(value, types.expression):
            if value.symbol_mapping:
                stream.symbol_mapping.update(value.symbol_mapping)

        if isinstance(value, types.template):
            value = types.value(value % symbols)
        if isinstance(value, types.value):
            stream.write("%s = %s" % (variable, value))
        elif isinstance(value, types.join):
            parts = []
            _v_count = 0

            for part in value:
                if isinstance(part, types.expression):
                    stream.symbol_mapping.update(part.symbol_mapping)
                if isinstance(part, types.template):
                    part = types.value(part % symbols)
                if isinstance(part, (types.parts, types.join)):
                    _v = stream.save()
                    assign = Assign(part, _v)
                    assign.begin(stream)
                    assign.end(stream)
                    _v_count += 1
                    parts.append(_v)
                elif isinstance(part, types.value):
                    parts.append(part)
                elif isinstance(part, unicode):
                    if stream.encoding:
                        parts.append(repr(part.encode(stream.encoding)))
                    else:
                        parts.append(repr(part))
                elif isinstance(part, str):
                    parts.append(repr(part))
                else:
                    raise ValueError("Not able to handle %s" % type(part))

            if len(parts) == 1:
                stream.write("%s = %s" % (variable, "".join(parts)))
            else:
                format = "%s" * len(parts)
                stream.write("%s = '%s' %% (%s)" %
                             (variable, format, ",".join(parts)))

            for i in range(_v_count):
                stream.restore()
        elif isinstance(value, basestring):
            stream.write("%s = %r" % (variable, value))
        else:
            raise TypeError("Can't assign value of type %s" % type(value))
Ejemplo n.º 2
0
    def _assign(self, variable, value, stream):
        stream.annotate(value)
        symbols = stream.symbols.as_dict()
        variable = variable % symbols

        if isinstance(value, types.expression):
            if value.symbol_mapping:
                stream.symbol_mapping.update(value.symbol_mapping)

        if isinstance(value, types.template):
            value = types.value(value % symbols)
        if isinstance(value, types.value):
            stream.write("%s = %s" % (variable, value))
        elif isinstance(value, types.join):
            parts = []
            _v_count = 0

            for part in value:
                if isinstance(part, types.expression):
                    stream.symbol_mapping.update(part.symbol_mapping)
                if isinstance(part, types.template):
                    part = types.value(part % symbols)
                if isinstance(part, (types.parts, types.join)):
                    _v = stream.save()
                    assign = Assign(part, _v)
                    assign.begin(stream)
                    assign.end(stream)
                    _v_count +=1
                    parts.append(_v)
                elif isinstance(part, types.value):
                    parts.append(part)
                elif isinstance(part, unicode):
                    if stream.encoding:
                        parts.append(repr(part.encode(stream.encoding)))
                    else:
                        parts.append(repr(part))
                elif isinstance(part, str):
                    parts.append(repr(part))
                else:
                    raise ValueError("Not able to handle %s" % type(part))

            if len(parts) == 1:
                stream.write("%s = %s" % (variable, "".join(parts)))
            else:
                format = "%s"*len(parts)
                stream.write("%s = '%s' %% (%s)" % (variable, format, ",".join(parts)))

            for i in range(_v_count):
                stream.restore()
        elif isinstance(value, basestring):
            stream.write("%s = %r" % (variable, value))
        else:
            raise TypeError("Can't assign value of type %s" % type(value))
Ejemplo n.º 3
0
    def write(self, stream):
        temp = stream.save()
        symbols = stream.symbols.as_dict()

        def write(template):
            stream.write(template % symbols)

        self.assign.begin(stream, temp)
        expr = temp

        stream.write("%s = %s" % (stream.symbols.tmp, expr))
        write(
            "if getattr(%(tmp)s, '__class__', type(%(tmp)s)) not in (str, unicode, int, float):"
        )
        stream.indent()
        write("try:")
        stream.indent()
        write("%(tmp)s = %(tmp)s.__html__")
        stream.outdent()
        write("except:")
        stream.indent()
        write("%%(tmp)s = %s" % translate_expression("%(tmp)s"))
        stream.outdent()
        write("else:")
        stream.indent()
        write("%(tmp)s = %(tmp)s()")
        self._maybe_validate(stream)
        stream.out(types.value(stream.symbols.tmp))
        write("%(tmp)s = None")
        stream.outdent()
        stream.outdent()

        write("if %(tmp)s is not None:")
        stream.indent()

        # only output unicode strings
        stream.ensure_unicode(stream.symbols.tmp)

        # escape markup
        if not self.structure:
            stream.escape(stream.symbols.tmp)

        self._maybe_validate(stream)
        stream.out(types.value(symbols['tmp']))

        stream.outdent()
        stream.restore()

        self.assign.end(stream)
Ejemplo n.º 4
0
    def translate(self, string, escape=None):
        """We use the ``parser`` module to determine if
        an expression is a valid python expression.

        Make sure the formatted syntax error exception contains the
        expression string.

        >>> from traceback import format_exc
        >>> translate = PythonTranslator().translate
        >>> try: translate('abc:def:ghi')
        ... except SyntaxError, e: 'abc:def:ghi' in format_exc(e)
        True
        """

        if isinstance(string, unicode):
            string = string.encode('utf-8')

        if string:
            expression = string.strip()
            parse(expression, 'eval')

            if isinstance(string, str):
                string = string.decode('utf-8')

            return types.value(string.strip())
Ejemplo n.º 5
0
    def translate(self, string, escape=None):
        """
        >>> import_translator = ImportTranslator()
        >>> resolve_dotted = import_translator.translate

        >>> resolve_dotted("")

        >>> resolve_dotted("chameleon.zpt")
        value("_resolve_dotted('chameleon.zpt')")

        >>> translator = StringTranslator(import_translator)
        >>> translator.tales('import: chameleon.zpt')
        parts(value("_resolve_dotted('chameleon.zpt')"), join('',))

        >>> translator.definitions('zpt import: chameleon.zpt; core import: chameleon.core')
        definitions((declaration('zpt'), parts(value("_resolve_dotted('chameleon.zpt')"), join('',))), (declaration('core'), parts(value("_resolve_dotted('chameleon.core')"), join('',))))

        """

        if not string:
            return None

        string = string.strip()

        if self.re_dotted.match(string) is None:
            raise SyntaxError(string)

        value = types.value("%s('%s')" % (self.symbol, string))
        value.symbol_mapping[self.symbol] = _resolve_dotted
        return value
Ejemplo n.º 6
0
    def write(self, stream):
        temp = stream.save()
        symbols = stream.symbols.as_dict()

        def write(template):
            stream.write(template % symbols)

        self.assign.begin(stream, temp)
        expr = temp

        stream.write("%s = %s" % (stream.symbols.tmp, expr))
        write("if %(tmp)s.__class__ not in (str, unicode, int, float):")
        stream.indent()
        write("try:")
        stream.indent()
        write("%(tmp)s = %(tmp)s.__html__")
        stream.outdent()
        write("except:")
        stream.indent()
        write("%%(tmp)s = %s" % translate_expression("%(tmp)s"))
        stream.outdent()
        write("else:")
        stream.indent()
        write("%(tmp)s = %(tmp)s()")
        self._maybe_validate(stream)
        stream.out(types.value(stream.symbols.tmp))
        write("%(tmp)s = None")
        stream.outdent()
        stream.outdent()

        write("if %(tmp)s is not None:")
        stream.indent()

        # only output unicode strings
        stream.ensure_unicode(stream.symbols.tmp)

        # escape markup
        if not self.structure:
            stream.escape(stream.symbols.tmp)

        self._maybe_validate(stream)
        stream.out(types.value(symbols['tmp']))

        stream.outdent()
        stream.restore()

        self.assign.end(stream)
Ejemplo n.º 7
0
    def translate(self, string, escape=None):
        obj, field_name = string.strip().split('#')

        value = types.value("%s(%s, '%s', view, request)" % \
                            (self.symbol, obj, field_name))

        value.symbol_mapping[self.symbol] = self.factory
        return value
Ejemplo n.º 8
0
 def translate(self, string, escape=None):
     if not string:
         return None
     string = string.strip()
     value = types.value("%s('%s', request, subpath='').rstrip('/')" % (
         self.symbol, string))
     value.symbol_mapping[self.symbol] = route_url
     return value
Ejemplo n.º 9
0
    def translate(self, string, escape=None):
        if not string:
            return None
        string = string.strip()

        if self.re_path.match(string) is None:
            raise SyntaxError(string)

        value = types.value("%s('%s', template)" % (self.symbol, string))
        value.symbol_mapping[self.symbol] = _lookup_skin
        return value
Ejemplo n.º 10
0
    def translate(self, string, escape=None):
        if not string:
            return None
        string = string.strip()

        if self.re_name.match(string) is None:
            raise SyntaxError(string)

        value = types.value("%s('%s', context, request)" % (self.symbol, string))
        value.symbol_mapping[self.symbol] = has_permission
        return value
Ejemplo n.º 11
0
    def begin(self, stream):
        stream.write("%s.update(dict(%s))" % (
            stream.symbols.scope,
            ", ".join("%s=%s" % (arg, arg) for arg in self.scope_args)))

        value = self.expression
        if isinstance(value, types.template):
            symbols = stream.symbols.as_dict()
            value = types.value(value % symbols)

        stream.write(value)
Ejemplo n.º 12
0
    def begin(self, stream):
        stream.write(
            "%s.update(dict(%s))" %
            (stream.symbols.scope, ", ".join("%s=%s" % (arg, arg)
                                             for arg in self.scope_args)))

        value = self.expression
        if isinstance(value, types.template):
            symbols = stream.symbols.as_dict()
            value = types.value(value % symbols)

        stream.write(value)
Ejemplo n.º 13
0
    def end(self, stream):
        if self.ret is not None:
            self.ret.begin(stream)
            stream.write('return _ret')
            self.ret.end(stream)
        
        stream.outdent()

        if self.dictionary is not None:
            assign = Assign(
                types.value(self.name), "%s['%s']" % \
                (self.dictionary, self.name))
            assign.begin(stream)
            assign.end(stream)
Ejemplo n.º 14
0
    def end(self, stream):
        if self.ret is not None:
            self.ret.begin(stream)
            stream.write('return _ret')
            self.ret.end(stream)

        stream.outdent()

        if self.dictionary is not None:
            assign = Assign(
                types.value(self.name), "%s['%s']" % \
                (self.dictionary, self.name))
            assign.begin(stream)
            assign.end(stream)
Ejemplo n.º 15
0
    def translate(self, string, escape=None):
        parts = string.strip().split('#')
        if len(parts) == 2:
            obj, name = parts
        else:
            obj = parts[0]
            name = u''

        python_translator = expressions.PythonTranslator()
        # just validate
        python_translator.translate(string)
        value = types.value("%s(%s, view, request, name='%s')" % \
                            (self.symbol, obj.strip(), name))

        value.symbol_mapping[self.symbol] = self.factory
        return value
Ejemplo n.º 16
0
    def translate(self, string, escape=None):
        parts = string.strip().split(':', 1)

        try:
            formatterName, string = parts[0], parts[1]
        except IndexError:
            raise SyntaxError(string)

        string = path_translator.translate(string, escape)

        args = formatterName.split(',')
        formatterName = args[0]
        formatterArgs = args[1:]

        value = types.value(
            "%s(request, '%s', %s, %s)" % \
            (self.symbol, formatterName, formatterArgs, string))

        value.symbol_mapping[self.symbol] = self.formatter_traverse

        return value
Ejemplo n.º 17
0
 def write(self, stream):
     temp = stream.save()
     self.assign.begin(stream, temp)
     stream.out(types.value(temp))
     self.assign.end(stream)
     stream.restore()
Ejemplo n.º 18
0
    def begin(self, stream):
        if self.cdata:
            stream.out('<![CDATA[')
            return

        stream.out('<%s' % self.tag)

        temp = stream.save()
        temp2 = stream.save()

        if self.expression:
            self.expression.begin(stream, stream.symbols.tmp)
            # loop over all attributes
            stream.write("for %s, %s in %s.items():" % \
                         (temp, temp2, stream.symbols.tmp))
            stream.indent()

            # only include attribute if expression is not None
            stream.write("if %s is not None:" % temp2)
            stream.indent()

            # if an encoding is specified, we need to check
            # whether we're dealing with unicode strings or not,
            # before writing out the attribute
            stream.ensure_unicode(temp2)

            # escape expression
            stream.escape(temp2, escape_double_quote=True)

            # write out attribute
            stream.out(
                types.value("' %%s=\"%%s\"' %% (%s, %s)" % (temp, temp2)))

            stream.outdent()
            stream.outdent()

        for attribute, value in self.attributes.items():
            if isinstance(value, types.expression):
                # as an optimization, we only define the `default` symbol,
                # if it's present in the evaluation value (as string
                # representation).
                if stream.symbols.default in repr(value):
                    default = self.defaults.get(attribute, marker)
                else:
                    default = None

                if default is marker:
                    stream.write("%s = %s" %
                                 (stream.symbols.default,
                                  stream.symbols.default_marker_symbol))
                elif default is not None:
                    stream.write("%s = %s" %
                                 (stream.symbols.default, repr(default)))

                assign = Assign(value)
                assign.begin(stream, temp)

                if default is not None:
                    stream.write("%s = None" % stream.symbols.default)

                # verify that attribute value is not the default marker
                stream.write("if %s is %s:" %
                             (temp, stream.symbols.default_marker_symbol))
                default_string = self.defaults.get(attribute)
                stream.indent()
                stream.write("%s = %s" % (temp, repr(default_string)))
                stream.outdent()

                # ignore trivial values
                stream.write("if %s is not None and %s is not False:" %
                             (temp, temp))
                stream.indent()

                # translate non-basic values
                stream.write(
                    "if getattr(%s, '__class__', type(%s)) not in (str, unicode, int, float):"
                    % (temp, temp))
                stream.indent()
                stream.write("%s = unicode(%s)" %
                             (temp, translate_expression(temp) %
                              (stream.symbols.as_dict())))
                stream.outdent()

                # if an encoding is specified, we need to check
                # whether we're dealing with unicode strings or not,
                # before writing out the attribute
                stream.write("else:")
                stream.indent()
                stream.ensure_unicode(temp)
                stream.outdent()

                # escape expression
                stream.escape(temp, escape_double_quote=True)

                # print attribute
                stream.out(types.value("' %s=\"'+%s+'\"'" % (attribute, temp)))

                stream.outdent()
                assign.end(stream)
            else:
                # escape expression
                value = utils.escape(value, '"', 'ascii')

                # if there are dynamic expressions, we only want to write
                # out static attributes if they're not in the dynamic
                # expression dictionary
                if self.expression:
                    stream.write("if '%s' not in %s:" %
                                 (attribute, stream.symbols.tmp))
                    stream.indent()

                stream.out(' %s="%s"' % (attribute, value))

                if self.expression:
                    stream.outdent()

        stream.restore()
        stream.restore()

        if self.selfclosing:
            stream.out(" />")
        else:
            stream.out(">")
Ejemplo n.º 19
0
 def content(self):
     content = self._content
     if content is not None:
         if isinstance(content, types.escape):
             return types.escape((types.value(self.content_symbol), ))
         return types.parts((types.value(self.content_symbol), ))
Ejemplo n.º 20
0
 def content(self):
     content = self._content
     if content is not None:
         if isinstance(content, types.escape):
             return types.escape((types.value(self.content_symbol),))
         return types.parts((types.value(self.content_symbol),))
Ejemplo n.º 21
0
 def write(self, stream):
     temp = stream.save()
     self.assign.begin(stream, temp)
     stream.out(types.value(temp))
     self.assign.end(stream)
     stream.restore()
Ejemplo n.º 22
0
 def translate(self, string, escape=None):
     value = types.value("%s(context, request, view, '%s')" % \
                             (self.symbol, string))
     value.symbol_mapping[self.symbol] = self.portlet_traverse
     return value
Ejemplo n.º 23
0
    def translate(self, string):
        if isinstance(string, str):
            string = string.decode('utf-8')

        return types.value(string.strip())
Ejemplo n.º 24
0
 def translate(self, string, escape=None):
     value = types.value("%s(request, '%s')" % (self.symbol, string))
     value.symbol_mapping[self.symbol] = render_contentprovider
     return value
Ejemplo n.º 25
0
    def begin(self, stream):
        if self.cdata:
            stream.out('<![CDATA['); return

        stream.out('<%s' % self.tag)

        temp = stream.save()
        temp2 = stream.save()
        
        if self.expression:
            self.expression.begin(stream, stream.symbols.tmp)
            # loop over all attributes
            stream.write("for %s, %s in %s.items():" % \
                         (temp, temp2, stream.symbols.tmp))
            stream.indent()

            # only include attribute if expression is not None
            stream.write("if %s is not None:" % temp2)
            stream.indent()

            # if an encoding is specified, we need to check
            # whether we're dealing with unicode strings or not,
            # before writing out the attribute
            stream.ensure_unicode(temp2)

            # escape expression
            stream.escape(temp2, escape_double_quote=True)

            # write out attribute
            stream.out(types.value(
                "' %%s=\"%%s\"' %% (%s, %s)" % (temp, temp2)))

            stream.outdent()
            stream.outdent()

        for attribute, value in self.attributes.items():
            if isinstance(value, types.expression):
                # as an optimization, we only define the `default` symbol,
                # if it's present in the evaluation value (as string
                # representation).
                if stream.symbols.default in repr(value):
                    default = self.defaults.get(attribute, marker)
                else:
                    default = None

                if default is marker:
                    stream.write("%s = %s" % (
                        stream.symbols.default,
                        stream.symbols.default_marker_symbol))
                elif default is not None:
                    stream.write("%s = %s" % (stream.symbols.default, repr(default)))

                assign = Assign(value)
                assign.begin(stream, temp)

                if default is not None:
                    stream.write("%s = None" % stream.symbols.default)

                # verify that attribute value is not the default marker
                stream.write("if %s is %s:" % (
                    temp, stream.symbols.default_marker_symbol))
                default_string = self.defaults.get(attribute)
                stream.indent()
                stream.write("%s = %s" % (
                    temp, repr(default_string)))
                stream.outdent()

                # ignore trivial values
                stream.write("if %s is not None and %s is not False:" % (
                    temp, temp))
                stream.indent()

                # translate non-basic values
                stream.write(
                    "if %s.__class__ not in (str, unicode, int, float):" % temp)
                stream.indent()
                stream.write("%s = unicode(%s)" % (
                    temp, translate_expression(temp) % (
                    stream.symbols.as_dict())))
                stream.outdent()

                # if an encoding is specified, we need to check
                # whether we're dealing with unicode strings or not,
                # before writing out the attribute
                stream.write("else:")
                stream.indent()
                stream.ensure_unicode(temp)
                stream.outdent()

                # escape expression
                stream.escape(temp, escape_double_quote=True)

                # print attribute
                stream.out(types.value(
                    "' %s=\"'+%s+'\"'" % (
                    attribute, temp)))

                stream.outdent()
                assign.end(stream)
            else:
                # escape expression
                value = utils.escape(value, '"', 'ascii')

                # if there are dynamic expressions, we only want to write
                # out static attributes if they're not in the dynamic
                # expression dictionary
                if self.expression:
                    stream.write("if '%s' not in %s:" % (
                        attribute, stream.symbols.tmp))
                    stream.indent()

                stream.out(' %s="%s"' % (attribute, value))

                if self.expression:
                    stream.outdent()

        stream.restore()
        stream.restore()

        if self.selfclosing:
            stream.out(" />")
        else:
            stream.out(">")
Ejemplo n.º 26
0
    def translate(self, string, escape=None):
        value = types.value("%s('%s')" % (self.symbol, string))
        value.symbol_mapping[self.symbol] = self.traverse

        return value