+boundVarsAlt (Adefault e) = boundVars e
+
+mkNtEnv :: Menv -> NtEnv
+mkNtEnv menv =
+ foldl M.union M.empty $
+ map (\ (mn,e) ->
+ foldr (\ (key,thing) rest ->
+ case thing of
+ Kind _ -> rest
+ Coercion (DefinedCoercion _ (lhs,rhs)) ->
+ case splitTyConApp_maybe lhs of
+ Just ((_,tc1),_) -> M.insert tc1 (rhs,Tcon (Just mn, key)) rest
+ _ -> rest) M.empty (etolist (tcenv_ e))) (etolist menv)
+
+substNewtys :: NtEnv -> Ty -> Ty
+substNewtys ntEnv = everywhere'Except (mkT go)
+ where go t | Just ((_,tc),_) <- splitTyConApp_maybe t =
+ case M.lookup tc ntEnv of
+ Just (rhs,_) -> rhs
+ Nothing -> t
+ go t = t
+
+newtypeCoercion_maybe :: NtEnv -> Ty -> Maybe Ty
+newtypeCoercion_maybe ntEnv t | Just ((_,tc),_) <- splitTyConApp_maybe t =
+ case M.lookup tc ntEnv of
+ Just (_, coercion) -> Just coercion
+ Nothing -> Nothing
+newtypeCoercion_maybe _ _ = Nothing
+
+-- first element: rep type
+-- second element: coercion tcon
+type NtEnv = M.Map Tcon (Ty, Ty)
+
+mkTapp :: Ty -> [Ty] -> Ty
+mkTapp = foldl Tapp