# Path: types_builtin.py
# def app_map(data, appTs):
#     apps = {}
#     for tv, at in ezip(data.tvars, appTs):
#         if isinstance(at, TVar) and at.typeVar is tv:
#             continue
#         apps[tv] = at
#     return apps
# 
# def subst(mapping, t):
#     return map_type_vars(lambda st: mapping.get(st.typeVar, st), t)


from base import *
from bedrock import *
from globs import *
from hashlib import sha256
from os import system
from types_builtin import app_map, subst
    n -= 0x10000000
    assert n < (0x100000000 - 0x10204080), "Int overflow"
    return chr(0xf0) + chr(n>>24 & 0xff) + chr(n>>16 & 0xff) + \
            chr(n>>8 & 0xff) + chr(n & 0xff)

def _encode_float(f):
    # XXX just blat these IEEE-style
    assert f >= 0 and f.is_integer()
    return _encode_int(int(f))

def _encode_str(s):
    b = s.encode('UTF-8')
    return _encode_int(len(b)) + b

def _serialize_node(node, t):

    # debugging
    if not have_env(SerialContext):
        in_env(SerialContext, DumpList(), lambda: _serialize_node(node, t))
        return

    if isinstance(node, Structured):
        ctxt = env(SerialContext)
        nm = extrinsic(Name, node) if has_extrinsic(Name, node) else type(node)
        ctxt.append((nm, t))

        assert isinstance(t, TData), "%r is not a datatype" % (t,)
        if not t.data.opts.valueType:
            env(Serialize).count += 1
        # Collect instantiations

# Path: types_builtin.py
# def app_map(data, appTs):
#     apps = {}
#     for tv, at in ezip(data.tvars, appTs):
#         if isinstance(at, TVar) and at.typeVar is tv:
#             continue
#         apps[tv] = at
#     return apps
# 
# def subst(mapping, t):
#     return map_type_vars(lambda st: mapping.get(st.typeVar, st), t)


# Path: native.py
from base import *
from bedrock import *
from globs import *
from hashlib import sha256
from os import system
from types_builtin import app_map, subst

    n -= 0x10000000
    assert n < (0x100000000 - 0x10204080), "Int overflow"
    return chr(0xf0) + chr(n>>24 & 0xff) + chr(n>>16 & 0xff) + \
            chr(n>>8 & 0xff) + chr(n & 0xff)

def _encode_float(f):
    # XXX just blat these IEEE-style
    assert f >= 0 and f.is_integer()
    return _encode_int(int(f))

def _encode_str(s):
    b = s.encode('UTF-8')
    return _encode_int(len(b)) + b

def _serialize_node(node, t):

    # debugging
    if not have_env(SerialContext):
        in_env(SerialContext, DumpList(), lambda: _serialize_node(node, t))
        return

    if isinstance(node, Structured):
        ctxt = env(SerialContext)
        nm = extrinsic(Name, node) if has_extrinsic(Name, node) else type(node)
        ctxt.append((nm, t))

        assert isinstance(t, TData), "%r is not a datatype" % (t,)
        if not t.data.opts.valueType:
            env(Serialize).count += 1
        # Collect instantiations

        apps = app_map(t.data, t.appTypes)