perga/lib/Check.hs

55 lines
2 KiB
Haskell
Raw Normal View History

2024-10-05 13:31:09 -07:00
module Check where
2024-11-11 17:57:14 -08:00
import Control.Monad.Except
import Data.List (intercalate, (!?))
2024-11-11 13:52:50 -08:00
2024-11-11 17:57:14 -08:00
import Control.Monad (unless)
2024-11-11 13:37:44 -08:00
import Expr
2024-10-05 13:31:09 -07:00
type Context = [Expr]
2024-11-12 00:00:51 -08:00
data TypeCheckError = SquareUntyped | UnboundVariable String | NotASort Expr Expr | ExpectedPiType Expr Expr | NotEquivalent Expr Expr Expr
instance Show TypeCheckError where
show SquareUntyped = "□ does not have a type"
show (UnboundVariable x) = "Unbound variable: " ++ x
show (NotASort x t) = "Expected " ++ pretty x ++ " to have type * or □, instead found " ++ pretty t
show (ExpectedPiType m a) = pretty m ++ " : " ++ pretty a ++ " is not a function"
show (NotEquivalent a a' e) = "Cannot unify " ++ pretty a ++ " with " ++ pretty a' ++ " when evaluating " ++ pretty e
2024-11-11 17:57:14 -08:00
type CheckResult = Either TypeCheckError
2024-11-12 00:00:51 -08:00
matchPi :: Expr -> Expr -> CheckResult (Expr, Expr)
matchPi _ (Pi _ a b) = Right (a, b)
matchPi m e = Left $ ExpectedPiType m e
2024-11-11 17:57:14 -08:00
showContext :: Context -> String
showContext g = "[" ++ intercalate ", " (map show g) ++ "]"
findType :: Context -> Expr -> CheckResult Expr
findType _ Star = Right Square
findType _ Square = Left SquareUntyped
2024-11-12 00:00:51 -08:00
findType g (Var n x) = do
t <- maybe (Left $ UnboundVariable x) Right $ g !? fromInteger n
2024-11-11 17:57:14 -08:00
s <- findType g t
2024-11-12 00:00:51 -08:00
unless (isSort s) $ throwError $ NotASort t s
2024-11-11 13:37:44 -08:00
pure t
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-12 00:00:51 -08:00
unless (betaEquiv a a') $ 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
s1 <- findType g a
2024-11-12 00:00:51 -08:00
unless (isSort s1) $ throwError $ NotASort a s1
2024-11-11 17:57:14 -08:00
b <- findType (incIndices a : map incIndices g) m
s2 <- findType g (Pi x a b)
2024-11-12 00:00:51 -08:00
unless (isSort s2) $ throwError $ NotASort (Pi x a b) s2
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
s1 <- findType g a
2024-11-12 00:00:51 -08:00
unless (isSort s1) $ throwError $ NotASort a s1
2024-11-11 17:57:14 -08:00
s2 <- findType (incIndices a : map incIndices g) b
2024-11-12 00:00:51 -08:00
unless (isSort s2) $ throwError $ NotASort b s2
2024-11-11 17:57:14 -08:00
pure s2