module Core.TT where
import Control.Monad.State
import Control.Monad.Trans.Error (Error(..))
import Debug.Trace
import qualified Data.Map as Map
import Data.Char
import Data.List
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import qualified Data.Binary as B
import Data.Binary hiding (get, put)
import Foreign.Storable (sizeOf)
import Util.Pretty hiding (Str)
data Option = TTypeInTType
| CheckConv
deriving Eq
data FC = FC { fc_fname :: String,
fc_line :: Int,
fc_column :: Int
}
instance Eq FC where
_ == _ = True
newtype FC' = FC' { unwrapFC :: FC }
instance Eq FC' where
FC' fc == FC' fc' = fcEq fc fc'
where fcEq (FC n l c) (FC n' l' c') = n == n' && l == l' && c == c'
emptyFC :: FC
emptyFC = fileFC ""
fileFC :: String -> FC
fileFC s = FC s 0 0
instance Sized FC where
size (FC f l c) = 1 + length f
instance Show FC where
show (FC f l c) = f ++ ":" ++ show l ++ ":" ++ show c
data Err = Msg String
| InternalMsg String
| CantUnify Bool Term Term Err [(Name, Type)] Int
| InfiniteUnify Name Term [(Name, Type)]
| CantConvert Term Term [(Name, Type)]
| UnifyScope Name Name Term [(Name, Type)]
| CantInferType String
| NonFunctionType Term Term
| CantIntroduce Term
| NoSuchVariable Name
| NoTypeDecl Name
| NotInjective Term Term Term
| CantResolve Term
| CantResolveAlts [String]
| IncompleteTerm Term
| UniverseError
| ProgramLineComment
| Inaccessible Name
| NonCollapsiblePostulate Name
| AlreadyDefined Name
| ProofSearchFail Err
| NoRewriting Term
| At FC Err
| Elaborating String Name Err
| ProviderError String
| LoadingFailed String Err
deriving Eq
instance Sized Err where
size (Msg msg) = length msg
size (InternalMsg msg) = length msg
size (CantUnify _ left right err _ score) = size left + size right + size err
size (InfiniteUnify _ right _) = size right
size (CantConvert left right _) = size left + size right
size (UnifyScope _ _ right _) = size right
size (NoSuchVariable name) = size name
size (NoTypeDecl name) = size name
size (NotInjective l c r) = size l + size c + size r
size (CantResolve trm) = size trm
size (NoRewriting trm) = size trm
size (CantResolveAlts _) = 1
size (IncompleteTerm trm) = size trm
size UniverseError = 1
size ProgramLineComment = 1
size (At fc err) = size fc + size err
size (Elaborating _ n err) = size err
size (ProviderError msg) = length msg
size (LoadingFailed fn e) = 1 + length fn + size e
size _ = 1
score :: Err -> Int
score (CantUnify _ _ _ m _ s) = s + score m
score (CantResolve _) = 20
score (NoSuchVariable _) = 1000
score (ProofSearchFail _) = 10000
score (InternalMsg _) = 1
score _ = 0
instance Show Err where
show (Msg s) = s
show (InternalMsg s) = "Internal error: " ++ show s
show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
++ show e ++ " in " ++ show sc ++ " " ++ show i
show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
show (ProviderError msg) = "Type provider error: " ++ msg
show (LoadingFailed fn e) = "Loading " ++ fn ++ " failed: " ++ show e
show _ = "Error"
instance Pretty Err where
pretty (Msg m) = text m
pretty (CantUnify _ l r e _ i) =
if size l + size r > breakingSize then
text "Cannot unify" <+> colon $$
nest nestingSize (pretty l <+> text "and" <+> pretty r) $$
nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
else
text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r $$
nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
pretty (ProviderError msg) = text msg
pretty err@(LoadingFailed _ _) = text (show err)
pretty _ = text "Error"
instance Error Err where
strMsg = Msg
data TC a = OK a
| Error Err
deriving (Eq, Functor)
instance Pretty a => Pretty (TC a) where
pretty (OK ok) = pretty ok
pretty (Error err) =
if size err > breakingSize then
text "Error" <+> colon $$ (nest nestingSize $ pretty err)
else
text "Error" <+> colon <+> pretty err
instance Show a => Show (TC a) where
show (OK x) = show x
show (Error str) = "Error: " ++ show str
instance Monad TC where
return = OK
x >>= k = case x of
OK v -> k v
Error e -> Error e
fail e = Error (InternalMsg e)
tfail :: Err -> TC a
tfail e = Error e
trun :: FC -> TC a -> TC a
trun fc (OK a) = OK a
trun fc (Error e) = Error (At fc e)
instance MonadPlus TC where
mzero = fail "Unknown error"
(OK x) `mplus` _ = OK x
_ `mplus` (OK y) = OK y
err `mplus` _ = err
discard :: Monad m => m a -> m ()
discard f = f >> return ()
showSep :: String -> [String] -> String
showSep sep [] = ""
showSep sep [x] = x
showSep sep (x:xs) = x ++ sep ++ showSep sep xs
pmap f (x, y) = (f x, f y)
traceWhen True msg a = trace msg a
traceWhen False _ a = a
data Name = UN String
| NS Name [String]
| MN Int String
| NErased
| SN SpecialName
deriving (Eq, Ord)
data SpecialName = WhereN Int Name Name
| InstanceN Name [String]
| ParentN Name String
| MethodN Name
| CaseN Name
deriving (Eq, Ord)
instance Sized Name where
size (UN n) = 1
size (NS n els) = 1 + length els
size (MN i n) = 1
size _ = 1
instance Pretty Name where
pretty (UN n) = text n
pretty (NS n s) = pretty n
pretty (MN i s) = lbrace <+> text s <+> (text . show $ i) <+> rbrace
pretty (SN s) = text (show s)
instance Show Name where
show (UN n) = n
show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
show (MN _ "underscore") = "_"
show (MN i s) = "{" ++ s ++ show i ++ "}"
show (SN s) = show s
show NErased = "_"
instance Show SpecialName where
show (WhereN i p c) = show p ++ ", " ++ show c
show (InstanceN cl inst) = showSep ", " inst ++ " instance of " ++ show cl
show (MethodN m) = "method " ++ show m
show (ParentN p c) = show p ++ "#" ++ c
show (CaseN n) = "case block in " ++ show n
showCG :: Name -> String
showCG (UN n) = n
showCG (NS n s) = showSep "." (reverse s) ++ "." ++ show n
showCG (MN _ "underscore") = "_"
showCG (MN i s) = "{" ++ s ++ show i ++ "}"
showCG (SN s) = showCG' s
where showCG' (WhereN i p c) = show p ++ ":" ++ show c ++ ":" ++ show i
showCG' (InstanceN cl inst) = '@':show cl ++ '$':showSep ":" inst
showCG' (MethodN m) = '!':show m
showCG' (ParentN p c) = show p ++ "#" ++ show c
showCG' (CaseN c) = show c ++ "_case"
showCG NErased = "_"
type Ctxt a = Map.Map Name (Map.Map Name a)
emptyContext = Map.empty
tcname (UN ('@':_)) = True
tcname (NS n _) = tcname n
tcname (SN (InstanceN _ _)) = True
tcname (SN (MethodN _)) = True
tcname (SN (ParentN _ _)) = True
tcname _ = False
implicitable (NS n _) = implicitable n
implicitable (UN (x:xs)) = isLower x
implicitable (MN _ _) = True
implicitable _ = False
nsroot (NS n _) = n
nsroot n = n
addDef :: Name -> a -> Ctxt a -> Ctxt a
addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
Nothing -> Map.insert (nsroot n)
(Map.insert n v Map.empty) ctxt
Just xs -> Map.insert (nsroot n)
(Map.insert n v xs) ctxt
lookupCtxtName :: Name -> Ctxt a -> [(Name, a)]
lookupCtxtName n ctxt = case Map.lookup (nsroot n) ctxt of
Just xs -> filterNS (Map.toList xs)
Nothing -> []
where
filterNS [] = []
filterNS ((found, v) : xs)
| nsmatch n found = (found, v) : filterNS xs
| otherwise = filterNS xs
nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
nsmatch (NS _ _) _ = False
nsmatch looking found = True
lookupCtxt :: Name -> Ctxt a -> [a]
lookupCtxt n ctxt = map snd (lookupCtxtName n ctxt)
lookupCtxtExact :: Name -> Ctxt a -> [a]
lookupCtxtExact n ctxt = [ v | (nm, v) <- lookupCtxtName n ctxt, nm == n]
updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
updateDef n f ctxt
= let ds = lookupCtxtName n ctxt in
foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
toAlist :: Ctxt a -> [(Name, a)]
toAlist ctxt = let allns = map snd (Map.toList ctxt) in
concat (map (Map.toList) allns)
addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
addAlist [] ctxt = ctxt
addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
data NativeTy = IT8 | IT16 | IT32 | IT64
deriving (Show, Eq, Ord, Enum)
instance Pretty NativeTy where
pretty IT8 = text "Bits8"
pretty IT16 = text "Bits16"
pretty IT32 = text "Bits32"
pretty IT64 = text "Bits64"
data IntTy = ITFixed NativeTy | ITNative | ITBig | ITChar
| ITVec NativeTy Int
deriving (Show, Eq, Ord)
data ArithTy = ATInt IntTy | ATFloat
deriving (Show, Eq, Ord)
instance Pretty ArithTy where
pretty (ATInt ITNative) = text "Int"
pretty (ATInt ITBig) = text "BigInt"
pretty (ATInt ITChar) = text "Char"
pretty (ATInt (ITFixed n)) = pretty n
pretty (ATInt (ITVec e c)) = pretty e <> text "x" <> (text . show $ c)
pretty ATFloat = text "Float"
nativeTyWidth :: NativeTy -> Int
nativeTyWidth IT8 = 8
nativeTyWidth IT16 = 16
nativeTyWidth IT32 = 32
nativeTyWidth IT64 = 64
intTyWidth :: IntTy -> Int
intTyWidth (ITFixed n) = nativeTyWidth n
intTyWidth ITNative = 8 * sizeOf (0 :: Int)
intTyWidth ITChar = error "IRTS.Lang.intTyWidth: Characters have platform and backend dependent width"
intTyWidth ITBig = error "IRTS.Lang.intTyWidth: Big integers have variable width"
data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
| B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64
| B8V (Vector Word8) | B16V (Vector Word16)
| B32V (Vector Word32) | B64V (Vector Word64)
| AType ArithTy | StrType
| PtrType | VoidType | Forgot
deriving (Eq, Ord)
instance Sized Const where
size _ = 1
instance Pretty Const where
pretty (I i) = text . show $ i
pretty (BI i) = text . show $ i
pretty (Fl f) = text . show $ f
pretty (Ch c) = text . show $ c
pretty (Str s) = text s
pretty (AType a) = pretty a
pretty StrType = text "String"
pretty PtrType = text "Ptr"
pretty VoidType = text "Void"
pretty Forgot = text "Forgot"
pretty (B8 w) = text . show $ w
pretty (B16 w) = text . show $ w
pretty (B32 w) = text . show $ w
pretty (B64 w) = text . show $ w
data Raw = Var Name
| RBind Name (Binder Raw) Raw
| RApp Raw Raw
| RType
| RForce Raw
| RConstant Const
deriving (Show, Eq)
instance Sized Raw where
size (Var name) = 1
size (RBind name bind right) = 1 + size bind + size right
size (RApp left right) = 1 + size left + size right
size RType = 1
size (RForce raw) = 1 + size raw
size (RConstant const) = size const
instance Pretty Raw where
pretty = text . show
data Binder b = Lam { binderTy :: b }
| Pi { binderTy :: b }
| Let { binderTy :: b,
binderVal :: b }
| NLet { binderTy :: b,
binderVal :: b }
| Hole { binderTy :: b}
| GHole { envlen :: Int,
binderTy :: b}
| Guess { binderTy :: b,
binderVal :: b }
| PVar { binderTy :: b }
| PVTy { binderTy :: b }
deriving (Show, Eq, Ord, Functor)
instance Sized a => Sized (Binder a) where
size (Lam ty) = 1 + size ty
size (Pi ty) = 1 + size ty
size (Let ty val) = 1 + size ty + size val
size (NLet ty val) = 1 + size ty + size val
size (Hole ty) = 1 + size ty
size (GHole _ ty) = 1 + size ty
size (Guess ty val) = 1 + size ty + size val
size (PVar ty) = 1 + size ty
size (PVTy ty) = 1 + size ty
fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
fmapMB f (Let t v) = liftM2 Let (f t) (f v)
fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
fmapMB f (Lam t) = liftM Lam (f t)
fmapMB f (Pi t) = liftM Pi (f t)
fmapMB f (Hole t) = liftM Hole (f t)
fmapMB f (GHole i t) = liftM (GHole i) (f t)
fmapMB f (PVar t) = liftM PVar (f t)
fmapMB f (PVTy t) = liftM PVTy (f t)
raw_apply :: Raw -> [Raw] -> Raw
raw_apply f [] = f
raw_apply f (a : as) = raw_apply (RApp f a) as
raw_unapply :: Raw -> (Raw, [Raw])
raw_unapply t = ua [] t where
ua args (RApp f a) = ua (a:args) f
ua args t = (t, args)
data RawFun = RawFun { rtype :: Raw,
rval :: Raw
}
deriving Show
data RawDatatype = RDatatype Name Raw [(Name, Raw)]
deriving Show
data RDef = RFunction RawFun
| RConst Raw
| RData RawDatatype
deriving Show
type RProgram = [(Name, RDef)]
data UExp = UVar Int
| UVal Int
deriving (Eq, Ord)
instance Sized UExp where
size _ = 1
instance Binary UExp where
put x = return ()
get = return (UVar (1))
instance Show UExp where
show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
| otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
show (UVal x) = show x
data UConstraint = ULT UExp UExp
| ULE UExp UExp
deriving Eq
instance Show UConstraint where
show (ULT x y) = show x ++ " < " ++ show y
show (ULE x y) = show x ++ " <= " ++ show y
type UCs = (Int, [UConstraint])
data NameType = Bound
| Ref
| DCon Int Int
| TCon Int Int
deriving (Show, Ord)
instance Sized NameType where
size _ = 1
instance Pretty NameType where
pretty = text . show
instance Eq NameType where
Bound == Bound = True
Ref == Ref = True
DCon _ a == DCon _ b = (a == b)
TCon _ a == TCon _ b = (a == b)
_ == _ = False
data TT n = P NameType n (TT n)
| V Int
| Bind n (Binder (TT n)) (TT n)
| App (TT n) (TT n)
| Constant Const
| Proj (TT n) Int
| Erased
| Impossible
| TType UExp
deriving (Ord, Functor)
class TermSize a where
termsize :: Name -> a -> Int
instance TermSize a => TermSize [a] where
termsize n [] = 0
termsize n (x : xs) = termsize n x + termsize n xs
instance TermSize (TT Name) where
termsize n (P _ x _)
| x == n = 1000000
| otherwise = 1
termsize n (V _) = 1
termsize n (Bind n' (Let t v) sc)
= let rn = if n == n' then MN 0 "noname" else n in
termsize rn v + termsize rn sc
termsize n (Bind n' b sc)
= let rn = if n == n' then MN 0 "noname" else n in
termsize rn sc
termsize n (App f a) = termsize n f + termsize n a
termsize n (Proj t i) = termsize n t
termsize n _ = 1
instance Sized a => Sized (TT a) where
size (P name n trm) = 1 + size name + size n + size trm
size (V v) = 1
size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
size (App l r) = 1 + size l + size r
size (Constant c) = size c
size Erased = 1
size (TType u) = 1 + size u
instance Pretty a => Pretty (TT a) where
pretty _ = text "test"
type EnvTT n = [(n, Binder (TT n))]
data Datatype n = Data { d_typename :: n,
d_typetag :: Int,
d_type :: (TT n),
d_cons :: [(n, TT n)] }
deriving (Show, Functor, Eq)
instance Eq n => Eq (TT n) where
(==) (P xt x _) (P yt y _) = x == y
(==) (V x) (V y) = x == y
(==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
(==) (App fx ax) (App fy ay) = fx == fy && ax == ay
(==) (TType _) (TType _) = True
(==) (Constant x) (Constant y) = x == y
(==) (Proj x i) (Proj y j) = x == y && i == j
(==) Erased _ = True
(==) _ Erased = True
(==) _ _ = False
isInjective :: TT n -> Bool
isInjective (P (DCon _ _) _ _) = True
isInjective (P (TCon _ _) _ _) = True
isInjective (Constant _) = True
isInjective (TType x) = True
isInjective (Bind _ (Pi _) sc) = True
isInjective (App f a) = isInjective f
isInjective _ = False
vinstances :: Int -> TT n -> Int
vinstances i (V x) | i == x = 1
vinstances i (App f a) = vinstances i f + vinstances i a
vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
where instancesB (Let t v) = vinstances i v
instancesB _ = 0
vinstances i t = 0
instantiate :: TT n -> TT n -> TT n
instantiate e = subst 0 where
subst i (V x) | i == x = e
subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
subst i (App f a) = App (subst i f) (subst i a)
subst i (Proj x idx) = Proj (subst i x) idx
subst i t = t
substV :: TT n -> TT n -> TT n
substV x tm = dropV 0 (instantiate x tm) where
dropV i (V x) | x > i = V (x 1)
| otherwise = V x
dropV i (Bind x b sc) = Bind x (fmap (dropV i) b) (dropV (i+1) sc)
dropV i (App f a) = App (dropV i f) (dropV i a)
dropV i (Proj x idx) = Proj (dropV i x) idx
dropV i t = t
explicitNames :: TT n -> TT n
explicitNames (Bind x b sc) = let b' = fmap explicitNames b in
Bind x b'
(explicitNames (instantiate
(P Bound x (binderTy b')) sc))
explicitNames (App f a) = App (explicitNames f) (explicitNames a)
explicitNames (Proj x idx) = Proj (explicitNames x) idx
explicitNames t = t
pToV :: Eq n => n -> TT n -> TT n
pToV n = pToV' n 0
pToV' n i (P _ x _) | n == x = V i
pToV' n i (Bind x b sc)
| n == x = Bind x (fmap (pToV' n i) b) sc
| otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
pToV' n i t = t
addBinder :: TT n -> TT n
addBinder t = ab 0 t
where
ab top (V i) | i >= top = V (i + 1)
| otherwise = V i
ab top (Bind x b sc) = Bind x (fmap (ab top) b) (ab (top + 1) sc)
ab top (App f a) = App (ab top f) (ab top a)
ab top (Proj t idx) = Proj (ab top t) idx
ab top t = t
pToVs :: Eq n => [n] -> TT n -> TT n
pToVs ns tm = pToVs' ns tm 0 where
pToVs' [] tm i = tm
pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
vToP :: TT n -> TT n
vToP = vToP' [] where
vToP' env (V i) = let (n, b) = (env !! i) in
P Bound n (binderTy b)
vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
Bind n b' (vToP' ((n, b'):env) sc)
vToP' env (App f a) = App (vToP' env f) (vToP' env a)
vToP' env t = t
finalise :: Eq n => TT n -> TT n
finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
finalise (App f a) = App (finalise f) (finalise a)
finalise t = t
subst :: Eq n => n -> TT n -> TT n -> TT n
subst n v tm = instantiate v (pToV n tm)
substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
substNames [] t = t
substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
substTerm :: Eq n => TT n -> TT n -> TT n -> TT n
substTerm old new = st where
st t | t == old = new
st (App f a) = App (st f) (st a)
st (Bind x b sc) = Bind x (fmap st b) (st sc)
st t = t
noOccurrence :: Eq n => n -> TT n -> Bool
noOccurrence n t = no' 0 t
where
no' i (V x) = not (i == x)
no' i (P Bound x _) = not (n == x)
no' i (Bind n b sc) = noB' i b && no' (i+1) sc
where noB' i (Let t v) = no' i t && no' i v
noB' i (Guess t v) = no' i t && no' i v
noB' i b = no' i (binderTy b)
no' i (App f a) = no' i f && no' i a
no' i (Proj x _) = no' i x
no' i _ = True
freeNames :: Eq n => TT n -> [n]
freeNames (P _ n _) = [n]
freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
++ freeNames t
freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
freeNames (App f a) = nub $ freeNames f ++ freeNames a
freeNames (Proj x i) = nub $ freeNames x
freeNames _ = []
arity :: TT n -> Int
arity (Bind n (Pi t) sc) = 1 + arity sc
arity _ = 0
unApply :: TT n -> (TT n, [TT n])
unApply t = ua [] t where
ua args (App f a) = ua (a:args) f
ua args t = (t, args)
mkApp :: TT n -> [TT n] -> TT n
mkApp f [] = f
mkApp f (a:as) = mkApp (App f a) as
forget :: TT Name -> Raw
forget tm = fe [] tm
where
fe env (P _ n _) = Var n
fe env (V i) = Var (env !! i)
fe env (Bind n b sc) = RBind n (fmap (fe env) b)
(fe (n:env) sc)
fe env (App f a) = RApp (fe env f) (fe env a)
fe env (Constant c)
= RConstant c
fe env (TType i) = RType
fe env Erased = RConstant Forgot
bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
bindAll [] t =t
bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
getArgTys :: TT n -> [(n, TT n)]
getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
getArgTys _ = []
getRetTy :: TT n -> TT n
getRetTy (Bind n (PVar _) sc) = getRetTy sc
getRetTy (Bind n (PVTy _) sc) = getRetTy sc
getRetTy (Bind n (Pi _) sc) = getRetTy sc
getRetTy sc = sc
uniqueName :: Name -> [Name] -> Name
uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
| otherwise = n
uniqueBinders :: [Name] -> TT Name -> TT Name
uniqueBinders ns (Bind n b sc)
= let n' = uniqueName n ns in
Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
uniqueBinders ns t = t
nextName (NS x s) = NS (nextName x) s
nextName (MN i n) = MN (i+1) n
nextName (UN x) = let (num', nm') = span isDigit (reverse x)
nm = reverse nm'
num = readN (reverse num') in
UN (nm ++ show (num+1))
where
readN "" = 0
readN x = read x
nextName (SN x) = SN (nextName' x)
where
nextName' (WhereN i f x) = WhereN i f (nextName x)
nextName' (CaseN n) = CaseN (nextName n)
nextName' (MethodN n) = MethodN (nextName n)
type Term = TT Name
type Type = Term
type Env = EnvTT Name
newtype WkEnvTT n = Wk (EnvTT n)
type WkEnv = WkEnvTT Name
instance (Eq n, Show n) => Show (TT n) where
show t = showEnv [] t
itBitsName IT8 = "Bits8"
itBitsName IT16 = "Bits16"
itBitsName IT32 = "Bits32"
itBitsName IT64 = "Bits64"
instance Show Const where
show (I i) = show i
show (BI i) = show i
show (Fl f) = show f
show (Ch c) = show c
show (Str s) = show s
show (B8 x) = show x
show (B16 x) = show x
show (B32 x) = show x
show (B64 x) = show x
show (B8V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B16V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B32V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (B64V x) = "<" ++ intercalate "," (map show (V.toList x)) ++ ">"
show (AType ATFloat) = "Float"
show (AType (ATInt ITBig)) = "Integer"
show (AType (ATInt ITNative)) = "Int"
show (AType (ATInt ITChar)) = "Char"
show (AType (ATInt (ITFixed it))) = itBitsName it
show (AType (ATInt (ITVec it c))) = itBitsName it ++ "x" ++ show c
show StrType = "String"
show PtrType = "Ptr"
show VoidType = "Void"
showEnv env t = showEnv' env t False
showEnvDbg env t = showEnv' env t True
prettyEnv env t = prettyEnv' env t False
where
prettyEnv' env t dbg = prettySe 10 env t dbg
bracket outer inner p
| inner > outer = lparen <> p <> rparen
| otherwise = p
prettySe p env (P nt n t) debug =
pretty n <+>
if debug then
lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
else
empty
prettySe p env (V i) debug
| i < length env =
if debug then
text . show . fst $ env!!i
else
lbrack <+> text (show i) <+> rbrack
| otherwise = text "unbound" <+> text (show i) <+> text "!"
prettySe p env (Bind n b@(Pi t) sc) debug
| noOccurrence n sc && not debug =
bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
prettySe p env (Bind n b sc) debug =
bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
prettySe p env (App f a) debug =
bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
prettySe p env (Proj x i) debug =
prettySe 1 env x debug <+> text ("!" ++ show i)
prettySe p env (Constant c) debug = pretty c
prettySe p env Erased debug = text "[_]"
prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
prettySb env n (Lam t) = prettyB env "λ" "=>" n t
prettySb env n (Hole t) = prettyB env "?defer" "." n t
prettySb env n (Pi t) = prettyB env "(" ") ->" n t
prettySb env n (PVar t) = prettyB env "pat" "." n t
prettySb env n (PVTy t) = prettyB env "pty" "." n t
prettySb env n (Let t v) = prettyBv env "let" "in" n t v
prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
prettyB env op sc n t debug =
text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
prettyBv env op sc n t v debug =
text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
prettySe 10 env v debug <> text sc
showEnv' env t dbg = se 10 env t where
se p env (P nt n t) = show n
++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
se p env (V i) | i < length env && i >= 0
= (show $ fst $ env!!i) ++
if dbg then "{" ++ show i ++ "}" else ""
| otherwise = "!!V " ++ show i ++ "!!"
se p env (Bind n b@(Pi t) sc)
| noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
se p env (Proj x i) = se 1 env x ++ "!" ++ show i
se p env (Constant c) = show c
se p env Erased = "[__]"
se p env Impossible = "[impossible]"
se p env (TType i) = "Type " ++ show i
sb env n (Lam t) = showb env "\\ " " => " n t
sb env n (Hole t) = showb env "? " ". " n t
sb env n (GHole i t) = showb env "?defer " ". " n t
sb env n (Pi t) = showb env "(" ") -> " n t
sb env n (PVar t) = showb env "pat " ". " n t
sb env n (PVTy t) = showb env "pty " ". " n t
sb env n (Let t v) = showbv env "let " " in " n t v
sb env n (Guess t v) = showbv env "?? " " in " n t v
showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
se 10 env v ++ sc
bracket outer inner str | inner > outer = "(" ++ str ++ ")"
| otherwise = str
pureTerm :: TT Name -> Bool
pureTerm (App f a) = pureTerm f && pureTerm a
pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where
pureBinder (Hole _) = False
pureBinder (Guess _ _) = False
pureBinder (Let t v) = pureTerm t && pureTerm v
pureBinder t = pureTerm (binderTy t)
notClassName (MN _ "class") = False
notClassName _ = True
pureTerm _ = True
weakenTm :: Int -> TT n -> TT n
weakenTm i t = wk i 0 t
where wk i min (V x) | x >= min = V (i + x)
wk i m (App f a) = App (wk i m f) (wk i m a)
wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
wk i m t = t
wkb i m t = fmap (wk i m) t
weakenEnv :: EnvTT n -> EnvTT n
weakenEnv env = wk (length env 1) env
where wk i [] = []
wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i 1) bs
weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
weakenTmEnv :: Int -> EnvTT n -> EnvTT n
weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
orderPats :: Term -> Term
orderPats tm = op [] tm
where
op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
op ps sc = bindAll (sortP ps) sc
sortP ps = pick [] (reverse ps)
namesIn (P _ n _) = [n]
namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
nb t = namesIn (binderTy t)
namesIn (App f a) = nub (namesIn f ++ namesIn a)
namesIn _ = []
pick acc [] = reverse acc
pick acc ((n, t) : ps) = pick (insert n t acc) ps
insert n t [] = [(n, t)]
insert n t ((n',t') : ps)
| n `elem` (namesIn (binderTy t') ++
concatMap namesIn (map (binderTy . snd) ps))
= (n', t') : insert n t ps
| otherwise = (n,t):(n',t'):ps