perga/lib/Check.hs

65 lines
2.1 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
2024-11-20 07:37:49 -08:00
import Eval (Env, betaEquiv, envLookupTy, isSort, 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
2024-11-22 19:44:31 -08:00
validateType :: Context -> Expr -> ReaderT Env Result Expr
validateType g a = do
s <- findType g a
isSort s >>= flip unless (throwError $ NotASort a s)
pure s
validateType_ :: Context -> Expr -> ReaderT Env Result ()
validateType_ g a = void $ validateType g a
2024-11-17 18:33:14 -08:00
findType :: Context -> Expr -> ReaderT Env Result Expr
2024-11-17 01:57:53 -08:00
findType _ Star = pure Square
findType _ Square = throwError SquareUntyped
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
2024-11-22 19:44:31 -08:00
findType _ (Free n) = do
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
2024-11-22 19:44:31 -08:00
validateType_ g a
2024-11-11 17:57:14 -08:00
b <- findType (incIndices a : map incIndices g) m
2024-11-22 19:44:31 -08:00
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
2024-11-22 19:44:31 -08:00
validateType_ g a
validateType (incIndices a : map incIndices g) b
findType g (Let _ v b) = findType g (subst 0 v b)
-- a <- findType g v
-- validateType_ g a
-- res <- findType (incIndices a : map incIndices g) b
-- pure $ subst 0 a res
2024-11-23 09:16:32 -08:00
-- this is kinda goofy, it's just like a function, except the resulting type
-- of the body doesn't need to result in a valid function type
-- this means things like `let x := * in ...` would be allowed, even though
-- you couldn't write a function that takes something of type `□` as an argument
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