# 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
        ('file', file),
        ('hash', None),
        ('count', int),
        ('depmap', {Module: int}))

Serialize = new_env('Serialize', SerialState)

SerialContext = new_env('SerialContext', None) # debug info

DIGEST_INDEX = {}

def _write(b):
    state = env(Serialize)
    state.file.write(b)
    state.hash.update(b)

def _write_ref(node, t):
    assert has_extrinsic(Location, node), \
            'Weak ref to unserialized: %r 0x%x' % (node, id(node))
    if isinstance(t, TVar):
        pass # Does it even make sense to check instantiations here?
    elif isinstance(t, TData):
        assert not t.data.opts.valueType, "->%r is a value DT" % (node,)
        adt = extrinsic(TrueRepresentation, t.data)
        assert isinstance(node, adt), "->%r is not a %s" % (node, adt)
    else:
        assert False, "%r is not a ref type" % (t,)
    loc = extrinsic(Location, node)
    b = _encode_int(loc.index)
    depmap = env(Serialize).depmap

# 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

        ('file', file),
        ('hash', None),
        ('count', int),
        ('depmap', {Module: int}))

Serialize = new_env('Serialize', SerialState)

SerialContext = new_env('SerialContext', None) # debug info

DIGEST_INDEX = {}

def _write(b):
    state = env(Serialize)
    state.file.write(b)
    state.hash.update(b)

def _write_ref(node, t):
    assert has_extrinsic(Location, node), \
            'Weak ref to unserialized: %r 0x%x' % (node, id(node))
    if isinstance(t, TVar):
        pass # Does it even make sense to check instantiations here?
    elif isinstance(t, TData):
        assert not t.data.opts.valueType, "->%r is a value DT" % (node,)
        adt = extrinsic(TrueRepresentation, t.data)
        assert isinstance(node, adt), "->%r is not a %s" % (node, adt)
    else:
        assert False, "%r is not a ref type" % (t,)
    loc = extrinsic(Location, node)
    b = _encode_int(loc.index)
    depmap = env(Serialize).depmap

    if loc.module not in depmap: