Example #1
0
def dump(code, f):
    head = code
    args = []
    while is_app(head):
        args.append(head[2])
        head = head[1]
    if is_nvar(head):
        _dump_head_argc(SYMB_TO_INT[_NVAR], 1 + len(args), f)
        _dump_raw_bytes(head[1], f)
    elif is_ivar(head):
        _dump_head_argc(SYMB_TO_INT[_IVAR], 1 + len(args), f)
        _dump_raw_bytes(str(head[1]), f)
    elif is_join(head):
        args.append(head[2])
        args.append(head[1])
        _dump_head_argc(SYMB_TO_INT[_JOIN], len(args), f)
    elif is_quote(head):
        args.append(head[1])
        _dump_head_argc(SYMB_TO_INT[_QUOTE], len(args), f)
    elif is_abs(head):
        args.append(head[1])
        _dump_head_argc(SYMB_TO_INT[_ABS], len(args), f)
    elif is_fun(head):
        args.append(head[2])
        args.append(head[1])
        _dump_head_argc(SYMB_TO_INT[_FUN], len(args), f)
    else:
        try:
            head = SYMB_TO_INT[head]
        except KeyError:
            raise ValueError('Failed to serialize code: {}'.format(code))
        _dump_head_argc(head, len(args), f)
    for arg in reversed(args):
        dump(arg, f)
Example #2
0
def compile_(code):
    if is_atom(code):
        return code
    elif is_nvar(code):
        return code
    elif is_app(code):
        x = compile_(code[1])
        y = compile_(code[2])
        return APP(x, y)
    elif is_join(code):
        x = compile_(code[1])
        y = compile_(code[2])
        return JOIN(x, y)
    elif is_quote(code):
        arg = compile_(code[1])
        return QUOTE(arg)
    elif is_fun(code):
        var = code[1]
        body = compile_(code[2])
        return abstract(var, body)
    else:
        raise ValueError('Cannot compile_: {}'.format(code))