Beispiel #1
0
class W_StructPropertyAccessor(values.W_Procedure):
    errorname = "struct-property-accessor"
    _immutable_fields_ = ["property"]
    import_from_mixin(SingleResultMixin)

    def __init__(self, prop):
        self.property = prop

    def get_arity(self):
        return Arity.ONE

    @make_call_method(
        [values.W_Object, default(values.W_Object, None)], simple=False)
    def call_with_extra_info(self, arg, fail, env, cont, app):
        from pycket.interpreter import return_value
        if isinstance(arg, W_StructType):
            w_val = arg.read_prop_precise(self.property)
            if w_val is not None:
                return return_value(w_val, env, cont)
        elif isinstance(arg, W_RootStruct):
            return arg.get_prop(self.property, env, cont)
        elif fail is not None:
            if fail.iscallable():
                return fail.call_with_extra_info([], env, cont, app)
            return return_value(fail, env, cont)
        raise SchemeException(
            "%s-accessor: expected %s? but got %s" %
            (self.property.name, self.property.name, arg.tostring()))
Beispiel #2
0
class W_ImpPropertyAccessor(W_ImpPropertyFunction):
    errorname = "impersonator-property-accessor"

    @make_call_method([values.W_Object, default(values.W_Object)]) # FIXME: handle second argument as proc
    def call(self, obj, fail):
        v = lookup_property(obj, self.descriptor)
        if v:
            return v
        if v:
            return v
        if fail:
            return fail
        raise SchemeException("missing impersonator property")
Beispiel #3
0
        return linkl, config


"""
 (define-values (1/read-compiled-linklet) (hash-ref linklet-primitive-table 'read-compiled-linklet #f))
 (define-values (1/instance-unset-variable!) (hash-ref linklet-primitive-table 'instance-unset-variable! #f))
 (define-values (1/variable-reference?) (hash-ref linklet-primitive-table 'variable-reference? #f))
 (define-values (1/variable-reference-constant?) (hash-ref linklet-primitive-table 'variable-reference-constant? #f))
"""

make_pred("linklet?", W_Linklet)

make_pred("instance?", W_LinkletInstance)

@expose("compile-linklet", [W_Object, default(W_Object, w_false), default(W_Object, w_false), default(W_Object, w_false), default(W_Object, w_false)], simple=False)
def compile_linklet(form, name, import_keys, get_import, options, env, cont):
    from pycket.util import console_log
    console_log("compiling linklet : %s %s\n import_keys : %s -- get_import : %s" % (name.tostring(), form.tostring(), import_keys.tostring(), get_import.tostring()), 5)
    with PerfRegionCPS("compile-linklet"):
        cont_ = finish_perf_region_cont("compile-linklet", env, cont)
        return do_compile_linklet(form, name, import_keys, get_import, options, env, cont_)

def do_compile_linklet(form, name, import_keys, get_import, options, env, cont):
    from pycket.util import console_log
    if isinstance(form, W_WrappedConsProper): # s-expr
        # read it and create an AST, put it in a W_Linklet and return
        if not isinstance(form.car(), W_Symbol) or "linklet" != form.car().tostring():
            raise SchemeException("Malformed s-expr. Expected a linklet, got %s" % form.tostring())
        else:
            w_name = W_Symbol.make("ad-hoc") if name is w_false else name
Beispiel #4
0
        raise SchemeException("make-ctype: expected (or/c #f procedure) in argument 2 got %s" %
                              ctr.tostring())
    return W_DerivedCType(ctype, rtc, ctr)

def validate_alignment(ctx, arg, align):
    if align is values.w_false:
        return -1
    if isinstance(align, values.W_Fixnum) and align.value in (1, 2, 4, 8, 16):
        return align.value
    msg = ("%s: expected (or/c #f 1 2 4 8 16) in argument %d got %s" %
           (ctx, arg, align.tostring()))
    raise SchemeException(msg)

@expose("make-cstruct-type",
        [values.W_List,
         default(values.W_Object, values.w_false),
         default(values.W_Object, values.w_false)])
def make_cstruct_type(types, abi, _alignment):
    alignment = validate_alignment("make-cstruct-type", 2, _alignment)

    if types.is_proper_list():
        types_list = []
        for ctype in values.from_list_iter(types):
            if not isinstance(ctype, W_CType):
                break
            types_list.append(ctype)
        else:
            return W_CStructType(types_list[:], abi, alignment)

    msg = "make-cstruct-type: expected (listof ctype?) in argument 0 got %s" % types.tostring()
    raise SchemeException(msg)
Beispiel #5
0
from pycket.prims.expose import unsafe, default, expose, subclass_unsafe

@expose("vector")
def vector(args):
    return values_vector.W_Vector.fromelements(args)

@expose("flvector")
def flvector(args):
    return values_vector.W_FlVector.fromelements(args)

# FIXME: immutable
@expose("vector-immutable")
def vector_immutable(args):
    return values_vector.W_Vector.fromelements(args, immutable=True)

@expose("make-vector", [values.W_Fixnum, default(values.W_Object, values.W_Fixnum(0))])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-vector: expected a positive fixnum")
    return values_vector.W_Vector.fromelement(w_val, size)

@expose("make-flvector", [values.W_Fixnum, default(values.W_Flonum, values.W_Flonum(0.0))])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-flvector: expected a positive fixnum")
    return values_vector.W_FlVector.fromelement(w_val, size)

@expose("vector-length", [values_vector.W_MVector])
def vector_length(v):
Beispiel #6
0
            if c2 == "t":
                return BooleanToken(values.w_true)
            if c2 == "f":
                return BooleanToken(values.w_false)
            if c2 in ["(", "[", "{"]:
                return LParenToken("#" + c2)
            if c2 == "\\":
                s = f.read(1)
                if not s:
                    raise SchemeException("unexpected end of file")
                c = ord(s[0]) # XXX deal with unicode
                return CharToken(values.W_Character.make(unichr(c)))
            raise SchemeException("bad token in read: %s" % c2)
        raise SchemeException("bad token in read: %s" % c)

@expose("read", [default(values.W_InputPort, None)], simple=False)
def read(port, env, cont):
    from pycket.interpreter import return_value
    if port is None:
        port = current_in_param.get(cont)
    v = read_stream(port)
    return return_value(v, env, cont)

def read_stream(stream):
    next_token = read_token(stream)
    if isinstance(next_token, SpecialToken):
        v = read_stream(stream)
        return next_token.finish(v)
    if isinstance(next_token, DelimToken):
        if not isinstance(next_token, LParenToken):
            raise SchemeException("read: unexpected %s"%next_token.str)
Beispiel #7
0
    ("=", "eq"),
]:
    make_fixedtype_cmps(*args)


@expose("unsafe-flsqrt", [unsafe(values.W_Flonum)])
def flsqrt(f):
    return f.arith_sqrt()


@expose("add1", [values.W_Number])
def add1(v):
    return v.arith_add(values.W_Fixnum.ONE)


@expose("atan", [values.W_Number, default(values.W_Number, None)])
def atan(y, x):
    if x is not None:
        # FIXME: signs determine the quadrant of the result
        # and care about NaNs and precision
        if x.arith_zerop() is values.w_false:
            z = y.arith_div(x)
        else:
            # we should raise exn_fail_contract_divide_by_zero
            raise SchemeException("zero_divisor")
    else:
        z = y
    return getattr(z, "arith_atan")()


def make_unary_arith(name,
Beispiel #8
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from pycket              import impersonators as imp
from pycket              import values
from pycket              import vector
from pycket.cont         import call_cont, Cont
from pycket.error        import SchemeException
from pycket.prims.expose import default, expose, make_callable_label, procedure

# Can use this to promote a get_cmk operation to a callable function.
CMKSetToListHandler = make_callable_label([values.W_Object])

@expose("current-continuation-marks",
        [default(values.W_ContinuationPromptTag, values.w_default_continuation_prompt_tag)],
        simple=False)
def current_cont_marks(prompt_tag, env, cont):
    from pycket.interpreter import return_value
    return return_value(values.W_ContinuationMarkSet(cont, prompt_tag), env, cont)

@expose("continuation-marks",
        [values.W_Continuation,
         default(values.W_ContinuationPromptTag, values.w_default_continuation_prompt_tag)])
def continuation_marks(cont, prompt_tag):
    # TODO Prompt tag
    return values.W_ContinuationMarkSet(cont.cont, prompt_tag)

@expose("continuation-mark-set->list",
        [values.W_ContinuationMarkSet, values.W_Object,
         default(values.W_ContinuationPromptTag, None)],
        simple=False)
Beispiel #9
0
    def remove_handle(self, handle):
        if handle in self.callbacks:
            del(self.callbacks[handle])

        if handle in self.weak_callbacks:
            del(self.weak_callbacks[handle])

current_plumber_param = values_parameter.W_Parameter(W_Plumber())
expose_val("current-plumber", current_plumber_param)

@expose("make-plumber", [])
def make_plumber():
    return W_Plumber()

@expose("plumber-add-flush!", [W_Plumber, procedure, default(values.W_Bool, values.w_false)])
def plumber_add_flush_bang(p, proc, is_weak):

    # create a new handle
    h = W_PlumberFlushHandle(p)

    # put the new handle into p's callbacks with the given proc
    if is_weak is values.w_true:
        p.set_weak_callback(h, proc)
    else:
        p.set_callback(h, proc)

    return h

@continuation
def plumber_flush_loop_cont(handlers_callbacks, index, env, cont, _vals):
Beispiel #10
0

@expose("syntax-tainted?", [values.W_Syntax])
def syntax_tainted(v):
    return values.w_false


@expose("syntax->datum", [values.W_Syntax])
def syntax_to_datum(stx):
    return stx.val


# FIXME: not implemented
@expose("datum->syntax", [
    values.W_Object, values.W_Object,
    default(values.W_Object, None),
    default(values.W_Object, None),
    default(values.W_Object, None)
])
def datum_to_syntax(ctxt, v, srcloc, prop, ignored):
    print "NOT YET IMPLEMENTED: datum->syntax"
    assert isinstance(ctxt, values.W_Syntax) or ctxt is values.w_false
    return values.W_Syntax(v)


@expose("syntax-source", [values.W_Syntax])
def syntax_source(stx):
    # XXX Obviously not correct
    return values.w_false

Beispiel #11
0
    ("<=", "le"),
    (">",  "gt"),
    (">=", "ge"),
    ("=",  "eq"),
    ]:
    make_fixedtype_cmps(*args)

@expose("unsafe-flsqrt", [unsafe(values.W_Flonum)])
def flsqrt(f):
    return f.arith_sqrt()

@expose("add1", [values.W_Number])
def add1(v):
    return v.arith_add(values.W_Fixnum.ONE)

@expose("atan", [values.W_Number, default(values.W_Number, None)])
def atan(y, x):
    if x is not None:
        # FIXME: signs determine the quadrant of the result
        # and care about NaNs and precision
        if x.arith_zerop() is values.w_false:
            z = y.arith_div(x)
        else:
            # we should raise exn_fail_contract_divide_by_zero
            raise SchemeException("zero_divisor")
    else:
        z = y
    return getattr(z, "arith_atan")()


def make_unary_arith(name, methname, flversion=False, fxversion=False,
Beispiel #12
0
    return W_DerivedCType(ctype, rtc, ctr)


def validate_alignment(ctx, arg, align):
    if align is values.w_false:
        return -1
    if isinstance(align, values.W_Fixnum) and align.value in (1, 2, 4, 8, 16):
        return align.value
    msg = ("%s: expected (or/c #f 1 2 4 8 16) in argument %d got %s" %
           (ctx, arg, align.tostring()))
    raise SchemeException(msg)


@expose("make-cstruct-type", [
    values.W_List,
    default(values.W_Object, values.w_false),
    default(values.W_Object, values.w_false)
])
def make_cstruct_type(types, abi, _alignment):
    alignment = validate_alignment("make-cstruct-type", 2, _alignment)

    if types.is_proper_list():
        types_list = []
        for ctype in values.from_list_iter(types):
            if not isinstance(ctype, W_CType):
                break
            types_list.append(ctype)
        else:
            return W_CStructType(types_list[:], abi, alignment)

    msg = "make-cstruct-type: expected (listof ctype?) in argument 0 got %s" % types.tostring(
Beispiel #13
0
    return values_vector.W_Vector.fromelements(args)

@expose("flvector")
def flvector(args):
    return values_vector.W_FlVector.fromelements(args)

@expose("extflvector?", [values.W_Object])
def extflvector(obj):
    return values.w_false

# FIXME: immutable
@expose("vector-immutable")
def vector_immutable(args):
    return values_vector.W_Vector.fromelements(args, immutable=True)

@expose("make-vector", [values.W_Fixnum, default(values.W_Object, values.W_Fixnum.ZERO)])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-vector: expected a positive fixnum")
    return values_vector.W_Vector.fromelement(w_val, size)

@expose("make-flvector", [values.W_Fixnum, default(values.W_Flonum, values.W_Flonum.ZERO)])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-flvector: expected a positive fixnum")
    return values_vector.W_FlVector.fromelement(w_val, size)

@expose("vector-length", [values_vector.W_MVector])
def vector_length(v):
Beispiel #14
0
    for start, end in reversed(lst):
        s    = values.W_Fixnum(start)
        e    = values.W_Fixnum(end)
        elem = values.W_Cons.make(s, e)
        acc  = values.W_Cons.make(elem, acc)
    return acc, end

EMPTY_BYTES = values.W_Bytes.from_string("")
NO_MATCH = values.Values.make([values.w_false, values.w_false])
ZERO = values.W_Fixnum.make(0)
ONE  = values.W_Fixnum.make(1)

RMP_ARGS = [
    values.W_Object,
    values.W_Object,
    default(values.W_Fixnum, ZERO),
    default(values.W_Object, values.w_false),
    default(values.W_Object, values.w_false),
    default(values.W_Bytes, EMPTY_BYTES)]

@expose("regexp-match-positions", RMP_ARGS)
@jit.unroll_safe
def rmp(pat, input, inp_start, inp_end, output_port, prefix):
    start = inp_start.value
    if inp_end is values.w_false:
        end = sys.maxint
    elif isinstance(inp_end, values.W_Fixnum):
        end = inp_end.value
    else:
        raise SchemeException("regexp-match-positions: expected fixnum or #f for argument 3")
    assert output_port is values.w_false, "output port not supported yet"
Beispiel #15
0
    return values_regex.W_PRegexp(w_str.as_str_utf8())

@expose("byte-regexp", [values.W_Bytes])
def byte_regrexp(w_str):
    return values_regex.W_ByteRegexp(w_str.as_str())

@expose("byte-pregexp", [values.W_Bytes])
def byte_pregrexp(w_str):
    return values_regex.W_BytePRegexp(w_str.as_str())

EMPTY_BYTES = values.W_Bytes.from_string("")
NO_MATCH = values.Values.make([values.w_false, values.w_false])

RM_ARGS = [
    values.W_Object, values.W_Object,
    default(values.W_Fixnum, values.W_Fixnum.ZERO),
    default(values.W_Object, values.w_false),
    default(values.W_Object, values.w_false),
    default(values.W_Bytes, EMPTY_BYTES)
    ]

@expose("regexp-match", RM_ARGS)
@jit.unroll_safe
def regexp_match(w_re, w_str, inp_start, inp_end, output_port, prefix):
    start = inp_start.value
    if inp_end is values.w_false:
        end = sys.maxint
    elif isinstance(inp_end, values.W_Fixnum):
        end = inp_end.value
    else:
        raise SchemeException("regexp-match: expected fixnum or #f for argument 3")
Beispiel #16
0
# [core:correlated->datum syntax->datum]
@expose("syntax->datum", [W_Object])
def correlated_to_datum(e):
    return correlated_to_datum_inner(e)


@continuation
def datum_to_corr_cont(datum, env, cont, _vals):
    srcloc_object = check_one_val(_vals)
    return return_value(W_Correlated(datum, srcloc_object, {}), env, cont)


# [core:datum->correlated datum->syntax]
@expose("datum->syntax",
        [W_Object, W_Object, default(W_Object, w_false)],
        simple=False)
def datum_to_correlated(ignored, datum, _srcloc, env, cont):

    if isinstance(datum, W_Correlated):
        return return_value(datum, env, cont)
    else:
        from pycket.prims.general import srcloc
        srcloc_const = srcloc.constructor
        if isinstance(_srcloc, W_Vector):
            #unerase = _srcloc.get_strategy().unerase
            #vector_contents = unerase(_srcloc.storage)
            v_ref = _srcloc.get_strategy().ref
            return srcloc_const.call([
                v_ref(_srcloc, 0),
                v_ref(_srcloc, 1),
Beispiel #17
0
    ("<=", "le"),
    (">",  "gt"),
    (">=", "ge"),
    ("=",  "eq"),
    ]:
    make_fixedtype_cmps(*args)

@expose("unsafe-flsqrt", [unsafe(values.W_Flonum)])
def flsqrt(f):
    return f.arith_sqrt()

@expose("add1", [values.W_Number])
def add1(v):
    return v.arith_add(values.W_Fixnum(1))

@expose("atan", [values.W_Number, default(values.W_Number, None)])
def atan(y, x):
    if x is not None:
        # FIXME: signs determine the quadrant of the result
        # and care about NaNs and precision
        if x.arith_zerop() is values.w_false:
            z = y.arith_div(x)
        else:
            # we should raise exn_fail_contract_divide_by_zero
            raise SchemeException("zero_divisor")
    else:
        z = y
    return getattr(z, "arith_atan")()


def make_unary_arith(name, methname, flversion=False, fxversion=False, unwrap_type=values.W_Number):
Beispiel #18
0
    s = w_s.as_str_utf8()
    try:
        if "." in s:
            return values.W_Flonum(rfloat.string_to_float(s))
        else:
            try:
                return values.W_Fixnum(rarithmetic.string_to_int(s, base=10))
            except ParseStringOverflowError:
                return values.W_Bignum(rbigint.rbigint.fromstr(s))
    except ParseStringError as e:
        return values.w_false


@expose("number->string",
        [values.W_Number,
         default(values.W_Fixnum, values.W_Fixnum.make(10))])
def num2str(a, radix):
    from rpython.rlib.rbigint import BASE8, BASE16
    if radix.value == 10:
        return W_String.fromascii(a.tostring())
    else:
        if isinstance(a, values.W_Fixnum):
            if radix.value == 16:
                res = hex(a.value)
                if a.value >= 0:
                    res = res[2:]
                else:
                    res = "-" + res[3:]
                return W_String.fromascii(res)
            #elif radix.value == 8:
            #    return W_String.fromascii(oct(a.value))
Beispiel #19
0
    else:
        return e

# [core:correlated->datum syntax->datum]
@expose("syntax->datum", [W_Object])
def correlated_to_datum(e):
    return correlated_to_datum_inner(e)


@continuation
def datum_to_corr_cont(datum, env, cont, _vals):
    srcloc_object = check_one_val(_vals)
    return return_value(W_Correlated(datum, srcloc_object, {}), env, cont)

# [core:datum->correlated datum->syntax]
@expose("datum->syntax", [W_Object, W_Object, default(W_Object, w_false)], simple=False)
def datum_to_correlated(ignored, datum, _srcloc, env, cont):

    if isinstance(datum, W_Correlated):
        return return_value(datum, env, cont)
    else:
        from pycket.prims.general import srcloc
        srcloc_const = srcloc.constructor
        if isinstance(_srcloc, W_Vector):
            #unerase = _srcloc.get_strategy().unerase
            #vector_contents = unerase(_srcloc.storage)
            v_ref = _srcloc.get_strategy().ref
            return srcloc_const.call([v_ref(_srcloc, 0),
                                      v_ref(_srcloc, 1),
                                      v_ref(_srcloc, 2),
                                      v_ref(_srcloc, 3),
Beispiel #20
0
                    receive_first_field(proc, v, v1, v2, env, cont))
    return proc.call([v, v1, v2], env, cont)

################################################################
# printing

@expose("current-logger", [])
def current_logger():
    return values.current_logger

@expose("make-logger", [values.W_Symbol, values.W_Logger])
def make_logger(name, parent):
    return values.W_Logger()

@expose("make-parameter",
        [values.W_Object, default(values.W_Object, values.w_false)])
def make_parameter(init, guard):
    return values.W_Parameter(init, guard)

@expose("system-library-subpath", [default(values.W_Object, values.w_false)])
def sys_lib_subpath(mode):
    return values.W_Path("x86_64-linux") # FIXME

@expose("primitive-closure?", [values.W_Object])
def prim_clos(v):
    return values.w_false

################################################################
# built-in struct types

def define_struct(name, super=values.w_null, fields=[]):
Beispiel #21
0
def syntax_tainted(v):
    return values.w_false

@expose("syntax->datum", [values.W_Syntax])
def syntax_to_datum(stx):
    return stx.val

@expose("syntax-e", [values.W_Syntax])
def syntax_e(stx):
    # XXX Obviously not correct
    print "NOT YET IMPLEMENTED: syntax-e"
    return stx.val

# FIXME: not implemented
@expose("datum->syntax", [values.W_Object, values.W_Object,
  default(values.W_Object, None), default(values.W_Object, None),
  default(values.W_Object, None)])
def datum_to_syntax(ctxt, v, srcloc, prop, ignored):
    print "NOT YET IMPLEMENTED: datum->syntax"
    assert isinstance(ctxt, values.W_Syntax) or ctxt is values.w_false
    return values.W_Syntax(v)

@expose("syntax-source", [values.W_Syntax])
def syntax_source(stx):
    # XXX Obviously not correct
    return values.w_false

@expose("syntax-source-module", [values.W_Syntax, default(values.W_Object, values.w_false)])
def syntax_source_module(stx, src):
    # XXX Obviously not correct
    return values.W_ResolvedModulePath(values.W_Symbol.make("fake symbol"))
Beispiel #22
0
from pycket                 import values
from pycket                 import values_parameter
from pycket.argument_parser import ArgParser, EndOfInput
from pycket.arity           import Arity
from pycket.base            import W_Object
from pycket.error           import SchemeException
from pycket.prims.expose    import expose, expose_val, default, procedure

@expose("make-parameter",
        [values.W_Object, default(values.W_Object, values.w_false)])
def make_parameter(init, guard):
    return values_parameter.W_Parameter(init, guard)

@expose("make-derived-parameter",
        [values_parameter.W_BaseParameter, procedure, procedure])
def make_derived_parameter(param, guard, wrap):
    return values_parameter.W_DerivedParameter(param, guard, wrap)

@expose("extend-parameterization", arity=Arity.geq(1))
def scheme_extend_parameterization(args):
    if len(args) == 0:
        raise SchemeException("extend-parameterization: expected 1 or more arguments")

    config = args[0]
    argc = len(args)

    if argc < 2 or not isinstance(config, values_parameter.W_Parameterization) or argc % 2 != 1:
        return config

    parser = ArgParser("extend-parameterization", args, start_at=1)
Beispiel #23
0
@expose(["flrandom", "unsafe-flrandom"], [values.W_PseudoRandomGenerator])
def flrandom(gen):
    return values.W_Flonum(rng.random())

@expose("random-seed", [values.W_Fixnum])
def random_seed(seed):
    key = [rarithmetic.r_uint(seed.value)]
    rng.init_by_array(key)
    return values.w_void

@expose("make-pseudo-random-generator", [])
def make_pseudo_random_generator():
    return values.W_PseudoRandomGenerator()

current_pseudo_random_generator = values_parameter.W_Parameter(values.W_PseudoRandomGenerator())
expose_val("current-pseudo-random-generator", current_pseudo_random_generator)

@expose("pseudo-random-generator->vector", [values.W_PseudoRandomGenerator])
def pseudo_random_generator_to_vector(gen):
    return values_vector.W_Vector.fromelements([])

@expose("vector->pseudo-random-generator", [values.W_PseudoRandomGenerator, default(values.W_MVector, None)])
def vector_to_pseudo_random_generator(gen, vec):
    return values.W_PseudoRandomGenerator()

@expose("pseudo-random-generator-vector?", [values.W_Object])
def pseudo_random_generator_vector_huh(vec):
    return values.W_Bool.make(isinstance(vec, values.W_MVector) and vec.length() == 0)

Beispiel #24
0
@continuation
def rewind_next_frame_cont(frames, index, final_cont, env, cont, _vals):
    return do_rewind_frames(frames, index - 1, env, final_cont)


def unwind_frames(frames, env, final_cont):
    return do_unwind_frames(frames, 0, env, final_cont)


def rewind_frames(frames, env, final_cont):
    return do_rewind_frames(frames, len(frames) - 1, env, final_cont)


@expose("continuation-prompt-available?",
        [values.W_ContinuationPromptTag,
         default(values.W_Continuation, None)],
        simple=False)
def cont_prompt_avail(tag, continuation, env, cont):
    from pycket.interpreter import return_value
    if continuation is not None:
        cont = continuation.cont
    prompt = find_continuation_prompt(tag, cont)
    available = values.W_Bool.make(prompt is not None)
    return return_value(available, env, cont)


@continuation
def dynamic_wind_pre_cont(value, pre, post, env, cont, _vals):
    cont = DynamicWindValueCont(pre, post, env, cont)
    return value.call([], env, cont)
Beispiel #25
0
    rng.init_by_array(key)
    return values.w_void


@expose("make-pseudo-random-generator", [])
def make_pseudo_random_generator():
    return values.W_PseudoRandomGenerator()


current_pseudo_random_generator = values_parameter.W_Parameter(
    values.W_PseudoRandomGenerator())
expose_val("current-pseudo-random-generator", current_pseudo_random_generator)


@expose("pseudo-random-generator->vector", [values.W_PseudoRandomGenerator])
def pseudo_random_generator_to_vector(gen):
    return values_vector.W_Vector.fromelements([])


@expose("vector->pseudo-random-generator",
        [values.W_PseudoRandomGenerator,
         default(values.W_MVector, None)])
def vector_to_pseudo_random_generator(gen, vec):
    return values.W_PseudoRandomGenerator()


@expose("pseudo-random-generator-vector?", [values.W_Object])
def pseudo_random_generator_vector_huh(vec):
    return values.W_Bool.make(
        isinstance(vec, values.W_MVector) and vec.length() == 0)
Beispiel #26
0
    topic           = values.w_false
    parent          = values.w_false
    propagate_level = DEBUG

    try:
        topic           = parser.symbol_or_false()
        parent          = parser.logger_or_false()
        propagate_level = parser.log_level()
    except EndOfInput:
        pass

    # Any remaining arguments are propagate topics
    propagate_topic = parser._symbol_or_false()

    return values.W_Logger(topic, parent, propagate_level, propagate_topic)

@expose("log-level?", [values.W_Object, values.W_Object, default(values.W_Object, values.w_false)])
def log_level(logger, level, topic):
    # TODO: Actual implementation
    return values.w_false

@expose("log-message", arity=Arity.oneof(4, 5, 6))
def log_message(args):
    # TODO: Actual implementation
    return

w_current_logger = values_parameter.W_Parameter(w_default_logger)
expose_val("current-logger", w_current_logger)

Beispiel #27
0
                return BooleanToken(values.w_true)
            if c2 == "f":
                return BooleanToken(values.w_false)
            if c2 in ["(", "[", "{"]:
                return LParenToken("#" + c2)
            if c2 == "\\":
                s = f.read(1)
                if not s:
                    raise SchemeException("unexpected end of file")
                c = ord(s[0])  # XXX deal with unicode
                return CharToken(values.W_Character.make(unichr(c)))
            raise SchemeException("bad token in read: %s" % c2)
        raise SchemeException("bad token in read: %s" % c)


@expose("read", [default(values.W_Object, None)], simple=False)
def read(port, env, cont):
    from pycket.interpreter import return_value
    cont = read_stream_cont(env, cont)
    return get_input_port(port, env, cont)


def get_input_port(port, env, cont):
    from pycket.interpreter import return_value
    if port is None:
        port = current_in_param.get(cont)
        return return_value(port, env, cont)
    else:
        return get_port(port, values_struct.w_prop_input_port,
                        values.W_InputPort, env, cont)
Beispiel #28
0
                                  values.w_default_continuation_prompt_tag)
    cont = post_build_exception(env, cont)
    return exn_fail.constructor.call([message, marks], env, cont)


def find_continuation_prompt(tag, cont):
    while cont is not None:
        if isinstance(cont, Prompt) and cont.tag is tag:
            return cont
        cont = cont.get_previous_continuation()
    return None


@expose("continuation-prompt-available?",
        [values.W_ContinuationPromptTag,
         default(values.W_Continuation, None)],
        simple=False)
def cont_prompt_avail(tag, continuation, env, cont):
    from pycket.interpreter import return_value
    if continuation is not None:
        cont = continuation.cont
    prompt = find_continuation_prompt(tag, cont)
    available = values.W_Bool.make(prompt is not None)
    return return_value(available, env, cont)


@continuation
def dynamic_wind_pre_cont(value, post, env, cont, _vals):
    return value.call([], env, dynamic_wind_value_cont(post, env, cont))

Beispiel #29
0
def symbol_to_string_impl(v):
    asciivalue = v.asciivalue()
    if asciivalue is not None:
        return W_String.fromascii(asciivalue)
    return W_String.fromunicode(v.unicodevalue())


@expose("string->symbol", [W_String])
def string_to_symbol(v):
    return values.W_Symbol.make(v.as_str_utf8())


@expose("string->number", [
    W_String,
    default(values.W_Integer, values.W_Fixnum(10)),
    default(values.W_Symbol, values.W_Symbol.make("number-or-false")),
    default(values.W_Symbol, values.W_Symbol.make("decimal-as-exact"))
])
def str2num(w_s, radix, convert_mode, decimal_mode):
    from rpython.rlib import rarithmetic, rfloat, rbigint
    from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError
    from rpython.rlib.rsre import rsre_re as re
    import math

    s = w_s.as_str_utf8()
    try:
        if re.match("[+-]?([\d]+)?.?\d+[tT]\d", s):
            # it's an extflonum
            return values.W_ExtFlonum(s)
Beispiel #30
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket import values_parameter, values_struct
from pycket.arity import Arity
from pycket.error import SchemeException
from pycket.prims.expose import unsafe, default, expose, expose_val

expose_val("current-inspector", values_struct.current_inspector_param)

expose_val("current-code-inspector", values_struct.current_inspector_param)


@expose("make-inspector", [default(values_struct.W_StructInspector, None)],
        simple=False)
def do_make_instpector(inspector, env, cont):
    from pycket.interpreter import return_value
    if inspector is None:
        inspector = values_struct.current_inspector_param.get(cont)
    new_inspector = values_struct.W_StructInspector.make(inspector)
    return return_value(new_inspector, env, cont)


@expose("make-sibling-inspector",
        [default(values_struct.W_StructInspector, None)],
        simple=False)
def do_make_sibling_instpector(inspector, env, cont):
    from pycket.interpreter import return_value
    if inspector is None:
        inspector = values_struct.current_inspector_param.get(cont)
Beispiel #31
0

@expose("flvector")
def flvector(args):
    return values_vector.W_FlVector.fromelements(args)


# FIXME: immutable
@expose("vector-immutable")
def vector_immutable(args):
    return values_vector.W_Vector.fromelements(args, immutable=True)


@expose("make-vector",
        [values.W_Fixnum,
         default(values.W_Object, values.W_Fixnum(0))])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-vector: expected a positive fixnum")
    return values_vector.W_Vector.fromelement(w_val, size)


@expose("make-flvector",
        [values.W_Fixnum,
         default(values.W_Flonum, values.W_Flonum(0.0))])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-flvector: expected a positive fixnum")
    return values_vector.W_FlVector.fromelement(w_val, size)
Beispiel #32
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from pycket import impersonators as imp
from pycket import values
from pycket import vector
from pycket.cont import call_cont
from pycket.error import SchemeException
from pycket.prims.expose import default, expose, make_callable_label, procedure

# Can use this to promote a get_cmk operation to a callable function.
CMKSetToListHandler = make_callable_label([values.W_Object])


@expose("current-continuation-marks", [
    default(values.W_ContinuationPromptTag,
            values.w_default_continuation_prompt_tag)
],
        simple=False)
def current_cont_marks(prompt_tag, env, cont):
    from pycket.interpreter import return_value
    return return_value(values.W_ContinuationMarkSet(cont, prompt_tag), env,
                        cont)


@expose("continuation-marks", [
    values.W_Continuation,
    default(values.W_ContinuationPromptTag,
            values.w_default_continuation_prompt_tag)
])
def continuation_marks(cont, prompt_tag):
    # TODO Prompt tag
Beispiel #33
0
        val, assocs = assocs.car(), assocs.cdr()
        if not isinstance(val, values.W_Cons):
            raise SchemeException("%s: expected list of pairs" % fname)
        keys.append(val.car())
        vals.append(val.cdr())
    return keys[:], vals[:]


@expose("make-weak-hasheq", [])
def make_weak_hasheq():
    # FIXME: not actually weak
    return make_simple_mutable_table(W_EqvMutableHashTable, None, None)


@expose(["make-weak-hash", "make-late-weak-hasheq"],
        [default(values.W_List, None)])
def make_weak_hash(assocs):
    if assocs is None:
        return W_EqualHashTable([], [], immutable=False)
    return W_EqualHashTable(*from_assocs(assocs, "make-weak-hash"),
                            immutable=False)


@expose("make-immutable-hash", [default(values.W_List, values.w_null)])
def make_immutable_hash(assocs):
    keys, vals = from_assocs(assocs, "make-immutable-hash")
    return W_EqualHashTable(keys, vals, immutable=True)


@expose("make-immutable-hasheq", [default(values.W_List, values.w_null)])
def make_immutable_hasheq(assocs):
Beispiel #34
0

@expose("extflvector?", [values.W_Object])
def extflvector(obj):
    return values.w_false


# FIXME: immutable
@expose("vector-immutable")
def vector_immutable(args):
    return values_vector.W_Vector.fromelements(args, immutable=True)


@expose(["make-vector", "make-fxvector"],
        [values.W_Fixnum,
         default(values.W_Object, values.W_Fixnum.ZERO)])
def make_vector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-vector: expected a positive fixnum")
    return values_vector.W_Vector.fromelement(w_val, size)


@expose("make-flvector",
        [values.W_Fixnum,
         default(values.W_Flonum, values.W_Flonum.ZERO)])
def make_flvector(w_size, w_val):
    size = w_size.value
    if size < 0:
        raise SchemeException("make-flvector: expected a positive fixnum")
    return values_vector.W_FlVector.fromelement(w_val, size)
Beispiel #35
0
            if c2 == "t":
                return BooleanToken(values.w_true)
            if c2 == "f":
                return BooleanToken(values.w_false)
            if c2 in ["(", "[", "{"]:
                return LParenToken("#" + c2)
            if c2 == "\\":
                s = f.read(1)
                if not s:
                    raise SchemeException("unexpected end of file")
                c = ord(s[0]) # XXX deal with unicode
                return CharToken(values.W_Character.make(unichr(c)))
            raise SchemeException("bad token in read: %s" % c2)
        raise SchemeException("bad token in read: %s" % c)

@expose("read", [default(values.W_InputPort, None)], simple=False)
def read(port, env, cont):
    from pycket.interpreter import return_value
    if port is None:
        port = current_in_param.get(cont)
    v = read_stream(port)
    return return_value(v, env, cont)

def read_stream(stream):
    next_token = read_token(stream)
    if isinstance(next_token, SpecialToken):
        v = read_stream(stream)
        return next_token.finish(v)
    if isinstance(next_token, DelimToken):
        if not isinstance(next_token, LParenToken):
            raise SchemeException("read: unexpected %s"%next_token.str)
Beispiel #36
0
        pass
    else:
        raise SchemeException("regexp-match: unknown kind of regexp")
    if isinstance(w_str, values_string.W_String):
        s = w_str.as_str_ascii() # XXX for now
        result = w_re.match_string(s)
        return result
    if isinstance(w_str, values.W_Bytes):
        result = w_re.match_string(w_str.as_str())
        return result
    if isinstance(w_str, values.W_InputPort):
        result = w_re.match_port(w_str)
        return result
    raise SchemeException("regexp-match: can't deal with this type")


@expose("regexp-match?", [values.W_Object, values.W_Object])
def regexp_matchp(w_r, w_o):
    result = match(w_r, w_o)
    if result:
        return values.w_true
    else:
        return values.w_false

# FIXME: implementation
define_nyi("regexp-replace", [values.W_Object, values.W_Object, values.W_Object,
                           default(values.W_Bytes, None)])
# def regexp_replace(pattern, input, insert, input_prefix):
#     raise NotImplementedError()
#     return input
Beispiel #37
0
Datei: box.py Projekt: 8l/pycket
@expose("unsafe-unbox", [subclass_unsafe(values.W_Box)], simple=False)
def unsafe_unbox(b, env, cont):
    return b.unbox(env, cont)

@expose("set-box!", [values.W_Box, values.W_Object], simple=False)
def set_box(box, v, env, cont):
    return box.set_box(v, env, cont)

@expose("unsafe-set-box!", [subclass_unsafe(values.W_Box), values.W_Object], simple=False)
def unsafe_set_box(box, v, env, cont):
    return box.set_box(v, env, cont)

# This implementation makes no guarantees about atomicity
@expose("box-cas!", [values.W_MBox, values.W_Object, values.W_Object])
def box_cas(box, old, new):
    if eq_prims.eqp_logic(box.value, old):
        box.value = new
        return values.w_true
    return values.w_false

@expose("make-weak-box", [values.W_Object])
def make_weak_box(val):
    return values.W_WeakBox(val)

@expose("weak-box-value",
        [values.W_WeakBox, default(values.W_Object, values.w_false)])
def weak_box_value(wb, default):
    v = wb.get()
    return v if v is not None else default

Beispiel #38
0
"""
 (define-values (1/read-compiled-linklet) (hash-ref linklet-primitive-table 'read-compiled-linklet #f))
 (define-values (1/instance-unset-variable!) (hash-ref linklet-primitive-table 'instance-unset-variable! #f))
 (define-values (1/variable-reference?) (hash-ref linklet-primitive-table 'variable-reference? #f))
 (define-values (1/variable-reference-constant?) (hash-ref linklet-primitive-table 'variable-reference-constant? #f))
"""

make_pred("linklet?", W_Linklet)

make_pred("instance?", W_LinkletInstance)


@expose("compile-linklet", [
    W_Object,
    default(W_Object, w_false),
    default(W_Object, w_false),
    default(W_Object, w_false),
    default(W_Object, w_false)
],
        simple=False)
def compile_linklet(form, name, import_keys, get_import, options, env, cont):
    from pycket.util import console_log
    console_log(
        "compiling linklet : %s %s\n import_keys : %s -- get_import : %s" %
        (name.tostring(), form.tostring(), import_keys.tostring(),
         get_import.tostring()), 5)
    with PerfRegionCPS("compile-linklet"):
        cont_ = finish_perf_region_cont("compile-linklet", env, cont)
        return do_compile_linklet(form, name, import_keys, get_import, options,
                                  env, cont_)
Beispiel #39
0
from pycket import values
from pycket import values_parameter
from pycket.argument_parser import ArgParser, EndOfInput
from pycket.arity import Arity
from pycket.base import W_Object
from pycket.error import SchemeException
from pycket.prims.expose import expose, expose_val, default, procedure
from rpython.rlib import jit


@expose("make-parameter", [values.W_Object, default(values.W_Object, values.w_false)])
def make_parameter(init, guard):
    return values_parameter.W_Parameter(init, guard)


@expose("make-derived-parameter", [values_parameter.W_BaseParameter, procedure, procedure])
def make_derived_parameter(param, guard, wrap):
    return values_parameter.W_DerivedParameter(param, guard, wrap)


@expose("extend-parameterization", arity=Arity.geq(1))
@jit.unroll_safe
def scheme_extend_parameterization(args):
    if len(args) == 0:
        raise SchemeException("extend-parameterization: expected 1 or more arguments")

    config = args[0]
    argc = len(args)

    if argc < 2 or not isinstance(config, values_parameter.W_Parameterization) or argc % 2 != 1:
        return config
Beispiel #40
0
    ("<=", "le"),
    (">",  "gt"),
    (">=", "ge"),
    ("=",  "eq"),
    ]:
    make_fixedtype_cmps(*args)

@expose("unsafe-flsqrt", [unsafe(values.W_Flonum)])
def flsqrt(f):
    return f.arith_sqrt()

@expose("add1", [values.W_Number])
def add1(v):
    return v.arith_add(values.W_Fixnum.ONE)

@expose("atan", [values.W_Number, default(values.W_Number, None)])
def atan(y, x):
    if x is not None:
        # FIXME: signs determine the quadrant of the result
        # and care about NaNs and precision
        if x.arith_zerop() is values.w_false:
            z = y.arith_div(x)
        else:
            # we should raise exn_fail_contract_divide_by_zero
            raise SchemeException("zero_divisor")
    else:
        z = y
    return getattr(z, "arith_atan")()


def make_unary_arith(name, methname, flversion=False, fxversion=False,
Beispiel #41
0
    from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError

    try:
        s = w_s.as_str_utf8()
        if "." in s:
            return values.W_Flonum(rfloat.string_to_float(s))
        else:
            try:
                return values.W_Fixnum(rarithmetic.string_to_int(s, base=0))
            except ParseStringOverflowError:
                return values.W_Bignum(rbigint.rbigint.fromstr(s))
    except ParseStringError as e:
        return values.w_false

@expose("number->string",
        [values.W_Number, default(values.W_Fixnum, values.W_Fixnum(10))])
def num2str(a, radix):
    from rpython.rlib.rbigint import BASE8, BASE16
    if radix.value == 10:
        return W_String.fromascii(a.tostring())
    else:
        if isinstance(a, values.W_Fixnum):
            if radix.value == 16:
                res = hex(a.value)
                if a.value >= 0:
                    res = res[2:]
                else:
                    res = "-" + res[3:]
                return W_String.fromascii(res)
            #elif radix.value == 8:
            #    return W_String.fromascii(oct(a.value))
Beispiel #42
0
def set_box(box, v, env, cont):
    return box.set_box(v, env, cont)


@expose("unsafe-set-box!", [subclass_unsafe(values.W_Box), values.W_Object],
        simple=False)
def unsafe_set_box(box, v, env, cont):
    return box.set_box(v, env, cont)


# This implementation makes no guarantees about atomicity
@expose("box-cas!", [values.W_MBox, values.W_Object, values.W_Object])
def box_cas(box, old, new):
    if eq_prims.eqp_logic(box.value, old):
        box.value = new
        return values.w_true
    return values.w_false


@expose("make-weak-box", [values.W_Object])
def make_weak_box(val):
    return values.W_WeakBox(val)


@expose("weak-box-value",
        [values.W_WeakBox,
         default(values.W_Object, values.w_false)])
def weak_box_value(wb, default):
    v = wb.get()
    return v if v is not None else default
Beispiel #43
0
@expose("symbol->string", [values.W_Symbol])
def symbol_to_string(v):
    return symbol_to_string_impl(v)

def symbol_to_string_impl(v):
    asciivalue = v.asciivalue()
    if asciivalue is not None:
        return W_String.fromascii(asciivalue)
    return W_String.fromunicode(v.unicodevalue())

@expose("string->symbol", [W_String])
def string_to_symbol(v):
    return values.W_Symbol.make(v.as_str_utf8())

@expose("string->number", [W_String,
                           default(values.W_Integer, values.W_Fixnum(10)),
                           default(values.W_Symbol, values.W_Symbol.make("number-or-false")),
                           default(values.W_Symbol, values.W_Symbol.make("decimal-as-exact"))])
def str2num(w_s, radix, convert_mode, decimal_mode):
    from rpython.rlib import rarithmetic, rfloat, rbigint
    from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError
    from rpython.rlib.rsre import rsre_re as re
    import math
    radix = radix.toint()
    s = w_s.as_str_utf8()
    try:
        if ((radix == 16 and re.match("^[0-9A-Fa-f]+$", s)) or
            (radix == 8 and re.match("^[0-7]+$", s)) or
            (radix == 10 and re.match("^[0-9]+$", s))):
            try:
                return values.W_Fixnum(rarithmetic.string_to_int(s, base=radix))
Beispiel #44
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket import values_struct
from pycket.error import SchemeException
from pycket.prims.expose import unsafe, default, expose

@expose("make-inspector", [default(values_struct.W_StructInspector,
    values_struct.current_inspector)])
def do_make_instpector(inspector):
    return values_struct.W_StructInspector.make(inspector)

@expose("make-sibling-inspector", [default(values_struct.W_StructInspector,
    values_struct.current_inspector)])
def do_make_sibling_instpector(inspector):
    return values_struct.W_StructInspector.make(inspector, True)

@expose("current-inspector")
def do_current_instpector(args):
    return values_struct.current_inspector

@expose("struct?", [values.W_Object])
def do_is_struct(v):
    return values.W_Bool.make(isinstance(v, values_struct.W_RootStruct) and
        values_struct.current_inspector.has_control(v.struct_type()))

@expose("struct-info", [values.W_Object])
def do_struct_info(v):
    if (isinstance(v, values_struct.W_RootStruct) and
        values_struct.current_inspector.has_control(v.struct_type())):
Beispiel #45
0
        xs.append(values.W_Cons.make(s, e))
    return values.to_list(xs)


@expose("regexp-match?", [values.W_Object, values.W_Object])
def regexp_matchp(w_r, w_o):
    result = match(w_r, w_o)
    if result:
        return values.w_true
    else:
        return values.w_false


@expose("regexp-max-lookbehind", [values.W_Object])
def regexp_max_lookbehind(obj):
    if not isinstance(obj, values_regex.W_Regexp) and not isinstance(
            obj, values_regex.W_ByteRegexp):
        raise SchemeException(
            "regexp-max-lookbehind: expected regexp or bytes-regexp")
    return values.W_Fixnum(1000)


# FIXME: implementation
define_nyi("regexp-replace", [
    values.W_Object, values.W_Object, values.W_Object,
    default(values.W_Bytes, None)
])
# def regexp_replace(pattern, input, insert, input_prefix):
#     raise NotImplementedError()
#     return input
Beispiel #46
0
@continuation
def unwind_next_frame_cont(frames, index, final_cont, env, cont, _vals):
    return do_unwind_frames(frames, index + 1, env, final_cont)

@continuation
def rewind_next_frame_cont(frames, index, final_cont, env, cont, _vals):
    return do_rewind_frames(frames, index - 1, env, final_cont)

def unwind_frames(frames, env, final_cont):
    return do_unwind_frames(frames, 0, env, final_cont)

def rewind_frames(frames, env, final_cont):
    return do_rewind_frames(frames, len(frames) - 1, env, final_cont)

@expose("continuation-prompt-available?", [values.W_ContinuationPromptTag, default(values.W_Continuation, None)], simple=False)
def cont_prompt_avail(tag, continuation, env, cont):
    from pycket.interpreter import return_value
    if continuation is not None:
        cont = continuation.cont
    prompt = find_continuation_prompt(tag, cont)
    available = values.W_Bool.make(prompt is not None)
    return return_value(available, env, cont)

@continuation
def dynamic_wind_pre_cont(value, pre, post, env, cont, _vals):
    cont = DynamicWindValueCont(pre, post, env, cont)
    return value.call([], env, cont)

@continuation
def dynamic_wind_value_cont(post, env, cont, _vals):
Beispiel #47
0
expose_val("_int16"  , values.W_Fixnum.make(1))
expose_val("_int32"  , values.W_Fixnum.make(2))
expose_val("_int64"  , values.W_Fixnum.make(3))
expose_val("_uint8"  , values.W_Fixnum.make(4))
expose_val("_uint16" , values.W_Fixnum.make(5))
expose_val("_uint32" , values.W_Fixnum.make(6))
expose_val("_uint64" , values.W_Fixnum.make(7))
expose_val("_bytes"  , values.W_Fixnum.make(8))
expose_val("_path"   , values.W_Fixnum.make(9))
expose_val("_void"   , values.W_Fixnum.make(10))
expose_val("_pointer"  , values.W_Fixnum.make(11))
expose_val("_fpointer" , values.W_Fixnum.make(12))

ctype = values.W_Fixnum

@expose("make-ctype", [ctype, default(values.W_Object, values.w_false), default(values.W_Object, values.w_false)])
def make_c_type(typ, rtc, ctr):
    return values.W_Fixnum(0)

@expose("compiler-sizeof", [values.W_Object])
def compiler_sizeof(sym):
    return values.W_Fixnum(8)

@expose("make-stubborn-will-executor", [])
def make_stub_will_executor():
    return values.w_false

@expose("ctype-sizeof", [ctype])
def ctype_sizeof(c):
    return values.W_Fixnum(8)
Beispiel #48
0
    keys = []
    vals = []
    while isinstance(assocs, values.W_Cons):
        val, assocs = assocs.car(), assocs.cdr()
        if not isinstance(val, values.W_Cons):
            raise SchemeException("%s: expected list of pairs" % fname)
        keys.append(val.car())
        vals.append(val.cdr())
    return keys[:], vals[:]

@expose("make-weak-hasheq", [])
def make_weak_hasheq():
    # FIXME: not actually weak
    return make_simple_mutable_table(W_EqvMutableHashTable, None, None)

@expose("make-weak-hash", [default(values.W_List, None)])
def make_weak_hash(assocs):
    if assocs is None:
        return W_EqualHashTable([], [], immutable=False)
    return W_EqualHashTable(*from_assocs(assocs, "make-weak-hash"), immutable=False)

@expose("make-immutable-hash", [default(values.W_List, values.w_null)])
def make_immutable_hash(assocs):
    keys, vals = from_assocs(assocs, "make-immutable-hash")
    return W_EqualHashTable(keys, vals, immutable=True)

@expose("make-immutable-hasheq", [default(values.W_List, values.w_null)])
def make_immutable_hasheq(assocs):
    return make_simple_immutable_table_assocs(W_EqImmutableHashTable, assocs, "make-immutable-hasheq")

@expose("make-immutable-hasheqv", [default(values.W_List, values.w_null)])
Beispiel #49
0
    ("<=", "le"),
    (">",  "gt"),
    (">=", "ge"),
    ("=",  "eq"),
    ]:
    make_fixedtype_cmps(*args)

@expose("unsafe-flsqrt", [unsafe(values.W_Flonum)])
def flsqrt(f):
    return f.arith_sqrt()

@expose("add1", [values.W_Number])
def add1(v):
    return v.arith_add(values.W_Fixnum.ONE)

@expose("atan", [values.W_Number, default(values.W_Number, None)])
def atan(y, x):
    if x is not None:
        # FIXME: signs determine the quadrant of the result
        # and care about NaNs and precision
        if x.arith_zerop() is values.w_false:
            z = y.arith_div(x)
        else:
            # we should raise exn_fail_contract_divide_by_zero
            raise SchemeException("zero_divisor")
    else:
        z = y
    return getattr(z, "arith_atan")()


def make_unary_arith(name, methname, flversion=False, fxversion=False,
Beispiel #50
0
        if handle in self.weak_callbacks:
            del (self.weak_callbacks[handle])


current_plumber_param = values_parameter.W_Parameter(W_Plumber())
expose_val("current-plumber", current_plumber_param)


@expose("make-plumber", [])
def make_plumber():
    return W_Plumber()


@expose("plumber-add-flush!",
        [W_Plumber, procedure,
         default(values.W_Bool, values.w_false)])
def plumber_add_flush_bang(p, proc, is_weak):

    # create a new handle
    h = W_PlumberFlushHandle(p)

    # put the new handle into p's callbacks with the given proc
    if is_weak is values.w_true:
        p.set_weak_callback(h, proc)
    else:
        p.set_callback(h, proc)

    return h


@continuation
Beispiel #51
0
@expose(prefix_hash_names("hash-iterate-value"),
        [W_HashTable, values.W_Fixnum], simple=False)
def hash_iterate_value(ht, pos, env, cont):
    return hash_iter_ref(ht, pos.value, env, cont, returns=_VALUE)

@expose(prefix_hash_names("hash-iterate-key+value"),
        [W_HashTable, values.W_Fixnum], simple=False)
def hash_iterate_key_value(ht, pos, env, cont):
    return hash_iter_ref(ht, pos.value, env, cont, returns=_KEY_AND_VALUE)

@expose(prefix_hash_names("hash-iterate-pair"),
        [W_HashTable, values.W_Fixnum], simple=False)
def hash_iterate_pair(ht, pos, env, cont):
    return hash_iter_ref(ht, pos.value, env, cont, returns=_PAIR)

@expose("hash-for-each", [W_HashTable, procedure, default(values.W_Object, values.w_false)], simple=False)
def hash_for_each(ht, f, try_order, env, cont):
    # FIXME: implmeent try-order? -- see hash-map
    return hash_for_each_loop(ht, f, 0, env, cont)

@loop_label
def hash_for_each_loop(ht, f, index, env, cont):
    from pycket.interpreter import return_value
    try:
        w_key, w_value = ht.get_item(index)
    except KeyError:
        return hash_for_each_loop(ht, f, index + 1, env, cont)
    except IndexError:
        return return_value(values.w_void, env, cont)
    return f.call([w_key, w_value], env,
            hash_for_each_cont(ht, f, index, env, cont))
Beispiel #52
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket import values_struct
from pycket.error import SchemeException
from pycket.prims.expose import unsafe, default, expose, procedure
from rpython.rlib        import jit

@expose("make-inspector", [default(values_struct.W_StructInspector, None)])
def do_make_instpector(inspector):
    return values_struct.W_StructInspector.make(inspector)

@expose("make-sibling-inspector", [default(values_struct.W_StructInspector, None)])
def do_make_sibling_instpector(inspector):
    return values_struct.W_StructInspector.make(inspector, True)

@expose("current-inspector")
def do_current_instpector(args):
    return values_struct.current_inspector

@expose("struct?", [values.W_Object])
def do_is_struct(v):
    return values.W_Bool.make(isinstance(v, values_struct.W_RootStruct) and
                              not v.struct_type().isopaque)

def is_struct_info(v):
    if isinstance(v, values.W_Cons):
        struct_info = values.from_list(v)
        if len(struct_info) == 6:
            if not isinstance(struct_info[0], values_struct.W_StructType) and\
Beispiel #53
0
    return values_regex.W_PRegexp(w_str.as_str_utf8())

@expose("byte-regexp", [values.W_Bytes])
def byte_regrexp(w_str):
    return values_regex.W_ByteRegexp(w_str.as_str())

@expose("byte-pregexp", [values.W_Bytes])
def byte_pregrexp(w_str):
    return values_regex.W_BytePRegexp(w_str.as_str())

EMPTY_BYTES = values.W_Bytes.from_string("")
NO_MATCH = values.Values.make([values.w_false, values.w_false])

RM_ARGS = [
    values.W_Object, values.W_Object,
    default(values.W_Fixnum, values.W_Fixnum.ZERO),
    default(values.W_Object, values.w_false),
    default(values.W_Object, values.w_false),
    default(values.W_Bytes, EMPTY_BYTES)
    ]

@expose("regexp-match", RM_ARGS)
@jit.unroll_safe
def regexp_match(w_re, w_str, inp_start, inp_end, output_port, prefix):
    start = inp_start.value
    if inp_end is values.w_false:
        end = sys.maxint
    elif isinstance(inp_end, values.W_Fixnum):
        end = inp_end.value
    else:
        raise SchemeException("regexp-match: expected fixnum or #f for argument 3")
Beispiel #54
0
# -*- coding: utf-8 -*-
from pycket import impersonators as imp
from pycket import values
from pycket.cont import call_cont
from pycket.error import SchemeException
from pycket.prims.expose import default, expose, make_callable_label, procedure

# Can use this to promote a get_cmk operation to a callable function.
CMKSetToListHandler = make_callable_label([values.W_Object])

#@expose("continuation-marks",
        #[values.W_Continuation, default(values.W_ContinuationPromptTag, None)])
#def continuation_marks(cont, prompt_tag):
    #return values.W_ContinuationPromptTag(cont.cont)

@expose("current-continuation-marks", [default(values.W_ContinuationPromptTag, None)], simple=False)
def current_cont_marks(prompt_tag, env, cont):
    from pycket.interpreter import return_value
    return return_value(values.W_ContinuationMarkSet(cont), env, cont)

@expose("continuation-mark-set->list",
        [values.W_ContinuationMarkSet, values.W_Object], simple=False)
def cms_list(cms, mark, env, cont):
    from pycket.interpreter import return_value
    from pycket.prims.general      import map_loop
    if isinstance(mark, values.W_ContinuationMarkKey):
        func  = CMKSetToListHandler(mark.get_cmk)
        marks = cms.cont.get_marks(imp.get_base_object(mark))
        return map_loop(func, [marks], env, cont)
    marks = cms.cont.get_marks(mark)
    return return_value(marks, env, cont)
Beispiel #55
0
@expose("symbol->string", [values.W_Symbol])
def symbol_to_string(v):
    return symbol_to_string_impl(v)

def symbol_to_string_impl(v):
    asciivalue = v.asciivalue()
    if asciivalue is not None:
        return W_String.fromascii(asciivalue)
    return W_String.fromunicode(v.unicodevalue())

@expose("string->symbol", [W_String])
def string_to_symbol(v):
    return values.W_Symbol.make(v.as_str_utf8())

@expose("string->number", [W_String,
                           default(values.W_Integer, values.W_Fixnum(10)),
                           default(values.W_Symbol, values.W_Symbol.make("number-or-false")),
                           default(values.W_Symbol, values.W_Symbol.make("decimal-as-exact"))])
def str2num(w_s, radix, convert_mode, decimal_mode):
    radix = radix.toint()
    s = w_s.as_str_utf8()
    return _str2num(s, radix)

def _str2num(s, radix):
    from rpython.rlib import rarithmetic, rfloat, rbigint
    from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError
    from rpython.rlib.rsre import rsre_re as re
    import math
    try:
        if ((radix == 16 and re.match("^[0-9A-Fa-f]+$", s)) or
            (radix == 8 and re.match("^[0-7]+$", s)) or