perga/lib/Check.hs

56 lines
1.7 KiB
Haskell
Raw Normal View History

2024-11-17 18:33:14 -08:00
{-# LANGUAGE LambdaCase #-}
2024-11-22 19:44:31 -08:00
module Check (checkType, findType) where
2024-10-05 13:31:09 -07:00
2024-11-14 22:02:04 -08:00
import Control.Monad.Except (MonadError (throwError))
2024-11-17 01:57:53 -08:00
import Data.List ((!?))
2024-11-17 18:33:14 -08:00
import Errors
import Eval (Env, betaEquiv, envLookupTy, subst, whnf)
2024-11-17 18:33:14 -08:00
import Expr (Expr (..), incIndices, occursFree)
2024-10-05 13:31:09 -07:00
type Context = [Expr]
2024-11-17 18:33:14 -08:00
matchPi :: Expr -> Expr -> ReaderT Env Result (Expr, Expr)
matchPi x mt =
whnf mt >>= \case
(Pi _ a b) -> pure (a, b)
t -> throwError $ ExpectedPiType x t
2024-11-11 17:57:14 -08:00
findLevel :: Context -> Expr -> ReaderT Env Result Integer
findLevel g a = do
2024-11-22 19:44:31 -08:00
s <- findType g a
whnf s >>= \case
Level i -> pure i
_ -> throwError $ NotASort a s
2024-11-22 19:44:31 -08:00
validateType :: Context -> Expr -> ReaderT Env Result ()
validateType g a = void $ findLevel g a
2024-11-22 19:44:31 -08:00
2024-11-17 18:33:14 -08:00
findType :: Context -> Expr -> ReaderT Env Result Expr
findType _ (Level i) = pure $ Level (i + 1)
2024-11-22 19:44:31 -08:00
findType g (Var x n) = do
t <- g !? fromInteger n `whenNothing` throwError (UnboundVariable x)
validateType g t
2024-11-11 13:37:44 -08:00
pure t
findType _ (Free n) = envLookupTy n
2024-11-20 07:37:49 -08:00
findType _ (Axiom n) = envLookupTy n
2024-11-12 00:00:51 -08:00
findType g e@(App m n) = do
(a, b) <- findType g m >>= matchPi m
2024-11-11 13:37:44 -08:00
a' <- findType g n
2024-11-17 18:33:14 -08:00
equiv <- betaEquiv a a'
2024-11-17 01:57:53 -08:00
unless equiv $ throwError $ NotEquivalent a a' e
pure $ subst 0 n b
2024-11-11 17:57:14 -08:00
findType g (Abs x a m) = do
validateType g a
2024-11-11 17:57:14 -08:00
b <- findType (incIndices a : map incIndices g) m
validateType g (Pi x a b)
2024-11-11 17:57:14 -08:00
pure $ if occursFree 0 b then Pi x a b else Pi "" a b
findType g (Pi _ a b) = do
i <- findLevel g a
j <- findLevel (incIndices a : map incIndices g) b
pure $ Level $ max (i - 1) j -- This feels very sketchy, but certainly adds impredicativity
findType g (Let _ v b) = findType g (subst 0 v b)
2024-11-17 01:57:53 -08:00
2024-11-17 18:33:14 -08:00
checkType :: Env -> Expr -> Result Expr
checkType env t = runReaderT (findType [] t) env