@@ -13,10 +13,7 @@
1313--
1414-----------------------------------------------------------------------------
1515
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE FlexibleInstances #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
16+{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-}
2017
2118module Language.PureScript.TypeChecker.Types (
2219 typesOf
@@ -36,137 +33,37 @@ module Language.PureScript.TypeChecker.Types (
3633
3734 checkFunctionApplication
3835 Check a function of a given type returns a value of another type when applied to its arguments
39−
40− subsumes
41− Check a type subsumes another type
4236-}
4337
38+import Data.Either (lefts, rights)
4439import Data.List
45−import Data.Maybe (maybeToList, fromMaybe)
46−import Data.Function (on)
47−import Data.Ord (comparing)
40+import Data.Maybe (fromMaybe)
4841import Data.Monoid
49−import Data.Either (lefts, rights)
42+import qualified Data.Map as M
43+
44+import Control.Applicative
45+import Control.Monad.Error
46+import Control.Monad.State
47+import Control.Monad.Unify
5048
5149import Language.PureScript.Declarations
52−import Language.PureScript.Types
50+import Language.PureScript.Environment
51+import Language.PureScript.Errors
5352import Language.PureScript.Kinds
5453import Language.PureScript.Names
55−import Language.PureScript.TypeClassDictionaries
56−import Language.PureScript.TypeChecker.Monad
54+import Language.PureScript.Pretty
55+import Language.PureScript.TypeChecker.Entailment
5756import Language.PureScript.TypeChecker.Kinds
57+import Language.PureScript.TypeChecker.Monad
58+import Language.PureScript.TypeChecker.Rows
59+import Language.PureScript.TypeChecker.Skolems
60+import Language.PureScript.TypeChecker.Subsumption
5861import Language.PureScript.TypeChecker.Synonyms
59−import Language.PureScript.Pretty
60−import Language.PureScript.Environment
61−import Language.PureScript.Errors
62+import Language.PureScript.TypeChecker.Unify
63+import Language.PureScript.TypeClassDictionaries
64+import Language.PureScript.Types
6265import qualified Language.PureScript.Constants as C
6366
64−import Control.Monad.State
65−import Control.Monad.Error
66−import Control.Monad.Unify
67−
68−import Control.Applicative
69−import Control.Arrow (Arrow(..))
70−
71−import qualified Data.Map as M
72−import qualified Data.HashMap.Strict as H
73−
74−instance Partial Type where
75− unknown = TUnknown
76− isUnknown (TUnknown u) = Just u
77− isUnknown _ = Nothing
78− unknowns = everythingOnTypes (++) go
79− where
80− go (TUnknown u) = [u]
81− go _ = []
82− ($?) sub = everywhereOnTypes go
83− where
84− go t@(TUnknown u) = case H.lookup u (runSubstitution sub) of
85− Nothing -> t
86− Just t' -> t'
87− go other = other
88−
89−instance Unifiable Check Type where
90− (=?=) = unifyTypes
91−
92−-- |
93−-- Unify two types, updating the current substitution
94−--
95−unifyTypes :: Type -> Type -> UnifyT Type Check ()
96−unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
97− unifyTypes' t1 t2
98− where
99− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
100− unifyTypes' (TUnknown u) t = u =:= t
101− unifyTypes' t (TUnknown u) = u =:= t
102− unifyTypes' (SaturatedTypeSynonym name args) ty = do
103− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
104− ty1 `unifyTypes` ty
105− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
106− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
107− case (sc1, sc2) of
108− (Just sc1', Just sc2') -> do
109− sko <- newSkolemConstant
110− let sk1 = skolemize ident1 sko sc1' ty1
111− let sk2 = skolemize ident2 sko sc2' ty2
112− sk1 `unifyTypes` sk2
113− _ -> error "Skolemized type variable was not given a scope"
114− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
115− sko <- newSkolemConstant
116− let sk = skolemize ident sko sc ty1
117− sk `unifyTypes` ty2
118− unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
119− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
120− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
121− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
122− guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
123− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
124− t3 `unifyTypes` t5
125− t4 `unifyTypes` t6
126− unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
127− unifyTypes' (KindedType ty1 _) ty2 = ty1 `unifyTypes` ty2
128− unifyTypes' ty1 (KindedType ty2 _) = ty1 `unifyTypes` ty2
129− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
130− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
131− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
132− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
133− unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
134− unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
135− unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
136−
137−-- |
138−-- Unify two rows, updating the current substitution
139−--
140−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
141−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
142−-- error.
143−--
144−unifyRows :: Type -> Type -> UnifyT Type Check ()
145−unifyRows r1 r2 =
146− let
147− (s1, r1') = rowToList r1
148− (s2, r2') = rowToList r2
149− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
150− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
151− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
152− in do
153− forM_ int (uncurry (=?=))
154− unifyRows' sd1 r1' sd2 r2'
155− where
156− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
157− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
158− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
159− unifyRows' sd1 (TUnknown u1) sd2 (TUnknown u2) = do
160− forM_ sd1 $ \(_, t) -> occursCheck u2 t
161− forM_ sd2 $ \(_, t) -> occursCheck u1 t
162− rest <- fresh
163− u1 =:= rowFromList (sd2, rest)
164− u2 =:= rowFromList (sd1, rest)
165− unifyRows' [] REmpty [] REmpty = return ()
166− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
167− unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
168− unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
169−
17067-- |
17168-- Infer the types of multiple mutually-recursive values, and return elaborated values including
17269-- type class dictionaries and type annotations.
@@ -252,7 +149,7 @@ typeForBindingGroupElement (ident, val) dict untypedDict = do
252149-- |
253150-- Check if a value contains a type annotation
254151--
255−isTyped :: (Ident, Expr) -> (Either (Ident, Expr) (Ident, (Expr, Type, Bool)))
152+isTyped :: (Ident, Expr) -> Either (Ident, Expr) (Ident, (Expr, Type, Bool))
256153isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
257154isTyped (name, value) = Left (name, value)
258155
@@ -281,291 +178,12 @@ replaceTypeClassDictionaries mn =
281178 go other = return other
282179
283180-- |
284−-- A simplified representation of expressions which are used to represent type
285−-- class dictionaries at runtime, which can be compared for equality
286−--
287−data DictionaryValue
288− -- |
289− -- A dictionary which is brought into scope by a local constraint
290− --
291− = LocalDictionaryValue (Qualified Ident)
292− -- |
293− -- A dictionary which is brought into scope by an instance declaration
294− --
295− | GlobalDictionaryValue (Qualified Ident)
296− -- |
297− -- A dictionary which depends on other dictionaries
298− --
299− | DependentDictionaryValue (Qualified Ident) [DictionaryValue]
300− -- |
301− -- A subclass dictionary
302− --
303− | SubclassDictionaryValue DictionaryValue (Qualified ProperName) Integer
304− deriving (Show, Ord, Eq)
305−
306−-- |
307−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
308−-- return a type class dictionary reference.
309−--
310−entails :: Environment -> ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Bool -> Check Expr
311−entails env moduleName context = solve (sortedNubBy canonicalizeDictionary (filter filterModule context))
312− where
313− sortedNubBy :: (Ord k) => (v -> k) -> [v] -> [v]
314− sortedNubBy f vs = M.elems (M.fromList (map (f &&& id) vs))
315−
316− -- Filter out type dictionaries which are in scope in the current module
317− filterModule :: TypeClassDictionaryInScope -> Bool
318− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
319− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
320− filterModule _ = False
321−
322− solve context' (className, tys) trySuperclasses =
323− checkOverlaps $ go trySuperclasses className tys
324− where
325− go trySuperclasses' className' tys' =
326− -- Look for regular type instances
327− [ mkDictionary (canonicalizeDictionary tcd) args
328− | tcd <- context'
329− -- Make sure the type class name matches the one we are trying to satisfy
330− , className' == tcdClassName tcd
331− -- Make sure the type unifies with the type in the type instance definition
332− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
333− -- Solve any necessary subgoals
334− , args <- solveSubgoals subst (tcdDependencies tcd) ] ++
335−
336− -- Look for implementations via superclasses
337− [ SubclassDictionaryValue suDict superclass index
338− | trySuperclasses'
339− , (subclassName, (args, _, implies)) <- M.toList (typeClasses env)
340− -- Try each superclass
341− , (index, (superclass, suTyArgs)) <- zip [0..] implies
342− -- Make sure the type class name matches the superclass name
343− , className' == superclass
344− -- Make sure the types unify with the types in the superclass implication
345− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' suTyArgs
346− -- Finally, satisfy the subclass constraint
347− , args' <- maybeToList $ mapM (flip lookup subst) (map fst args)
348− , suDict <- go True subclassName args' ]
349−
350− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
351− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
352− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
353− solveSubgoals :: [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [DictionaryValue]]
354− solveSubgoals _ Nothing = return Nothing
355− solveSubgoals subst (Just subgoals) = do
356− dict <- mapM (uncurry (go True) . second (map (replaceAllTypeVars subst))) subgoals
357− return $ Just dict
358− -- Make a dictionary from subgoal dictionaries by applying the correct function
359− mkDictionary :: Qualified Ident -> Maybe [DictionaryValue] -> DictionaryValue
360− mkDictionary fnName Nothing = LocalDictionaryValue fnName
361− mkDictionary fnName (Just []) = GlobalDictionaryValue fnName
362− mkDictionary fnName (Just dicts) = DependentDictionaryValue fnName dicts
363− -- Turn a DictionaryValue into a Expr
364− dictionaryValueToValue :: DictionaryValue -> Expr
365− dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
366− dictionaryValueToValue (GlobalDictionaryValue fnName) = Var fnName
367− dictionaryValueToValue (DependentDictionaryValue fnName dicts) = foldl App (Var fnName) (map dictionaryValueToValue dicts)
368− dictionaryValueToValue (SubclassDictionaryValue dict superclassName index) =
369− App (Accessor (C.__superclass_ ++ show superclassName ++ "_" ++ show index)
370− (dictionaryValueToValue dict))
371− valUndefined
372− -- Ensure that a substitution is valid
373− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
374− verifySubstitution subst = do
375− let grps = groupBy ((==) `on` fst) subst
376− guard (all (pairwise (unifiesWith env) . map snd) grps)
377− return $ map head grps
378− -- |
379− -- Check for overlapping instances
380− --
381− checkOverlaps :: [DictionaryValue] -> Check Expr
382− checkOverlaps dicts =
383− case [ (d1, d2) | d1 <- dicts, d2 <- dicts, d1 `overlapping` d2 ] of
384− (d1, d2) : _ -> throwError . strMsg $ unlines
385− [ "Overlapping instances found for " ++ show className ++ " " ++ unwords (map prettyPrintType tys) ++ "."
386− , "For example:"
387− , prettyPrintDictionaryValue d1
388− , "and:"
389− , prettyPrintDictionaryValue d2
390− ]
391− _ -> case chooseSimplestDictionaries dicts of
392− [] -> throwError . strMsg $
393− "No instance found for " ++ show className ++ " " ++ unwords (map prettyPrintTypeAtom tys)
394− d : _ -> return $ dictionaryValueToValue d
395− -- Choose the simplest DictionaryValues from a list of candidates
396− -- The reason for this function is as follows:
397− -- When considering overlapping instances, we don't want to consider the same dictionary
398− -- to be an overlap of itself when obtained as a superclass of another class.
399− -- Observing that we probably don't want to select a superclass instance when an instance
400− -- is available directly, and that there is no way for a superclass instance to actually
401− -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
402− -- obtained as superclass instances if there are simpler instances available.
403− chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
404− chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
405− [] -> ds
406− simple -> simple
407− isSimpleDictionaryValue SubclassDictionaryValue{} = False
408− isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
409− isSimpleDictionaryValue _ = True
410− -- |
411− -- Check if two dictionaries are overlapping
412− --
413− -- Dictionaries which are subclass dictionaries cannot overlap, since otherwise the overlap would have
414− -- been caught when constructing superclass dictionaries.
415− --
416− overlapping :: DictionaryValue -> DictionaryValue -> Bool
417− overlapping (LocalDictionaryValue nm1) (LocalDictionaryValue nm2) | nm1 == nm2 = False
418− overlapping (GlobalDictionaryValue nm1) (GlobalDictionaryValue nm2) | nm1 == nm2 = False
419− overlapping (DependentDictionaryValue nm1 ds1) (DependentDictionaryValue nm2 ds2)
420− | nm1 == nm2 = any id $ zipWith overlapping ds1 ds2
421− overlapping (SubclassDictionaryValue _ _ _) _ = False
422− overlapping _ (SubclassDictionaryValue _ _ _) = False
423− overlapping _ _ = True
424− -- |
425− -- Render a DictionaryValue fit for human consumption in error messages
426− --
427− prettyPrintDictionaryValue :: DictionaryValue -> String
428− prettyPrintDictionaryValue = unlines . indented 0
429− where
430− indented n (LocalDictionaryValue _) = [spaces n ++ "Dictionary in scope"]
431− indented n (GlobalDictionaryValue nm) = [spaces n ++ show nm]
432− indented n (DependentDictionaryValue nm args) = (spaces n ++ show nm ++ " via") : concatMap (indented (n + 2)) args
433− indented n (SubclassDictionaryValue sup nm _) = (spaces n ++ show nm ++ " via superclass") : indented (n + 2) sup
434−
435− spaces n = replicate n ' ' ++ "- "
436−
437− valUndefined :: Expr
438− valUndefined = Var (Qualified (Just (ModuleName [ProperName C.prim])) (Ident C.undefined))
439−
440−-- |
441−-- Check all values in a list pairwise match a predicate
442−--
443−pairwise :: (a -> a -> Bool) -> [a] -> Bool
444−pairwise _ [] = True
445−pairwise _ [_] = True
446−pairwise p (x : xs) = all (p x) xs && pairwise p xs
447−
448−-- |
449−-- Check that two types unify
450−--
451−unifiesWith :: Environment -> Type -> Type -> Bool
452−unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
453−unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
454−unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
455−unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
456−unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
457−unifiesWith e (SaturatedTypeSynonym name args) t2 =
458− case expandTypeSynonym' e name args of
459− Left _ -> False
460− Right t1 -> unifiesWith e t1 t2
461−unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
462−unifiesWith _ _ _ = False
463−
464−-- |
465−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
466−-- and return a substitution from type variables to types which makes the type heads unify.
467−--
468−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
469−typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
470−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
471−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
472−typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
473−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
474− Left _ -> Nothing
475− Right t1 -> typeHeadsAreEqual m e t1 t2
476−typeHeadsAreEqual _ _ _ _ = Nothing
477−
478−-- |
479−-- Ensure skolem variables do not escape their scope
480−--
481−skolemEscapeCheck :: Expr -> Check ()
482−skolemEscapeCheck (TypedValue False _ _) = return ()
483−skolemEscapeCheck root@TypedValue{} =
484− -- Every skolem variable is created when a ForAll type is skolemized.
485− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
486− -- field of the ForAll constructor.
487− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
488− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
489− -- an escaped skolem variable.
490− let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
491− in case f root of
492− [] -> return ()
493− ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ExprError val))
494− where
495− def s _ = (s, [])
496−
497− go :: [(SkolemScope, Expr)] -> Expr -> ([(SkolemScope, Expr)], [(Maybe Expr, Expr)])
498− go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
499− go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
500− (sco : _) -> (scos, [(findBindingScope sco, val)])
501− _ -> (scos, [])
502− where
503− collectSkolems :: Type -> [SkolemScope]
504− collectSkolems = nub . everythingOnTypes (++) collect
505− where
506− collect (Skolem _ _ scope) = [scope]
507− collect _ = []
508− go scos _ = (scos, [])
509− findBindingScope :: SkolemScope -> Maybe Expr
510− findBindingScope sco =
511− let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
512− in getFirst $ f root
513− where
514− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
515− go' _ = mempty
516−skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ExprError val))
517−
518−-- |
519−-- Ensure rows do not contain duplicate labels
520−--
521−checkDuplicateLabels :: Expr -> Check ()
522−checkDuplicateLabels =
523− let (_, f, _) = everywhereOnValuesM def go def
524− in void . f
525− where
526− def :: a -> Check a
527− def = return
528−
529− go :: Expr -> Check Expr
530− go e@(TypedValue _ val ty) = do
531− checkDups ty
532− return e
533−
534− where
535− checkDups :: Type -> Check ()
536− checkDups (TypeApp t1 t2) = checkDups t1 >> checkDups t2
537− checkDups (SaturatedTypeSynonym _ ts) = mapM_ checkDups ts
538− checkDups (ForAll _ t _) = checkDups t
539− checkDups (ConstrainedType args t) = do
540− mapM_ (checkDups) $ concatMap snd args
541− checkDups t
542− checkDups r@(RCons _ _ _) =
543− let (ls, _) = rowToList r in
544− case firstDup . sort . map fst $ ls of
545− Just l -> throwError $ mkErrorStack ("Duplicate label " ++ show l ++ " in row") $ Just (ExprError val)
546− Nothing -> return ()
547− checkDups _ = return ()
548−
549− firstDup :: (Eq a) => [a] -> Maybe a
550− firstDup (x : xs@(x' : _))
551− | x == x' = Just x
552− | otherwise = firstDup xs
553− firstDup _ = Nothing
554−
555− go other = return other
556−
557−-- |
558−-- Replace outermost unsolved unification variables with named type variables
181+-- Check the kind of a type, failing if it is not of kind *.
559182--
560−varIfUnknown :: Type -> Type
561−varIfUnknown ty =
562− let unks = nub $ unknowns ty
563− toName = (:) 't' . show
564− ty' = everywhereOnTypes typeToVar ty
565− typeToVar :: Type -> Type
566− typeToVar (TUnknown u) = TypeVar (toName u)
567− typeToVar t = t
568− in mkForAll (sort . map toName $ unks) ty'
183+checkTypeKind :: ModuleName -> Type -> UnifyT t Check ()
184+checkTypeKind moduleName ty = do
185+ kind <- liftCheck $ kindOf moduleName ty
186+ guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
569187
570188-- |
571189-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
@@ -584,67 +202,6 @@ instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
584202 return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
585203instantiatePolyTypeWithUnknowns val ty = return (val, ty)
586204
587−-- |
588−-- Replace a single type variable with a new unification variable
589−--
590−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
591−replaceVarWithUnknown ident ty = do
592− tu <- fresh
593− return $ replaceTypeVars ident tu ty
594−
595−-- |
596−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
597−-- better error messages during unification.
598−--
599−replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
600−replaceAllTypeSynonyms' env d =
601− let
602− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
603− in
604− saturateAllTypeSynonyms syns d
605−
606−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
607−replaceAllTypeSynonyms d = do
608− env <- getEnv
609− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
610−
611−-- |
612−-- \"Desaturate\" @SaturatedTypeSynonym@s
613−--
614−desaturateAllTypeSynonyms :: Type -> Type
615−desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
616− where
617− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
618− replaceSaturatedTypeSynonym t = t
619−
620−-- |
621−-- Replace a type synonym and its arguments with the aliased type
622−--
623−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
624−expandTypeSynonym' env name args =
625− case M.lookup name (typeSynonyms env) of
626− Just (synArgs, body) -> do
627− let repl = replaceAllTypeVars (zip (map fst synArgs) args) body
628− replaceAllTypeSynonyms' env repl
629− Nothing -> error "Type synonym was not defined"
630−
631−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
632−expandTypeSynonym name args = do
633− env <- getEnv
634− either (throwError . strMsg) return $ expandTypeSynonym' env name args
635−
636−expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
637−expandAllTypeSynonyms = everywhereOnTypesTopDownM go
638− where
639− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
640− go other = return other
641−
642−-- |
643−-- Ensure a set of property names and value does not contain duplicate labels
644−--
645−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
646−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
647−
648205-- |
649206-- Infer a type for a value, rethrowing any error to provide a more useful error message
650207--
@@ -733,8 +290,7 @@ infer' (SuperClassDictionary className tys) = do
733290 return $ TypeClassDictionary False (className, tys) dicts
734291infer' (TypedValue checkType val ty) = do
735292 Just moduleName <- checkCurrentModule <$> get
736− kind <- liftCheck $ kindOf moduleName ty
737− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
293+ checkTypeKind moduleName ty
738294 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
739295 val' <- if checkType then check val ty' else return val
740296 return $ TypedValue True val' ty'
@@ -745,8 +301,7 @@ inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Typ
745301inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
746302inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
747303 Just moduleName <- checkCurrentModule <$> get
748− kind <- liftCheck $ kindOf moduleName ty
749− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
304+ checkTypeKind moduleName ty
750305 let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
751306 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
752307 TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
@@ -766,7 +321,7 @@ inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
766321 let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
767322 makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
768323inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
769− ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
324+ (d' : ds', val') <- inferLetBinding seen (d : ds) ret j
770325 return (PositionedDeclaration pos d' : ds', val')
771326inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
772327
@@ -865,44 +420,6 @@ checkBinders nvals ret (CaseAlternative binders result : bs) = do
865420 rs <- checkBinders nvals ret bs
866421 return $ r : rs
867422
868−-- |
869−-- Generate a new skolem constant
870−--
871−newSkolemConstant :: UnifyT Type Check Int
872−newSkolemConstant = fresh'
873−
874−-- |
875−-- Generate a new skolem scope
876−--
877−newSkolemScope :: UnifyT Type Check SkolemScope
878−newSkolemScope = SkolemScope <$> fresh'
879−
880−-- |
881−-- Skolemize a type variable by replacing its instances with fresh skolem constants
882−--
883−skolemize :: String -> Int -> SkolemScope -> Type -> Type
884−skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
885−
886−-- |
887−-- This function has one purpose - to skolemize type variables appearing in a
888−-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
889−-- only example of scoped type variables.
890−--
891−skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
892−skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
893− where
894− go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
895− go other = other
896−
897−-- |
898−-- Introduce skolem scope at every occurence of a ForAll
899−--
900−introduceSkolemScope :: Type -> UnifyT Type Check Type
901−introduceSkolemScope = everywhereOnTypesM go
902− where
903− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
904− go other = return other
905−
906423-- |
907424-- Check the type of a value, rethrowing errors to provide a better error message
908425--
@@ -986,8 +503,7 @@ check' (SuperClassDictionary className tys) _ = do
986503 return $ TypeClassDictionary False (className, tys) dicts
987504check' (TypedValue checkType val ty1) ty2 = do
988505 Just moduleName <- checkCurrentModule <$> get
989− kind <- liftCheck $ kindOf moduleName ty1
990− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
506+ checkTypeKind moduleName ty1
991507 ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
992508 ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
993509 val' <- subsumes (Just val) ty1' ty2'
@@ -1036,7 +552,7 @@ check' (Constructor c) ty = do
1036552 _ <- subsumes Nothing repl ty
1037553 return $ TypedValue True (Constructor c) ty
1038554check' (Let ds val) ty = do
1039− (ds', val') <- inferLetBinding [] ds val (flip check ty)
555+ (ds', val') <- inferLetBinding [] ds val (`check` ty)
1040556 return $ TypedValue True (Let ds' val') ty
1041557check' val ty | containsTypeSynonyms ty = do
1042558 ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
@@ -1064,7 +580,7 @@ checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
1064580 go [] [] REmpty = return []
1065581 go [] [] u@(TUnknown _) = do u =?= REmpty
1066582 return []
1067− go [] [] (Skolem _ _ _) | lax = return []
583+ go [] [] Skolem{} | lax = return []
1068584 go [] ((p, _): _) _ | lax = return []
1069585 | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
1070586 go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
@@ -1127,84 +643,17 @@ checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1127643checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1128644 ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1129645 checkFunctionApplication fn ty arg ret
1130−checkFunctionApplication' fn (KindedType ty _) arg ret = do
646+checkFunctionApplication' fn (KindedType ty _) arg ret =
1131647 checkFunctionApplication fn ty arg ret
1132648checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1133649 dicts <- getTypeClassDictionaries
1134650 checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1135−checkFunctionApplication' fn fnTy dict@(TypeClassDictionary _ _ _) _ =
651+checkFunctionApplication' fn fnTy dict@TypeClassDictionary{} _ =
1136652 return (fnTy, App fn dict)
1137653checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1138654 ++ prettyPrintType fnTy
1139655 ++ " to argument " ++ prettyPrintValue arg
1140656
1141−-- |
1142−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1143−--
1144−subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1145−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
1146− where
1147− errorMessage = "Error checking that type "
1148− ++ prettyPrintType ty1
1149− ++ " subsumes type "
1150− ++ prettyPrintType ty2
1151−
1152−-- |
1153−-- Check whether one type subsumes another
1154−--
1155−subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1156−subsumes' val (ForAll ident ty1 _) ty2 = do
1157− replaced <- replaceVarWithUnknown ident ty1
1158− subsumes val replaced ty2
1159−subsumes' val ty1 (ForAll ident ty2 sco) =
1160− case sco of
1161− Just sco' -> do
1162− sko <- newSkolemConstant
1163− let sk = skolemize ident sko sco' ty2
1164− subsumes val ty1 sk
1165− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1166−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1167− _ <- subsumes Nothing arg2 arg1
1168− _ <- subsumes Nothing ret1 ret2
1169− return val
1170−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1171− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1172− subsumes val ty1 ty2
1173−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1174− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1175− subsumes val ty1 ty2
1176−subsumes' val (KindedType ty1 _) ty2 = do
1177− subsumes val ty1 ty2
1178−subsumes' val ty1 (KindedType ty2 _) = do
1179− subsumes val ty1 ty2
1180−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1181− dicts <- getTypeClassDictionaries
1182− subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1183−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1184− let
1185− (ts1, r1') = rowToList r1
1186− (ts2, r2') = rowToList r2
1187− ts1' = sortBy (comparing fst) ts1
1188− ts2' = sortBy (comparing fst) ts2
1189− go ts1' ts2' r1' r2'
1190− return val
1191− where
1192− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1193− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1194− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1195− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1196− go ts1 ts2 r1' r2'
1197− | p1 < p2 = do rest <- fresh
1198− r2' =?= RCons p1 ty1 rest
1199− go ts1 ((p2, ty2) : ts2) r1' rest
1200− | otherwise = do rest <- fresh
1201− r1' =?= RCons p2 ty2 rest
1202− go ((p1, ty1) : ts1) ts2 rest r2'
1203−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1204−subsumes' val ty1 ty2 = do
1205− ty1 =?= ty2
1206− return val
1207−
1208657-- |
1209658-- Compute the meet of two types, i.e. the most general type which both types subsume.
1210659-- TODO: handle constrained types
@@ -1220,9 +669,8 @@ meet e1 e2 t1 t2 = do
1220669 t1 =?= t2
1221670 return (e1, e2, t1)
1222671
1223−
1224−
1225−
1226−
1227−
1228−
672+-- |
673+-- Ensure a set of property names and value does not contain duplicate labels
674+--
675+ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
676+ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps