コード例 #1
0
ファイル: test_builtin.py プロジェクト: rlamy/hippyvm
def test_builder():
    def add(space, m, n):
        return space.newint(m + n)
    signature = ['space', int, int]
    builder = BuiltinFunctionBuilder(signature, add)
    assert builder.make_source() == """\
@unroll_safe
def php_add(interp, args_w, w_this, thisclass):
    nb_args = len(args_w)
    space = interp.space
    if nb_args != 2:
        arguments_exactly(interp, fname, 2, nb_args, error_handler)
    nb_args = 2  # constant below
    arg0 = space
    w_arg = args_w[0].deref_unique()
    try:
        arg1 = w_arg.as_int_arg(space)
    except ConvertError:
        raise argument_not(interp, "long", fname, 1, w_arg.tp, error_handler)
    w_arg = args_w[1].deref_unique()
    try:
        arg2 = w_arg.as_int_arg(space)
    except ConvertError:
        raise argument_not(interp, "long", fname, 2, w_arg.tp, error_handler)
    return (arg0, arg1, arg2)
"""

    def incr(space, a, increment=1):
        return space.newint(a + increment)
    signature = ['space', 'reference', Optional(int)]
    builder = BuiltinFunctionBuilder(signature, incr)
    expected = """\
@unroll_safe
def php_incr(interp, args_w, w_this, thisclass):
    nb_args = len(args_w)
    space = interp.space
    if nb_args < 1:
        warn_at_least(space, fname, 1, nb_args)
    if nb_args > 2:
        warn_at_most(space, fname, 2, nb_args)
    arg2 = default2
    arg0 = space
    w_arg = args_w[0]
    arg1 = check_reference(space, w_arg, fname)
    if nb_args > 1:
        w_arg = args_w[1].deref_unique()
        try:
            arg2 = w_arg.as_int_arg(space)
        except ConvertError:
            raise argument_not(interp, "long", fname, 2, w_arg.tp, error_handler)
    return (arg0, arg1, arg2)
"""
    assert builder.make_source() == expected

    def foo(space, fname, ctx=None):
        pass
    signature = ['space', FilenameArg(False), Optional(Nullable(StreamContextArg(False)))]
    builder = BuiltinFunctionBuilder(signature, foo)
    assert builder.make_source() == """\
コード例 #2
0
def test_signature():
    sig = BuiltinSignature(['space', int, int])
    assert sig.php_indices == [0, 0, 1]

    sig = BuiltinSignature(['space', 'reference', Optional(int)])
    assert sig.php_indices == [0, 0, 1]
    assert sig.min_args == 1
    assert sig.max_args == 2

    with py.test.raises(ValueError) as excinfo:
        sig = BuiltinSignature([Optional(int), 'args_w'])
    assert excinfo.value.args[0].startswith("Cannot combine")
コード例 #3
0
ファイル: klass.py プロジェクト: rlamy/hippyvm
    return interp.space.wrap(filename)


@wrap_method(['interp', ThisUnwrapper(W_ReflectionClass)],
             name='ReflectionClass::getStaticProperties')
def reflection_class_get_static_properties(interp, this):
    static_property_values = []
    for k, v in this.refl_klass.properties.items():
        if v.is_static():
            static_property_values.append(v.value)
    return interp.space.new_array_from_list(static_property_values)


@wrap_method(
    ['interp', ThisUnwrapper(W_ReflectionClass),
     Optional(int)],
    name='ReflectionClass::getProperties')
def reflection_class_get_properties(interp, this, flags=0):
    properties = []
    for name in this.refl_klass.properties.keys():
        reflection_prop = k_ReflectionProperty.call_args(
            interp,
            [interp.space.wrap(this.refl_klass.name),
             interp.space.wrap(name)])
        assert isinstance(reflection_prop, W_ReflectionProperty)
        prop_flags = reflection_prop.flags
        if flags == 0:
            properties.append(reflection_prop)

        elif flags & prop_flags:
            properties.append(reflection_prop)
コード例 #4
0
ファイル: php_dir.py プロジェクト: youaani/hippyvm

def _get_path(interp, this):
    return this.path


def _set_handle(interp, this, w_value):
    assert isinstance(w_value, W_DirResource)
    this.handle = w_value


def _get_handle(interp, this):
    return this.handle


@wrap(['interp', str, Optional(StreamContextArg(None))])
def dir(interp, directory, w_ctx=None):
    space = interp.space

    if w_ctx:
        if not interp.space.is_resource(w_ctx):
            interp.warn("dir() expects parameter 2 to be resource, %s given" %
                        interp.space.get_type_name(w_ctx.tp).lower())
            return interp.space.w_Null

    if directory == '':
        return interp.space.w_False

    if not os.path.isdir(directory):
        warn_str = "dir(" + directory + \
                   "): failed to open dir: No such file or directory"
コード例 #5
0
    stream = rzlib.deflateInit(level=level, wbits=encoding)
    bytes = rzlib.compress(stream, data)
    bytes += rzlib.compress(stream, "", rzlib.Z_FINISH)
    rzlib.deflateEnd(stream)
    return bytes


def _decode(data, encoding):
    stream = rzlib.inflateInit(wbits=encoding)
    bytes, finished, unused = rzlib.decompress(stream, data,
                                               rzlib.Z_FINISH)
    rzlib.inflateEnd(stream)
    return bytes


@wrap(['interp', str, Optional(int), Optional(int)])
def gzdeflate(interp, source, level=-1, encoding=ZLIB_ENCODING_RAW):
    res = _encode(source, level, encoding)
    return interp.space.wrap(res)


@wrap(['interp', str, Optional(int), Optional(int)])
def gzencode(interp, source, level=-1, encoding=ZLIB_ENCODING_GZIP):
    res = _encode(source, level, encoding)
    return interp.space.wrap(res)


@wrap(['interp', str, Optional(int), Optional(int)])
def gzcompress(interp, source, level=-1, encoding=ZLIB_ENCODING_DEFLATE):
    res = _encode(source, level, encoding)
    return interp.space.wrap(res)
コード例 #6
0
        return GetterSetter(self.getter, self.setter, self.name, klass,
                            self.accflags)


class W_ExceptionObject(W_InstanceObject):
    def setup(self, interp):
        self.traceback = interp.get_traceback()

    def get_message(self, interp):
        return self.getattr(interp, 'message', k_Exception)


@wrap_method([
    'interp',
    ThisUnwrapper(W_ExceptionObject),
    Optional(str),
    Optional(int),
    Optional('object')
],
             name='Exception::__construct')
def new_exception(interp, this, message='', code=0, w_previous=None):
    this.setattr(interp, 'file', interp.space.wrap(this.traceback[0][0]),
                 k_Exception)
    this.setattr(interp, 'message', interp.space.wrap(message), k_Exception)
    this.setattr(interp, 'code', interp.space.wrap(code), k_Exception)
    if w_previous is None:
        w_previous = interp.space.w_Null
    elif not k_Exception.is_parent_of(w_previous.klass):
        interp.fatal("Wrong parameters for "
                     "Exception([string $exception [, long $code [, "
                     "Exception $previous = NULL]]])")
コード例 #7
0
            setter = self.setter
        return GetterSetter(getter, setter, self.name, klass, self.accflags)


class W_ExceptionObject(W_InstanceObject):
    def setup(self, interp):
        self.traceback = interp.get_traceback()

    def get_message(self, interp):
        return self.getattr(interp, 'message', k_Exception)


@wrap_method([
    'interp',
    ThisUnwrapper(W_ExceptionObject),
    Optional(str),
    Optional(int),
    Optional(Nullable('object'))
],
             name='Exception::__construct')
def new_exception(interp, this, message='', code=0, w_previous=None):
    space = interp.space
    this.setattr(interp, 'file', space.wrap(this.traceback[0][0]), k_Exception)
    this.setattr(interp, 'line', space.wrap(this.traceback[0][2]), k_Exception)
    this.setattr(interp, 'message', space.wrap(message), k_Exception)
    this.setattr(interp, 'code', space.wrap(code), k_Exception)
    if w_previous is None:
        w_previous = space.w_Null
    elif not k_Exception.is_parent_of(w_previous.klass):
        interp.fatal("Wrong parameters for "
                     "Exception([string $exception [, long $code [, "
コード例 #8
0
ファイル: buffering.py プロジェクト: youaani/hippyvm
            val = self.space.str_w(w_buffer)
        if self.prev is None:
            interp.writestr(val, buffer=False)
        else:
            self.prev.write(val)
        self.reset()
        return True

    def clean(self):
        self.reset()

    def get_contents(self):
        return self.space.newstr(self.buffer.build())


@wrap(['interp', Optional(W_Root), Optional(int), Optional(int)])
def ob_start(interp, w_callback=None, chunk_size=4096, flags=112):
    callback = None
    name = 'default output handler'
    if chunk_size < 0:
        chunk_size = 0
    if w_callback:
        try:
            callback = interp.space._get_callback(w_callback)
            if isinstance(w_callback, W_StringObject):
                name = interp.space.str_w(w_callback)
            else:
                name = 'Closure::__invoke'
        except InvalidCallback as e:

            interp.warn("ob_start(): %s" % e.msg)
コード例 #9
0
@k_ReflectionClass.def_method(['interp', 'this'])
def getFileName(interp, this):
    filename = rpath.realpath(this.refl_klass.decl.reflection.filename)
    return interp.space.wrap(filename)


@k_ReflectionClass.def_method(['interp', 'this'])
def getStaticProperties(interp, this):
    static_property_values = []
    for k, v in this.refl_klass.properties.items():
        if v.is_static():
            static_property_values.append(v.value)
    return interp.space.new_array_from_list(static_property_values)


@k_ReflectionClass.def_method(['interp', 'this', Optional(int)])
def getProperties(interp, this, flags=0):
    properties = []
    for name in this.refl_klass.properties.keys():
        reflection_prop = k_ReflectionProperty.call_args(
            interp, [interp.space.wrap(this.refl_klass.name),
                     interp.space.wrap(name)])
        assert isinstance(reflection_prop, W_ReflectionProperty)
        prop_flags = reflection_prop.flags
        if flags == 0:
            properties.append(reflection_prop)

        elif flags & prop_flags:
            properties.append(reflection_prop)

    return interp.space.new_array_from_list(properties)
コード例 #10
0
    return space.w_True


def _fits_in_base(c, base):
    if ord('0') <= ord(c) <= ord('9'):
        if ord(c) - ord('0') < base:
            return True
        return False
    if ord('a') <= ord(c) <= ord('z'):
        if ord(c) - ord('a') < base - 10:
            return True
        return False
    return False


@wrap(['space', W_Root, Optional(LongArg(None))])
def intval(space, w_obj, base=10):
    """ Get the integer value of a variable"""
    if w_obj.tp == space.tp_array:
        if space.arraylen(w_obj) == 0:
            return space.wrap(0)
        return space.wrap(1)
    elif w_obj.tp == space.tp_int:
        return w_obj
    elif w_obj.tp == space.tp_bool:
        return space.as_number(w_obj)
    elif w_obj.tp == space.tp_null:
        return space.wrap(0)
    elif w_obj.tp == space.tp_float:
        try:
            res = intmask(int(space.float_w(w_obj)))
コード例 #11
0
ファイル: funcs.py プロジェクト: youaani/hippyvm
from hippy.builtin import wrap, Optional


@wrap(['interp', str, Optional(str)], error=False)
def mb_strlen(interp, s, encoding='utf-8'):
    encoding = encoding.lower()
    if encoding != 'utf-8' and encoding != 'utf8':
        interp.warn('mb_strlen(): Unsupported encoding "%s"' % encoding)
        return interp.space.w_False
    #
    # special-case logic to handle UTF-8 the fast way
    length = end = len(s)
    i = 0
    while i < end:
        c = s[i]
        if ord(c) < 0xc0:
            i += 1
        elif ord(c) < 0xe0:
            length -= 1
            i += 2
        elif ord(c) < 0xf0:
            length -= 2
            i += 3
        else:
            length -= 3
            i += 4
    return interp.space.wrap(length)
コード例 #12
0

@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), str],
             name='SplFileInfo::__construct')
def construct(interp, this, file_name):
    this.file_name = file_name
    this.path_name = rpath.realpath(file_name)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)],
             name='SplFileInfo::__toString')
def spl_toString(interp, this):
    return interp.space.wrap(this.file_name)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), Optional(str)],
             name='SplFileInfo::getBasename')
def get_basename(interp, this, suffix=''):
    return _basename(interp.space, this.file_name, suffix)


def _extension(interp, filename):
    name_split = filename.rsplit('.', 1)
    if len(name_split) == 2:
        filename, extension = name_split
    else:
        extension = ''
    return interp.space.wrap(extension)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)],
コード例 #13
0
ファイル: datetimezone_klass.py プロジェクト: youaani/hippyvm
                    (space.wrap("offset"), space.wrap(int(o))),
                    (space.wrap("timezone_id"), space.wrap(f))
                ])
            ))
            i += 1
        results.append((space.wrap(k), space.new_array_from_pairs(w_arr_x)))
    return space.new_array_from_pairs(results)


@wrap_method(['space'], name='DateTimeZone::listAbbreviations',
             flags=consts.ACC_STATIC)
def list_abbreviations(space):
    return _abbreviations_list(space)


@wrap_method(['space', Optional(LongArg(None)), Optional(StringArg(None))],
             name='DateTimeZone::listIdentifiers', flags=consts.ACC_STATIC)
def identifiers_list(space, what=2047, country=None):
    return common.timezone_identifiers_list(space, what, country)


@wrap_method(['interp', ThisUnwrapper(W_DateTimeZone), Optional(int), Optional(int)],
             name='DateTimeZone::getTransitions', error=False)
def get_transition(interp, this,
                   timestamp_begin=-sys.maxint - 1,
                   timestamp_end=sys.maxint):

    return common.timezone_transitions_get(
        interp, this, timestamp_begin, timestamp_end)

@wrap_method(['interp', ThisUnwrapper(W_DateTimeZone)],
コード例 #14
0
    [GetterSetterWrapper(_get_storage, _set_storage, 'storage', consts.ACC_PRIVATE)],
    instance_class=W_SplArray,
    implements=[k_IteratorAggregate, k_ArrayAccess])


k_ArrayIterator = def_class(
    'ArrayIterator',
    ['__construct', 'offsetExists', 'offsetGet', 'offsetSet', 'offsetUnset',
     'append', 'count',
     'current', 'next', 'key', 'rewind', 'valid'],
    [GetterSetterWrapper(_get_storage, _set_storage, 'storage', consts.ACC_PRIVATE)],
    instance_class=W_ArrayIterator,
    implements=[k_ArrayAccess, k_Iterator])


@k_ArrayObject.def_method(['interp', 'this', Optional(W_Root), Optional(int),
    Optional(str)])
def __construct(interp, this, w_arr=None, flags=0,
        iterator_class='ArrayIterator'):
    if w_arr is None:
        w_arr = interp.space.new_array_from_list([])
    if (not isinstance(w_arr, W_InstanceObject) and
            not isinstance(w_arr, W_ArrayObject)):
        raise interp.throw("Passed variable is not an array or object, using "
            "empty array instead", klass=k_InvalidArgumentException)
    this.iterator_class = iterator_class
    this.w_arr = w_arr


@k_ArrayIterator.def_method(['interp', 'this', Optional(W_Root)])
def __construct(interp, this, w_arr=None):
コード例 #15
0
ファイル: funcs.py プロジェクト: mnazimek/hippyvm
    """jakis komentarz"""
    return space.wrap(w_imagick_res.writeImages(filename, adjoin))


"""
@wrap(['space', ImagickResourceArg(None),int,int])
def thumbnailImage(space, w_imagick_res,columns,rows):
    ""jakis komentarz""
    return space.wrap(w_imagick_res.thumbnailImage(columns,rows))
"""


@wrap(['space', ImagickResourceArg(None), float])
def setImageOpacity(space, w_imagick_res, opacity):
    """jakis komentarz"""
    return space.wrap(w_imagick_res.setImageOpacity(opacity))


@wrap(['space', ImagickResourceArg(None), int])
def setImageCompressionQuality(space, w_imagick_res, quality):
    """jakis komentarz"""
    return space.wrap(w_imagick_res.setImageCompressionQuality(quality))


@wrap(['space', ImagickResourceArg(None), int, int, int, float, Optional(int)])
def resizeImage(space, w_imagick_res, columns, rows, filter, blur, bestfit=0):
    """jakis komentarz"""
    return space.wrap(w_imagick_res.setImageCompressionQuality(columns, rows, filter, blur, bestfit))


コード例 #16
0
ファイル: funcs.py プロジェクト: netyum/hippyvm
import os
import posix
from hippy.builtin import LongArg, wrap, Optional, FilenameArg
from hippy.objects.base import W_Root
from hippy.objects.resources import W_Resource
from hippy.rpwd import getpwnam, getpwuid, initgroups
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib import rposix
from rpython.rlib.rarithmetic import intmask
from collections import OrderedDict


@wrap(['space', str, Optional(int)], error=False)
def posix_access(space, fname, mode=0):
    """ posix_access - Determine accessibility of a file
    mode can be
        'POSIX_F_OK': 0,
        'POSIX_R_OK': 4,
        'POSIX_W_OK': 2,
        'POSIX_X_OK': 1,
        """
    r = mode & 4 != 0
    w = mode & 2 != 0
    x = mode & 1 != 0
    try:
        res = os.path.isfile(fname)
        if w:
            res &= os.access(fname, os.W_OK)
        if r:
            res &= os.access(fname, os.R_OK)
        if x:
コード例 #17
0
ファイル: funcs.py プロジェクト: youaani/hippyvm
from hippy.builtin import wrap
from hippy.builtin import Optional
from hippy.builtin import BoolArg
from hippy.objects.base import W_Root
from collections import OrderedDict

PHP_WHITESPACE = '\x0b\0'


@wrap(['interp', Optional(W_Root)])
def session_cache_expire(interp, w_new=None):
    """Return current cache expire"""
    act = interp.session.cache_expire
    space = interp.space
    if not w_new:
        return space.newint(act)

    w_num = space.as_number(w_new)
    interp.config.set_ini_w('session.cache_expire', w_num)
    n = space.int_w(w_num)
    interp.session.cache_expire = n
    return space.newint(act)


@wrap(['interp', Optional(str)])
def session_cache_limiter(interp, limiter=None):
    """Get and/or set the current cache limiter"""
    act = interp.session.cache_limiter
    space = interp.space
    if limiter is None:
        return space.newstr(act)
コード例 #18
0
        if klass is not None:
            return klass.constants_w.get(realname, None)
    return None


@wrap(['space', str])
def constant(space, constname):
    """ Returns the value of a constant"""
    w_obj = _lookup_constant(space, constname)
    if w_obj is None:
        space.ec.warn("constant(): Couldn't find constant %s" % constname)
        return space.w_Null
    return w_obj


@wrap(['space', str, W_Root, Optional(bool)])
def define(space, name, w_obj, case_insensitive=False):
    """ Defines a named constant"""
    if name in space.ec.interpreter.constants:
        space.ec.notice("Constant %s already defined" % name)
        return space.w_False
    space.ec.interpreter.constants[name] = w_obj
    return space.w_True


@wrap(['space', str])
def defined(space, name):
    """ Checks whether a given named constant exists"""
    return space.newbool(_lookup_constant(space, name) is not None)

コード例 #19
0
        return space.newstr(n)
    except rsocket.RSocketError:
        return space.w_False


def header_register_callback():
    """ Call a header function"""
    return NotImplementedError()


def header_remove():
    """ Remove previously set headers"""
    return NotImplementedError()


@wrap(['interp', StringArg(None), Optional(BoolArg(None)), Optional(int)])
def header(interp, data, replace=True, response_code=0):
    """ Send a raw HTTP header"""
    assert response_code == 0
    interp.header(data, replace)


def headers_list():
    """ Returns a list of response headers sent(or ready to send)"""
    return NotImplementedError()


@wrap(['space'])
def headers_sent(space):
    """ Checks if or where headers have been sent"""
    return space.wrap(space.ec.interpreter.any_output)
コード例 #20
0
ファイル: exec_.py プロジェクト: youaani/hippyvm
    s = StringBuilder(len(arg) + 2)
    s.append("'")
    for c in arg:
        if c == "'":
            s.append("'")
            s.append("\\")
            s.append("'")
            s.append("'")
        else:
            s.append(c)
    s.append("'")
    return interp.space.wrap(s.build())


@wrap(['interp', str,
       Optional('reference'),
       Optional('reference')],
      error=False,
      name='exec')
def exec_(interp, cmd, r_output=None, r_return_var=None):
    space = interp.space
    if not cmd:
        raise ExitFunctionWithError('Cannot execute a blank command')
    if r_output is not None:
        if not space.is_array(r_output.deref_temp()):
            r_output.store(space.new_array_from_list([]))
        w_output = r_output.deref_unique()
    else:
        w_output = None
    try:
        pfile = create_popen_file(cmd, 'r')
コード例 #21
0
ファイル: spl.py プロジェクト: netyum/hippyvm

@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), str],
             name='SplFileInfo::__construct')
def construct(interp, this, file_name):
    this.file_name = file_name
    this.path_name = rpath.realpath(file_name)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)],
             name='SplFileInfo::__toString')
def spl_toString(interp, this):
    return interp.space.wrap(this.file_name)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), Optional(str)],
             name='SplFileInfo::getBasename')
def get_basename(interp, this, suffix=''):
    return _basename(interp.space, this.file_name, suffix)


@wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)],
             name='SplFileInfo::getExtension')
def get_extension(interp, this):
    path = this.file_name
    filename = rpath.split(path)[1]
    name_split = filename.rsplit('.', 1)
    if len(name_split) == 2:
        filename, extension = name_split
    else:
        extension = ''
コード例 #22
0

def dns_get_mx():
    """ Alias of getmxrr"""
    return NotImplementedError()


def dns_get_record():
    """ Fetch DNS Resource Records associated with a hostname"""
    return NotImplementedError()


@wrap([
    'interp',
    StringArg(None),
    Optional(int),
    Optional('reference'),
    Optional('reference'),
    Optional(float)
],
      error=False)
def fsockopen(interp,
              hostname,
              port=-1,
              w_ref_errno=None,
              w_ref_errstr=None,
              timeout=-1):
    """ Open Internet or Unix domain socket connection"""
    space = interp.space
    r = urlsplit(hostname)
    host = r.host
コード例 #23
0
ファイル: mail.py プロジェクト: youaani/hippyvm
from hippy.builtin import wrap,   Optional


@wrap(['interp',   str,   str,   str,   Optional(str),   Optional(str)])
def mail(interp,   to,   topic,   content,
         extra_headers=None,   extra_params=None):
    # XXXX dummy
    return interp.space.w_True
コード例 #24
0
ファイル: iterator.py プロジェクト: youaani/hippyvm
        '__construct', 'rewind', 'valid', 'key', 'current', 'next',
        'getInnerIterator', 'beginIteration', 'endIteration',
        'callHasChildren', 'callGetChildren', 'beginChildren', 'endChildren',
        'nextElement'
    ],
    constants=[
        ('LEAVES_ONLY', W_IntObject(LEAVES_ONLY)),
        ('SELF_FIRST', W_IntObject(SELF_FIRST)),
        ('CHILD_FIRST', W_IntObject(CHILD_FIRST)),
    ],
    implements=[k_OuterIterator],
    instance_class=W_RecursiveIteratorIterator)


@k_RecursiveIteratorIterator.def_method(
    ['interp', 'this', 'object', Optional(int)])
def __construct(interp, this, w_iter, mode=LEAVES_ONLY):
    if w_iter.klass.is_iterable:
        w_iter = interp.call_method(w_iter, 'getIterator', [])
    if (not isinstance(w_iter, W_InstanceObject)
            or not w_iter.klass.is_subclass_of_class_or_intf_name(
                'RecursiveIterator')):
        raise interp.throw(
            "An instance of RecursiveIterator or "
            "IteratorAggregate creating it is required",
            klass=k_InvalidArgumentException)
    this.w_iter = w_iter
    this.mode = mode
    this.in_iteration = False
    this.stack = [RII_Node(this.w_iter)]
    this.level = 0
コード例 #25
0
ファイル: url.py プロジェクト: youaani/hippyvm
                return self._label_parse(s, pos_p, pos_ue)
            else:
                self.path = s[pos_s:pos_ue]
        return self

    def _label_parse(self, s, pos_p, pos_ue):
        pos_p += 1
        if pos_ue != pos_p:
            self.fragment = s[pos_p:pos_ue]
        return self

    def _just_path(self, s, pos_s):
        return self._nohost(s, pos_s, pos_s + len(s))


@wrap(['space', StringArg(None), Optional(BoolArg(None))])
def base64_decode(space, data, strict=False):
    res = b64_decode(data, strict)
    if res is None:
        return space.w_False
    return space.wrap(res)


@wrap(['space', StringArg(None)])
def base64_encode(space, data):
    res = b64_encode(data)
    if res is None:
        return space.w_False
    return space.wrap(res[:-1])

コード例 #26
0
    except ValueError:
        return space.wrap(-rfloat.INFINITY)


@wrap(['space', float])
def log1p(space, d):
    """ Base-10 logarithm"""
    if d < 0:
        return space.wrap(rfloat.NAN)
    try:
        return space.wrap(math.log1p(d))
    except ValueError:
        return space.wrap(-rfloat.INFINITY)


@wrap(['space', float, 'num_args', Optional(float)])
def log(space, x, num_args, b=0.0):
    """ Base-10 logarithm"""
    if x < 0:
        return space.wrap(rfloat.NAN)
    try:
        if num_args == 2:
            if b <= 0:
                space.ec.warn("log(): base must be greater than 0")
                return space.w_False
            return space.wrap(math.log(x) / math.log(b))
        return space.wrap(math.log(x))
    except ValueError:
        return space.wrap(-rfloat.INFINITY)
    except ZeroDivisionError:
        return space.wrap(rfloat.NAN)
コード例 #27
0
ファイル: property.py プロジェクト: youaani/hippyvm
k_ReflectionProperty = def_class('ReflectionProperty', [
    'export', '__construct', 'getName', 'getValue', 'setValue',
    'getDeclaringClass', "isPublic", "isPrivate", "isProtected", "isStatic",
    "isDefault", "getModifiers", "__toString"
], [
    GetterSetterWrapper(_get_name, _set_name, 'name', consts.ACC_PUBLIC),
    GetterSetterWrapper(_get_class, _set_class, 'class', consts.ACC_PUBLIC)
], [('IS_STATIC', W_IntObject(IS_STATIC)),
    ('IS_PUBLIC', W_IntObject(IS_PUBLIC)),
    ('IS_PROTECTED', W_IntObject(IS_PROTECTED)),
    ('IS_PRIVATE', W_IntObject(IS_PRIVATE))],
                                 instance_class=W_ReflectionProperty)


@k_ReflectionProperty.def_method(
    ['interp', W_Root, str, Optional(bool)], flags=consts.ACC_STATIC)
def export(interp, w_klass, name, return_string=False):
    refl = k_ReflectionProperty.call_args(
        interp, [w_klass, interp.space.wrap(name)])
    result = refl.get_str()
    if return_string:
        return interp.space.wrap(result)
    else:
        interp.writestr(result)
        interp.writestr('\n')
        return interp.space.w_Null


@k_ReflectionProperty.def_method(['interp', 'this', W_Root, str])
def __construct(interp, this, w_class, property_name):
    space = interp.space
コード例 #28
0
ファイル: arrayiter.py プロジェクト: mnazimek/hippyvm
from hippy.builtin_klass import k_Iterator
from hippy.builtin import ThisUnwrapper, Optional, wrap_method
from hippy.klass import def_class
from hippy.objects.base import W_Root
from hippy.objects.instanceobject import W_InstanceObject
from hippy import consts


class W_ApplevelArrayIterator(W_InstanceObject):
    pass


@wrap_method(
    ['interp',
     ThisUnwrapper(W_ApplevelArrayIterator),
     Optional(W_Root)],
    name='ArrayIterator::__construct')
def ArrayIterator_construct(interp, this, w_arr=None):
    if w_arr is None:
        w_arr = interp.space.new_array_from_list([])
    this.setattr(interp, "storage", w_arr, k_ArrayIterator)


@wrap_method([], name='ArrayIterator::current')
def ArrayIterator_current():
    pass


@wrap_method([], name='ArrayIterator::next')
def ArrayIterator_next():
    pass
コード例 #29
0
from hippy.builtin import (wrap_method, Optional, ThisUnwrapper, StringArg,
                           LongArg, BoolArg, InstanceUnwrapper,
                           handle_as_exception)
from hippy.klass import def_class
from hippy.builtin_klass import GetterSetterWrapper, k_Exception

from hippy.module.date import timelib
from hippy.module.date import W_DateTime, W_DateTimeZone
from hippy.module.date.dateinterval_klass import W_DateInterval, k_DateInterval
from hippy.module.date import common


@wrap_method([
    'interp',
    ThisUnwrapper(W_DateTime),
    Optional(StringArg()),
    Optional(InstanceUnwrapper(W_DateTimeZone, 'DateTimeZone'))
],
             name='DateTime::__construct',
             error_handler=handle_as_exception)
def construct(interp, this, format_string=None, w_datetimezone=None):

    error = common.initialize_date(interp, 'DateTime::__construct', this,
                                   format_string, w_datetimezone)

    if error:
        raise PHPException(
            k_Exception.call_args(interp, [
                interp.space.wrap("%s(): %s" %
                                  ('DateTime::__construct', error))
            ]))
コード例 #30
0
""" This module contains various internal php functions
"""

from collections import OrderedDict
from hippy.builtin import wrap, W_Root, Optional
from hippy.klass import W_BoundMethod
from hippy.objects.instanceobject import W_InstanceObject
from hippy.error import VisibilityError
from rpython.rlib import jit


@wrap(['space', W_Root, Optional(bool), Optional('reference')])
def is_callable(space, w_name, syntax_only=False, w_callable_name=None):
    assert w_callable_name is None
    if syntax_only:
        if space.is_str(w_name):
            return space.w_True
        if space.is_array(w_name):
            if space.arraylen(w_name) != 2:
                return space.w_False
            w_item = space.getitem(w_name, space.wrap(0))
            if (not isinstance(w_item, W_InstanceObject)
                    and not space.is_str(w_item)):
                return space.w_False
            w_name = space.getitem(w_name, space.wrap(1))
            return space.wrap(space.is_str(w_name))
        if isinstance(w_name, W_InstanceObject):
            return space.w_True
        return space.w_False
    interp = space.ec.interpreter
    w_callable = interp.space.get_callback(None, 0, w_name, False)